Compare commits

..
Author SHA1 Message Date
Graham Steffaniak 4072e46e44 updated with changes for backend pinned files (#2533) 2026-06-10 18:34:33 -05:00
Graham Steffaniak 38d141eb97 updated with code review fixes (#2535) 2026-06-10 17:59:14 -05:00
21dfc6169e Beta/v1.4.3 (#2530)
Co-authored-by: Kevin B. <kurami32_kbm@proton.me>
Co-authored-by: Graham Steffaniak <graham@debian-lake.ghome.net>
Co-authored-by: Neil <kylelzzz02@icloud.com>
Co-authored-by: Graham <info@quantumx-apps.com>
Co-authored-by: Anatolii Prylutskyi <anpryl@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 12:36:10 -05:00
4708faec5f fix(preview): keep opened file selected after closing its preview (#2515)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Kevin B. <kurami32_kbm@proton.me>
2026-06-09 14:48:04 -05:00
fa5abc8c67 Beta/v1.4.2 (#2485)
Co-authored-by: Kevin B. <kurami32_kbm@proton.me>
Co-authored-by: Stephan Paternotte <Stephan-P@users.noreply.github.com>
Co-authored-by: codacy-production[bot] <61871480+codacy-production[bot]@users.noreply.github.com>
2026-05-22 11:14:27 -05:00
687dc01293 Update en.json (#2456)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Co-authored-by: codacy-production[bot] <61871480+codacy-production[bot]@users.noreply.github.com>
2026-05-18 14:43:31 -05:00
bfde65a41e Update nl.json (#2448)
Co-authored-by: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Co-authored-by: codacy-production[bot] <61871480+codacy-production[bot]@users.noreply.github.com>
2026-05-18 14:43:18 -05:00
1802e12811 updated to fix critical bug (#2424) (#2427)
Co-authored-by: Kevin B. <kurami32_kbm@proton.me>
Co-authored-by: Stephan Paternotte <Stephan-P@users.noreply.github.com>
Co-authored-by: Nebula <40148908+nebula-it@users.noreply.github.com>
Co-authored-by: Juan Soler <juansoler@gmail.com>
2026-05-14 10:47:26 -05:00
0f215333ee Beta/v1.4.0 (#2421)
Co-authored-by: Kevin B. <kurami32_kbm@proton.me>
Co-authored-by: Stephan Paternotte <Stephan-P@users.noreply.github.com>
Co-authored-by: Nebula <40148908+nebula-it@users.noreply.github.com>
Co-authored-by: Juan Soler <juansoler@gmail.com>
2026-05-13 14:56:35 -05:00
305 changed files with 8561 additions and 8614 deletions

No files matched your search

+1
View File
@@ -23,6 +23,7 @@ frontend/tsconfig.tsbuildinfo
/frontend/generated
/frontend/tests/playwright-files/demo*
/frontend/loginAuth.json
/frontend/sharePrepStorage.json
/backend/vendor
/backend/*.cov
/backend/*test_config.yaml
+56
View File
@@ -2,6 +2,62 @@
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).
## v1.4.3
**Security**:
- [High] Path traversal in subtitle handler allows any authenticated user to read arbitrary files (GHSA-vvp7-h4fj-m28w)
**New Features**:
- pinned files/folders (#2396) (#2510)
- Markdown Image relative reference support (#2355)
- Add an option to create a new folder for unarchiving (#2338)
**Notes**:
- added fallback to show text in notification if copy fails (#2517)
- added `alt`+`arrow up` shortcut as alias of `backspace` to go into parent directory (#2501) (#2521)
- added `alt`+`arrow down` shortcut as alias of `enter` to open files in Listing View (#2501) (#2521)
- updated help menu with better translations
- migrate i18n to v11 (#2472) (#2504)
- migrate eslint (#2459)
- improved preview cancellation to improve performance when navigating UI.
**BugFixes**:
- fix lyrics regex parsing (#2505)
- fix folder previews issue (#2487) (#2492)
- fix accidental exit on images while using gestures (#2508)
- navigating using the up/down arrow keys in Listing View was "jumping randomly" in some view modes (#2521)
- socket field in config.yaml is ignored (#2497)
- fix keep opened file selected after closing its preview @anpryl (#2515)
## v1.4.2
**Security**:
- [Moderate] Add Rate Limiting on Authentication Endpoint Enables Brute Force Attacks (GHSA-r4v7-6wcg-ghj5)
- [Critical] Path traversal in public share PATCH allows file ops outside shared directory -- thanks @Revanth011 and @fg0x0 (GHSA-qqqm-5547-774x)
**New Features**:
- read-only source configuration via `source.config.readOnly: true` (#2438)
**Notes**:
- auth rate limiting can be disabled via `auth.disableRateLimit`
- updated share hash middleware (#2443)
- updated source info popup to include private and readOnly properties
**BugFixes**:
- Logout from share page now redirects to the share instead of `/Login` again. (#2245)
- `This location cannot be reached` error when navigating with FileTree in shares. (#2245)
- Fix FileTree rename and move actions in previews. (#2245)
- Delete prompt not showing date and thumbnails in some previews. (#2245)
- fix path slash issue on windows (#2451) (#2433) (#2419)
- Always force url rewrite for onlyoffice internal URL. Fixes Error saving with OnlyOffice (#2450)
- Overriding a Deny with an Allow not working (#2405)
## v1.4.1
**Security**:
- Fix critical: unauthenticated user can view source info
## v1.4.0
**New Features**:
+7 -64
View File
@@ -5,17 +5,22 @@ Thank you for your interest in contributing to FileBrowser Quantum! This guide w
## Prerequisites
- **Go 1.25+** (see `backend/go.mod`)
- **Node.js 20.0.0+** with npm 9.0.0+ (see `frontend/package.json`)
- **Node.js 22.0.0+** with npm 9.0.0+ (see `frontend/package.json`)
- **Docker** (optional, for containerized development)
- **Git** especially improtant on windows -- needed for bash support.
### Optional Tools
- **ffmpeg**: For media features (subtitles, thumbnails, heic)
- **ffmpeg/ffprobe**: 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)
- **exiftool**: For photo metadata processing (RAW/HEIC previews, EXIF orientation)
- Ubuntu/Debian: `sudo apt-get install libimage-exiftool-perl`
- macOS: `brew install exiftool`
- Windows: Download from [exiftool.org](https://exiftool.org/) (install `exiftool.exe` and add it to your PATH, or set `integrations.media.exiftoolPath` in config)
- **mupdf-tools**: For PDF preview generation
- Ubuntu/Debian: `sudo apt-get install mupdf-tools`
- macOS: `brew install mupdf-tools`
@@ -90,18 +95,6 @@ make test-playwright # E2E tests in Docker
E2E tests run with three authentication modes: standard auth, no auth, and proxy auth.
### Coverage & Performance
```bash
cd backend
./run_check_coverage.sh # Coverage report with HTML output
./run_benchmark.sh # Benchmarks
```
**Code Coverage:**
- View report: Open `backend/coverage.html` after running coverage script
- CI enforces coverage for critical packages
- Use `go test -cover` for quick package coverage
## Code Standards
### Backend (Go)
@@ -156,53 +149,3 @@ type(scope): description
Types: feat, fix, docs, refactor, test, chore
```
## Roadmap
Check the [Project Roadmap](https://github.com/users/gtsteffaniak/projects/4/views/2) to see issues sorted by priority. This helps you understand what features are planned and where you can contribute most effectively.
## Troubleshooting
### Common Issues
**Build failures:**
```bash
# Frontend
cd frontend && rm -rf node_modules && npm install
# Backend
cd backend && go mod tidy && go clean -modcache
```
**Authentication Issues:**
Always first enable debug logging in your config file if you have issues.
1. **OIDC Login Fails:**
- Check redirect URLs match your config
- Verify OIDC provider settings
- Enable debug logs to see auth flow
- Common issue: mismatched callback URLs
2. **Proxy Auth Not Working:**
- Verify header names match config
- Check nginx/reverse proxy passes headers
- Test with: `curl -H "X-Auth: username" localhost:8080`
- Enable `--log-level debug` to see headers
3. **TOTP Issues:**
- Ensure server time is synchronized
- Check QR code generation in logs
- Test with authenticator app time settings
- Database might have stale TOTP secrets
4. **Session/Cookie Problems:**
- Clear browser cookies and localStorage
- Verify cookie domain settings
- Try incognito/private browsing mode
### Getting Help
- **Wiki**: [Project Wiki](https://github.com/gtsteffaniak/filebrowser/wiki)
- **Issues**: [GitHub Issues](https://github.com/gtsteffaniak/filebrowser/issues)
- **PR Template**: See `.github/PULL_REQUEST_TEMPLATE.md`
+2
View File
@@ -19,5 +19,7 @@ COPY [ "./backend/http/embed/", "./http/dist/"]
ENV FILEBROWSER_PLAYWRIGHT_TEST=true
RUN ./filebrowser set -u testuser1,testuser1
RUN ./filebrowser set rule -s access -p / -r user -v admin -allow -c config.yaml
RUN ./filebrowser set rule -s access -p /excluded/showme.txt -r user -v admin -allow -c config.yaml
RUN ./filebrowser set rule -s access -p /denied -r user -v admin -c config.yaml
RUN ./filebrowser set rule -s access -p /excluded -r user -v admin -c config.yaml
RUN ./filebrowser & sleep 2 && cd ../frontend && npx playwright test
@@ -3,7 +3,7 @@ server-main: &server-main
baseURL: "/"
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
name: "playwright + files"
+1 -1
View File
@@ -2,7 +2,7 @@ server:
port: 8080
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
config:
+1 -1
View File
@@ -3,7 +3,7 @@ server:
baseURL: "/files/"
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
name: "exclude"
+1 -1
View File
@@ -1,7 +1,7 @@
server:
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
config:
+1 -1
View File
@@ -3,7 +3,7 @@ server:
baseURL: "/"
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
+1 -1
View File
@@ -3,7 +3,7 @@ server:
baseURL: "/subpath"
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
config:
+1 -1
View File
@@ -3,7 +3,7 @@ server:
baseURL: "/files/"
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
name: "playwright"
+1 -1
View File
@@ -3,7 +3,7 @@ server:
baseURL: "/"
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
name: "playwright + files"
+1 -1
View File
@@ -3,7 +3,7 @@ server:
baseURL: "/"
logging:
- levels: "info|error|warning|debug"
apiFilter: '.*'
apiFilter: 'disabled'
sources:
- path: "../frontend/tests/playwright-files"
name: "playwright + files"
+4 -4
View File
@@ -357,7 +357,7 @@ func TestOverrideDirectoryToFile(t *testing.T) {
{Name: "Test Object", Type: "directory"},
},
}
idx.UpdateMetadata(rootInfo, nil) // nil scanner for test
idx.UpdateMetadata(rootInfo, nil, true) // nil scanner for test
// Delete the old directory item from the database before replacing it with a file
idx.DeleteMetadata("/Test Object", true, false)
@@ -375,7 +375,7 @@ func TestOverrideDirectoryToFile(t *testing.T) {
},
},
}
idx.UpdateMetadata(rootInfo, nil) // nil scanner for test
idx.UpdateMetadata(rootInfo, nil, true) // nil scanner for test
// Verify the directory was replaced with a file in the mock data
rootInfo, exists := idx.GetMetadataInfo("/", true, false)
@@ -467,7 +467,7 @@ func TestOverrideFileToDirectory(t *testing.T) {
{ItemInfo: iteminfo.ItemInfo{Name: "Test Object", Size: 12}}, // Length of "test content"
},
}
idx.UpdateMetadata(rootInfo, nil) // nil scanner for test
idx.UpdateMetadata(rootInfo, nil, true) // nil scanner for test
// Delete the old file item from the database before replacing it with a directory
idx.DeleteMetadata("/Test Object", false, false)
@@ -483,7 +483,7 @@ func TestOverrideFileToDirectory(t *testing.T) {
Type: "directory",
},
}
idx.UpdateMetadata(rootInfo, nil) // nil scanner for test
idx.UpdateMetadata(rootInfo, nil, true) // nil scanner for test
// Verify the file was replaced with a directory in the mock data
rootInfo, exists := idx.GetMetadataInfo("/", true, false)
+49 -29
View File
@@ -27,6 +27,8 @@ import (
"github.com/gtsteffaniak/go-logger/logger"
)
var reDuration = regexp.MustCompile(`^\[(?:(\d{1,2}):)?(\d{1,2}):(\d{1,2})\.(\d+)\](.*)`)
// CheckPermissionsFunc allows tests to override CheckPermissions behavior
var CheckPermissionsFunc = checkPermissionsImpl
@@ -87,7 +89,7 @@ func processDirectoryMetadata(response *iteminfo.ExtendedFileInfo, idx *indexing
wg.Wait()
}
// finalizeResponse handles final response adjustments (OnlyOffice ID, scope stripping)
// finalizeResponse handles final response adjustments (OnlyOffice ID, scope stripping).
func finalizeResponse(response *iteminfo.ExtendedFileInfo, info *iteminfo.FileInfo, realPath string, user *users.User, userScope string) {
// Add OnlyOffice ID if applicable
if settings.Config.Integrations.OnlyOffice.Secret != "" && info.Type != "directory" && iteminfo.IsOnlyOffice(info.Name) {
@@ -145,7 +147,7 @@ func checkPermissionsImpl(opts utils.FileOptions, access *access.Storage, user *
// Layer 1: USER ACCESS CONTROL
// Quick check: Does THIS user have permission?
if !access.Permitted(idx.Path, indexPath, user.Username) {
return "", "", errors.ErrAccessDenied
return indexPath, "", errors.ErrAccessDenied
}
return indexPath, userScope, nil
}
@@ -157,30 +159,30 @@ type Items struct {
// This removes files whose names match any extension in hideFileExt.
func filterFilesByExt(files []iteminfo.ExtendedItemInfo, hideFileExt string) []iteminfo.ExtendedItemInfo {
if hideFileExt == "" {
return files
}
filtered := files[:0]
for _, f := range files {
if !utils.HideFileByExt(f.Name, hideFileExt) {
filtered = append(filtered, f)
}
}
return filtered
if hideFileExt == "" {
return files
}
filtered := files[:0]
for _, f := range files {
if !utils.HideFileByExt(f.Name, hideFileExt) {
filtered = append(filtered, f)
}
}
return filtered
}
func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.User) (Items, error) {
items := Items{}
indexPath, _, err := CheckPermissions(opts, access, user)
if err != nil {
return items, err
indexPath, _, topLevelErr := CheckPermissions(opts, access, user)
accessRulesErr := topLevelErr != nil && topLevelErr == errors.ErrAccessDenied && indexPath != ""
if topLevelErr != nil && !accessRulesErr {
return items, topLevelErr
}
// Get index
idx := indexing.GetIndex(opts.Source)
if idx == nil {
return items, fmt.Errorf("could not get index: %v ", opts.Source)
}
info, err := idx.GetFileInfo(indexing.FileInfoRequest{
IndexPath: indexPath,
FollowSymlinks: opts.FollowSymlinks,
@@ -198,6 +200,10 @@ func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.Use
if err := access.CheckChildItemAccess(info, idx, user.Username); err != nil {
return items, err
}
hasAccessibleItems := len(info.Files) > 0 || len(info.Folders) > 0
if accessRulesErr && !hasAccessibleItems {
return items, errors.ErrAccessDenied
}
if opts.Only == "files" || opts.Only == "" {
for _, file := range info.Files {
if opts.HideFileExt != "" && utils.HideFileByExt(file.Name, opts.HideFileExt) {
@@ -224,9 +230,10 @@ func FileInfoFaster(opts utils.FileOptions, access *access.Storage, user *users.
// fileInfoFasterImpl is the actual implementation of FileInfoFaster
func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *users.User, share *share.Storage) (*iteminfo.ExtendedFileInfo, error) {
response := &iteminfo.ExtendedFileInfo{}
indexPath, userScope, err := CheckPermissions(opts, access, user)
if err != nil {
return response, err
indexPath, userScope, topLevelErr := CheckPermissions(opts, access, user)
accessRulesErr := topLevelErr != nil && topLevelErr == errors.ErrAccessDenied && indexPath != ""
if topLevelErr != nil && !accessRulesErr {
return response, topLevelErr
}
// Get index
idx := indexing.GetIndex(opts.Source)
@@ -246,13 +253,16 @@ func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *us
if err != nil {
return response, err // Path excluded by index rules OR doesn't exist
}
// otherwise response keeps unfiltered Folders/Files while CheckChildItemAccess only mutates info.
if info.Type == "directory" {
if err := access.CheckChildItemAccess(info, idx, user.Username); err != nil {
return response, err
}
}
hasAccessibleItems := len(info.Files) > 0 || len(info.Folders) > 0
if accessRulesErr && !hasAccessibleItems {
return response, errors.ErrAccessDenied
}
// Build response
response.FileInfo = *info
@@ -269,6 +279,12 @@ func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *us
}
response.IsShared = share.IsShared(response.Path, idx.Path, user.ID)
}
if info.Type == "directory" && opts.ShowPinnedItems {
if source, ok := users.ResolveSourceKey(response.Source); ok {
response.PinnedItems = user.PinnedNamesForDirectory(source.Path, response.Path)
}
}
defer finalizeResponse(response, info, response.RealPath, user, userScope)
if opts.SkipExtendedAttrs {
if info.Type == "directory" && opts.HideFileExt != "" {
@@ -373,13 +389,12 @@ func generateOfficeId(realPath string) string {
func parseLRC(raw string) []iteminfo.Lyric {
var lines []iteminfo.Lyric
scanner := bufio.NewScanner(strings.NewReader(raw))
re := regexp.MustCompile(`^\[(?:(\d{1,2}):)?(\d{1,2}):(\d{1,2})\.(\d+)\](.*)`)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
matches := re.FindStringSubmatch(line)
matches := reDuration.FindStringSubmatch(line)
if len(matches) == 6 {
// Hours default to 0 (if not present in the timestamps)
h := 0
@@ -458,10 +473,12 @@ func extractAudioMetadata(ctx context.Context, item *iteminfo.ExtendedItemInfo,
if rawLyrics := m.Lyrics(); rawLyrics != "" {
item.Metadata.HasLyrics = true
} else {
// Check for .lrc file
ext := filepath.Ext(realPath)
base := strings.TrimSuffix(realPath, ext)
lrcPath := base + ".lrc"
// Check for sidecar .lrc file
dir := filepath.Dir(realPath)
base := filepath.Base(realPath)
ext := filepath.Ext(base)
nameWithoutExt := strings.TrimSuffix(base, ext)
lrcPath := filepath.Join(dir, nameWithoutExt+".lrc")
if _, err := os.Stat(lrcPath); err == nil {
item.Metadata.HasLyrics = true
}
@@ -526,9 +543,12 @@ func ExtractLyrics(realPath string) ([]iteminfo.Lyric, error) {
lyrics = parseLRC(raw)
}
if len(lyrics) == 0 {
ext := filepath.Ext(realPath)
base := strings.TrimSuffix(realPath, ext)
lrcPath := base + ".lrc"
// Check for sidecar .lrc file
dir := filepath.Dir(realPath)
base := filepath.Base(realPath)
ext := filepath.Ext(base)
nameWithoutExt := strings.TrimSuffix(base, ext)
lrcPath := filepath.Join(dir, nameWithoutExt+".lrc")
if data, err := os.ReadFile(lrcPath); err == nil {
lyrics = parseLRC(string(data))
}
+10 -20
View File
@@ -25,10 +25,9 @@ type webAuthnSession struct {
}
type WebAuthnService struct {
wa *webauthn.WebAuthn
sessions sync.Map
stopCh chan struct{}
originMu sync.Mutex
wa *webauthn.WebAuthn
sessions sync.Map
stopCh chan struct{}
}
var webAuthnInstance *WebAuthnService
@@ -66,24 +65,15 @@ func IsWebAuthnEnabled() bool {
return webAuthnInstance != nil
}
// EnsureOrigin dynamically adds the given origin to the allowed RP origins list.
// This supports self-hosted deployments where the access domain may vary.
func (s *WebAuthnService) EnsureOrigin(origin string) {
s.originMu.Lock()
defer s.originMu.Unlock()
for _, o := range s.wa.Config.RPOrigins {
if o == origin {
return
// ValidateOrigin checks if the given origin is in the configured whitelist.
// Returns true if the origin is allowed, false otherwise.
func (s *WebAuthnService) ValidateOrigin(origin string) bool {
for _, allowedOrigin := range s.wa.Config.RPOrigins {
if allowedOrigin == origin {
return true
}
}
s.wa.Config.RPOrigins = append(s.wa.Config.RPOrigins, origin)
}
// EnsureRPID dynamically updates the relying party ID to match the request host.
func (s *WebAuthnService) EnsureRPID(rpID string) {
s.originMu.Lock()
defer s.originMu.Unlock()
s.wa.Config.RPID = rpID
return false
}
func generateSessionID() string {
+4 -4
View File
@@ -118,10 +118,10 @@ type JwtAuthConfig struct {
// PasskeyAuthConfig configures WebAuthn / Passkey authentication as a second factor.
type PasskeyAuthConfig struct {
Enabled bool `json:"enabled"` // whether to enable passkey MFA
RPDisplayName string `json:"rpDisplayName"` // the Relying Party display name (defaults to frontend name)
RPID string `json:"rpId"` // the Relying Party ID; if empty, auto-derived from base URL host
RPOrigins []string `json:"rpOrigins"` // allowed origins; if empty, auto-derived from base URL
Enabled bool `json:"enabled"` // whether to enable passkey MFA
RPDisplayName string `json:"rpDisplayName"` // the Relying Party display name (defaults to frontend name)
RPID string `json:"rpId"` // the Relying Party ID; if empty, auto-derived from base URL host
RPOrigins []string `json:"rpOrigins"` // allowed origins; if empty, auto-derived from base URL
LoginButtonText string `json:"loginButtonText"` // custom text for the passkey login button
}
+14 -8
View File
@@ -8,7 +8,6 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
@@ -53,6 +52,7 @@ func Initialize(configFile string) {
}
setupFs()
setupServer()
setupHttp()
setupAuth(false)
setupSources(false)
InitializeUserResolvers() // Initialize user package resolvers after sources are set up
@@ -62,6 +62,9 @@ func Initialize(configFile string) {
}
func setupServer() {
if Config.Server.Socket != "" && (Config.Server.TLSCert != "" || Config.Server.TLSKey != "") {
logger.Fatal("server.socket cannot be used with tlsCert or tlsKey")
}
if Config.Server.ListenAddress == "" {
Config.Server.ListenAddress = "0.0.0.0"
}
@@ -83,6 +86,15 @@ func setupEnv() {
}
}
func setupHttp() {
if len(Config.Http.TrustedHeadersArray) > 0 {
Config.Http.TrustedHeaders = make(map[string]bool)
for _, header := range Config.Http.TrustedHeadersArray {
Config.Http.TrustedHeaders[strings.ToLower(header)] = true
}
}
}
func setupFs() {
// Convert permission values (like 644, 755) to octal interpretation
filePermOctal, err := strconv.ParseUint(Config.Server.Filesystem.CreateFilePermission, 8, 32)
@@ -961,12 +973,6 @@ func loadEnvConfig() {
}
func SetDefaults(generate bool) Settings {
// get number of CPUs available
numCpus := 4 // default to 4 CPUs if runtime.NumCPU() fails or is not available
cpus := runtime.NumCPU()
if cpus > 0 && !generate {
numCpus = cpus
}
database := os.Getenv("FILEBROWSER_DATABASE")
if database == "" {
database = "database.db"
@@ -977,7 +983,7 @@ func SetDefaults(generate bool) Settings {
s := Settings{
Server: Server{
Port: 80,
NumImageProcessors: numCpus,
NumImageProcessors: 4,
BaseURL: "",
Database: database,
SourceMap: map[string]*Source{},
+5 -1
View File
@@ -133,6 +133,10 @@ func ApplyUserDefaults(u *users.User) {
// FileLoading settings
u.FileLoading = d.FileLoading
if u.Username == "anonymous" {
return
}
// Permissions
u.Permissions.Api = d.Account.Permissions.Api
u.Permissions.Admin = d.Account.Permissions.Admin
@@ -147,7 +151,7 @@ func ApplyUserDefaults(u *users.User) {
u.LoginMethod = users.LoginMethod(d.Account.LoginMethod)
}
if len(u.Scopes) == 0 && u.Username != "anonymous" {
if len(u.Scopes) == 0 {
for _, source := range Config.Server.Sources {
if source.Config.DefaultEnabled {
u.Scopes = append(u.Scopes, users.SourceScope{
+11 -2
View File
@@ -20,6 +20,14 @@ type Settings struct {
Frontend Frontend `json:"frontend"`
UserDefaults UserDefaults `json:"userDefaults"`
Integrations Integrations `json:"integrations"`
Http Http `json:"http"`
}
type Http struct {
TrustedHeadersArray []string `json:"trustedHeaders"` // list of headers to trust, useful when behind a reverse proxy.
DisableRateLimit bool `json:"disableRateLimit"` // turns off built-in auth route rate limiting and failed-login lockout (default false).
// internal map of trusted headers
TrustedHeaders map[string]bool `json:"-"`
}
type Environment struct {
@@ -41,8 +49,8 @@ type Environment struct {
type Server struct {
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
NumImageProcessors int `json:"numImageProcessors"` // number of concurrent image processing jobs used to create previews, default is 4.
Socket string `json:"socket"` // socket to listen on - eg. /var/run/filebrowser.sock
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
@@ -203,6 +211,7 @@ type Source struct {
type SourceConfig struct {
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.
ReadOnly bool `json:"readOnly,omitempty"` // read-only source, changes from the UI, webdav, and API will be disabled.
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"` // deprecated: create a rule with indexingIntervalMinutes to set the indexing interval for this source
Conditionals ConditionalFilter `json:"conditionals"` // deprecated: use source.rules instead
+28
View File
@@ -3,11 +3,29 @@ package utils
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"golang.org/x/crypto/bcrypt"
)
func randomBytes(n int) ([]byte, error) {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return nil, err
}
return b, nil
}
// RandomHex returns a hex-encoded string from byteLen bytes of crypto/rand (length 2*byteLen).
func RandomHex(byteLen int) (string, error) {
b, err := randomBytes(byteLen)
if err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
var BcryptCost = bcrypt.DefaultCost
var InvalidPasswordHash = ""
@@ -44,3 +62,13 @@ func GenerateKey() string {
}
return string(b)
}
// CSPNonce returns a base64-encoded random value suitable for Content-Security-Policy nonces
// and matching HTML nonce="" attributes (cryptographically random, URL/header safe characters).
func CSPNonce() (string, error) {
b, err := randomBytes(16)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(b), nil
}
+2 -1
View File
@@ -57,6 +57,7 @@ type FileOptions struct {
ExtractEmbeddedSubtitles bool // whether to extract embedded subtitles from media files
AlbumArt bool // whether to get album art from media files
ShowHidden bool // whether to show hidden files (true = show, false = hide)
ShowPinnedItems bool // whether to show pinned items
HideFileExt string // Hide files based on extensions (eg: '.lrc' or '.srt')
FollowSymlinks bool // whether to follow symlinks
Only string // whether to only get files or folders
@@ -108,4 +109,4 @@ func HideFileByExt(filename, hideExt string) bool {
}
}
return false
}
}
-2
View File
@@ -6,8 +6,6 @@ server:
sources:
- path: "/srv"
auth:
key: "change-me-to-a-random-string"
totpSecret: "change-me-to-another-random-string"
methods:
password:
enabled: true
+3 -3
View File
@@ -43,9 +43,9 @@ type CommonShare struct {
AllowReplacements bool `json:"allowReplacements,omitempty"` // allow replacements of files
SidebarLinks []users.SidebarLink `json:"sidebarLinks"` // customizable sidebar links
HasPassword bool `json:"hasPassword,omitempty"`
ShowHidden bool `json:"showHidden,omitempty"` // show hidden files in share (true = show, false = hide)
HideFileExt string `json:"hideFileExt,omitempty"`// show hidden files based on extensions in shares
DisableLoginOption bool `json:"disableLoginOption"` // disable login option in share (true = hide, false = show)
ShowHidden bool `json:"showHidden,omitempty"` // show hidden files in share (true = show, false = hide)
HideFileExt string `json:"hideFileExt,omitempty"` // show hidden files based on extensions in shares
DisableLoginOption bool `json:"disableLoginOption"` // disable login option in share (true = hide, false = show)
SourceURL string `json:"sourceURL,omitempty"`
CanEditShare bool `json:"canEditShare,omitempty"`
}
+1 -1
View File
@@ -21,7 +21,7 @@ func (s settingsBackend) Save(set *settings.Settings) error {
func (s settingsBackend) GetServer() (*settings.Server, error) {
server := &settings.Server{
Port: 80,
NumImageProcessors: 1,
NumImageProcessors: 4,
}
return server, get(s.db, "server", server)
}
+4 -4
View File
@@ -492,13 +492,13 @@ func TestFilterRestrictedFields(t *testing.T) {
}{
{
name: "all allowed fields",
fields: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode"},
expected: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode"},
fields: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode", "PinnedItems"},
expected: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode", "PinnedItems"},
},
{
name: "mixed allowed and restricted",
fields: []string{"DarkMode", "Permissions", "Scopes", "OtpEnabled"},
expected: []string{"DarkMode", "OtpEnabled"},
fields: []string{"DarkMode", "Permissions", "Scopes", "OtpEnabled", "PinnedItems"},
expected: []string{"DarkMode", "OtpEnabled", "PinnedItems"},
},
{
name: "all restricted fields",
+69
View File
@@ -0,0 +1,69 @@
package users
import "slices"
// Add records a pinned item name under sourcePath and indexDirPath.
func (p PinnedItems) Add(sourcePath, indexDirPath, name string) {
if p == nil {
return
}
if p[sourcePath] == nil {
p[sourcePath] = make(map[string][]string)
}
items := p[sourcePath][indexDirPath]
if slices.Contains(items, name) {
return
}
p[sourcePath][indexDirPath] = append(items, name)
}
// Remove deletes a pinned item name and prunes empty map entries.
func (p PinnedItems) Remove(sourcePath, indexDirPath, name string) {
if p == nil {
return
}
byDir, ok := p[sourcePath]
if !ok {
return
}
items := byDir[indexDirPath]
idx := slices.Index(items, name)
if idx < 0 {
return
}
items = append(items[:idx], items[idx+1:]...)
if len(items) == 0 {
delete(byDir, indexDirPath)
} else {
byDir[indexDirPath] = items
}
if len(byDir) == 0 {
delete(p, sourcePath)
}
}
// PinnedNamesForDirectory returns pinned item names for a source/index directory path.
func (u *User) PinnedNamesForDirectory(sourcePath, indexDirPath string) []string {
if u == nil || len(u.PinnedItems) == 0 {
return nil
}
byDir, ok := u.PinnedItems[sourcePath]
if !ok {
return nil
}
names := byDir[indexDirPath]
if len(names) == 0 {
return nil
}
out := make([]string, len(names))
copy(out, names)
return out
}
// EnsurePinnedItems returns a non-nil map for mutation.
func (u *User) EnsurePinnedItems() PinnedItems {
if u.PinnedItems == nil {
u.PinnedItems = make(PinnedItems)
}
return u.PinnedItems
}
@@ -0,0 +1,98 @@
package users
import "testing"
func TestPinnedItemsAddRemove(t *testing.T) {
p := make(PinnedItems)
const source = "/data/files"
const dir = "/photos/"
const name = "vacation.jpg"
p.Add(source, dir, name)
if len(p[source][dir]) != 1 || p[source][dir][0] != name {
t.Fatalf("add failed: %#v", p)
}
p.Add(source, dir, name)
if len(p[source][dir]) != 1 {
t.Fatalf("duplicate add should be ignored: %#v", p)
}
p.Remove(source, dir, name)
if len(p) != 0 {
t.Fatalf("remove should prune empty maps: %#v", p)
}
}
func TestPinnedNamesForDirectory(t *testing.T) {
u := &User{
NonAdminEditable: NonAdminEditable{
PinnedItems: PinnedItems{
"/data/files": {
"/photos/": {"vacation.jpg", "notes.txt"},
},
},
},
}
names := u.PinnedNamesForDirectory("/data/files", "/photos/")
if len(names) != 2 || names[0] != "vacation.jpg" || names[1] != "notes.txt" {
t.Fatalf("unexpected names: %#v", names)
}
if got := u.PinnedNamesForDirectory("/missing", "/photos/"); got != nil {
t.Fatalf("expected nil for missing source, got %#v", got)
}
}
func TestPinnedItemsRemoveMissing(t *testing.T) {
p := make(PinnedItems)
p.Remove("/data/files", "/photos/", "vacation.jpg")
if len(p) != 0 {
t.Fatalf("remove on empty map should be no-op: %#v", p)
}
}
func TestPinnedItemsMultipleItems(t *testing.T) {
p := make(PinnedItems)
const source = "/data/files"
const dir = "/photos/"
p.Add(source, dir, "a.jpg")
p.Add(source, dir, "b.jpg")
p.Add(source, dir, "c.jpg")
if len(p[source][dir]) != 3 {
t.Fatalf("expected 3 items, got %d", len(p[source][dir]))
}
p.Remove(source, dir, "b.jpg")
items := p[source][dir]
if len(items) != 2 || items[0] != "a.jpg" || items[1] != "c.jpg" {
t.Fatalf("unexpected items after remove: %#v", items)
}
}
func TestPinnedItemsMultipleDirectories(t *testing.T) {
p := make(PinnedItems)
const source = "/data/files"
const photosDir = "/photos/"
const docsDir = "/docs/"
p.Add(source, photosDir, "a.jpg")
p.Add(source, docsDir, "notes.txt")
if len(p[source][photosDir]) != 1 || p[source][photosDir][0] != "a.jpg" {
t.Fatalf("unexpected photos dir: %#v", p[source][photosDir])
}
if len(p[source][docsDir]) != 1 || p[source][docsDir][0] != "notes.txt" {
t.Fatalf("unexpected docs dir: %#v", p[source][docsDir])
}
p.Remove(source, photosDir, "a.jpg")
if _, ok := p[source][photosDir]; ok {
t.Fatalf("photos dir should be pruned: %#v", p)
}
if len(p[source][docsDir]) != 1 {
t.Fatalf("docs dir should remain: %#v", p[source][docsDir])
}
}
+55 -51
View File
@@ -96,24 +96,27 @@ type Preview struct {
Models bool `json:"models"` // show live thumbnails for 3D models files
}
// source filesystem path -> index directory path -> pinned item names (unique within the directory)
type PinnedItems map[string]map[string][]string
// User describes a persisted account. Scopes and source sidebar links store filesystem paths in Name/SourceName;
// JSON responses use display names only (see http prepForFrontend).
type User struct {
NonAdminEditable
DisableSettings bool `json:"disableSettings"`
ID uint `storm:"id,increment" json:"id"`
Username string `storm:"unique" json:"username"`
Scopes []SourceScope `json:"scopes"`
Scope string `json:"scope,omitempty"`
LockPassword bool `json:"lockPassword"`
Permissions Permissions `json:"permissions"`
ApiKeys map[string]AuthToken `json:"apiKeys,omitempty"` // deprecated: use Tokens instead
Tokens map[string]AuthToken `json:"tokens,omitempty"`
TOTPSecret string `json:"totpSecret,omitempty"`
TOTPNonce string `json:"totpNonce,omitempty"`
LoginMethod LoginMethod `json:"loginMethod"`
OtpEnabled bool `json:"otpEnabled"` // true if TOTP is enabled, false otherwise
Version int `json:"version"`
DisableSettings bool `json:"disableSettings"`
ID uint `storm:"id,increment" json:"id"`
Username string `storm:"unique" json:"username"`
Scopes []SourceScope `json:"scopes"`
Scope string `json:"scope,omitempty"`
LockPassword bool `json:"lockPassword"`
Permissions Permissions `json:"permissions"`
ApiKeys map[string]AuthToken `json:"apiKeys,omitempty"` // deprecated: use Tokens instead
Tokens map[string]AuthToken `json:"tokens,omitempty"`
TOTPSecret string `json:"totpSecret,omitempty"`
TOTPNonce string `json:"totpNonce,omitempty"`
LoginMethod LoginMethod `json:"loginMethod"`
OtpEnabled bool `json:"otpEnabled"` // true if TOTP is enabled, false otherwise
Version int `json:"version"`
// legacy for migration purposes... og filebrowser has perm attribute
Perm Permissions `json:"perm,omitzero"` // deprecated: use Permissions instead
}
@@ -125,43 +128,44 @@ type SourceScope struct {
// json tags must match variable name with smaller case first letter
type NonAdminEditable struct {
EditorQuickSave bool `json:"editorQuickSave"` // show quick save button in editor
HideSidebarFileActions bool `json:"hideSidebarFileActions"` // hide the file actions in the sidebar
DisableQuickToggles bool `json:"disableQuickToggles"` // disable the quick toggles in the sidebar
DisableSearchOptions bool `json:"disableSearchOptions"` // disable the search options in the search bar
DeleteWithoutConfirming bool `json:"deleteWithoutConfirming"` // delete files without confirmation
Preview Preview `json:"preview"`
StickySidebar bool `json:"stickySidebar"` // keep sidebar open when navigating
DarkMode bool `json:"darkMode"` // should dark mode be enabled
Password string `json:"password,omitempty"`
Locale string `json:"locale"` // language to use: eg. de, en, or fr
ViewMode string `json:"viewMode"` // view mode to use: eg. normal, list, grid, or compact
SingleClick bool `json:"singleClick"` // open directory on single click, also enables middle click to open in new tab
Sorting Sorting `json:"sorting"`
ShowHidden bool `json:"showHidden"` // show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files
HideFileExt string `json:"hideFileExt"` // space separated list of file extensions to hide in UI and API
DateFormat bool `json:"dateFormat"` // when false, the date is relative, when true, the date is an exact timestamp
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
DisableUpdateNotifications bool `json:"disableUpdateNotifications"` // disable update notifications
FileLoading FileLoading `json:"fileLoading"` // upload and download settings
DisableOfficePreviewExt string `json:"disableOfficePreviewExt"` // deprecated
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // deprecated
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
ShowCopyPath bool `json:"showCopyPath"` // show copy path action in the context menu
ShowToolsInSidebar bool `json:"showToolsInSidebar"` // when false, sidebar hides links with category "tool" (default: true)
DebugOffice bool `json:"debugOffice"` // debug onlyoffice editor
OtpEnabled bool `json:"otpEnabled"` // allow non-admin users to disable their own OTP
SidebarLinks []SidebarLink `json:"sidebarLinks"` // customizable sidebar links
HideFilesInTree bool `json:"hideFilesInTree"` // hide files in the sidebar tree navigation, when true, will show only directories.
DeleteAfterArchive bool `json:"deleteAfterArchive"` // delete source files after successful creation/extraction of archives
PreferEditorForMarkdown bool `json:"preferEditorForMarkdown"` // prefer editor first for markdown files instead of the Markdown Viewer
ShowFirstLogin bool `json:"showFirstLogin"`
PasskeyCredentials []WebAuthnCredential `json:"passkeyCredentials,omitempty"`
EditorQuickSave bool `json:"editorQuickSave"` // show quick save button in editor
HideSidebarFileActions bool `json:"hideSidebarFileActions"` // hide the file actions in the sidebar
DisableQuickToggles bool `json:"disableQuickToggles"` // disable the quick toggles in the sidebar
DisableSearchOptions bool `json:"disableSearchOptions"` // disable the search options in the search bar
DeleteWithoutConfirming bool `json:"deleteWithoutConfirming"` // delete files without confirmation
Preview Preview `json:"preview"`
StickySidebar bool `json:"stickySidebar"` // keep sidebar open when navigating
DarkMode bool `json:"darkMode"` // should dark mode be enabled
Password string `json:"password,omitempty"`
Locale string `json:"locale"` // language to use: eg. de, en, or fr
ViewMode string `json:"viewMode"` // view mode to use: eg. normal, list, grid, or compact
SingleClick bool `json:"singleClick"` // open directory on single click, also enables middle click to open in new tab
Sorting Sorting `json:"sorting"`
ShowHidden bool `json:"showHidden"` // show hidden files in the UI. On windows this includes files starting with a dot and windows hidden files
HideFileExt string `json:"hideFileExt"` // space separated list of file extensions to hide in UI and API
DateFormat bool `json:"dateFormat"` // when false, the date is relative, when true, the date is an exact timestamp
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
DisableUpdateNotifications bool `json:"disableUpdateNotifications"` // disable update notifications
FileLoading FileLoading `json:"fileLoading"` // upload and download settings
DisableOfficePreviewExt string `json:"disableOfficePreviewExt"` // deprecated
DisableOnlyOfficeExt string `json:"disableOnlyOfficeExt"` // deprecated
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
ShowCopyPath bool `json:"showCopyPath"` // show copy path action in the context menu
ShowToolsInSidebar bool `json:"showToolsInSidebar"` // when false, sidebar hides links with category "tool" (default: true)
DebugOffice bool `json:"debugOffice"` // debug onlyoffice editor
OtpEnabled bool `json:"otpEnabled"` // allow non-admin users to disable their own OTP
SidebarLinks []SidebarLink `json:"sidebarLinks"` // customizable sidebar links
HideFilesInTree bool `json:"hideFilesInTree"` // hide files in the sidebar tree navigation, when true, will show only directories.
DeleteAfterArchive bool `json:"deleteAfterArchive"` // delete source files after successful creation/extraction of archives
PreferEditorForMarkdown bool `json:"preferEditorForMarkdown"` // prefer editor first for markdown files instead of the Markdown Viewer
ShowFirstLogin bool `json:"showFirstLogin"`
PasskeyCredentials []WebAuthnCredential `json:"passkeyCredentials,omitempty"`
PinnedItems PinnedItems `json:"pinnedItems,omitempty"`
}
type FileLoading struct {
+15 -15
View File
@@ -10,30 +10,30 @@ require (
github.com/dsoprea/go-exif/v3 v3.0.1
github.com/gen2brain/go-fitz v1.24.15
github.com/go-ldap/ldap/v3 v3.4.13
github.com/go-playground/validator/v10 v10.30.2
github.com/go-webauthn/webauthn v0.17.3
github.com/go-playground/validator/v10 v10.30.3
github.com/go-webauthn/webauthn v0.17.4
github.com/goccy/go-yaml v1.19.2
github.com/golang-jwt/jwt/v4 v4.5.2
github.com/google/go-cmp v0.7.0
github.com/gtsteffaniak/go-cache v1.1.0
github.com/gtsteffaniak/go-logger v1.1.0
github.com/kovidgoyal/imaging v1.8.21
github.com/mattn/go-sqlite3 v1.14.44
github.com/mattn/go-sqlite3 v1.14.45
github.com/pquerna/otp v1.5.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.51.0
golang.org/x/image v0.40.0
golang.org/x/crypto v0.52.0
golang.org/x/image v0.41.0
golang.org/x/mod v0.36.0
golang.org/x/net v0.54.0
golang.org/x/net v0.55.0
golang.org/x/oauth2 v0.36.0
golang.org/x/sys v0.44.0
golang.org/x/sys v0.45.0
golang.org/x/time v0.15.0
golang.org/x/tools v0.45.0
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.50.1
modernc.org/sqlite v1.51.0
)
require (
@@ -60,7 +60,7 @@ require (
github.com/Masterminds/semver/v3 v3.5.0 // indirect
github.com/MirrexOne/unqueryvet v1.5.4 // indirect
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
github.com/air-verse/air v1.65.1 // indirect
github.com/air-verse/air v1.65.3 // indirect
github.com/alecthomas/chroma/v2 v2.24.1 // indirect
github.com/alecthomas/go-check-sumtype v0.3.1 // indirect
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
@@ -106,7 +106,7 @@ require (
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/ebitengine/purego v0.10.0 // indirect
github.com/ebitengine/purego v0.10.1 // indirect
github.com/ettle/strcase v0.2.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
@@ -121,8 +121,8 @@ require (
github.com/go-errors/errors v1.5.1 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-openapi/jsonpointer v0.23.1 // indirect
github.com/go-openapi/jsonreference v0.21.5 // indirect
github.com/go-openapi/spec v0.22.4 // indirect
github.com/go-openapi/jsonreference v0.21.6 // indirect
github.com/go-openapi/spec v0.22.5 // indirect
github.com/go-openapi/swag/conv v0.26.0 // indirect
github.com/go-openapi/swag/jsonname v0.26.0 // indirect
github.com/go-openapi/swag/jsonutils v0.26.0 // indirect
@@ -140,14 +140,14 @@ require (
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.5.0 // indirect
github.com/go-webauthn/x v0.2.5 // indirect
github.com/go-webauthn/x v0.2.6 // indirect
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godoc-lint/godoc-lint v0.11.2 // indirect
github.com/gofrs/flock v0.13.0 // indirect
github.com/gohugoio/hugo v0.149.1 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/golang/geo v0.0.0-20260512202753-e3c51de6d1b6 // indirect
github.com/golang/geo v0.0.0-20260605061815-58f45aa500f1 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golangci/asciicheck v0.5.0 // indirect
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect
@@ -294,7 +294,7 @@ require (
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
honnef.co/go/tools v0.7.0 // indirect
modernc.org/libc v1.72.3 // indirect
modernc.org/libc v1.72.5 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
mvdan.cc/gofumpt v0.9.2 // indirect
+38 -38
View File
@@ -85,8 +85,8 @@ 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.65.1 h1:G4hy4YemKrIcGAvYMor+86PhxdtBEq0n9ebJ4RoYy8w=
github.com/air-verse/air v1.65.1/go.mod h1:OaJZSfZqf7wyjS2oP/CcEVyIt0JmZuPh5x1gdtklmmY=
github.com/air-verse/air v1.65.3 h1:7NUAqofZuSf5vZbVoZpdTr/4LuKkOCj1JTiMrOdUs7A=
github.com/air-verse/air v1.65.3/go.mod h1:OaJZSfZqf7wyjS2oP/CcEVyIt0JmZuPh5x1gdtklmmY=
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.24.1 h1:m5ffpfZbIb++k8AqFEKy9uVgY12xIQtBsQlc6DfZJQM=
@@ -256,8 +256,8 @@ github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 h1:DilThiXje
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349/go.mod h1:4GC5sXji84i/p+irqghpPFZBF8tRN/Q7+700G0/DLe8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
@@ -318,10 +318,10 @@ 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.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4=
github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY=
github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE=
github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw=
github.com/go-openapi/spec v0.22.4 h1:4pxGjipMKu0FzFiu/DPwN3CTBRlVM2yLf/YTWorYfDQ=
github.com/go-openapi/spec v0.22.4/go.mod h1:WQ6Ai0VPWMZgMT4XySjlRIE6GP1bGQOtEThn3gcWLtQ=
github.com/go-openapi/jsonreference v0.21.6 h1:NZ5nGfnaM1n4I43Xjm1e5/M2GjOwQwndQz22uhxwD+Y=
github.com/go-openapi/jsonreference v0.21.6/go.mod h1:xzbgtQ3ZbWxvET3AxdzCJlJt6vkovbf+IfSPJjD0tUY=
github.com/go-openapi/spec v0.22.5 h1:KhO7RBlKQfonUWX2WzQCoLIXVA6AcNqDGZ3a1Dutdlo=
github.com/go-openapi/spec v0.22.5/go.mod h1:vxpOtMya5TXtENXKE5bKqv5NjocVhyhxHrlZfvKnZ74=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag/conv v0.26.0 h1:5yGGsPYI1ZCva93U0AoKi/iZrNhaJEjr324YVsiD89I=
github.com/go-openapi/swag/conv v0.26.0/go.mod h1:tpAmIL7X58VPnHHiSO4uE3jBeRamGsFsfdDeDtb5ECE=
@@ -339,18 +339,18 @@ github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFu
github.com/go-openapi/swag/typeutils v0.26.0/go.mod h1:oovDuIUvTrEHVMqWilQzKzV4YlSKgyZmFh7AlfABNVE=
github.com/go-openapi/swag/yamlutils v0.26.0 h1:H7O8l/8NJJQ/oiReEN+oMpnGMyt8G0hl460nRZxhLMQ=
github.com/go-openapi/swag/yamlutils v0.26.0/go.mod h1:1evKEGAtP37Pkwcc7EWMF0hedX0/x3Rkvei2wtG/TbU=
github.com/go-openapi/testify/enable/yaml/v2 v2.4.2 h1:5zRca5jw7lzVREKCZVNBpysDNBjj74rBh0N2BGQbSR0=
github.com/go-openapi/testify/enable/yaml/v2 v2.4.2/go.mod h1:XVevPw5hUXuV+5AkI1u1PeAm27EQVrhXTTCPAF85LmE=
github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4=
github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=
github.com/go-openapi/testify/enable/yaml/v2 v2.5.1 h1:q9NtHwK4qHF7yZziBPvZyv7zWAIk8ok88Gh2mR6Jpc8=
github.com/go-openapi/testify/enable/yaml/v2 v2.5.1/go.mod h1:JW0MXIotCYps/XsgJnG3a8Q7rE5xAiBwoOD5OfaIQBk=
github.com/go-openapi/testify/v2 v2.5.1 h1:TMdhCaw8fUNraVSf3Omoob1dO/AzBfhtFAPW0an6sBo=
github.com/go-openapi/testify/v2 v2.5.1/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=
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=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.2 h1:JiFIMtSSHb2/XBUbWM4i/MpeQm9ZK2xqPNk8vgvu5JQ=
github.com/go-playground/validator/v10 v10.30.2/go.mod h1:mAf2pIOVXjTEBrwUMGKkCWKKPs9NheYGabeB04txQSc=
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
@@ -377,10 +377,10 @@ github.com/go-toolsmith/typep v1.1.0 h1:fIRYDyF+JywLfqzyhdiHzRop/GQDxxNhLGQ6gFUN
github.com/go-toolsmith/typep v1.1.0/go.mod h1:fVIw+7zjdsMxDA3ITWnH1yOiw1rnTQKCsF/sk2H/qig=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-webauthn/webauthn v0.17.3 h1:XHZ0TXV7k8vChcE4TFgPitOPJ5cb7h1dpAeFDS0cjCo=
github.com/go-webauthn/webauthn v0.17.3/go.mod h1:PlkMgmuL9McCT7dvgBj/Sz/fgs3V6ZID6/KnFkEcPvQ=
github.com/go-webauthn/x v0.2.5 h1:wEVTfU04XFyPTXGQbKOQwMKhcDWfDAkdsDDBsDaG9yY=
github.com/go-webauthn/x v0.2.5/go.mod h1:Qna/yJz9rV6lRzwl5BfYbmTJpVGxcBIds3gJtw2tlGg=
github.com/go-webauthn/webauthn v0.17.4 h1:KFTSz3R2RYDiUn/0cDi3XTJgFenSG74eKTTHlqWhlxk=
github.com/go-webauthn/webauthn v0.17.4/go.mod h1:pZk63EE/BdztlmyS4Yc+9H5g4a8blNlbtGmdHQHbZX8=
github.com/go-webauthn/x v0.2.6 h1:TEyDuQAIiEgYpx60nKiBJIX/5nSUC8LxNbH+uf5U9uk=
github.com/go-webauthn/x v0.2.6/go.mod h1:45bA7YEqyQhRcQJ/TiBb46Ww8yqHBGvgEhQ3WWF0aDo=
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=
@@ -417,8 +417,8 @@ github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArs
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-20260512202753-e3c51de6d1b6 h1:maAhA7cpighmEi96eTgDdmlhwnHYEgwhR6t+T7k3Png=
github.com/golang/geo v0.0.0-20260512202753-e3c51de6d1b6/go.mod h1:Mymr9kRGDc64JPr03TSZmuIBODZ3KyswLzm1xL0HFA8=
github.com/golang/geo v0.0.0-20260605061815-58f45aa500f1 h1:vkAT/N8DPfmQ3ZltANiX95HhM0nv/tqoq5Innoimcwo=
github.com/golang/geo v0.0.0-20260605061815-58f45aa500f1/go.mod h1:Mymr9kRGDc64JPr03TSZmuIBODZ3KyswLzm1xL0HFA8=
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=
@@ -664,8 +664,8 @@ github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8=
github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
github.com/mattn/go-sqlite3 v1.14.45 h1:6KA/spDguL3KV8rnybG7ezSaE4SeMR3KC9VbUoAQaIk=
github.com/mattn/go-sqlite3 v1.14.45/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
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.15.0 h1:vJ0HzSBzfNyPbHKolgiFjHxLek9KUijhqh42yGoqZ8Q=
@@ -952,8 +952,8 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
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=
@@ -972,8 +972,8 @@ golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 h1:qWFG1Dj7TBjOjO
golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358/go.mod h1:4Mzdyp/6jzw9auFDJ3OMF5qksa7UvPnzKqTVGcb04ms=
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.40.0 h1:Tw4GyDXMo+daZN1znreBRC3VayR1aLFUyUEOLUdW1a8=
golang.org/x/image v0.40.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
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=
@@ -1036,8 +1036,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
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.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
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=
@@ -1107,8 +1107,8 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
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.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -1294,18 +1294,18 @@ honnef.co/go/tools v0.7.0 h1:w6WUp1VbkqPEgLz4rkBzH/CSU6HkoqNLp6GstyTx3lU=
honnef.co/go/tools v0.7.0/go.mod h1:pm29oPxeP3P82ISxZDgIYeOaf9ta6Pi0EWvCFoLG2vc=
modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=
modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=
modernc.org/ccgo/v4 v4.34.0/go.mod h1:AS5WYMyBakQ+fhsHhtP8mWB82KTGPkNNJDGfGQCe0/A=
modernc.org/ccgo/v4 v4.34.2 h1:mxsy2FdrB6+qG3NfXefz1AmWv0ehOSDO4jxgxd7h9yo=
modernc.org/ccgo/v4 v4.34.2/go.mod h1:1L7us56+kAKu04p25EATpmBBvhbcqqZ85ibqWVwVgog=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc=
modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
modernc.org/libc v1.72.5 h1:m2OGx9Ser1VvTS4Z9ZJlWs+CBMxutLaTiAWkNz+NB9U=
modernc.org/libc v1.72.5/go.mod h1:np0N7KDJ7eUtMZmOqVZNldrZyG+DHLl2B5pg8Hbar3U=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
@@ -1314,8 +1314,8 @@ modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=
modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
modernc.org/sqlite v1.51.0 h1:aH/MMSoayAIhozZ7uJbVTT9QO/VhzBf0J9tymmmuC/U=
modernc.org/sqlite v1.51.0/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+1 -7
View File
@@ -4,8 +4,6 @@ import (
"archive/tar"
"archive/zip"
"compress/gzip"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -46,11 +44,7 @@ var (
)
func randomArchiveToken() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
return utils.RandomHex(16)
}
func stopArchiveSpoolIdleTimer(token string) {
+4 -2
View File
@@ -221,7 +221,9 @@ func setupJwtUser(r *http.Request, data *requestContext, username string, claims
// @Param X-Password header string true "URL-encoded password"
// @Param X-Secret header string false "TOTP code (if 2FA is enabled)"
// @Success 200 {string} string "JWT token for authentication"
// @Failure 401 {object} map[string]string "Unauthorized - authentication failed"
// @Failure 403 {object} map[string]string "Forbidden - authentication failed"
// @Failure 429 {object} map[string]string "Too many requests - rate limited or temporarily locked out after failed attempts"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/auth/login [post]
func loginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
@@ -320,7 +322,7 @@ func logoutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/auth/signup [post]
func signupHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
if !settings.Config.Auth.Methods.PasswordAuth.Signup {
if !config.Auth.Methods.PasswordAuth.Signup {
return http.StatusMethodNotAllowed, fmt.Errorf("signup is disabled")
}
@@ -340,7 +342,7 @@ func signupHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
},
LoginMethod: users.LoginMethodPassword,
}
err := storage.CreateUser(user, settings.ConvertPermissionsToUsers(settings.Config.UserDefaults.Account.Permissions))
err := storage.CreateUser(user, settings.ConvertPermissionsToUsers(config.UserDefaults.Account.Permissions))
if err != nil {
logger.Debug(err.Error())
// Return the actual error message instead of a generic one
+269
View File
@@ -0,0 +1,269 @@
package http
import (
"fmt"
"math"
"net/http"
"strconv"
"time"
"github.com/gtsteffaniak/go-cache/cache"
"golang.org/x/time/rate"
)
// Built-in auth rate limits (per process). Toggle all off with http.disableRateLimit.
//
// Credential tier (login, OTP verify): dual token buckets (per IP + per username) plus
// failed-login lockout (per IP+username). Tune burst ≤ maxAttempts so rapid floods hit
// HTTP 429 from the bucket before lockout; lockout covers paced attacks that stay under RPM.
const (
authCredentialRPM = 10 // sustained ~1 attempt / 6s per IP and per username
authCredentialBurst = 8 // rapid burst; 9th immediate attempt gets 429
authModerateRPM = 30 // signup, logout, OTP generate
authModerateBurst = 10
authOIDCRPM = 60 // OIDC redirects (browser-driven, higher ceiling)
authOIDCBurst = 20
authAuthenticatedRPM = 180 // session/token management for logged-in users
authAuthenticatedBurst = 60
authFailedLoginMaxAttempts = 8 // lockout after N consecutive 401s (same IP + username)
authFailedLoginLockoutMins = 15
// Evict idle per-key token buckets so unique IPs/usernames cannot grow without bound.
authLimiterEntryTTL = 24 * time.Hour
)
// In-memory failed-attempt counters and lockout flags (per server process).
var (
authFailCounts = cache.NewCache[int](time.Minute, 10*time.Minute)
authLockouts = cache.NewCache[bool](time.Minute, 10*time.Minute)
)
// Per-route-class token buckets (keys: IP or username). Expired entries are dropped by go-cache.
var (
authRateLimitCredentialByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL)
authRateLimitCredentialByUsername = cache.NewCache[*rate.Limiter](authLimiterEntryTTL)
authRateLimitModerateByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL)
authRateLimitOIDCByIP = cache.NewCache[*rate.Limiter](authLimiterEntryTTL)
authRateLimitAuthenticatedByUser = cache.NewCache[*rate.Limiter](authLimiterEntryTTL)
)
const authRateKeySep = "\x1e"
// AuthRateLimitKind selects which /api/auth rate limit tier applies (see withRateLimit and withRateLimitChain).
type AuthRateLimitKind int
const (
// AuthRateLimitCredential: strict per-IP and per-username limits; no failed-login lockout.
AuthRateLimitCredential AuthRateLimitKind = iota
// AuthRateLimitCredentialLockout: same limits as Credential, plus lockout after repeated 401s.
AuthRateLimitCredentialLockout
AuthRateLimitModerate
AuthRateLimitOIDC
// AuthRateLimitAuthenticated: per logged-in username (compose: withUser(withRateLimitChain(AuthRateLimitAuthenticated, h))).
AuthRateLimitAuthenticated
)
// withRateLimitChain applies a rate limit tier then fn for nesting inside withUser / withOrWithoutUser / withoutUser.
func withRateLimitChain(kind AuthRateLimitKind, fn handleFunc) handleFunc {
switch kind {
case AuthRateLimitCredential:
return withAuthRateLimitCredential(false, fn)
case AuthRateLimitCredentialLockout:
return withAuthRateLimitCredential(true, fn)
case AuthRateLimitModerate:
return withAuthRateLimitModerate(fn)
case AuthRateLimitOIDC:
return withAuthRateLimitOIDC(fn)
case AuthRateLimitAuthenticated:
return withAuthRateLimitAuthenticated(fn)
default:
return fn
}
}
// withRateLimit registers a rate-limited route (same shape as withTimeout: option first, handler second).
func withRateLimit(kind AuthRateLimitKind, fn handleFunc) http.HandlerFunc {
return wrapHandler(withRateLimitChain(kind, fn))
}
func authRateLimitActive() bool {
if config.Http.DisableRateLimit {
return false
}
if config.Auth.Methods.NoAuth {
return false
}
return true
}
func tokenBucketLimiter(c *cache.KeyCache[*rate.Limiter], key string, requestsPerMinute, burst int) *rate.Limiter {
if requestsPerMinute < 1 {
requestsPerMinute = 1
}
if burst < 1 {
burst = 1
}
if lim, ok := c.Get(key); ok && lim != nil {
c.SetWithExp(key, lim, authLimiterEntryTTL)
return lim
}
lim := rate.NewLimiter(rate.Limit(float64(requestsPerMinute))/60.0, burst)
c.SetWithExp(key, lim, authLimiterEntryTTL)
return lim
}
func retryAfterSeconds(lim *rate.Limiter) int {
res := lim.Reserve()
delay := res.Delay()
res.Cancel()
secs := int(math.Ceil(delay.Seconds()))
if secs < 1 {
secs = 1
}
return secs
}
func allowCredential(r *http.Request, loginUsername string) (retryAfter int, ok bool) {
ip := getRemoteIP(r)
limIP := tokenBucketLimiter(authRateLimitCredentialByIP, ip, authCredentialRPM, authCredentialBurst)
if !limIP.Allow() {
return retryAfterSeconds(limIP), false
}
if loginUsername != "" {
limUser := tokenBucketLimiter(authRateLimitCredentialByUsername, loginUsername, authCredentialRPM, authCredentialBurst)
if !limUser.Allow() {
return retryAfterSeconds(limUser), false
}
}
return 0, true
}
func allowModerate(r *http.Request) (retryAfter int, ok bool) {
ip := getRemoteIP(r)
lim := tokenBucketLimiter(authRateLimitModerateByIP, ip, authModerateRPM, authModerateBurst)
if !lim.Allow() {
return retryAfterSeconds(lim), false
}
return 0, true
}
func allowOIDC(r *http.Request) (retryAfter int, ok bool) {
ip := getRemoteIP(r)
lim := tokenBucketLimiter(authRateLimitOIDCByIP, ip, authOIDCRPM, authOIDCBurst)
if !lim.Allow() {
return retryAfterSeconds(lim), false
}
return 0, true
}
func allowAuthenticated(username string) (retryAfter int, ok bool) {
lim := tokenBucketLimiter(authRateLimitAuthenticatedByUser, username, authAuthenticatedRPM, authAuthenticatedBurst)
if !lim.Allow() {
return retryAfterSeconds(lim), false
}
return 0, true
}
func authFailKey(ip, username string) string {
return "fail" + authRateKeySep + ip + authRateKeySep + username
}
func authLockKey(ip, username string) string {
return "lock" + authRateKeySep + ip + authRateKeySep + username
}
func authLockoutRetryAfterSecs() int {
return authFailedLoginLockoutMins * 60
}
func isAuthLockout(ip, username string) bool {
locked, ok := authLockouts.Get(authLockKey(ip, username))
return ok && locked
}
func clearAuthLockout(ip, username string) {
authLockouts.Delete(authLockKey(ip, username))
authFailCounts.Delete(authFailKey(ip, username))
}
func recordAuthFailure(ip, username string) {
if username == "" {
return
}
window := time.Duration(authFailedLoginLockoutMins) * time.Minute
fk := authFailKey(ip, username)
n := 0
if v, ok := authFailCounts.Get(fk); ok {
n = v
}
n++
authFailCounts.SetWithExp(fk, n, window)
if n >= authFailedLoginMaxAttempts {
authLockouts.SetWithExp(authLockKey(ip, username), true, window)
}
}
// withRateLimitInternal applies token-bucket allow checks: when inactive, calls fn; when denied, 429 + Retry-After.
func withRateLimitInternal(fn handleFunc, allow func(*http.Request, *requestContext) (retryAfter int, ok bool)) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
if !authRateLimitActive() {
return fn(w, r, d)
}
if after, ok := allow(r, d); !ok {
w.Header().Set("Retry-After", strconv.Itoa(after))
return http.StatusTooManyRequests, fmt.Errorf("too many requests")
}
return fn(w, r, d)
}
}
// withAuthRateLimitCredential enforces the credential tier (and optional per-username limits).
// When trackFailures is true, 401 responses increment failed-attempt state for lockout; success clears it.
func withAuthRateLimitCredential(trackFailures bool, fn handleFunc) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
if !authRateLimitActive() {
return fn(w, r, d)
}
username := r.URL.Query().Get("username")
if isAuthLockout(getRemoteIP(r), username) {
w.Header().Set("Retry-After", strconv.Itoa(authLockoutRetryAfterSecs()))
return http.StatusTooManyRequests, fmt.Errorf("too many failed authentication attempts")
}
if after, ok := allowCredential(r, username); !ok {
w.Header().Set("Retry-After", strconv.Itoa(after))
return http.StatusTooManyRequests, fmt.Errorf("too many requests")
}
status, err := fn(w, r, d)
if !trackFailures {
return status, err
}
ip := getRemoteIP(r)
if status == http.StatusUnauthorized && username != "" {
recordAuthFailure(ip, username)
}
if err == nil && (status == 0 || status == http.StatusOK) {
clearAuthLockout(ip, username)
}
return status, err
}
}
func withAuthRateLimitModerate(fn handleFunc) handleFunc {
return withRateLimitInternal(fn, func(r *http.Request, _ *requestContext) (int, bool) {
return allowModerate(r)
})
}
func withAuthRateLimitOIDC(fn handleFunc) handleFunc {
return withRateLimitInternal(fn, func(r *http.Request, _ *requestContext) (int, bool) {
return allowOIDC(r)
})
}
func withAuthRateLimitAuthenticated(fn handleFunc) handleFunc {
return withRateLimitInternal(fn, func(_ *http.Request, d *requestContext) (int, bool) {
if d.user == nil || d.user.Username == "" || d.user.Username == "anonymous" {
return 0, true
}
return allowAuthenticated(d.user.Username)
})
}
+53 -35
View File
@@ -10,6 +10,7 @@ import (
"io/fs"
"net"
"net/http"
"os"
"time"
_ "net/http/pprof"
@@ -80,35 +81,40 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
publicRoutes := http.NewServeMux()
publicApi := http.NewServeMux()
// health routes
api.HandleFunc("GET /health", healthHandler)
publicApi.HandleFunc("GET /health", healthHandler)
// ========================================
// User Routes - /api/users/ (with public routes)
// ========================================
api.HandleFunc("GET /users", withUser(userGetHandler))
api.HandleFunc("POST /users", withSelfOrAdmin(usersPostHandler))
api.HandleFunc("PUT /users", withUser(userPutHandler))
api.HandleFunc("PATCH /users/pinnedItems", withUser(userPatchPinnedItemsHandler))
api.HandleFunc("DELETE /users", withSelfOrAdmin(userDeleteHandler))
publicApi.HandleFunc("GET /users", withUser(userGetHandler))
// ========================================
// Auth Routes - /api/auth/
// ========================================
api.HandleFunc("POST /auth/login", loginHelper(loginHandler))
api.HandleFunc("POST /auth/logout", withOrWithoutUser(logoutHandler))
api.HandleFunc("POST /auth/signup", withoutUser(signupHandler))
api.HandleFunc("POST /auth/otp/generate", withOrWithoutUser(generateOTPHandler))
api.HandleFunc("POST /auth/otp/verify", withOrWithoutUser(verifyOTPHandler))
api.HandleFunc("POST /auth/renew", withUser(renewHandler))
api.HandleFunc("POST /auth/token", withUser(createApiTokenHandler))
api.HandleFunc("DELETE /auth/token", withUser(deleteApiTokenHandler))
api.HandleFunc("GET /auth/token/list", withUser(listApiTokensHandler))
api.HandleFunc("GET /auth/token", withUser(getApiTokenHandler))
api.HandleFunc("GET /auth/oidc/callback", wrapHandler(oidcCallbackHandler))
api.HandleFunc("GET /auth/oidc/login", wrapHandler(oidcLoginHandler))
api.HandleFunc("POST /auth/webauthn/begin-login", withoutUser(beginPasskeyLoginHandler))
api.HandleFunc("POST /auth/webauthn/finish-login", withoutUser(finishPasskeyLoginHandler))
api.HandleFunc("POST /auth/webauthn/begin-register", withUser(beginPasskeyRegistrationHandler))
api.HandleFunc("POST /auth/webauthn/finish-register", withUser(finishPasskeyRegistrationHandler))
api.HandleFunc("DELETE /auth/webauthn/{id}", withUser(deletePasskeyCredentialHandler))
api.HandleFunc("POST /auth/login", withRateLimit(AuthRateLimitCredentialLockout, loginHelper(loginHandler)))
api.HandleFunc("POST /auth/logout", withOrWithoutUser(withRateLimitChain(AuthRateLimitModerate, logoutHandler)))
api.HandleFunc("POST /auth/signup", withoutUser(withRateLimitChain(AuthRateLimitModerate, signupHandler)))
api.HandleFunc("POST /auth/otp/generate", withOrWithoutUser(withRateLimitChain(AuthRateLimitModerate, generateOTPHandler)))
api.HandleFunc("POST /auth/otp/verify", withOrWithoutUser(withRateLimitChain(AuthRateLimitCredentialLockout, verifyOTPHandler)))
api.HandleFunc("POST /auth/renew", withUser(withRateLimitChain(AuthRateLimitAuthenticated, renewHandler)))
api.HandleFunc("POST /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, createApiTokenHandler)))
api.HandleFunc("DELETE /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, deleteApiTokenHandler)))
api.HandleFunc("GET /auth/token/list", withUser(withRateLimitChain(AuthRateLimitAuthenticated, listApiTokensHandler)))
api.HandleFunc("GET /auth/token", withUser(withRateLimitChain(AuthRateLimitAuthenticated, getApiTokenHandler)))
api.HandleFunc("GET /auth/oidc/callback", withRateLimit(AuthRateLimitOIDC, oidcCallbackHandler))
api.HandleFunc("GET /auth/oidc/login", withRateLimit(AuthRateLimitOIDC, oidcLoginHandler))
api.HandleFunc("POST /auth/webauthn/begin-login", withoutUser(withRateLimitChain(AuthRateLimitCredential, beginPasskeyLoginHandler)))
api.HandleFunc("POST /auth/webauthn/finish-login", withoutUser(withRateLimitChain(AuthRateLimitCredential, finishPasskeyLoginHandler)))
api.HandleFunc("POST /auth/webauthn/begin-register", withUser(withRateLimitChain(AuthRateLimitAuthenticated, beginPasskeyRegistrationHandler)))
api.HandleFunc("POST /auth/webauthn/finish-register", withUser(withRateLimitChain(AuthRateLimitAuthenticated, finishPasskeyRegistrationHandler)))
api.HandleFunc("DELETE /auth/webauthn/{id}", withUser(withRateLimitChain(AuthRateLimitAuthenticated, deletePasskeyCredentialHandler)))
// ========================================
// Resources Routes - /api/resources/ (with public routes)
@@ -123,7 +129,7 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
api.HandleFunc("POST /resources/archive", withUser(archiveCreateHandler))
api.HandleFunc("POST /resources/unarchive", withUser(unarchiveHandler))
api.HandleFunc("GET /resources/download", withUser(downloadHandler))
api.HandleFunc("GET /resources/preview", withTimeout(60*time.Second, withUserHelper(previewHandler)))
api.HandleFunc("GET /resources/preview", withTimeout(30*time.Second, withUserHelper(previewHandler)))
api.HandleFunc("POST /resources/pause", withUser(resourcePauseHandler))
publicApi.HandleFunc("GET /resources", withHashFile(publicGetResourceHandler))
publicApi.HandleFunc("GET /resources/items", withHashFile(publicItemsGetHandler))
@@ -133,7 +139,7 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
publicApi.HandleFunc("DELETE /resources/bulk", withHashFile(publicBulkDeleteHandler))
publicApi.HandleFunc("PATCH /resources", withHashFile(publicPatchHandler))
publicApi.HandleFunc("GET /resources/download", withHashFile(publicDownloadHandler))
publicApi.HandleFunc("GET /resources/preview", withHashFile(publicPreviewHandler))
publicApi.HandleFunc("GET /resources/preview", withTimeout(30*time.Second, withHashFileHelper(publicPreviewHandler)))
publicApi.HandleFunc("POST /resources/pause", withHashFile(publicPauseHandler))
// Legacy routes (backwards compatibility)
api.HandleFunc("GET /raw", withUser(downloadHandler))
@@ -199,7 +205,6 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
// ========================================
// Misc Routes
// ========================================
api.HandleFunc("GET /health", healthHandler)
api.HandleFunc("GET /events", withUser(sseHandler))
if settings.Env.IsDevMode {
api.HandleFunc("GET /inspectIndex", inspectIndex)
@@ -250,16 +255,28 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
})
}
var scheme string
port := ""
srv := &http.Server{
Addr: fmt.Sprintf("%v:%v", config.Server.ListenAddress, config.Server.Port),
Handler: muxWithMiddleware(router),
}
listenAddress := config.Server.ListenAddress
go func() {
// Determine whether to use HTTPS (TLS) or HTTP
if config.Server.TLSCert != "" && config.Server.TLSKey != "" {
var listener net.Listener
if config.Server.Socket != "" {
if err := os.Remove(config.Server.Socket); err != nil && !os.IsNotExist(err) {
logger.Fatalf("Could not remove existing socket: %v", err)
}
var err error
listener, err = net.Listen("unix", config.Server.Socket)
if err != nil {
logger.Fatalf("Could not listen on unix socket: %v", err)
}
logger.Infof("Running at : unix://%s%s", config.Server.Socket, config.Server.BaseURL)
} else if config.Server.TLSCert != "" && config.Server.TLSKey != "" {
var scheme string
port := ""
// Determine whether to use HTTPS (TLS) or HTTP
// Load the TLS certificate and key
cer, err := tls.LoadX509KeyPair(config.Server.TLSCert, config.Server.TLSKey)
if err != nil {
@@ -283,8 +300,6 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
logger.Infof("Running at : %s", fullURL)
// Attempt to get listener from socket activation with TLS configuration
var listener net.Listener
socketActivationListeners, err := activation.TLSListeners(tlsConfig)
if err == nil && len(socketActivationListeners) > 0 {
listener = socketActivationListeners[0]
@@ -303,10 +318,9 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
}
}
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
logger.Fatalf("Server error: %v", err)
}
} else {
var scheme string
port := ""
// Set HTTP scheme and the default port for HTTP
scheme = "http"
if config.Server.Port != 80 {
@@ -317,8 +331,6 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
fullURL := fmt.Sprintf("%s://%s%s%s", scheme, listenAddress, port, config.Server.BaseURL)
logger.Infof("Running at : %s", fullURL)
var listener net.Listener
// Attempt to get the listener from socket activation
socketActivationListeners, err := activation.Listeners()
if err == nil && len(socketActivationListeners) > 0 {
@@ -344,10 +356,10 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
}
}
// Start HTTP server
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
logger.Fatalf("Server error: %v", err)
}
}
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
logger.Fatalf("Server error: %v", err)
}
}()
@@ -386,6 +398,12 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
logger.Info("HTTP server shut down gracefully.")
}
if config.Server.Socket != "" {
if err := os.Remove(config.Server.Socket); err != nil && !os.IsNotExist(err) {
logger.Debugf("Could not remove unix socket: %v", err)
}
}
// Signal that shutdown is complete
close(shutdownComplete)
}
+2 -2
View File
@@ -26,7 +26,7 @@ func AuthenticateLDAPUser(username, password string) (*users.User, error) {
}
// Use the configured UserIdentifier if available, otherwise use the login username
ldapCfg := settings.Config.Auth.Methods.LdapAuth
ldapCfg := config.Auth.Methods.LdapAuth
mappedUsername := username
if ldapCfg.UserIdentifier != "" {
if val, ok := userAttributes[ldapCfg.UserIdentifier]; ok && val != "" {
@@ -42,7 +42,7 @@ func AuthenticateLDAPUser(username, password string) (*users.User, error) {
}
func authenticateLDAP(username, password string) ([]string, map[string]string, error) {
c := settings.Config.Auth.Methods.LdapAuth
c := config.Auth.Methods.LdapAuth
logger.Debugf("ldap: connecting to %s", c.Server)
var opts []ldap.DialOpt
+74 -57
View File
@@ -5,15 +5,13 @@ import (
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/ffmpeg"
"github.com/gtsteffaniak/filebrowser/backend/indexing"
)
// subtitlesHandler handles subtitle requests for both external files and embedded streams
@@ -38,58 +36,49 @@ func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
name := r.URL.Query().Get("name")
embedded := r.URL.Query().Get("embedded") == "true"
if path == "" || source == "" {
return http.StatusBadRequest, fmt.Errorf("path and source are required")
}
if name == "" {
return http.StatusBadRequest, fmt.Errorf("name parameter is required")
}
userscope, err := d.user.GetScopeForSourceName(source)
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
FollowSymlinks: true,
Path: path,
Source: source,
Expand: true,
Content: false,
Metadata: true,
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles,
ShowHidden: d.user.ShowHidden,
HideFileExt: d.user.HideFileExt,
SkipExtendedAttrs: false,
}, store.Access, d.user, store.Share)
if err != nil {
return http.StatusForbidden, err
return errToStatus(err), err
}
if !strings.HasPrefix(fileInfo.Type, "video") {
return http.StatusNotFound, fmt.Errorf("file is not a video")
}
idx := indexing.GetIndex(source)
if idx == nil {
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
track := findSubtitleTrack(fileInfo.Subtitles, name, embedded)
if track == nil {
return http.StatusNotFound, fmt.Errorf("subtitle track '%s' not found", name)
}
realPath, _, err := idx.GetRealPath(userscope, path)
if err != nil {
return http.StatusNotFound, fmt.Errorf("file not found: %v", err)
}
parentDir := filepath.Dir(realPath)
var content string
if !embedded {
content, err = utils.GetSubtitleSidecarContent(filepath.Join(parentDir, name))
subtitlePath := filepath.Join(filepath.Dir(fileInfo.RealPath), filepath.Base(track.Name))
content, err = utils.GetSubtitleSidecarContent(subtitlePath)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to get subtitle sidecar content: %v", err)
}
} else {
// For embedded subtitles, we need to find the stream index by name
// Get file modification time for caching
fileInfo, err := os.Stat(realPath)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to stat file: %v", err)
}
// Detect embedded subtitles
embeddedSubs := ffmpeg.DetectEmbeddedSubtitles(realPath, fileInfo.ModTime())
// Find the subtitle track by name
var streamIndex *int
for _, sub := range embeddedSubs {
if sub.Name == name {
streamIndex = sub.Index
break
}
}
if streamIndex == nil {
if track.Index == nil {
return http.StatusNotFound, fmt.Errorf("embedded subtitle track '%s' not found", name)
}
content, err = ffmpeg.ExtractSubtitleContent(realPath, *streamIndex)
content, err = ffmpeg.ExtractSubtitleContent(fileInfo.RealPath, *track.Index)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to extract embedded subtitle: %v", err)
}
@@ -103,6 +92,16 @@ func subtitlesHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
return http.StatusOK, nil
}
func findSubtitleTrack(subtitles []utils.SubtitleTrack, name string, embedded bool) *utils.SubtitleTrack {
for i := range subtitles {
sub := &subtitles[i]
if sub.Name == name && sub.Embedded == embedded {
return sub
}
}
return nil
}
// metadataHandler returns the same directory resource shape as GET /api/resources with metadata enabled,
// for client-side patching after a fast listing load.
// @Summary Directory with media metadata
@@ -129,7 +128,7 @@ func metadataHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
Content: false,
Metadata: true,
AlbumArt: albumArt,
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles,
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles,
ShowHidden: d.user.ShowHidden,
HideFileExt: d.user.HideFileExt,
SkipExtendedAttrs: false,
@@ -167,7 +166,7 @@ func publicMetadataHandler(w http.ResponseWriter, r *http.Request, d *requestCon
Content: false,
Metadata: true,
AlbumArt: albumArt,
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles && d.share.ExtractEmbeddedSubtitles,
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles && d.share.ExtractEmbeddedSubtitles,
ShowHidden: d.share.ShowHidden,
HideFileExt: d.user.HideFileExt,
FollowSymlinks: false,
@@ -197,19 +196,26 @@ func lyricsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
if path == "" || source == "" {
return http.StatusBadRequest, fmt.Errorf("path and source are required")
}
userscope, err := d.user.GetScopeForSourceName(source)
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
FollowSymlinks: true,
Path: path,
Source: source,
Expand: true,
Content: false,
Metadata: false,
ShowHidden: d.user.ShowHidden,
HideFileExt: d.user.HideFileExt,
SkipExtendedAttrs: false,
}, store.Access, d.user, store.Share)
if err != nil {
return http.StatusForbidden, err
return errToStatus(err), err
}
idx := indexing.GetIndex(source)
if idx == nil {
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
if !strings.HasPrefix(fileInfo.Type, "audio") {
return http.StatusNotFound, fmt.Errorf("file is not an audio file")
}
realPath, _, err := idx.GetRealPath(userscope, path)
if err != nil {
return http.StatusNotFound, err
}
lyrics, err := files.ExtractLyrics(realPath)
lyrics, err := files.ExtractLyrics(fileInfo.RealPath)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to extract lyrics: %v", err)
}
@@ -231,15 +237,26 @@ func publicLyricsHandler(w http.ResponseWriter, r *http.Request, d *requestConte
if !ok {
return http.StatusNotFound, fmt.Errorf("source not found")
}
idx := indexing.GetIndex(sourceCfg.Name)
if idx == nil {
return http.StatusNotFound, fmt.Errorf("source not found")
}
realPath, _, err := idx.GetRealPath(d.IndexPath)
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Path: d.IndexPath,
Source: sourceCfg.Name,
Expand: true,
Content: false,
Metadata: false,
ShowHidden: d.share.ShowHidden,
HideFileExt: d.user.HideFileExt,
FollowSymlinks: false,
SkipExtendedAttrs: false,
}, store.Access, d.shareUser, store.Share)
if err != nil {
return http.StatusNotFound, errors.New("could not find real path for file")
return errToStatus(err), err
}
lyrics, err := files.ExtractLyrics(realPath)
if !strings.HasPrefix(fileInfo.Type, "audio") {
return http.StatusNotFound, fmt.Errorf("file is not an audio file")
}
lyrics, err := files.ExtractLyrics(fileInfo.RealPath)
if err != nil {
return http.StatusInternalServerError, errors.New("failed to extract lyrics")
}
+15 -52
View File
@@ -8,6 +8,7 @@ import (
"net"
"net/http"
"net/url"
"path/filepath"
"runtime"
"slices"
"strings"
@@ -31,7 +32,6 @@ type requestContext struct {
fileInfo iteminfo.ExtendedFileInfo
token string
share *share.Link
shareValid bool
ctx context.Context
MaxBandwidth int
Data interface{}
@@ -58,6 +58,7 @@ func withHashFileHelper(fn handleFunc) handleFunc {
if err != nil && inputPath != "" {
return http.StatusBadRequest, err
}
path = filepath.ToSlash(path)
// Get the file link by hash
link, err := store.Share.GetByHash(hash)
@@ -132,9 +133,9 @@ func withHashFileHelper(fn handleFunc) handleFunc {
Content: getContent,
Metadata: getMetadata,
AlbumArt: strings.Contains(r.URL.Path, "/preview"),
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles && link.ExtractEmbeddedSubtitles,
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles && link.ExtractEmbeddedSubtitles,
ShowHidden: link.ShowHidden,
HideFileExt: link.HideFileExt,
HideFileExt: link.HideFileExt,
FollowSymlinks: true,
}, store.Access, data.shareUser, store.Share)
if err != nil {
@@ -227,57 +228,19 @@ func extractUserFromExpiredToken(r *http.Request, data *requestContext) *users.U
// If authentication fails, the request continues without a user.
func withOrWithoutUserHelper(fn handleFunc) handleFunc {
return func(w http.ResponseWriter, r *http.Request, data *requestContext) (int, error) {
var link *share.Link
var isShareRequest bool
var shareHash string
hash := r.URL.Query().Get("hash")
if hash != "" {
// Get the file link by hash
isShareRequest = true
shareHash = hash
link, _ = store.Share.GetByHash(hash)
} else {
prefix := config.Server.BaseURL + "public/share/"
reconstructed := config.Server.BaseURL + "public" + r.URL.Path
if strings.HasPrefix(reconstructed, prefix) {
remaining := strings.TrimPrefix(reconstructed, prefix)
if remaining != "" {
if idx := strings.IndexByte(remaining, '/'); idx >= 0 {
remaining = remaining[:idx]
}
if remaining != "" {
isShareRequest = true
shareHash = remaining
var err error
link, err = store.Share.GetByHash(remaining)
if err != nil {
logger.Debugf("error getting share by hash: %v", err)
}
}
}
}
}
// If this is a share request, always create a share context (even if invalid)
if isShareRequest {
if link != nil {
data.share = link
data.shareValid = true
} else {
// Create an empty share with just the hash for invalid shares
data.share = &share.Link{Hash: shareHash}
data.shareValid = false
_, err := store.Share.GetByHash(hash)
if err != nil {
return http.StatusNotFound, fmt.Errorf("share hash not found")
}
}
// Try to authenticate user first
status, err := withUserHelper(nil)(w, r, data)
if err == nil && status < 400 {
if data.share != nil && data.shareValid {
if data.user != nil {
data.user.CustomTheme = data.share.ShareTheme
}
if data.share != nil && data.user != nil {
data.user.CustomTheme = data.share.ShareTheme
}
return fn(w, r, data)
}
@@ -288,7 +251,7 @@ func withOrWithoutUserHelper(fn handleFunc) handleFunc {
userFromExpiredToken := extractUserFromExpiredToken(r, data)
if userFromExpiredToken != nil {
data.user = userFromExpiredToken
if data.share != nil && data.shareValid {
if data.share != nil {
data.user.CustomTheme = data.share.ShareTheme
}
setUserInResponseWriter(w, data.user)
@@ -300,7 +263,7 @@ func withOrWithoutUserHelper(fn handleFunc) handleFunc {
settings.ApplyUserDefaults(data.user)
// Clear any user data that might have been partially set
data.token = ""
if data.share != nil && data.shareValid {
if data.share != nil {
data.user.CustomTheme = data.share.ShareTheme
}
// Call the handler function without user context
@@ -664,8 +627,8 @@ func withoutUser(fn handleFunc) http.HandlerFunc {
return wrapHandler(withoutUserHelper(fn))
}
func loginHelper(fn handleFunc) http.HandlerFunc {
return wrapHandler(LoginHelper(false, fn))
func loginHelper(fn handleFunc) handleFunc {
return LoginHelper(false, fn)
}
func withSelfOrAdmin(fn handleFunc) http.HandlerFunc {
@@ -760,7 +723,7 @@ func setUserInResponseWriter(w http.ResponseWriter, user *users.User) {
func getRemoteIP(r *http.Request) string {
// 1. Check X-Forwarded-For
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
if config.Http.TrustedHeaders["x-forwarded-for"] && xff != "" {
// The first IP is the original client
ips := strings.Split(xff, ",")
return strings.TrimSpace(ips[0])
@@ -768,7 +731,7 @@ func getRemoteIP(r *http.Request) string {
// 2. Check X-Real-IP
xri := r.Header.Get("X-Real-IP")
if xri != "" {
if config.Http.TrustedHeaders["x-real-ip"] && xri != "" {
return xri
}
+2 -2
View File
@@ -159,7 +159,7 @@ func parseOIDCGroupsValue(groupsVal interface{}) []string {
// @Success 302 {string} string "Redirect to OIDC provider"
// @Router /api/auth/oidc/login [get]
func oidcLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
oidcCfg := settings.Config.Auth.Methods.OidcAuth
oidcCfg := config.Auth.Methods.OidcAuth
if !oidcCfg.Enabled {
return http.StatusForbidden, fmt.Errorf("oidc authentication is not enabled")
}
@@ -197,7 +197,7 @@ func oidcLoginHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
// @Router /api/auth/oidc/callback [get]
func oidcCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
ctx := r.Context()
oidcCfg := settings.Config.Auth.Methods.OidcAuth
oidcCfg := config.Auth.Methods.OidcAuth
if oidcCfg.Provider == nil || oidcCfg.Verifier == nil {
// Ensure Provider and Verifier are initialized on application startup
// This check is good, keep it.
+121 -16
View File
@@ -11,6 +11,7 @@ import (
"path/filepath"
"strconv"
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
@@ -28,8 +29,16 @@ const (
onlyOfficeStatusDocumentClosedWithNoChanges = 4
onlyOfficeStatusForceSaveWhileDocumentStillOpen = 6
onlyOfficeStatusForceSaveError = 7
onlyOfficeDownloadTimeout = 10 * time.Second
)
// onlyOfficeDownloadClient fetches saved documents from the OnlyOffice document server.
// A bounded timeout avoids hanging goroutines when the server is unreachable.
var onlyOfficeDownloadClient = &http.Client{
Timeout: onlyOfficeDownloadTimeout,
}
type OnlyOfficeCallback struct {
Actions []OnlyOfficeAction `json:"actions,omitempty"`
ChangesURL string `json:"changesurl,omitempty"`
@@ -81,7 +90,7 @@ type OnlyOfficeJWTPayload struct {
// @Router /api/office/config [get]
// @Security ApiKeyAuth
func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
if settings.Config.Integrations.OnlyOffice.Url == "" {
if config.Integrations.OnlyOffice.Url == "" {
return http.StatusInternalServerError, errors.New("only-office integration must be configured in settings")
}
@@ -107,13 +116,13 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
var sourceInfo *settings.Source
var ok bool
if hash != "" {
sourceInfo, ok = settings.Config.Server.SourceMap[d.share.Source]
sourceInfo, ok = config.Server.SourceMap[d.share.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]
sourceInfo, ok = config.Server.NameToSource[source]
if !ok {
logger.Error("OnlyOffice: source not found")
return http.StatusInternalServerError, fmt.Errorf("source not found")
@@ -210,7 +219,7 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
"title": d.fileInfo.Name,
"url": downloadURL,
"permissions": map[string]interface{}{
"edit": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
"edit": utils.Ternary(config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
"download": true,
"print": true,
},
@@ -227,14 +236,14 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
"uiTheme": themeMode,
},
"lang": d.user.Locale,
"mode": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
"mode": utils.Ternary(config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
},
}
// Sign configuration with JWT if secret is configured
if settings.Config.Integrations.OnlyOffice.Secret != "" {
if config.Integrations.OnlyOffice.Secret != "" {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(clientConfig))
signature, err := token.SignedString([]byte(settings.Config.Integrations.OnlyOffice.Secret))
signature, err := token.SignedString([]byte(config.Integrations.OnlyOffice.Secret))
if err != nil {
logger.Errorf("OnlyOffice: failed to sign JWT: %v", err)
return http.StatusInternalServerError, fmt.Errorf("failed to sign configuration")
@@ -249,10 +258,10 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
func buildOnlyOfficeDownloadURL(r *http.Request, source, path, hash, token string) string {
// Determine base URL (internal URL takes priority for OnlyOffice server communication)
var baseURL string
if settings.Config.Server.InternalUrl != "" {
if config.Server.InternalUrl != "" {
// InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
internalURL := strings.TrimSuffix(config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(config.Server.BaseURL, "/")
if baseURLPath != "" {
baseURL = internalURL + "/" + baseURLPath
} else {
@@ -276,7 +285,7 @@ func buildOnlyOfficeDownloadURL(r *http.Request, source, path, hash, token strin
host = r.Host
scheme = getScheme(r)
}
baseURL = fmt.Sprintf("%s://%s%s", scheme, host, settings.Config.Server.BaseURL)
baseURL = fmt.Sprintf("%s://%s%s", scheme, host, config.Server.BaseURL)
}
escapedPath := url.QueryEscape(path)
@@ -293,10 +302,10 @@ func buildOnlyOfficeDownloadURL(r *http.Request, source, path, hash, token strin
func buildOnlyOfficeCallbackURL(r *http.Request, source, path, hash, token string) string {
// Determine base URL (internal URL takes priority for OnlyOffice server communication)
var baseURL string
if settings.Config.Server.InternalUrl != "" {
if config.Server.InternalUrl != "" {
// InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
internalURL := strings.TrimSuffix(config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(config.Server.BaseURL, "/")
if baseURLPath != "" {
baseURL = internalURL + "/" + baseURLPath
} else {
@@ -320,7 +329,7 @@ func buildOnlyOfficeCallbackURL(r *http.Request, source, path, hash, token strin
host = r.Host
scheme = getScheme(r)
}
baseURL = fmt.Sprintf("%s://%s%s", scheme, host, settings.Config.Server.BaseURL)
baseURL = fmt.Sprintf("%s://%s%s", scheme, host, config.Server.BaseURL)
}
var callbackURL string
@@ -347,6 +356,97 @@ func buildOnlyOfficeCallbackURL(r *http.Request, source, path, hash, token strin
return callbackURL
}
// resolveOnlyOfficeDownloadURL validates a callback document URL against
// integrations.office.url and optionally rewrites the origin to integrations.office.internalUrl.
// Returns an empty string when the URL is missing, malformed, or not hosted on the configured
// OnlyOffice server (SSRF protection).
func resolveOnlyOfficeDownloadURL(rawURL string) string {
if rawURL == "" {
return ""
}
publicBase := config.Integrations.OnlyOffice.Url
if publicBase == "" {
logger.Warningf("OnlyOffice callback: integrations.office.url is not configured")
return ""
}
parsedURL, err := url.Parse(rawURL)
if err != nil {
logger.Warningf("OnlyOffice callback: could not parse document URL (%q): %v", rawURL, err)
return ""
}
publicURL, err := url.Parse(publicBase)
if err != nil {
logger.Warningf("OnlyOffice callback: could not parse integrations.office.url (%q): %v", publicBase, err)
return ""
}
if !onlyOfficeURLHostsMatch(parsedURL, publicURL) {
logger.Warningf("OnlyOffice callback: rejecting document URL with untrusted host %q (expected %q)",
parsedURL.Host, publicURL.Host)
return ""
}
internalBase := config.Integrations.OnlyOffice.InternalUrl
if internalBase == "" {
return rawURL
}
internalURL, err := url.Parse(internalBase)
if err != nil {
logger.Warningf("OnlyOffice callback: could not parse integrations.office.internalUrl (%q): %v", internalBase, err)
return ""
}
if !isAllowedOnlyOfficeScheme(internalURL.Scheme) || internalURL.Host == "" {
logger.Warningf("OnlyOffice callback: invalid integrations.office.internalUrl (%q)", internalBase)
return ""
}
rewritten := *parsedURL
rewritten.Scheme = internalURL.Scheme
rewritten.Host = internalURL.Host
result := rewritten.String()
if result != rawURL {
logger.Debugf("OnlyOffice callback: rewrote URL from %s to %s", rawURL, result)
}
return result
}
func isAllowedOnlyOfficeScheme(scheme string) bool {
return scheme == "http" || scheme == "https"
}
func onlyOfficeEffectivePort(u *url.URL) string {
if port := u.Port(); port != "" {
return port
}
switch u.Scheme {
case "https":
return "443"
case "http":
return "80"
default:
return ""
}
}
// onlyOfficeURLHostsMatch reports whether callback and configured URLs refer to the same
// OnlyOffice host, comparing hostname and effective port (so office.local matches office.local:80).
func onlyOfficeURLHostsMatch(callback, configured *url.URL) bool {
if !isAllowedOnlyOfficeScheme(callback.Scheme) || !isAllowedOnlyOfficeScheme(configured.Scheme) {
return false
}
if callback.Hostname() == "" || configured.Hostname() == "" {
return false
}
if !strings.EqualFold(callback.Hostname(), configured.Hostname()) {
return false
}
return onlyOfficeEffectivePort(callback) == onlyOfficeEffectivePort(configured)
}
// 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
@@ -492,7 +592,12 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques
}
// Download the updated document from OnlyOffice server
doc, err := http.Get(data.URL)
downloadURL := resolveOnlyOfficeDownloadURL(data.URL)
if downloadURL == "" {
logger.Errorf("OnlyOffice callback: missing or untrusted document URL in callback payload")
return returnOnlyOfficeError(w, r, 500, "missing or untrusted document URL in callback payload")
}
doc, err := onlyOfficeDownloadClient.Get(downloadURL)
if err != nil {
logger.Errorf("OnlyOffice callback: failed to download updated document: %v", err)
return returnOnlyOfficeError(w, r, 500, "failed to download updated document")
+102
View File
@@ -0,0 +1,102 @@
package http
import (
"net/url"
"testing"
)
func TestResolveOnlyOfficeDownloadURL(t *testing.T) {
orig := config.Integrations.OnlyOffice
t.Cleanup(func() {
config.Integrations.OnlyOffice = orig
})
config.Integrations.OnlyOffice.Url = "http://192.168.88.100:8282"
config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice"
cachePath := "/cache/files/data/doc_1/output.ods/output.ods?md5=abc&expires=1"
publicURL := "http://192.168.88.100:8282" + cachePath
internalURL := "http://onlyoffice" + cachePath
tests := []struct {
name string
input string
want string
}{
{
name: "rewrites public cache URL to internal host",
input: publicURL,
want: internalURL,
},
{
name: "empty URL",
input: "",
want: "",
},
{
name: "untrusted host rejected",
input: "http://other-host:8282" + cachePath,
want: "",
},
{
name: "non-http scheme rejected",
input: "ftp://192.168.88.100:8282" + cachePath,
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := resolveOnlyOfficeDownloadURL(tt.input)
if got != tt.want {
t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, tt.want)
}
})
}
t.Run("pass through public URL when internalUrl unset", func(t *testing.T) {
config.Integrations.OnlyOffice.InternalUrl = ""
got := resolveOnlyOfficeDownloadURL(publicURL)
if got != publicURL {
t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, publicURL)
}
})
t.Run("hostname match with default http port", func(t *testing.T) {
config.Integrations.OnlyOffice.Url = "http://office.local"
config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice"
input := "http://office.local:80" + cachePath
want := "http://onlyoffice" + cachePath
got := resolveOnlyOfficeDownloadURL(input)
if got != want {
t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want %q", got, want)
}
})
t.Run("reject when public url not configured", func(t *testing.T) {
config.Integrations.OnlyOffice.Url = ""
config.Integrations.OnlyOffice.InternalUrl = "http://onlyoffice"
got := resolveOnlyOfficeDownloadURL(publicURL)
if got != "" {
t.Errorf("resolveOnlyOfficeDownloadURL() = %q, want empty", got)
}
})
}
func TestOnlyOfficeURLHostsMatch(t *testing.T) {
mustParse := func(raw string) *url.URL {
t.Helper()
u, err := url.Parse(raw)
if err != nil {
t.Fatalf("url.Parse(%q): %v", raw, err)
}
return u
}
if !onlyOfficeURLHostsMatch(mustParse("http://office.local:80/x"), mustParse("http://office.local/x")) {
t.Fatal("expected office.local:80 to match office.local with default port")
}
if onlyOfficeURLHostsMatch(mustParse("http://evil.example/x"), mustParse("http://office.local/x")) {
t.Fatal("expected different hostnames not to match")
}
}
+127
View File
@@ -0,0 +1,127 @@
package http
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/database/users"
"github.com/gtsteffaniak/filebrowser/backend/indexing"
)
// pinnedItemPatchRequest is the JSON body for PATCH /api/users/pinnedItems.
type pinnedItemPatchRequest struct {
Source string `json:"source" validate:"required"`
Path string `json:"path" validate:"required"` // scope-relative parent directory
Name string `json:"name" validate:"required"` // item basename within path
}
// scopeRelativeDirToIndexPath maps a scope-relative directory to source and index paths.
func scopeRelativeDirToIndexPath(sourceName, userScope, directoryPath string) (sourcePath, indexDirPath string, err error) {
userScope = strings.TrimRight(userScope, "/")
source, ok := users.ResolveSourceKey(sourceName)
if !ok {
return "", "", fmt.Errorf("source not found: %s", sourceName)
}
idx := indexing.GetIndex(source.Name)
if idx == nil {
return "", "", fmt.Errorf("index not found for source %s", source.Name)
}
cleanDir, err := utils.SanitizeUserPath(directoryPath)
if err != nil {
return "", "", fmt.Errorf("invalid path: %w", err)
}
fullDirPath := utils.JoinPathAsUnix(userScope, cleanDir)
return source.Path, idx.MakeIndexPath(fullDirPath, true), nil
}
// pinnedItemAction returns the patch action query param, defaulting to "add".
func pinnedItemAction(r *http.Request) string {
action := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("action")))
if action == "" {
return "add"
}
return action
}
// userPatchPinnedItemsHandler adds or removes a single pinned item for the authenticated user.
// @Summary Add or remove a pinned item
// @Description Patches one pinned item at a time. Defaults to add; pass ?action=remove to unpin.
// @Tags Users
// @Accept json
// @Produce json
// @Param action query string false "add (default) or remove"
// @Param body body pinnedItemPatchRequest true "Pinned item"
// @Success 204 "No Content"
// @Failure 400 {object} map[string]string "Bad Request"
// @Failure 403 {object} map[string]string "Forbidden"
// @Failure 500 {object} map[string]string "Internal Server Error"
// @Router /api/users/pinnedItems [patch]
func userPatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
var body pinnedItemPatchRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
return http.StatusBadRequest, fmt.Errorf("failed to decode body: %w", err)
}
defer r.Body.Close()
action := pinnedItemAction(r)
if action != "add" && action != "remove" {
return http.StatusBadRequest, fmt.Errorf("action must be add or remove")
}
if body.Source == "" || body.Path == "" || body.Name == "" {
return http.StatusBadRequest, fmt.Errorf("source, path, and name are required")
}
cleanPath, err := utils.SanitizeUserPath(body.Path)
if err != nil {
return http.StatusBadRequest, err
}
body.Path = cleanPath
cleanName, err := utils.SanitizeUserPath(body.Name)
if err != nil {
return http.StatusBadRequest, err
}
body.Name = cleanName
source, ok := users.ResolveSourceKey(body.Source)
if !ok {
return http.StatusBadRequest, fmt.Errorf("source not found: %s", body.Source)
}
if !d.user.HasSourceByPath(source.Path) {
return http.StatusForbidden, fmt.Errorf("access denied to source %s", body.Source)
}
userScope, err := d.user.GetScopeForSourcePath(source.Path)
if err != nil {
return http.StatusForbidden, err
}
sourcePath, indexDirPath, err := scopeRelativeDirToIndexPath(body.Source, userScope, body.Path)
if err != nil {
return http.StatusBadRequest, err
}
u, err := store.Users.Get(d.user.ID)
if err != nil {
return http.StatusInternalServerError, err
}
pinned := u.EnsurePinnedItems()
switch action {
case "add":
pinned.Add(sourcePath, indexDirPath, body.Name)
case "remove":
pinned.Remove(sourcePath, indexDirPath, body.Name)
}
if err := store.Users.Update(u, d.user.Permissions.Admin, "PinnedItems"); err != nil {
return http.StatusInternalServerError, err
}
return http.StatusNoContent, nil
}
+34 -14
View File
@@ -14,7 +14,6 @@ import (
"time"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
"github.com/gtsteffaniak/filebrowser/backend/preview"
@@ -85,6 +84,22 @@ func previewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
return status, nil
}
func shouldServeOriginalPreview(ext string, resizable bool, realPath, previewSize string, fileSize int64) bool {
if !resizable {
return false
}
// HEIC/TIFF still need conversion for reliable web display.
switch ext {
case ".heic", ".heif", ".tiff", ".tif":
return false
}
const maxSizeForOriginal = 256 * 1024 // 256KB
if config.Server.DisableResize || fileSize < maxSizeForOriginal {
return true
}
return preview.ShouldServeOriginalImage(realPath, previewSize)
}
func rawFileHandler(w http.ResponseWriter, r *http.Request, file iteminfo.ExtendedFileInfo) (int, error) {
fd, err := os.Open(file.RealPath)
if err != nil {
@@ -121,7 +136,7 @@ func getDirectoryPreview(r *http.Request, d *requestContext, frameIndex int) (*i
path := utils.JoinPathAsUnix(d.fileInfo.Path, name)
user := d.user
if d.share != nil {
sourceInfo, ok := settings.Config.Server.SourceMap[d.share.Source]
sourceInfo, ok := config.Server.SourceMap[d.share.Source]
if !ok {
return nil, fmt.Errorf("source not found for share")
}
@@ -156,6 +171,11 @@ func getDirectoryPreview(r *http.Request, d *requestContext, frameIndex int) (*i
}
func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
ctx := r.Context()
if d.ctx != nil {
ctx = d.ctx
}
previewSize := r.URL.Query().Get("size")
if !(previewSize == "large" || previewSize == "original" || previewSize == "xlarge") {
previewSize = "small"
@@ -192,6 +212,12 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext
}
fileInfo, err := getDirectoryPreview(r, d, dirFrameIndex)
if err != nil {
if isClientCancellation(ctx, err) {
return http.StatusOK, nil
}
if ctx.Err() == context.DeadlineExceeded || errors.Is(err, context.DeadlineExceeded) {
return http.StatusRequestTimeout, fmt.Errorf("preview generation timed out")
}
logger.Errorf("error getting directory preview: %v", err)
return http.StatusInternalServerError, err
}
@@ -204,9 +230,9 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext
ext := strings.ToLower(filepath.Ext(d.fileInfo.Name))
resizable := iteminfo.ResizableImageTypes[ext]
// For small, displayable images (jpg, png, etc.) serve the original to avoid processing.
const maxSizeForOriginal = 128 * 1024 // 128KB
if resizable && (config.Server.DisableResize || d.fileInfo.Size < maxSizeForOriginal) && isImage {
// For small displayable images (jpg, png, etc.) serve the original to avoid processing.
// Also serve the original when dimensions already fit the requested preview size.
if isImage && shouldServeOriginalPreview(ext, resizable, d.fileInfo.RealPath, previewSize, d.fileInfo.Size) {
return rawFileHandler(w, r, d.fileInfo)
}
@@ -214,7 +240,7 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext
if d.fileInfo.OnlyOfficeId != "" {
pathUrl := fmt.Sprintf("/api/resources/download?file=%s&source=%s", url.QueryEscape(d.fileInfo.Path), url.QueryEscape(d.fileInfo.Source))
pathUrl = pathUrl + "&auth=" + d.token
if settings.Config.Server.InternalUrl != "" {
if config.Server.InternalUrl != "" {
officeUrl = config.Server.InternalUrl + pathUrl
} else {
scheme := "http"
@@ -224,12 +250,6 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext
officeUrl = scheme + "://" + r.Host + pathUrl
}
}
// Use the context from the request context (which includes timeout)
ctx := r.Context()
if d.ctx != nil {
ctx = d.ctx
}
previewImg, err := preview.GetPreviewForFile(ctx, d.fileInfo, previewSize, officeUrl, seekPercentage)
if err != nil {
// Check if it was a context cancellation (client navigated away)
@@ -240,8 +260,8 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext
// Check if it was a context timeout (server-side timeout)
if ctx.Err() == context.DeadlineExceeded || errors.Is(err, context.DeadlineExceeded) {
logger.Errorf("Preview timeout for file '%s' after 60 seconds", d.fileInfo.Name)
return http.StatusRequestTimeout, fmt.Errorf("preview generation timed out after 60 seconds")
logger.Errorf("Preview timeout for file '%s' after 15 seconds", d.fileInfo.Name)
return http.StatusRequestTimeout, fmt.Errorf("preview generation timed out after 15 seconds")
}
// Log detailed error information for actual server errors
+12 -4
View File
@@ -8,7 +8,6 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
"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/preview"
"github.com/gtsteffaniak/go-logger/logger"
@@ -80,7 +79,7 @@ func publicDownloadHandler(w http.ResponseWriter, r *http.Request, d *requestCon
}
// Get the actual source name from the share's source mapping
sourceInfo, ok := settings.Config.Server.SourceMap[d.share.Source]
sourceInfo, ok := config.Server.SourceMap[d.share.Source]
if !ok {
return http.StatusInternalServerError, fmt.Errorf("source not found for share")
}
@@ -368,10 +367,19 @@ func publicPatchHandler(w http.ResponseWriter, r *http.Request, d *requestContex
// Note: Share paths are absolute, so we don't strip user scope here
// resourcePatchHandler will skip adding scope for shares
for i := range req.Items {
var sanitizedPath string
sanitizedPath, err = utils.SanitizeUserPath(req.Items[i].FromPath)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid from path: %w", err)
}
req.Items[i].FromSource = sourceName
req.Items[i].FromPath = utils.JoinPathAsUnix(d.share.Path, req.Items[i].FromPath)
req.Items[i].FromPath = utils.JoinPathAsUnix(d.share.Path, sanitizedPath)
sanitizedPath, err = utils.SanitizeUserPath(req.Items[i].ToPath)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid to path: %w", err)
}
req.Items[i].ToSource = sourceName
req.Items[i].ToPath = utils.JoinPathAsUnix(d.share.Path, req.Items[i].ToPath)
req.Items[i].ToPath = utils.JoinPathAsUnix(d.share.Path, sanitizedPath)
}
d.Data = req
+87 -13
View File
@@ -18,7 +18,6 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
"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/indexing"
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
@@ -99,11 +98,12 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
Expand: true,
Content: getContent,
Metadata: getMetadata,
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles,
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles,
ShowHidden: d.user.ShowHidden,
HideFileExt: d.user.HideFileExt,
SkipExtendedAttrs: skipExtendedAttrs,
ShowSharedAttr: true,
ShowPinnedItems: true,
}, store.Access, d.user, store.Share)
if err != nil {
return errToStatus(err), err
@@ -146,18 +146,27 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon
if !d.user.Permissions.Delete {
return http.StatusForbidden, fmt.Errorf("user is not allowed to delete")
}
path := r.URL.Query().Get("path")
source := r.URL.Query().Get("source")
if path == "/" {
return http.StatusForbidden, fmt.Errorf("cannot delete your user's root directory")
}
idx := indexing.GetIndex(source)
if idx == nil {
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
}
if idx.Config.ReadOnly {
return http.StatusForbidden, fmt.Errorf("source is read-only")
}
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Path: path,
Source: source,
Expand: false,
ShowHidden: d.user.ShowHidden,
Path: path,
Source: source,
Expand: false,
ShowHidden: d.user.ShowHidden,
HideFileExt: d.user.HideFileExt,
}, store.Access, d.user, store.Share)
if err != nil {
@@ -286,8 +295,33 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques
if d.share != nil {
sourceName := d.share.GetSourceName()
if sourceName == "" {
return http.StatusNotFound, fmt.Errorf("source not available")
response.Failed = append(response.Failed, BulkDeleteItem{
Source: item.Source,
Path: sanitizedPath,
Message: "source name is empty",
})
continue
}
idx := indexing.GetIndex(sourceName)
if idx == nil {
response.Failed = append(response.Failed, BulkDeleteItem{
Source: item.Source,
Path: sanitizedPath,
Message: "source not found",
})
continue
}
if idx.Config.ReadOnly {
response.Failed = append(response.Failed, BulkDeleteItem{
Source: item.Source,
Path: sanitizedPath,
Message: "source is read-only",
})
continue
}
// get user scope path from share
userScope, err := d.shareUser.GetScopeForSourceName(sourceName)
if err != nil {
@@ -356,6 +390,15 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques
continue
}
if idx.Config.ReadOnly {
response.Failed = append(response.Failed, BulkDeleteItem{
Source: item.Source,
Path: sanitizedPath,
Message: "source is read-only",
})
continue
}
// Get file info
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
FollowSymlinks: true,
@@ -493,6 +536,17 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
if d.share == nil && !d.user.Permissions.Create {
return http.StatusForbidden, fmt.Errorf("user is not allowed to create or modify")
}
idx := indexing.GetIndex(source)
if idx == nil {
logger.Debugf("source %s not found", source)
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
}
if idx.Config.ReadOnly {
return http.StatusForbidden, fmt.Errorf("source is read-only")
}
filePermUser := d.user
if d.share != nil {
filePermUser = d.shareUser
@@ -504,11 +558,6 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
Expand: false,
FollowSymlinks: true,
}
idx := indexing.GetIndex(source)
if idx == nil {
logger.Debugf("source %s not found", source)
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
}
userscope, err := filePermUser.GetScopeForSourceName(source)
if err != nil {
@@ -722,6 +771,9 @@ func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContex
if idx == nil {
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
}
if idx.Config.ReadOnly {
return http.StatusForbidden, fmt.Errorf("source is read-only")
}
if store.Access != nil && !store.Access.Permitted(idx.Path, fullIndexPath, d.user.Username) {
logger.Debugf("user %s denied access to path %s", d.user.Username, fullIndexPath)
return http.StatusForbidden, fmt.Errorf("access denied to path %s", path)
@@ -855,6 +907,28 @@ func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestCont
continue
}
if srcIdx.Config.ReadOnly && req.Action == "move" {
item.Message = "From source is read-only and cannot be moved"
if d.share != nil {
response.Failed = append(response.Failed, MoveCopyItem{
Message: item.Message,
})
continue
}
}
if dstIdx.Config.ReadOnly {
item.Message = "destination source is read-only"
if d.share != nil {
response.Failed = append(response.Failed, MoveCopyItem{
Message: item.Message,
})
continue
}
response.Failed = append(response.Failed, item)
continue
}
// Build full index paths for access control
fullSrcIndexPath := utils.JoinPathAsUnix(userscopeSrc, item.FromPath)
fullDstIndexPath := utils.JoinPathAsUnix(userscopeDst, item.ToPath)
+7 -8
View File
@@ -8,7 +8,6 @@ import (
"strconv"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/indexing"
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
@@ -43,12 +42,12 @@ type scopedSourcePath struct {
//
// Per-source search scope (preferred for multi-source):
//
// Repeated query parameter "scope" with the value "sourceName:relativePath",
// split on the first colon. The path is user-relative (same as the legacy single-scope
// path). Encode the whole value with the normal query string rules (e.g. %3A for ':' if needed).
// Examples:
// ?scope=mydisk:/&scope=backup:/Photos
// Duplicate source names: the last repeated scope for that source wins.
// Repeated query parameter "scope" with the value "sourceName:relativePath",
// split on the first colon. The path is user-relative (same as the legacy single-scope
// path). Encode the whole value with the normal query string rules (e.g. %3A for ':' if needed).
// Examples:
// ?scope=mydisk:/&scope=backup:/Photos
// Duplicate source names: the last repeated scope for that source wins.
//
// Legacy (still supported):
//
@@ -257,7 +256,7 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro
parsed := iteminfo.BuildSearchOptionsFromQuery(query, normalizedTerms, matchAllTerms)
minLen := settings.Config.Server.MinSearchLength
minLen := config.Server.MinSearchLength
if !largest {
if len(normalizedTerms) > 0 {
for _, t := range normalizedTerms {
+7 -1
View File
@@ -206,6 +206,12 @@ func sharePatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext
return http.StatusBadRequest, fmt.Errorf("hash and path are required")
}
sanitizedPath, err := utils.SanitizeUserPath(body.Path)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path: %w", err)
}
body.Path = sanitizedPath
// only allow users to update their own shares
thisShare, err := store.Share.GetByHash(body.Hash)
if err != nil {
@@ -215,7 +221,7 @@ func sharePatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext
return http.StatusForbidden, fmt.Errorf("you are not allowed to update this share")
}
// Update the share path
err = store.Share.UpdateSharePath(body.Hash, body.Path)
err = store.Share.UpdateSharePath(body.Hash, sanitizedPath)
if err != nil {
return http.StatusInternalServerError, err
}
+7 -7
View File
@@ -95,8 +95,8 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
favicon := staticURL + "/favicon" + faviconExt
shareHash := ""
data := make(map[string]interface{})
disableNavButtons := settings.Config.Frontend.DisableNavButtons
if d.share != nil && d.shareValid {
disableNavButtons := config.Frontend.DisableNavButtons
if d.share != nil {
if d.share.Favicon != "" {
if strings.HasPrefix(d.share.Favicon, "http") {
favicon = d.share.Favicon
@@ -185,28 +185,28 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
"pwaIcon512": pwaIcon512,
"manifestURL": staticURL + "/site.webmanifest",
}
// 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.UI.DarkMode,
"darkMode": config.UserDefaults.UI.DarkMode,
"baseURL": config.Server.BaseURL,
"version": versionString,
"commitSHA": commitSHAString,
"signup": settings.Config.Auth.Methods.PasswordAuth.Signup,
"signup": config.Auth.Methods.PasswordAuth.Signup,
"noAuth": config.Auth.Methods.NoAuth,
"enableThumbs": !config.Server.DisablePreviews,
"externalLinks": externalLinks,
"externalUrl": strings.TrimSuffix(config.Server.ExternalUrl, "/"),
"onlyOfficeUrl": settings.Config.Integrations.OnlyOffice.Url,
"onlyOfficeUrl": config.Integrations.OnlyOffice.Url,
"oidcAvailable": config.Auth.Methods.OidcAuth.Enabled,
"jwtAvailable": config.Auth.Methods.JwtAuth.Enabled,
"proxyAvailable": config.Auth.Methods.ProxyAuth.Enabled,
"passwordAvailable": config.Auth.Methods.PasswordAuth.Enabled,
"ldapAvailable": config.Auth.Methods.LdapAuth.Enabled,
"mediaAvailable": settings.MediaEnabled(),
"exiftoolAvailable": settings.Config.Integrations.Media.ExiftoolPath != "",
"exiftoolAvailable": config.Integrations.Media.ExiftoolPath != "",
"muPdfAvailable": settings.Env.MuPdfAvailable,
"updateAvailable": utils.GetUpdateAvailableUrl(),
"disableNavButtons": disableNavButtons,
+2 -2
View File
@@ -14,7 +14,6 @@ import (
"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/storage"
"github.com/gtsteffaniak/filebrowser/backend/database/users"
@@ -101,6 +100,7 @@ func prepForFrontend(u *users.User) {
u.TOTPNonce = ""
u.Scopes = u.GetFrontendScopes()
u.SidebarLinks = GetFrontendSidebarLinks(u.SidebarLinks, u.ShowToolsInSidebar)
u.PinnedItems = nil
u.Locale = normalizeLocale(u.Locale)
for i := range u.PasskeyCredentials {
u.PasskeyCredentials[i].PublicKey = ""
@@ -132,7 +132,7 @@ func GetFrontendSidebarLinks(links []users.SidebarLink, showToolsInSidebar bool)
if !ok {
continue
}
if full, ok := settings.Config.Server.SourceMap[source.Path]; ok {
if full, ok := config.Server.SourceMap[source.Path]; ok {
if full.Config.ResolvedRules.IndexingDisabled && link.Category != "source-minimal" {
link.Category = "source-alt"
}
+20 -12
View File
@@ -27,7 +27,9 @@ func beginPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *request
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
}
registerRequestOrigin(r)
if err := validateRequestOrigin(r); err != nil {
return http.StatusForbidden, err
}
username := r.URL.Query().Get("username")
password := r.Header.Get("X-Password")
@@ -70,7 +72,9 @@ func finishPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *reques
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
}
registerRequestOrigin(r)
if err := validateRequestOrigin(r); err != nil {
return http.StatusForbidden, err
}
sessionID := r.URL.Query().Get("session_id")
if sessionID == "" {
@@ -100,7 +104,9 @@ func beginPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d *
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
}
registerRequestOrigin(r)
if err := validateRequestOrigin(r); err != nil {
return http.StatusForbidden, err
}
rpID := deriveRPID(r)
svc := auth.GetWebAuthn()
@@ -134,7 +140,9 @@ func finishPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
}
registerRequestOrigin(r)
if err := validateRequestOrigin(r); err != nil {
return http.StatusForbidden, err
}
sessionID := r.URL.Query().Get("session_id")
credentialName := r.URL.Query().Get("name")
@@ -207,8 +215,9 @@ func deriveRPID(r *http.Request) string {
return host
}
// registerRequestOrigin registers the request's origin and RP ID with the WebAuthn service.
func registerRequestOrigin(r *http.Request) {
// validateRequestOrigin validates that the request's origin is in the configured whitelist.
// Returns an error if the origin is not allowed.
func validateRequestOrigin(r *http.Request) error {
scheme := "http"
if r.TLS != nil {
scheme = "https"
@@ -220,13 +229,12 @@ func registerRequestOrigin(r *http.Request) {
host = r.Host
}
origin := fmt.Sprintf("%s://%s", scheme, host)
rpID := host
if i := strings.LastIndex(rpID, ":"); i != -1 {
rpID = rpID[:i]
}
svc := auth.GetWebAuthn()
if svc != nil {
svc.EnsureOrigin(origin)
svc.EnsureRPID(rpID)
if !svc.ValidateOrigin(origin) {
return fmt.Errorf("origin %s is not in the configured whitelist", origin)
}
}
return nil
}
+49 -49
View File
@@ -12,9 +12,9 @@ import (
storm "github.com/asdine/storm/v3"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
commonerrors "github.com/gtsteffaniak/filebrowser/backend/common/errors"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
commonerrors "github.com/gtsteffaniak/filebrowser/backend/common/errors"
"github.com/gtsteffaniak/filebrowser/backend/database/access"
"github.com/gtsteffaniak/filebrowser/backend/database/share"
"github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt"
@@ -41,7 +41,7 @@ func setupWebDAVTestEnv(t *testing.T) (string, string) {
filepath.Join(dockerPath, "data"),
filepath.Join(source2Path, "shared"),
}
for _, dir := range dirs {
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
@@ -50,12 +50,12 @@ func setupWebDAVTestEnv(t *testing.T) (string, string) {
// Create test files
testFiles := map[string]string{
filepath.Join(source1Path, "public", "readme.txt"): "public content",
filepath.Join(source1Path, "private", "secret.txt"): "private content",
filepath.Join(source1Path, "viewable-only", "data.txt"): "viewable content",
filepath.Join(source1Path, "not-viewable", "hidden.txt"): "hidden content",
filepath.Join(dockerPath, "data", "config.yml"): "docker config",
filepath.Join(source2Path, "shared", "document.txt"): "shared content",
filepath.Join(source1Path, "public", "readme.txt"): "public content",
filepath.Join(source1Path, "private", "secret.txt"): "private content",
filepath.Join(source1Path, "viewable-only", "data.txt"): "viewable content",
filepath.Join(source1Path, "not-viewable", "hidden.txt"): "hidden content",
filepath.Join(dockerPath, "data", "config.yml"): "docker config",
filepath.Join(source2Path, "shared", "document.txt"): "shared content",
}
for path, content := range testFiles {
@@ -74,18 +74,18 @@ func setupWebDAVTestEnv(t *testing.T) (string, string) {
if err != nil {
t.Fatal(err)
}
// Clear any previous access rules
store.Access.AllRules = make(access.SourceRuleMap)
store.Access.Groups = make(access.GroupMap)
// Set cache directory for index database
settings.Config.Server.CacheDir = tempDir
// Setup config with sources - update both the local config var AND the global settings.Config
config.Server.CacheDir = tempDir
// Setup config with sources - update both the local config var AND the global config
config = &settings.Settings{
Server: settings.Server{
BaseURL: "/", // Use / for tests to avoid prefix mismatch
BaseURL: "/", // Use / for tests to avoid prefix mismatch
CacheDir: tempDir,
SourceMap: map[string]*settings.Source{
source1Path: {
@@ -109,8 +109,8 @@ func setupWebDAVTestEnv(t *testing.T) (string, string) {
},
},
}
// CRITICAL: Also update the global settings.Config so access.Permitted can find sources
// CRITICAL: Also update the global config so access.Permitted can find sources
settings.Config.Server.SourceMap = config.Server.SourceMap
settings.Config.Server.NameToSource = config.Server.NameToSource
@@ -136,11 +136,11 @@ func setupWebDAVTestEnv(t *testing.T) (string, string) {
// mockCheckPermissions mocks the CheckPermissions function to bypass index lookups
func mockCheckPermissions(t *testing.T, source1Path, source2Path string) {
t.Helper()
// Store original function
originalCheckPermissions := files.CheckPermissionsFunc
t.Cleanup(func() { files.CheckPermissionsFunc = originalCheckPermissions })
// Mock the function
files.CheckPermissionsFunc = func(opts utils.FileOptions, access *access.Storage, user *users.User) (string, string, error) {
// Get the source path
@@ -152,7 +152,7 @@ func mockCheckPermissions(t *testing.T, source1Path, source2Path string) {
} else {
return "", "", fmt.Errorf("unknown source: %s", opts.Source)
}
// Get user scope for this source - match by source PATH, not name
userScope := "/"
hasScope := false
@@ -163,26 +163,26 @@ func mockCheckPermissions(t *testing.T, source1Path, source2Path string) {
break
}
}
// If user has no scope for this source, deny access
if !hasScope && len(user.Scopes) > 0 {
return "", "", fmt.Errorf("user has no access to source: %s", opts.Source)
}
// Sanitize path
safePath, err := utils.SanitizeUserPath(opts.Path)
if err != nil {
return "", "", commonerrors.ErrAccessDenied
}
// Combine scope + sanitized path
indexPath := utils.JoinPathAsUnix(userScope, safePath)
// Check access control
if access != nil && !access.Permitted(sourcePath, indexPath, user.Username) {
return "", "", commonerrors.ErrAccessDenied
}
return indexPath, userScope, nil
}
}
@@ -203,7 +203,7 @@ func mockWebDAVIndexing(t *testing.T, source1Path, source2Path string) {
} else {
return nil, fmt.Errorf("unknown source: %s", opts.Source)
}
// Simulate access control
if access != nil && user != nil {
// Simple scope check based on user's configured scopes (which use source PATH)
@@ -214,7 +214,7 @@ func mockWebDAVIndexing(t *testing.T, source1Path, source2Path string) {
// Check if path is within user's scope
userScope := scope.Scope
fullPath := utils.JoinPathAsUnix(userScope, opts.Path)
// Check if user has permission using the access storage
if !access.Permitted(sourcePath, fullPath, user.Username) {
return nil, commonerrors.ErrAccessDenied
@@ -229,12 +229,12 @@ func mockWebDAVIndexing(t *testing.T, source1Path, source2Path string) {
// Simulate indexing rules
path := opts.Path
// Paths containing "not-viewable" are not indexed and not viewable
if strings.Contains(path, "not-viewable") {
return nil, commonerrors.ErrNotViewable
}
// Paths containing "viewable-only" are not indexed but viewable
if strings.Contains(path, "viewable-only") {
return nil, commonerrors.ErrNotIndexed
@@ -333,12 +333,12 @@ func TestWebDAV_PROPFIND_UserScopes(t *testing.T) {
}
testCases := []struct {
name string
user *users.User
source string
path string
expectedStatus int
shouldHaveContent bool
name string
user *users.User
source string
path string
expectedStatus int
shouldHaveContent bool
}{
{
name: "Admin can access root of source1",
@@ -353,7 +353,7 @@ func TestWebDAV_PROPFIND_UserScopes(t *testing.T) {
user: scopedUser,
source: "source1",
path: "/",
expectedStatus: 207, // PROPFIND returns 207 Multi-Status
expectedStatus: 207, // PROPFIND returns 207 Multi-Status
shouldHaveContent: false, // Empty because _docker is not viewable
},
{
@@ -390,19 +390,19 @@ func TestWebDAV_PROPFIND_UserScopes(t *testing.T) {
req := httptest.NewRequest("PROPFIND", "/dav/"+tc.source+tc.path, nil)
req.SetPathValue("source", tc.source)
req.SetPathValue("path", tc.path)
w := httptest.NewRecorder()
ctx := &requestContext{user: tc.user}
status, err := webDAVHandler(w, req, ctx)
// If handler returned an error status, use that instead of response code
if status != 0 && status != http.StatusOK {
if w.Code == 0 || w.Code == http.StatusOK {
w.Code = status
}
}
// Check the actual HTTP response status code from ResponseWriter
if w.Code != tc.expectedStatus {
t.Errorf("expected status %d, got %d (err: %v)", tc.expectedStatus, w.Code, err)
@@ -529,7 +529,7 @@ func TestWebDAV_WriteOperations(t *testing.T) {
name: "Scoped user can write in their scope",
user: scopedUser,
method: http.MethodPut,
path: "/scopedfile.txt", // Path relative to scope (/public)
path: "/scopedfile.txt", // Path relative to scope (/public)
expectedStatus: http.StatusCreated, // 201 for new file
},
{
@@ -551,19 +551,19 @@ func TestWebDAV_WriteOperations(t *testing.T) {
req := httptest.NewRequest(tc.method, "/dav/source1"+tc.path, body)
req.SetPathValue("source", "source1")
req.SetPathValue("path", tc.path)
w := httptest.NewRecorder()
ctx := &requestContext{user: tc.user}
status, err := webDAVHandler(w, req, ctx)
// If handler returned an error status, use that instead of response code
if status != 0 && status != http.StatusOK {
if w.Code == 0 || w.Code == http.StatusOK {
w.Code = status
}
}
// Check the actual HTTP response status code from ResponseWriter
if w.Code != tc.expectedStatus {
t.Errorf("expected status %d, got %d (err: %v)", tc.expectedStatus, w.Code, err)
@@ -611,7 +611,7 @@ func TestWebDAV_AccessControl(t *testing.T) {
// Initialize index
initTestIndex(t, "source1", source1Path)
// Create access rules by using the internal structure
// User1 can access /private, user2 cannot
// Set up a deny rule for user2 at /private
@@ -621,7 +621,7 @@ func TestWebDAV_AccessControl(t *testing.T) {
Users: access.StringSet{"user2": struct{}{}},
},
}
// Add the rule to the access storage
if store.Access.AllRules == nil {
store.Access.AllRules = make(access.SourceRuleMap)
@@ -668,19 +668,19 @@ func TestWebDAV_AccessControl(t *testing.T) {
req := httptest.NewRequest("PROPFIND", "/dav/source1"+tc.path, nil)
req.SetPathValue("source", "source1")
req.SetPathValue("path", tc.path)
w := httptest.NewRecorder()
ctx := &requestContext{user: tc.user}
status, err := webDAVHandler(w, req, ctx)
// If handler returned an error status, use that instead of response code
if status != 0 && status != http.StatusOK {
if w.Code == 0 || w.Code == http.StatusOK {
w.Code = status
}
}
// Check the actual HTTP response status code from ResponseWriter
if w.Code != tc.expectedStatus {
t.Errorf("expected status %d, got %d (err: %v)", tc.expectedStatus, w.Code, err)
@@ -775,19 +775,19 @@ func TestWebDAV_IndexingStates(t *testing.T) {
req := httptest.NewRequest(tc.method, "/dav/source1"+tc.path, body)
req.SetPathValue("source", "source1")
req.SetPathValue("path", tc.path)
w := httptest.NewRecorder()
ctx := &requestContext{user: user}
status, err := webDAVHandler(w, req, ctx)
// If handler returned an error status, use that instead of response code
if status != 0 && status != http.StatusOK {
if w.Code == 0 || w.Code == http.StatusOK {
w.Code = status
}
}
// Check the actual HTTP response status code from ResponseWriter
if w.Code != tc.expectedStatus {
t.Errorf("%s: expected status %d, got %d (err: %v)", tc.description, tc.expectedStatus, w.Code, err)
+2
View File
@@ -2,6 +2,7 @@ package icons
import (
"bytes"
"context"
"errors"
"fmt"
"io/fs"
@@ -205,6 +206,7 @@ func generateSingleIcon(previewService *preview.Service, sourceData []byte, icon
// Resize image using the preview service's Resize method
err = previewService.Resize(
context.Background(),
bytes.NewReader(sourceData),
outFile,
preview.ResizeOptions{
+8 -6
View File
@@ -29,7 +29,7 @@ var (
// This is a simplified helper for shallow calculations and API calls
// For scanning with hardlink detection, use handleFile instead
// If useLogicalSize is true, returns the logical file size instead
func getDiskUsage(fileInfo os.FileInfo, realPath string, useLogicalSize bool) int64 {
func getDiskUsage(fileInfo os.FileInfo, useLogicalSize bool) int64 {
// If useLogicalSize is true, return logical size (no block alignment)
if useLogicalSize {
if fileInfo.IsDir() {
@@ -95,6 +95,8 @@ type Stats struct {
type ReducedIndex struct {
Stats
IdxName string `json:"name"`
ReadOnly bool `json:"readOnly"`
Private bool `json:"private"`
Status IndexStatus `json:"status"`
Scanners []*ScannerInfo `json:"scanners,omitempty"`
}
@@ -538,7 +540,7 @@ func (idx *Index) GetFileInfo(req FileInfoRequest) (*iteminfo.FileInfo, error) {
// getFileInfoFromContext returns info for a single file
func (idx *Index) getFileInfoFromContext(ctx *PathContext, isIndexable bool) (*iteminfo.FileInfo, error) {
size := idx.getFileSizeForDisplay(ctx.FileInfo, ctx.RealPath)
size := idx.getFileSizeForDisplay(ctx.FileInfo)
fileInfo := &iteminfo.FileInfo{
Path: ctx.IndexPath,
ItemInfo: iteminfo.ItemInfo{
@@ -622,7 +624,7 @@ func (idx *Index) indexDirectory(indexPath string, opts Options, scanner *Scanne
if err2 != nil {
return 0, false, err2
}
idx.UpdateMetadata(dirFileInfo, scanner)
idx.UpdateMetadata(dirFileInfo, scanner, !opts.Recursive)
// Always store the calculated directory size in the in-memory map
// This ensures parent directories are updated after copy/move operations
@@ -827,7 +829,7 @@ func (idx *Index) processFileItem(file os.FileInfo, indexPath string, opts Optio
var size uint64
var shouldCountSize bool
if !opts.Recursive && scanner == nil {
size = uint64(idx.getFileSizeForDisplay(file, fullCombined))
size = uint64(idx.getFileSizeForDisplay(file))
shouldCountSize = true
} else {
size, shouldCountSize = idx.handleFile(file, indexPath, fullCombined, opts.IsRoutineScan, scanner)
@@ -1157,14 +1159,14 @@ func (idx *Index) GetFolderSizeForDisplay(path string) int64 {
}
// getFileSizeForDisplay returns file size with appropriate calculation based on config
func (idx *Index) getFileSizeForDisplay(file os.FileInfo, realPath string) int64 {
func (idx *Index) getFileSizeForDisplay(file os.FileInfo) int64 {
if idx.Config.UseLogicalSize {
// Logical size mode: return actual bytes
return file.Size()
}
// Disk usage mode: use getDiskUsage helper
return getDiskUsage(file, realPath, false)
return getDiskUsage(file, false)
}
// SyncFolderSizesToDB syncs in-memory folder sizes to the database after a scan completes
+71 -16
View File
@@ -1,6 +1,7 @@
package indexing
import (
"errors"
"os"
"path/filepath"
"strings"
@@ -73,11 +74,12 @@ func (s *Scanner) executeScan() {
}()
if s.scanPath != "/" && !s.directoryExists() {
logger.Debugf("Scanner [%s] skipping: directory no longer exists", s.scanPath)
s.removeSelf()
s.handlePathGone("pre-scan check")
return
}
s.prepareScanState()
s.idx.mu.Lock()
s.idx.activeScannerPath = s.scanPath
s.idx.mu.Unlock()
@@ -173,13 +175,14 @@ func (s *Scanner) runFullScanRoot() {
s.purgeStaleEntries(true, false) // isRoot=true, isQuickScan=false
s.syncStatsWithDB()
if s.processedInodes != nil {
s.processedInodes = nil
s.foundHardLinks = nil
}
s.resetHardlinkTracking()
s.idx.mu.Lock()
s.idx.scanUpdatedPaths = make(map[string]bool)
if s.idx.scanUpdatedPaths == nil {
s.idx.scanUpdatedPaths = make(map[string]bool)
} else {
clear(s.idx.scanUpdatedPaths)
}
s.idx.mu.Unlock()
}
@@ -277,6 +280,10 @@ func (s *Scanner) runFullScanChild() {
_, _, err := s.idx.indexDirectory(s.scanPath, config, s)
if err != nil {
if isPathGone(err) {
s.handlePathGone("full scan")
return
}
logger.Errorf("Scanner [%s] error: %v", s.scanPath, err)
} else if config.Recursive && config.IsRoutineScan {
s.idx.mu.Lock()
@@ -294,10 +301,7 @@ func (s *Scanner) runFullScanChild() {
}
}
if s.processedInodes != nil {
s.processedInodes = nil
s.foundHardLinks = nil
}
s.resetHardlinkTracking()
s.idx.mu.Lock()
for path := range s.idx.scanUpdatedPaths {
@@ -498,6 +502,45 @@ func (s *Scanner) updateComplexity() {
}
}
// ensureScanUpdatedPaths initializes scan path tracking for the current scan session.
func (idx *Index) ensureScanUpdatedPaths() {
idx.mu.Lock()
defer idx.mu.Unlock()
if idx.scanUpdatedPaths == nil {
idx.scanUpdatedPaths = make(map[string]bool)
}
}
// prepareScanState initializes per-scan maps. Quick scans previously skipped this and could
// panic with "assignment to entry in nil map" when writing scanUpdatedPaths or hardlink tracking.
func (s *Scanner) prepareScanState() {
s.idx.ensureScanUpdatedPaths()
if s.processedInodes == nil {
s.processedInodes = make(map[uint64]struct{})
}
if s.foundHardLinks == nil {
s.foundHardLinks = make(map[string]uint64)
}
}
func (s *Scanner) resetHardlinkTracking() {
s.processedInodes = nil
s.foundHardLinks = nil
}
func isPathGone(err error) bool {
return err != nil && (os.IsNotExist(err) || errors.Is(err, os.ErrNotExist))
}
// handlePathGone removes a child scanner whose root directory was deleted.
func (s *Scanner) handlePathGone(context string) {
if s.scanPath == "/" {
return
}
logger.Infof("Scanner [%s] stopping (%s): directory no longer exists", s.scanPath, context)
s.removeSelf()
}
// directoryExists checks if the scanner's directory still exists
func (s *Scanner) directoryExists() bool {
realPath := strings.TrimRight(s.idx.Path, "/") + s.scanPath
@@ -553,7 +596,10 @@ func (s *Scanner) checkFolderModtime(folderPath string) (bool, error) {
info, err := os.Stat(realPath)
if err != nil {
if os.IsNotExist(err) {
// Folder was deleted - will be caught by purge
if folderPath == s.scanPath {
s.handlePathGone("quick scan")
}
// Subfolder deleted — stale entries are removed by purge
return false, nil
}
logger.Errorf("[QUICK_SCAN] Error stating %s: %v", folderPath, err)
@@ -589,10 +635,13 @@ func (s *Scanner) checkFolderModtime(folderPath string) (bool, error) {
}
// Update metadata (will be batched)
s.idx.UpdateMetadata(dirInfo, s)
s.idx.UpdateMetadata(dirInfo, s, true)
// Track this directory as having been updated (for file purge logic)
s.idx.mu.Lock()
if s.idx.scanUpdatedPaths == nil {
s.idx.scanUpdatedPaths = make(map[string]bool)
}
s.idx.scanUpdatedPaths[folderPath] = true
s.idx.mu.Unlock()
@@ -601,11 +650,17 @@ func (s *Scanner) checkFolderModtime(folderPath string) (bool, error) {
// Modtime unchanged - update last_updated to prevent folder from being purged
// Note: we DON'T add this folder to scanUpdatedPaths, so Phase 2 won't check its files
// Use cached aggregate size: BulkInsertItems overwrites DB size;0 would corrupt LoadFolderSizes on restart.
// BulkInsertItems overwrites all columns — preserve size/hasPreview/hidden from cache/DB, not hardcoded defaults.
var sizeForDB int64
if cached, ok := s.idx.GetFolderSize(folderPath); ok {
sizeForDB = int64(cached)
}
hasPreview := false
hidden := IsHidden(realPath)
if existing, ok := s.idx.GetReducedMetadata(folderPath, true); ok && existing != nil {
hasPreview = existing.HasPreview
hidden = existing.Hidden
}
fileInfo := &iteminfo.FileInfo{
Path: folderPath,
ItemInfo: iteminfo.ItemInfo{
@@ -613,8 +668,8 @@ func (s *Scanner) checkFolderModtime(folderPath string) (bool, error) {
Size: sizeForDB,
ModTime: info.ModTime(),
Type: "directory",
Hidden: false,
HasPreview: false,
Hidden: hidden,
HasPreview: hasPreview,
},
}
+115
View File
@@ -0,0 +1,115 @@
package indexing
import (
"os"
"testing"
"time"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
dbsql "github.com/gtsteffaniak/filebrowser/backend/database/sql"
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
)
func TestPrepareScanStateInitializesMaps(t *testing.T) {
idx := &Index{
Source: settings.Source{Name: "test", Path: t.TempDir()},
}
s := &Scanner{scanPath: "/music/", idx: idx}
s.prepareScanState()
idx.mu.Lock()
idx.scanUpdatedPaths["/music/"] = true
idx.mu.Unlock()
if s.processedInodes == nil {
t.Fatal("processedInodes should be initialized")
}
s.processedInodes[1] = struct{}{}
}
func TestIsPathGone(t *testing.T) {
if isPathGone(nil) {
t.Fatal("nil error should not be path gone")
}
if !isPathGone(os.ErrNotExist) {
t.Fatal("os.ErrNotExist should be path gone")
}
}
// TestCheckFolderModtime_unchangedPreservesHasPreviewAndHidden verifies quick-scan touch updates
// do not clobber has_preview/hidden when folder modtime is unchanged.
func TestCheckFolderModtime_unchangedPreservesHasPreviewAndHidden(t *testing.T) {
if indexDB == nil {
var err error
indexDB, _, err = dbsql.NewIndexDB("test_scanner_modtime", "OFF", 1000, 32, false)
if err != nil {
t.Fatalf("Failed to create test database: %v", err)
}
}
root := t.TempDir()
photosDir := root + "/photos"
if err := os.Mkdir(photosDir, 0o755); err != nil {
t.Fatalf("mkdir photos: %v", err)
}
idx := &Index{
ReducedIndex: ReducedIndex{},
Source: settings.Source{
Name: "test_modtime",
Path: root,
},
db: indexDB,
scanUpdatedPaths: make(map[string]bool),
folderSizes: make(map[string]uint64),
folderSizesUnsynced: make(map[string]struct{}),
}
folderPath := "/photos/"
now := time.Now()
stored := &iteminfo.FileInfo{
Path: folderPath,
ItemInfo: iteminfo.ItemInfo{
Name: "photos",
Type: "directory",
Size: 42,
ModTime: now.Add(-time.Hour),
Hidden: true,
HasPreview: true,
},
}
if err := idx.db.InsertItem("test_modtime", folderPath, stored); err != nil {
t.Fatalf("InsertItem: %v", err)
}
idx.SetFolderSize(folderPath, 42)
s := &Scanner{
scanPath: "/",
idx: idx,
}
s.withStatsLock(func() {
s.lastScanned = time.Now()
})
s.batchItems = make([]*iteminfo.FileInfo, 0, idx.db.BatchSize)
changed, err := s.checkFolderModtime(folderPath)
if err != nil {
t.Fatalf("checkFolderModtime: %v", err)
}
if changed {
t.Fatal("expected unchanged folder")
}
s.flushBatch()
got, ok := idx.GetReducedMetadata(folderPath, true)
if !ok || got == nil {
t.Fatal("expected folder metadata after touch update")
}
if !got.HasPreview {
t.Error("HasPreview should be preserved on unchanged modtime touch update")
}
if !got.Hidden {
t.Error("Hidden should be preserved on unchanged modtime touch update")
}
}
+6 -6
View File
@@ -213,11 +213,7 @@ func (idx *Index) runSerialScanPass() {
paths := sortedScannerPaths(idx)
idx.mu.Lock()
idx.schedulerBatch++
batchDepth := idx.schedulerBatch
idx.mu.Unlock()
logger.Debugf("[%s] scheduler: serialPass start paths=%d batchDepth=%d adaptive=%v",
idx.Name, len(paths), batchDepth, idx.useAdaptiveScheduling())
defer func() {
idx.mu.Lock()
idx.schedulerBatch--
@@ -225,7 +221,6 @@ func (idx *Index) runSerialScanPass() {
if err := idx.PostScan(); err != nil {
logger.Errorf("PostScan after serial pass: %v", err)
}
logger.Debugf("[%s] scheduler: serialPass done", idx.Name)
}()
for _, p := range paths {
@@ -236,6 +231,7 @@ func (idx *Index) runSerialScanPass() {
continue
}
if s.scanPath != "/" && !s.directoryExists() {
s.removeSelf()
continue
}
s.executeScan()
@@ -283,6 +279,10 @@ func (idx *Index) schedulerAdaptiveTick() {
}
})
logger.Debugf("[%s] scheduler: adaptive run path=%s nextRun=%s", idx.Name, s.scanPath, nextRunStr)
if s.scanPath != "/" && !s.directoryExists() {
s.removeSelf()
continue
}
s.executeScan()
}
}
@@ -329,7 +329,7 @@ func (idx *Index) runIndexScheduler() {
for {
now := time.Now()
next := idx.earliestSlotWake(now)
d := time.Until(next)
d := time.Until(next).Truncate(time.Second)
if d < time.Second {
d = time.Second
}
+1
View File
@@ -67,4 +67,5 @@ type ExtendedFileInfo struct {
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:"-"`
PinnedItems []string `json:"pinnedItems,omitempty"` // pinned item names in this directory listing
}
-13
View File
@@ -411,20 +411,7 @@ func ShouldBubbleUpToFolderPreview(item ItemInfo) bool {
if item.Type == "directory" || !item.HasPreview {
return false
}
// Get the simple type (e.g., "image", "video", "text")
simpleType := strings.Split(item.Type, "/")[0]
// Text files should NOT bubble up
if simpleType == "text" {
return false
}
// Office documents should NOT bubble up
if IsOnlyOffice(item.Name) {
return false
}
// Document convertable files (PDFs, etc.) should NOT bubble up
if HasDocConvertableExtension(item.Name, item.Type) {
return false
}
// Only allow images, videos, and audio with album art to bubble up
if simpleType == "image" || simpleType == "video" || simpleType == "audio" {
return true
+1 -1
View File
@@ -30,7 +30,7 @@ func (idx *Index) CreateMockData(numDirs, numFilesPerDir int) {
Files: files,
}
idx.UpdateMetadata(dirInfo, nil) // nil scanner for mock
idx.UpdateMetadata(dirInfo, nil, true) // nil scanner for mock
}
}
+18 -35
View File
@@ -13,57 +13,35 @@ import (
)
// UpdateMetadata persists a completed directory listing to the index. The directory row's has_preview
// scanner is optional — if nil (API refresh), inserts run immediately; otherwise items batch until flush.
func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo, scanner *Scanner) bool {
// reflects direct previewable children only (see GetDirInfoCore).
func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo, scanner *Scanner, persistListedFolders bool) bool {
items := make([]*iteminfo.FileInfo, 0, len(info.Files)+len(info.Folders)+1)
dirItem := *info
items = append(items, &dirItem)
// Check if we're in a batch scan (scanner provided)
isBatchScan := scanner != nil
includeListedFolders := !isBatchScan || persistListedFolders
if isBatchScan {
// During recursive scans: only insert directory itself and direct files
// Subdirectories will be inserted by their own recursive indexDirectory call
// This avoids redundant inserts and maintains the in-memory size calculation pattern
for i := range info.Files {
f := &info.Files[i]
// Construct index path for the file
filePath := strings.TrimRight(info.Path, "/") + "/" + f.Name
fileItem := &iteminfo.FileInfo{
ItemInfo: f.ItemInfo,
Path: filePath, // Store index path, not absolute path
}
items = append(items, fileItem)
}
} else {
// Not in batch scan (e.g., API-triggered updates): insert everything
// Add folders to the bulk insert with index paths
if includeListedFolders {
for i := range info.Folders {
folder := &info.Folders[i]
// Construct index path for the folder (with trailing slash)
folderPath := strings.TrimRight(info.Path, "/") + "/" + folder.Name + "/"
folderItem := &iteminfo.FileInfo{
ItemInfo: *folder,
Path: folderPath, // Store index path with trailing slash
Path: folderPath,
}
items = append(items, folderItem)
}
}
// Add files to the bulk insert with index paths
for i := range info.Files {
f := &info.Files[i]
// Construct index path for the file
filePath := strings.TrimRight(info.Path, "/") + "/" + f.Name
fileItem := &iteminfo.FileInfo{
ItemInfo: f.ItemInfo,
Path: filePath, // Store index path, not absolute path
}
items = append(items, fileItem)
for i := range info.Files {
f := &info.Files[i]
filePath := strings.TrimRight(info.Path, "/") + "/" + f.Name
fileItem := &iteminfo.FileInfo{
ItemInfo: f.ItemInfo,
Path: filePath,
}
items = append(items, fileItem)
}
// Use scanner-specific batch if available
@@ -71,6 +49,9 @@ func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo, scanner *Scanner) bool
// Track that this directory was updated by the scan (for timestamp conflict detection)
normalizedPath := utils.AddTrailingSlashIfNotExists(info.Path)
idx.mu.Lock()
if idx.scanUpdatedPaths == nil {
idx.scanUpdatedPaths = make(map[string]bool)
}
idx.scanUpdatedPaths[normalizedPath] = true
idx.mu.Unlock()
@@ -380,6 +361,8 @@ func GetIndexInfo(sourceName string, forceCacheRefresh bool) (ReducedIndex, erro
reducedIdx.LastScanned = lastIndexed
reducedIdx.LastIndexedUnix = lastIndexed.Unix()
reducedIdx.Status = idx.getStatusUnlocked()
reducedIdx.ReadOnly = idx.Config.ReadOnly
reducedIdx.Private = idx.Config.Private
idx.mu.RUnlock()
return reducedIdx, nil
}
+66 -2
View File
@@ -242,7 +242,7 @@ func TestUpdateFileMetadata(t *testing.T) {
mock: true,
}
success := index.UpdateMetadata(info, nil) // nil scanner for test
success := index.UpdateMetadata(info, nil, true) // nil scanner for test
if !success {
t.Fatalf("expected UpdateFileMetadata to succeed")
}
@@ -315,9 +315,73 @@ func TestSetDirectoryInfo(t *testing.T) {
{ItemInfo: iteminfo.ItemInfo{Name: "testfile.txt", ModTime: time.Now()}},
},
}
index.UpdateMetadata(dir, nil) // nil scanner for test
index.UpdateMetadata(dir, nil, true) // nil scanner for test
storedDir, exists := index.GetMetadataInfo("/newPath/", true, false)
if !exists || storedDir.Files[0].Name != "testfile.txt" {
t.Fatalf("expected SetDirectoryInfo to store directory info correctly")
}
}
func TestUpdateMetadata_batchScanPersistListedFolders(t *testing.T) {
t.Parallel()
if indexDB == nil {
var err error
indexDB, _, err = dbsql.NewIndexDB("test_mutate_batch", "OFF", 1000, 32, false)
if err != nil {
t.Fatalf("Failed to create test database: %v", err)
}
}
index := &Index{
Source: settings.Source{
Name: "test_batch_folders",
Path: "/mock/path",
},
db: indexDB,
mock: true,
}
scanner := &Scanner{idx: index, batchItems: make([]*iteminfo.FileInfo, 0, 16)}
now := time.Now()
parent := &iteminfo.FileInfo{
Path: "/parent/",
ItemInfo: iteminfo.ItemInfo{
Name: "parent",
Type: "directory",
ModTime: now,
},
Folders: []iteminfo.ItemInfo{
{
Name: "child",
Type: "directory",
Size: 100,
ModTime: now,
HasPreview: true,
Hidden: true,
},
},
}
index.UpdateMetadata(parent, scanner, false)
scanner.flushBatch()
_, exists := index.GetReducedMetadata("/parent/child/", true)
if exists {
t.Fatal("recursive batch scan should not persist listed subfolders when persistListedFolders is false")
}
scanner.batchItems = scanner.batchItems[:0]
index.UpdateMetadata(parent, scanner, true)
scanner.flushBatch()
child, exists := index.GetReducedMetadata("/parent/child/", true)
if !exists || child == nil {
t.Fatal("expected child folder row after persistListedFolders=true batch update")
}
if !child.HasPreview {
t.Error("child HasPreview should be persisted from listing")
}
if !child.Hidden {
t.Error("child Hidden should be persisted from listing")
}
}
+49 -9
View File
@@ -2,6 +2,7 @@ package preview
import (
"bytes"
"context"
"fmt"
"image"
"image/jpeg"
@@ -12,6 +13,22 @@ import (
"github.com/kovidgoyal/imaging"
)
// configureImagingParallelism limits kovidgoyal/imaging to one thread per resize.
// Concurrent preview jobs are capped separately by imageSem (like OG filebrowser).
func configureImagingParallelism() {
imaging.SetMaxProcs(1)
}
// previewDecodeOpts returns decode options tuned for thumbnails: skip ICC/sRGB conversion
// (not needed for previews) and optionally apply EXIF orientation.
func previewDecodeOpts(autoOrient bool) []imaging.DecodeOption {
opts := []imaging.DecodeOption{imaging.ColorSpace(imaging.NO_CHANGE_OF_COLORSPACE)}
if autoOrient {
opts = append(opts, imaging.AutoOrientation(true))
}
return opts
}
// Format is an image file format.
/*
ENUM(
@@ -150,12 +167,26 @@ type ResizeOptions struct {
JpegQuality int // JPEG encoding quality (1-100), 0 means use Quality default
}
func (s *Service) Resize(in io.Reader, out io.Writer, opts ResizeOptions) error {
return s.ResizeWithSize(in, out, 0, opts)
func (s *Service) Resize(ctx context.Context, in io.Reader, out io.Writer, opts ResizeOptions) error {
return s.ResizeWithSize(ctx, in, out, 0, opts)
}
// ResizeWithSize resizes an image with file size information for appropriate semaphore selection
func (s *Service) ResizeWithSize(in io.Reader, out io.Writer, fileSize int64, opts ResizeOptions) error {
// ResizeWithSize resizes an image with file size information for appropriate semaphore selection.
// Resize runs synchronously so the image semaphore accurately bounds concurrent CPU work.
// A detached goroutine would return on ctx cancellation while still decoding/resizing,
// defeating the semaphore and piling up orphaned work that causes preview timeouts under load.
func (s *Service) ResizeWithSize(ctx context.Context, in io.Reader, out io.Writer, fileSize int64, opts ResizeOptions) error {
if ctx.Err() != nil {
return ctx.Err()
}
err := s.resizeWithSize(in, out, fileSize, opts)
if ctx.Err() != nil {
return ctx.Err()
}
return err
}
func (s *Service) resizeWithSize(in io.Reader, out io.Writer, fileSize int64, opts ResizeOptions) error {
// Set defaults
if opts.ResizeMode == 0 {
opts.ResizeMode = ResizeModeFit
@@ -193,7 +224,7 @@ func (s *Service) ResizeWithSize(in io.Reader, out io.Writer, fileSize int64, op
}
// Decode the image - try imaging library first, fall back to format-specific decoder if it fails
img, err := imaging.Decode(wrappedReader, imaging.AutoOrientation(true))
img, err := imaging.Decode(wrappedReader, previewDecodeOpts(true)...)
if err != nil {
// Imaging library failed, try format-specific standard decoder as fallback
// Reset reader if possible
@@ -217,7 +248,16 @@ func (s *Service) ResizeWithSize(in io.Reader, out io.Writer, fileSize int64, op
}
}
// Resize
// Skip resize in Fit mode when the image is already within target dimensions.
// Fill mode may still need to upscale or crop to reach the target size.
bounds := img.Bounds()
if opts.ResizeMode != ResizeModeFill && bounds.Dx() <= opts.Width && bounds.Dy() <= opts.Height {
if opts.Format == FormatJpeg {
return jpeg.Encode(out, img, &jpeg.Options{Quality: opts.JpegQuality})
}
return imaging.Encode(out, img, opts.Format.toImaging())
}
resampleFilter := opts.Quality.resampleFilter()
switch opts.ResizeMode {
case ResizeModeFill:
@@ -242,7 +282,7 @@ func applyOrientationToPreviewBytes(imageBytes []byte, orientation string) []byt
if len(imageBytes) < 100 {
return imageBytes
}
img, err := imaging.Decode(bytes.NewReader(imageBytes))
img, err := imaging.Decode(bytes.NewReader(imageBytes), previewDecodeOpts(false)...)
if err != nil {
return imageBytes
}
@@ -268,7 +308,7 @@ func applyOrientationToPreviewBytes(imageBytes []byte, orientation string) []byt
return imageBytes
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, out, &jpeg.Options{Quality: 90}); err != nil {
if err := jpeg.Encode(&buf, out, &jpeg.Options{Quality: 80}); err != nil {
return imageBytes
}
return buf.Bytes()
@@ -357,6 +397,6 @@ func CreateThumbnail(rawData io.Reader, width, height int) (image.Image, error)
if err != nil {
return nil, fmt.Errorf("failed to decode image: %w", err)
}
thumb := imaging.Fit(img, width, height, imaging.Lanczos)
thumb := imaging.Fit(img, width, height, imaging.CatmullRom)
return thumb, nil
}
+41 -5
View File
@@ -2,6 +2,7 @@ package preview
import (
"bytes"
"context"
"errors"
"image"
"image/gif"
@@ -247,7 +248,7 @@ func TestService_Resize(t *testing.T) {
defer source.Close()
buf := &bytes.Buffer{}
err := svc.Resize(source, buf, test.options)
err := svc.Resize(context.Background(), source, buf, test.options)
if (err != nil) != test.wantErr {
t.Fatalf("GetMarketSpecs() error = %v, wantErr %v", err, test.wantErr)
}
@@ -459,7 +460,7 @@ func TestResize_ConcurrencyLimit(t *testing.T) {
source := newGrayJpeg(t, 100, 100)
defer source.Close()
out := &bytes.Buffer{}
err := svc.Resize(source, out, ResizeOptions{Width: 50, Height: 50})
err := svc.Resize(context.Background(), source, out, ResizeOptions{Width: 50, Height: 50})
require.NoError(t, err)
require.Greater(t, out.Len(), 0)
}
@@ -473,7 +474,7 @@ func TestResize_ConcurrencyLimit_NoFFmpeg(t *testing.T) {
source := newGrayJpeg(t, 100, 100)
defer source.Close()
out := &bytes.Buffer{}
err := svc.Resize(source, out, ResizeOptions{Width: 50, Height: 50})
err := svc.Resize(context.Background(), source, out, ResizeOptions{Width: 50, Height: 50})
require.NoError(t, err)
require.Greater(t, out.Len(), 0)
}
@@ -494,12 +495,47 @@ func TestCreatePreviewFromReader_UsesConcurrencyLimit(t *testing.T) {
require.NoError(t, err)
// Create preview from reader
out, err := svc.CreatePreview(bytes.NewReader(data), int64(len(data)), options)
out, err := svc.CreatePreview(context.Background(), bytes.NewReader(data), int64(len(data)), options)
require.NoError(t, err)
require.NotEmpty(t, out)
// Same via another call for parity
out2, err := svc.CreatePreview(bytes.NewReader(data), int64(len(data)), options)
out2, err := svc.CreatePreview(context.Background(), bytes.NewReader(data), int64(len(data)), options)
require.NoError(t, err)
require.Equal(t, out, out2)
}
func TestImageFitsPreviewSize(t *testing.T) {
t.Parallel()
tests := []struct {
name string
width int
height int
previewSize string
want bool
}{
{name: "fits xlarge", width: 800, height: 600, previewSize: "xlarge", want: true},
{name: "exceeds xlarge width", width: 1200, height: 600, previewSize: "xlarge", want: false},
{name: "fits large", width: 640, height: 480, previewSize: "large", want: true},
{name: "fits small", width: 256, height: 200, previewSize: "small", want: true},
{name: "exceeds small height", width: 200, height: 300, previewSize: "small", want: false},
{name: "original always fits", width: 5000, height: 5000, previewSize: "original", want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
require.Equal(t, tt.want, ImageFitsPreviewSize(tt.width, tt.height, tt.previewSize))
})
}
}
func TestReadImageFileDimensions(t *testing.T) {
t.Parallel()
width, height, err := ReadImageFileDimensions("testdata/gray-sample.jpg")
require.NoError(t, err)
require.Greater(t, width, 0)
require.Greater(t, height, 0)
}
+9 -6
View File
@@ -87,14 +87,17 @@ func (s *Service) GenerateOfficePreview(ctx context.Context, filetype, key, titl
return data, fmt.Errorf("error from OnlyOffice: %s", response.Error)
}
// make get request to binary data response.FileURL and return the body as a byte array data
resp, err = http.Get(response.FileURL)
thumbReq, err := http.NewRequestWithContext(ctx, http.MethodGet, response.FileURL, nil)
if err != nil {
return data, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return data, fmt.Errorf("failed to get preview file, status code: %d", resp.StatusCode)
thumbResp, err := client.Do(thumbReq)
if err != nil {
return data, err
}
return io.ReadAll(resp.Body)
defer thumbResp.Body.Close()
if thumbResp.StatusCode != http.StatusOK {
return data, fmt.Errorf("failed to get preview file, status code: %d", thumbResp.StatusCode)
}
return io.ReadAll(thumbResp.Body)
}
+66 -7
View File
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"image"
"io"
"os"
"path/filepath"
@@ -49,6 +50,8 @@ type Service struct {
// 3-6 processors: 2 large, rest small
// 7+ processors: 3 large, rest small
func NewPreviewGenerator(concurrencyLimit int, cacheDir string) *Service {
configureImagingParallelism()
if concurrencyLimit < 1 {
concurrencyLimit = 1
}
@@ -342,6 +345,13 @@ func (s *Service) generateVideoPreviewBytes(ctx context.Context, file iteminfo.E
// generateImagePreview generates preview for regular image files
func (s *Service) generateImagePreview(ctx context.Context, file iteminfo.ExtendedFileInfo, previewSize string) ([]byte, error) {
const maxSizeForOriginal = 256 * 1024 // 256KB
if previewSize != "original" && (file.Size < maxSizeForOriginal || ShouldServeOriginalImage(file.RealPath, previewSize)) {
if original, err := os.ReadFile(file.RealPath); err == nil {
return original, nil
}
}
// Stream from file instead of os.ReadFile so we don't load every image fully into memory
f, err := os.Open(file.RealPath)
if err != nil {
@@ -355,8 +365,11 @@ func (s *Service) generateImagePreview(ctx context.Context, file iteminfo.Extend
return nil, err
}
imageBytes, err := s.CreatePreview(f, file.Size, options)
imageBytes, err := s.CreatePreview(ctx, f, file.Size, options)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// For JPEG files, try FFmpeg fallback if initial decode failed
if strings.HasPrefix(file.Type, "image/jpeg") {
return handleJPEGFallback(ctx, s, file, previewSize, err)
@@ -496,8 +509,18 @@ func GeneratePreviewWithMD5(ctx context.Context, file iteminfo.ExtendedFileInfo,
return nil, err
}
resizedBytes, err := service.CreatePreview(bytes.NewReader(imageBytes), 0, options)
if cfg, _, cfgErr := image.DecodeConfig(bytes.NewReader(imageBytes)); cfgErr == nil && ImageFitsPreviewSize(cfg.Width, cfg.Height, previewSize) {
if err = service.fileCache.Store(ctx, cacheKey, imageBytes); err != nil {
logger.Errorf("failed to cache image: %v", err)
}
return imageBytes, nil
}
resizedBytes, err := service.CreatePreview(ctx, bytes.NewReader(imageBytes), 0, options)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// For JPEG files, try FFmpeg fallback if resize failed
if strings.HasPrefix(file.Type, "image/jpeg") {
resizedBytes, err = handleJPEGFallback(ctx, service, file, previewSize, err)
@@ -533,6 +556,42 @@ func GeneratePreview(ctx context.Context, file iteminfo.ExtendedFileInfo, previe
return GeneratePreviewWithMD5(ctx, file, previewSize, officeUrl, seekPercentage, cacheHash)
}
// ImageFitsPreviewSize reports whether both image dimensions are within the preview bounds.
func ImageFitsPreviewSize(imgWidth, imgHeight int, previewSize string) bool {
if previewSize == "original" {
return true
}
opts, err := getPreviewOptions(previewSize)
if err != nil {
return false
}
return imgWidth <= opts.Width && imgHeight <= opts.Height
}
// ReadImageFileDimensions reads image width and height without decoding the full image.
func ReadImageFileDimensions(path string) (int, int, error) {
f, err := os.Open(path)
if err != nil {
return 0, 0, err
}
defer f.Close()
cfg, _, err := image.DecodeConfig(f)
if err != nil {
return 0, 0, err
}
return cfg.Width, cfg.Height, nil
}
// ShouldServeOriginalImage reports whether an on-disk image is already within preview bounds.
func ShouldServeOriginalImage(path, previewSize string) bool {
width, height, err := ReadImageFileDimensions(path)
if err != nil {
return false
}
return ImageFitsPreviewSize(width, height, previewSize)
}
// getPreviewOptions returns resize options for the given preview size
func getPreviewOptions(previewSize string) (ResizeOptions, error) {
switch previewSize {
@@ -549,15 +608,15 @@ func getPreviewOptions(previewSize string) (ResizeOptions, error) {
Width: 640,
Height: 640,
ResizeMode: ResizeModeFit,
Quality: QualityHigh,
Quality: QualityMedium,
Format: FormatJpeg,
}, nil
case "small":
return ResizeOptions{
Width: 256,
Height: 256,
ResizeMode: ResizeModeFit,
Quality: QualityMedium,
ResizeMode: ResizeModeFill,
Quality: QualityLow,
Format: FormatJpeg,
}, nil
default:
@@ -566,9 +625,9 @@ func getPreviewOptions(previewSize string) (ResizeOptions, error) {
}
// CreatePreview resizes an image from a reader with the given options
func (s *Service) CreatePreview(reader io.Reader, fileSize int64, options ResizeOptions) ([]byte, error) {
func (s *Service) CreatePreview(ctx context.Context, reader io.Reader, fileSize int64, options ResizeOptions) ([]byte, error) {
output := &bytes.Buffer{}
if err := s.ResizeWithSize(reader, output, fileSize, options); err != nil {
if err := s.ResizeWithSize(ctx, reader, output, fileSize, options); err != nil {
return nil, err
}
return output.Bytes(), nil
+150 -2
View File
@@ -512,6 +512,15 @@ const docTemplate = `{
"type": "string"
}
},
"401": {
"description": "Unauthorized - authentication failed",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden - authentication failed",
"schema": {
@@ -521,6 +530,15 @@ const docTemplate = `{
}
}
},
"429": {
"description": "Too many requests - rate limited or temporarily locked out after failed attempts",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
@@ -3582,6 +3600,70 @@ const docTemplate = `{
}
}
},
"/api/users/pinnedItems": {
"patch": {
"description": "Patches one pinned item at a time. Defaults to add; pass ?action=remove to unpin.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Users"
],
"summary": "Add or remove a pinned item",
"parameters": [
{
"type": "string",
"description": "add (default) or remove",
"name": "action",
"in": "query"
},
{
"description": "Pinned item",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/http.pinnedItemPatchRequest"
}
}
],
"responses": {
"204": {
"description": "No Content"
},
"400": {
"description": "Bad Request",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/health": {
"get": {
"description": "Returns the health status of the API.",
@@ -5016,6 +5098,27 @@ const docTemplate = `{
}
}
},
"http.pinnedItemPatchRequest": {
"type": "object",
"required": [
"name",
"path",
"source"
],
"properties": {
"name": {
"description": "item basename within path",
"type": "string"
},
"path": {
"description": "scope-relative parent directory",
"type": "string"
},
"source": {
"type": "string"
}
}
},
"http.unarchiveRequest": {
"type": "object",
"properties": {
@@ -5132,6 +5235,13 @@ const docTemplate = `{
"description": "path scoped to the associated index",
"type": "string"
},
"pinnedItems": {
"description": "pinned item names in this directory listing",
"type": "array",
"items": {
"type": "string"
}
},
"size": {
"description": "length in bytes for regular files",
"type": "integer"
@@ -5586,6 +5696,22 @@ const docTemplate = `{
}
}
},
"settings.Http": {
"type": "object",
"properties": {
"disableRateLimit": {
"description": "turns off built-in auth route rate limiting and failed-login lockout (default false).",
"type": "boolean"
},
"trustedHeaders": {
"description": "list of headers to trust, useful when behind a reverse proxy.",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"settings.IndexSqlConfig": {
"type": "object",
"properties": {
@@ -6113,7 +6239,7 @@ const docTemplate = `{
"type": "integer"
},
"numImageProcessors": {
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
"description": "number of concurrent image processing jobs used to create previews, default is 4.",
"type": "integer"
},
"port": {
@@ -6121,7 +6247,7 @@ const docTemplate = `{
"type": "integer"
},
"socket": {
"description": "socket to listen on",
"description": "socket to listen on - eg. /var/run/filebrowser.sock",
"type": "string"
},
"sources": {
@@ -6149,6 +6275,9 @@ const docTemplate = `{
"frontend": {
"$ref": "#/definitions/settings.Frontend"
},
"http": {
"$ref": "#/definitions/settings.Http"
},
"integrations": {
"$ref": "#/definitions/settings.Integrations"
},
@@ -6218,6 +6347,10 @@ const docTemplate = `{
"description": "designate as source as private -- currently just means no sharing permitted.",
"type": "boolean"
},
"readOnly": {
"description": "read-only source, changes from the UI, webdav, and API will be disabled.",
"type": "boolean"
},
"rules": {
"description": "list of item rules to apply to specific paths",
"type": "array",
@@ -7308,6 +7441,18 @@ const docTemplate = `{
}
}
},
"users.PinnedItems": {
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"users.Preview": {
"type": "object",
"properties": {
@@ -7536,6 +7681,9 @@ const docTemplate = `{
"permissions": {
"$ref": "#/definitions/users.Permissions"
},
"pinnedItems": {
"$ref": "#/definitions/users.PinnedItems"
},
"preferEditorForMarkdown": {
"description": "prefer editor first for markdown files instead of the Markdown Viewer",
"type": "boolean"
+150 -2
View File
@@ -501,6 +501,15 @@
"type": "string"
}
},
"401": {
"description": "Unauthorized - authentication failed",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden - authentication failed",
"schema": {
@@ -510,6 +519,15 @@
}
}
},
"429": {
"description": "Too many requests - rate limited or temporarily locked out after failed attempts",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
@@ -3571,6 +3589,70 @@
}
}
},
"/api/users/pinnedItems": {
"patch": {
"description": "Patches one pinned item at a time. Defaults to add; pass ?action=remove to unpin.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Users"
],
"summary": "Add or remove a pinned item",
"parameters": [
{
"type": "string",
"description": "add (default) or remove",
"name": "action",
"in": "query"
},
{
"description": "Pinned item",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/http.pinnedItemPatchRequest"
}
}
],
"responses": {
"204": {
"description": "No Content"
},
"400": {
"description": "Bad Request",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"403": {
"description": "Forbidden",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/health": {
"get": {
"description": "Returns the health status of the API.",
@@ -5005,6 +5087,27 @@
}
}
},
"http.pinnedItemPatchRequest": {
"type": "object",
"required": [
"name",
"path",
"source"
],
"properties": {
"name": {
"description": "item basename within path",
"type": "string"
},
"path": {
"description": "scope-relative parent directory",
"type": "string"
},
"source": {
"type": "string"
}
}
},
"http.unarchiveRequest": {
"type": "object",
"properties": {
@@ -5121,6 +5224,13 @@
"description": "path scoped to the associated index",
"type": "string"
},
"pinnedItems": {
"description": "pinned item names in this directory listing",
"type": "array",
"items": {
"type": "string"
}
},
"size": {
"description": "length in bytes for regular files",
"type": "integer"
@@ -5575,6 +5685,22 @@
}
}
},
"settings.Http": {
"type": "object",
"properties": {
"disableRateLimit": {
"description": "turns off built-in auth route rate limiting and failed-login lockout (default false).",
"type": "boolean"
},
"trustedHeaders": {
"description": "list of headers to trust, useful when behind a reverse proxy.",
"type": "array",
"items": {
"type": "string"
}
}
}
},
"settings.IndexSqlConfig": {
"type": "object",
"properties": {
@@ -6102,7 +6228,7 @@
"type": "integer"
},
"numImageProcessors": {
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
"description": "number of concurrent image processing jobs used to create previews, default is 4.",
"type": "integer"
},
"port": {
@@ -6110,7 +6236,7 @@
"type": "integer"
},
"socket": {
"description": "socket to listen on",
"description": "socket to listen on - eg. /var/run/filebrowser.sock",
"type": "string"
},
"sources": {
@@ -6138,6 +6264,9 @@
"frontend": {
"$ref": "#/definitions/settings.Frontend"
},
"http": {
"$ref": "#/definitions/settings.Http"
},
"integrations": {
"$ref": "#/definitions/settings.Integrations"
},
@@ -6207,6 +6336,10 @@
"description": "designate as source as private -- currently just means no sharing permitted.",
"type": "boolean"
},
"readOnly": {
"description": "read-only source, changes from the UI, webdav, and API will be disabled.",
"type": "boolean"
},
"rules": {
"description": "list of item rules to apply to specific paths",
"type": "array",
@@ -7297,6 +7430,18 @@
}
}
},
"users.PinnedItems": {
"type": "object",
"additionalProperties": {
"type": "object",
"additionalProperties": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"users.Preview": {
"type": "object",
"properties": {
@@ -7525,6 +7670,9 @@
"permissions": {
"$ref": "#/definitions/users.Permissions"
},
"pinnedItems": {
"$ref": "#/definitions/users.PinnedItems"
},
"preferEditorForMarkdown": {
"description": "prefer editor first for markdown files instead of the Markdown Viewer",
"type": "boolean"
+106 -2
View File
@@ -324,6 +324,21 @@ definitions:
- $ref: '#/definitions/http.fileWatchMetadata'
description: File metadata for non-text files
type: object
http.pinnedItemPatchRequest:
properties:
name:
description: item basename within path
type: string
path:
description: scope-relative parent directory
type: string
source:
type: string
required:
- name
- path
- source
type: object
http.unarchiveRequest:
properties:
deleteAfter:
@@ -410,6 +425,11 @@ definitions:
path:
description: path scoped to the associated index
type: string
pinnedItems:
description: pinned item names in this directory listing
items:
type: string
type: array
size:
description: length in bytes for regular files
type: integer
@@ -758,6 +778,18 @@ definitions:
styling:
$ref: '#/definitions/settings.StylingConfig'
type: object
settings.Http:
properties:
disableRateLimit:
description: turns off built-in auth route rate limiting and failed-login
lockout (default false).
type: boolean
trustedHeaders:
description: list of headers to trust, useful when behind a reverse proxy.
items:
type: string
type: array
type: object
settings.IndexSqlConfig:
properties:
batchSize:
@@ -1168,13 +1200,13 @@ definitions:
type: integer
numImageProcessors:
description: number of concurrent image processing jobs used to create previews,
default is number of cpu cores available.
default is 4.
type: integer
port:
description: port to listen on
type: integer
socket:
description: socket to listen on
description: socket to listen on - eg. /var/run/filebrowser.sock
type: string
sources:
items:
@@ -1195,6 +1227,8 @@ definitions:
$ref: '#/definitions/settings.Auth'
frontend:
$ref: '#/definitions/settings.Frontend'
http:
$ref: '#/definitions/settings.Http'
integrations:
$ref: '#/definitions/settings.Integrations'
server:
@@ -1246,6 +1280,10 @@ definitions:
description: designate as source as private -- currently just means no sharing
permitted.
type: boolean
readOnly:
description: read-only source, changes from the UI, webdav, and API will be
disabled.
type: boolean
rules:
description: list of item rules to apply to specific paths
items:
@@ -2045,6 +2083,14 @@ definitions:
description: allow sharing files
type: boolean
type: object
users.PinnedItems:
additionalProperties:
additionalProperties:
items:
type: string
type: array
type: object
type: object
users.Preview:
properties:
audio:
@@ -2209,6 +2255,8 @@ definitions:
description: legacy for migration purposes... og filebrowser has perm attribute
permissions:
$ref: '#/definitions/users.Permissions'
pinnedItems:
$ref: '#/definitions/users.PinnedItems'
preferEditorForMarkdown:
description: prefer editor first for markdown files instead of the Markdown
Viewer
@@ -2686,12 +2734,25 @@ paths:
description: JWT token for authentication
schema:
type: string
"401":
description: Unauthorized - authentication failed
schema:
additionalProperties:
type: string
type: object
"403":
description: Forbidden - authentication failed
schema:
additionalProperties:
type: string
type: object
"429":
description: Too many requests - rate limited or temporarily locked out
after failed attempts
schema:
additionalProperties:
type: string
type: object
"500":
description: Internal server error
schema:
@@ -4815,6 +4876,49 @@ paths:
summary: Update a user's details
tags:
- Users
/api/users/pinnedItems:
patch:
consumes:
- application/json
description: Patches one pinned item at a time. Defaults to add; pass ?action=remove
to unpin.
parameters:
- description: add (default) or remove
in: query
name: action
type: string
- description: Pinned item
in: body
name: body
required: true
schema:
$ref: '#/definitions/http.pinnedItemPatchRequest'
produces:
- application/json
responses:
"204":
description: No Content
"400":
description: Bad Request
schema:
additionalProperties:
type: string
type: object
"403":
description: Forbidden
schema:
additionalProperties:
type: string
type: object
"500":
description: Internal Server Error
schema:
additionalProperties:
type: string
type: object
summary: Add or remove a pinned item
tags:
- Users
/health:
get:
consumes:
-54
View File
@@ -1,54 +0,0 @@
{
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/eslint-config-typescript",
"plugin:@intlify/vue-i18n/recommended"
],
"settings": {
"vue-i18n": {
"localeDir": "./src/i18n/en.json",
"messageSyntaxVersion": "^9.0.0"
}
},
"rules": {
"no-unreachable": "off",
// vue-i18n rules:
// This rule will check if the key used in $t() exists in your locale messages.
// The localeDir setting above points to en.json as the single source of truth.
"@intlify/vue-i18n/no-missing-keys": "error",
// Check for unused keys in en.json (keys that exist but are never used in code)
"@intlify/vue-i18n/no-unused-keys": [
"error",
{
"src": "./src",
"extensions": [".js", ".vue", ".ts"]
}
],
"@intlify/vue-i18n/no-raw-text": [
"error",
{
"ignoreNodes": ["i", "v-icon"]
}
],
// If you have your sync script, you might not need this one for other locales.
"@intlify/vue-i18n/no-missing-keys-in-other-locales": "off",
"vue/multi-word-component-names": "off",
"vue/no-mutating-props": [
"error",
{
"shallowOnly": true
}
]
},
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
}
}
+123
View File
@@ -0,0 +1,123 @@
import { defineConfig } from "eslint/config";
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
import vueI18n from '@intlify/eslint-plugin-vue-i18n';
import vueParser from "vue-eslint-parser";
import globals from "globals";
export default defineConfig(
{
ignores: [
"**/dist/**",
"**/node_modules/**",
"**/public/**",
"**/i18n/is.json",
],
},
// Defaults
js.configs.recommended,
...tseslint.configs.recommended,
...pluginVue.configs["flat/essential"],
...vueI18n.configs.recommended,
// i18n
{
settings: {
"vue-i18n": {
localeDir: "src/i18n/en.json",
messageSyntaxVersion: "^11.0.0",
},
},
rules: {
"@intlify/vue-i18n/no-missing-keys": "error",
"@intlify/vue-i18n/no-unused-keys": ["error", {
src: "./src",
extensions: [".js", ".vue", ".ts"],
ignores: ["/^languages\\./"],
}],
"@intlify/vue-i18n/no-raw-text": ["error", {
ignoreNodes: ["i", "v-icon"],
}],
"@intlify/vue-i18n/no-missing-keys-in-other-locales": "warn",
},
},
// Shared globals + rule overrides
{
files: ["**/*.js", "**/*.ts", "**/*.vue"],
languageOptions: {
globals: {
...globals.node,
...globals.browser,
...globals.es2022,
globalVars: "readonly",
router: "readonly",
$t: "readonly",
next: "readonly",
downloadFiles: "readonly",
},
},
rules: {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-empty-object-type": "warn",
"@typescript-eslint/ban-ts-comment": "warn",
"@typescript-eslint/no-unused-vars": ["error", {
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
caughtErrors: "none",
}],
"eqeqeq": ["warn", "always"],
"no-var": "error",
"prefer-const": "warn",
"no-unused-expressions": ["error", { allowShortCircuit: true, allowTernary: true }],
"prefer-template": "warn",
"@typescript-eslint/consistent-type-definitions": "warn",
"@typescript-eslint/prefer-optional-chain": "warn",
"prefer-object-has-own": "error",
"no-prototype-builtins": "error",
"no-restricted-globals": [
"error",
{ name: "isNaN", message: "Use Number.isNaN instead." },
{ name: "isFinite", message: "Use Number.isFinite instead." }
],
},
},
{
files: ["**/*.ts", "**/*.js"],
languageOptions: {
parser: tseslint.parser,
parserOptions: {
ecmaVersion: "latest",
projectService: true,
tsconfigRootDir: import.meta.dirname,
extraFileExtensions: ['.vue'],
},
},
},
// Vue files
{
files: ["**/*.vue"],
languageOptions: {
parser: vueParser,
parserOptions: {
parser: tseslint.parser,
ecmaVersion: "latest",
sourceType: "module",
projectService: true,
extraFileExtensions: ['.vue'],
},
},
rules: {
"vue/multi-word-component-names": "off",
"vue/no-mutating-props": ["error", { shallowOnly: true }],
//"vue/order-in-components": "warn",
"vue/require-v-for-key": "error",
"vue/no-reserved-component-names": "off",
"vue/no-unused-components": "warn",
},
},
);
+1174 -1327
View File
File diff suppressed because it is too large. Load diff
+11 -10
View File
@@ -18,7 +18,7 @@
"i18n:check": "node ./scripts/sync-translations.js --check",
"i18n:enforce-order": "node scripts/sync-translations.js --enforce-order",
"i18n:cleanup": "node scripts/sync-translations.js --cleanup",
"format": "prettier --write .",
"format": "biome format --write .",
"test": "vitest run "
},
"dependencies": {
@@ -38,8 +38,7 @@
"srt-support-for-html5-videos": "^2.6.11",
"three": "^0.182.0",
"vue": "^3.4.21",
"vue-i18n": "^9.10.2",
"vue-lazyload": "^3.0.0",
"vue-i18n": "^11.4.4",
"vue-router": "^4.3.0"
},
"overrides": {
@@ -47,23 +46,25 @@
"@xmldom/xmldom": "^0.8.12"
},
"devDependencies": {
"@intlify/eslint-plugin-vue-i18n": "^3.2.0",
"@intlify/unplugin-vue-i18n": "^4.0.0",
"@eslint/js": "^10.0.1",
"@intlify/eslint-plugin-vue-i18n": "^4.4.0",
"@intlify/unplugin-vue-i18n": "^11.2.3",
"@playwright/test": "^1.54.1",
"@types/node": "^24.1.0",
"@vitejs/plugin-vue": "^5.0.4",
"@vue/eslint-config-typescript": "^13.0.0",
"deepl-node": "^1.16.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-vue": "^9.24.0",
"eslint": "^10.4.0",
"eslint-plugin-vue": "^10.9.1",
"fs-extra": "^11.3.0",
"globals": "^17.6.0",
"jsdom": "^25.0.1",
"typescript": "^6.0.0",
"typescript-eslint": "^8.59.4",
"vite": "^6.2.0",
"vite-plugin-checker": "^0.10.3",
"vite-plugin-compression2": "^1.0.0",
"vitest": "^3.0.7",
"vitest": "^4.1.8",
"vue-eslint-parser": "^10.4.0",
"vue-tsc": "^2.0.7"
}
}
+6 -2
View File
@@ -1,8 +1,8 @@
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
numImageProcessors: 4 # number of concurrent image processing jobs used to create previews, default is 4.
socket: "" # socket to listen on - eg. /var/run/filebrowser.sock
tlsKey: "" # path to TLS key
tlsCert: "" # path to TLS cert
disablePreviews: false # disable all previews thumbnails, simple icons will be used
@@ -26,6 +26,7 @@ server:
config:
denyByDefault: false # deny access unless an "allow" access rule was specifically created.
private: false # designate as source as private -- currently just means no sharing permitted.
readOnly: false # read-only source, changes from the UI, webdav, and API will be disabled.
disabled: false # disable the source, this is useful so you don't need to remove it from the config file
rules: # list of item rules to apply to specific paths
- neverWatchPath: "" # index the folder in the first pass to get included in search, but never re-indexed.
@@ -257,3 +258,6 @@ integrations:
debug: false # output ffmpeg stdout for media integration -- careful can produces lots of output!
extractEmbeddedSubtitles: false # extract embedded subtitles from media files
exiftoolPath: "" # path to exiftool executable
http:
trustedHeaders: # list of headers to trust, useful when behind a reverse proxy.
disableRateLimit: false # turns off built-in auth route rate limiting and failed-login lockout (default false).
+14 -14
View File
@@ -1,9 +1,9 @@
// scripts/sync-translations.js
import fs from 'fs-extra';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as glob from 'glob';
import * as deepl from 'deepl-node';
import fs from 'fs-extra';
import * as glob from 'glob';
// Parse command line arguments
const args = process.argv.slice(2);
@@ -76,7 +76,7 @@ async function translateText(text, targetLanguage, keyPath = '') {
try {
console.log(`Translating "${text}" from '${masterLanguageCode}' to '${targetLanguage}'...`);
let deeplTargetLang = deeplLangMap[targetLanguage.toLowerCase()] || targetLanguage.toUpperCase();
const deeplTargetLang = deeplLangMap[targetLanguage.toLowerCase()] || targetLanguage.toUpperCase();
const result = await translator.translateText(textToTranslate, masterLanguageCode, deeplTargetLang, options);
@@ -104,8 +104,8 @@ function reorderObject(obj, masterObj) {
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) return obj;
const newObj = {};
for (const key in masterObj) {
if (Object.prototype.hasOwnProperty.call(masterObj, key)) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (Object.hasOwn(masterObj, key)) {
if (Object.hasOwn(obj, key)) {
newObj[key] = reorderObject(obj[key], masterObj[key]);
}
}
@@ -120,7 +120,7 @@ async function processKeys(masterObj, targetObj, targetLangCode, currentPathPart
// First pass: Add/update keys from master to target
for (const key in masterObj) {
if (Object.prototype.hasOwnProperty.call(masterObj, key)) {
if (Object.hasOwn(masterObj, key)) {
const currentPathPartsNext = [...currentPathParts, key];
const currentKeyPath = currentPathPartsNext.join('.');
@@ -153,7 +153,7 @@ async function processKeys(masterObj, targetObj, targetLangCode, currentPathPart
if (targetObj[key] && typeof targetObj[key] === 'object') {
const result = await processKeys( masterValue, targetObj[key], targetLangCode, currentPathPartsNext,
doEnforceOrder, doCleanupOnly);
if (result == "UNSUPPORTED") {
if (result === "UNSUPPORTED") {
console.log(`Skipping translation for "${targetLangCode}" due to unsupported structure.`);
return "UNSUPPORTED";
}
@@ -168,7 +168,7 @@ async function processKeys(masterObj, targetObj, targetLangCode, currentPathPart
// Only handle non‑object values
if (typeof masterValue === 'string') {
const existingTargetValue = targetObj[key];
const isMissing = !Object.prototype.hasOwnProperty.call(targetObj, key) || existingTargetValue === '' || existingTargetValue === null;
const isMissing = !Object.hasOwn(targetObj, key) || existingTargetValue === '' || existingTargetValue === null;
if (isMissing) {
if (checkOnly) {
@@ -180,7 +180,7 @@ async function processKeys(masterObj, targetObj, targetLangCode, currentPathPart
} else {
// Sync translation
const result = await translateText(masterValue, targetLangCode, currentKeyPath);
if (result == "") {
if (result === "") {
return "UNSUPPORTED";
}
targetObj[key] = result;
@@ -188,7 +188,7 @@ async function processKeys(masterObj, targetObj, targetLangCode, currentPathPart
}
}
} else {
if (!Object.prototype.hasOwnProperty.call(targetObj, key)) {
if (!Object.hasOwn(targetObj, key)) {
if (checkOnly) {
console.log(`Would copy key "${currentKeyPath}" (non-string) from English to ${targetLangCode}.json`);
meaningfulChanges++; // Copying non-string values is meaningful
@@ -206,8 +206,8 @@ async function processKeys(masterObj, targetObj, targetLangCode, currentPathPart
// Second pass: Remove obsolete keys that exist in target but not in master
const keysToRemove = [];
for (const key in targetObj) {
if (Object.prototype.hasOwnProperty.call(targetObj, key)) {
if (!Object.prototype.hasOwnProperty.call(masterObj, key)) {
if (Object.hasOwn(targetObj, key)) {
if (!Object.hasOwn(masterObj, key)) {
keysToRemove.push(key);
}
}
@@ -259,7 +259,7 @@ async function syncAllTranslations() {
const targetLangCode = path.basename(targetFile, '.json');
let targetContent = {};
let originalTargetContent = null;
let fileExisted = await fs.pathExists(targetFile);
const fileExisted = await fs.pathExists(targetFile);
if (fileExisted) {
try {
@@ -349,4 +349,4 @@ syncAllTranslations()
.catch(error => {
console.error("\n❌ An error occurred during translation synchronization:", error);
process.exit(1);
});
});
+1 -6
View File
@@ -5,6 +5,7 @@
<script>
import { onMounted } from "vue";
import { mutations } from "@/store"; // Import your store's mutations
mutations.setLoading("main-app", true);
export default {
name: "app",
@@ -21,9 +22,3 @@ export default {
},
};
</script>
<style>
/* Always load styles.css */
@import "./css/styles.css";
@import "./css/dark.css";
</style>
+1 -1
View File
@@ -1,5 +1,5 @@
import { fetchJSON } from './utils'
import { getApiPath } from '@/utils/url.js'
import { fetchJSON } from './utils'
/**
* @param {string} source
+2 -2
View File
@@ -1,6 +1,6 @@
import { fetchURL } from "./utils";
import { getApiPath } from "@/utils/url.js";
import { notify } from "@/notify";
import { getApiPath } from "@/utils/url.js";
import { fetchURL } from "./utils";
/**
* Create an archive on the server (server-side only).
+35 -29
View File
@@ -1,6 +1,6 @@
import { fetchURL, fetchJSON } from '@/api/utils'
import { getApiPath } from '@/utils/url.js'
import { fetchJSON, fetchURL } from '@/api/utils'
import { notify } from '@/notify'
import { getApiPath } from '@/utils/url.js'
// POST /api/auth/login
export async function login(username, password, recaptcha, otp) {
@@ -14,29 +14,33 @@ export async function login(username, password, recaptcha, otp) {
password = ''
}
const params = { username, recaptcha };
let apiPath = getApiPath('auth/login', params);
const res = await fetch(apiPath, {
method: 'POST',
credentials: 'same-origin',
headers: {
'X-Password': encodeURIComponent(password),
'X-Secret': otp,
}
});
const bodyText = await res.text();
let body;
try {
body = JSON.parse(bodyText);
} catch {
body = { message: bodyText };
}
const params = { username, recaptcha };
const apiPath = getApiPath('auth/login', params);
const res = await fetch(apiPath, {
method: 'POST',
credentials: 'same-origin',
headers: {
'X-Password': encodeURIComponent(password),
'X-Secret': otp,
}
});
if (res.status != 200) {
const msg = body.message || 'Forbidden';
throw new Error(msg);
const bodyText = await res.text();
let body;
try {
body = JSON.parse(bodyText);
} catch {
body = { message: bodyText };
}
if (res.status !== 200) {
const msg = body.message || 'Forbidden';
throw new Error(msg);
}
} catch (err) {
throw err instanceof Error ? err : new Error(String(err));
}
}
@@ -54,7 +58,7 @@ export async function logout() {
// POST /api/auth/signup
export async function signup(username, password, otp) {
const params = { username, password, otp }
let apiPath = getApiPath('auth/signup', params)
const apiPath = getApiPath('auth/signup', params)
const res = await fetch(apiPath, {
method: 'POST',
headers: {
@@ -69,7 +73,7 @@ export async function signup(username, password, otp) {
if (errorData.message) {
errorMessage = errorData.message
}
} catch (parseError) {
} catch (_parseError) {
// If parsing fails, keep the status code as error message
}
throw new Error(errorMessage)
@@ -80,7 +84,7 @@ export async function signup(username, password, otp) {
export async function generateOTP(username, password) {
const params = { username }
try {
let apiPath = getApiPath('auth/otp/generate', params)
const apiPath = getApiPath('auth/otp/generate', params)
const res = await fetch(apiPath, {
method: 'POST',
credentials: 'same-origin',
@@ -104,7 +108,7 @@ export async function generateOTP(username, password) {
export async function verifyOTP(username, password, otp) {
const params = { username }
try {
let apiPath = getApiPath('auth/otp/verify', params)
const apiPath = getApiPath('auth/otp/verify', params)
const res = await fetch(apiPath, {
method: 'POST',
credentials: 'same-origin',
@@ -113,7 +117,7 @@ export async function verifyOTP(username, password, otp) {
'X-Secret': otp,
}
})
if (res.status != 200) {
if (res.status !== 200) {
let msg = 'Failed to verify OTP'
try {
const errBody = await res.json()
@@ -186,7 +190,9 @@ export function deleteApiKey(params) {
function arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer)
let binary = ''
bytes.forEach(b => binary += String.fromCharCode(b))
bytes.forEach(b => {
binary += String.fromCharCode(b);
})
return btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
}
+15 -16
View File
@@ -10,25 +10,24 @@
// - /api/media/ -> media.js
// - /public/api/* -> public functions in respective files (e.g., resourcesApi.fetchFilesPublic)
import * as authApi from "./auth";
import * as usersApi from "./users";
import * as resourcesApi from "./resources";
import * as accessApi from "./access";
import * as shareApi from "./share";
import * as settingsApi from "./settings";
import * as toolsApi from "./tools";
import * as officeApi from "./office";
import * as authApi from "./auth";
import * as mediaApi from "./media";
import * as officeApi from "./office";
import * as resourcesApi from "./resources";
import * as settingsApi from "./settings";
import * as shareApi from "./share";
import * as toolsApi from "./tools";
import * as usersApi from "./users";
export {
authApi,
usersApi,
resourcesApi,
export {
accessApi,
shareApi,
settingsApi,
toolsApi,
authApi,
mediaApi,
officeApi,
mediaApi
resourcesApi,
settingsApi,
shareApi,
toolsApi,
usersApi,
};
+4 -5
View File
@@ -1,7 +1,7 @@
import { fetchURL, adjustedData } from "./utils";
import { notify } from "@/notify";
import { getApiPath, getPublicApiPath } from "@/utils/url.js";
import { state } from "@/store";
import { getApiPath, getPublicApiPath } from "@/utils/url.js";
import { adjustedData, fetchURL } from "./utils";
// GET /api/media/subtitles
export async function getSubtitleContent(source, path, subtitleName, embedded = false) {
@@ -45,8 +45,7 @@ export async function getLyricsPublic(path, hash, password = "") {
});
if (!response.ok) {
const error = new Error(response.statusText);
let data = null;
data = await response.json();
const data = await response.json();
if (data?.message) {
error.message = data.message;
}
@@ -90,7 +89,7 @@ export async function fetchDirectoryMediaMetadataPublic(path, hash, password = "
let data = null;
try {
data = await response.json();
} catch (e) {
} catch (_e) {
// ignore
}
if (data?.message) {
+2 -2
View File
@@ -1,6 +1,6 @@
import { fetchURL } from './utils'
import { getApiPath, getPublicApiPath } from '@/utils/url.js'
import { notify } from '@/notify'
import { getApiPath, getPublicApiPath } from '@/utils/url.js'
import { fetchURL } from './utils'
// GET /api/office/config or /public/api/office/config
export async function getConfig(req) {
+45 -36
View File
@@ -1,9 +1,11 @@
import { fetchURL, adjustedData } from './utils'
import { getApiPath, getPublicApiPath } from '@/utils/url.js'
import { state, mutations } from '@/store'
import { notify } from '@/notify'
import { mutations, state } from '@/store'
import { globalVars } from '@/utils/constants'
import { downloadManager } from '@/utils/downloadManager'
import { getApiPath, getPublicApiPath } from '@/utils/url.js'
import { adjustedData, fetchURL } from './utils'
export { fetchPreviewImage } from '@/utils/previewRequests'
// Notify if errors occur
export async function fetchFiles(source, path, content = false, metadata = false, skipExtendedAttrs = false) {
@@ -58,7 +60,7 @@ export async function signalUploadPause(source, path, shareHash = null) {
path: path,
})
const headers = {}
const sharePassword = localStorage.getItem('sharepass:' + shareHash)
const sharePassword = localStorage.getItem(`sharepass:${shareHash}`)
if (sharePassword) {
headers['X-SHARE-PASSWORD'] = sharePassword
}
@@ -78,7 +80,7 @@ async function resourceAction(source, path, method, content) {
}
try {
const apiPath = getApiPath('resources', { path, source })
let opts = { method }
const opts = { method }
if (content) {
opts.body = content
}
@@ -90,7 +92,7 @@ async function resourceAction(source, path, method, content) {
let data = null;
try {
data = await response.json()
} catch (e) {
} catch (_e) {
// ignore
}
if (data) {
@@ -177,7 +179,7 @@ export async function download(format, files, shareHash = "") {
if (shareHash) {
filePaths = files.map((file) => file.path)
} else {
for (let file of files) {
for (const file of files) {
if (!file.source) {
throw new Error('File source is required for downloads')
}
@@ -264,11 +266,17 @@ async function resolveDownloadContentLength(url) {
headers: { Range: 'bytes=0-0' },
credentials: 'same-origin',
})
const cancelBody = () => {
if (res.body && typeof res.body.cancel === 'function') {
res.body.cancel().catch(() => {})
}
}
try {
token = res.headers.get('X-Archive-Token') || token
if (res.status === 206) {
const total = totalFromContentRange(res.headers.get('Content-Range'))
if (total > 0) {
cancelBody()
return { size: total, token }
}
}
@@ -277,20 +285,17 @@ async function resolveDownloadContentLength(url) {
if (cl) {
const n = parseInt(cl, 10)
if (Number.isFinite(n) && n > 0) {
cancelBody()
return { size: n, token }
}
}
}
} finally {
if (res.body && typeof res.body.cancel === 'function') {
try {
await res.body.cancel()
} catch {
// ignore
}
}
cancelBody()
return { size: 0, token }
} catch (e) {
cancelBody()
throw e
}
return { size: 0, token: null }
}
function archiveDisplayFileName(format, files) {
@@ -299,20 +304,20 @@ function archiveDisplayFileName(format, files) {
if (files.length === 1 && first.isDir) {
const base =
first.name ||
(first.path && first.path.split('/').filter(Boolean).pop()) ||
(first.path?.split('/').filter(Boolean).pop()) ||
'download'
return base + ext
return `${base}${ext}`
}
if (first && first.path) {
if (first?.path) {
const parts = first.path.split('/').filter(Boolean)
if (parts.length >= 2) {
return parts[parts.length - 2] + ext
return `${parts[parts.length - 2]}${ext}`
}
if (parts.length === 1) {
return parts[0] + ext
return `${parts[0]}${ext}`
}
}
return 'download' + ext
return `download${ext}`
}
/**
@@ -337,7 +342,7 @@ async function chunkedRangeDownloadToBlob(
while (offset < totalSize) {
const download = downloadManager.findById(downloadId)
if (download && download.status === 'cancelled') {
if (download?.status === 'cancelled') {
return null
}
@@ -430,7 +435,7 @@ async function chunkedRangeDownloadToBlob(
}
} catch (readError) {
const download = downloadManager.findById(downloadId)
if (readError.name === 'AbortError' || (download && download.status === 'cancelled')) {
if (readError.name === 'AbortError' || (download?.status === 'cancelled')) {
downloadManager.setStatus(downloadId, 'cancelled')
return null
}
@@ -492,7 +497,7 @@ async function downloadChunkedArchive(url, format, files, filePaths, source, sha
downloadManager.setStatus(downloadId, 'downloading')
const hasDownloadPrompt = state.prompts && state.prompts.some((h) => h.name === 'download')
const hasDownloadPrompt = state.prompts?.some((h) => h.name === 'download')
if (!hasDownloadPrompt) {
mutations.showPrompt({ name: 'download' })
}
@@ -532,7 +537,7 @@ async function downloadChunkedArchive(url, format, files, filePaths, source, sha
}, 100)
} catch (error) {
const download = downloadManager.findById(downloadId)
if (error.name === 'AbortError' || (download && download.status === 'cancelled')) {
if (error.name === 'AbortError' || (download?.status === 'cancelled')) {
downloadManager.setStatus(downloadId, 'cancelled')
return
}
@@ -580,7 +585,7 @@ async function downloadChunked(file, shareHash = "") {
downloadManager.setStatus(downloadId, "downloading")
// Show download prompt if not already shown (it should already be shown by downloadFiles, but check to be safe)
const hasDownloadPrompt = state.prompts && state.prompts.some(h => h.name === 'download');
const hasDownloadPrompt = state.prompts?.some(h => h.name === 'download');
if (!hasDownloadPrompt) {
mutations.showPrompt({ name: 'download' })
@@ -623,7 +628,7 @@ async function downloadChunked(file, shareHash = "") {
} catch (error) {
// Check if download was cancelled by user
const download = downloadManager.findById(downloadId);
if (error.name === 'AbortError' || (download && download.status === "cancelled")) {
if (error.name === 'AbortError' || (download?.status === "cancelled")) {
downloadManager.setStatus(downloadId, "cancelled")
// Don't throw error or show notification for user-initiated cancellation
return;
@@ -686,7 +691,7 @@ export function post(
try {
const errorData = JSON.parse(request.responseText);
errorMessage = errorData.message || errorMessage;
} catch (e) {
} catch (_e) {
errorMessage = request.responseText || errorMessage;
}
const error = new Error(errorMessage);
@@ -831,6 +836,10 @@ export function getDownloadURL(source, path, inline, useExternal) {
}
}
/**
* Build a preview API URL. Use fetchPreviewImage(url, signal) to load it;
* pass an AbortSignal so the caller can cancel on navigation or unmount.
*/
export function getPreviewURL(source, path, modified) {
if (!source || source === undefined || source === null) {
throw new Error('no source provided')
@@ -940,7 +949,7 @@ export async function fetchFilesPublic(path, hash, password = "", content = fals
let data = null;
try {
data = await response.json()
} catch (e) {
} catch (_e) {
// ignore
}
if (data) {
@@ -949,7 +958,7 @@ export async function fetchFilesPublic(path, hash, password = "", content = fals
(/** @type {any} */ (error)).status = response.status;
throw error;
}
let data = await response.json()
const data = await response.json()
const adjusted = adjustedData(data);
return adjusted
}
@@ -1027,7 +1036,7 @@ export function postPublic(
if (!hash || hash === undefined || hash === null) {
throw new Error('no hash provided')
}
let sharePassword = localStorage.getItem("sharepass:" + hash);
const sharePassword = localStorage.getItem(`sharepass:${hash}`);
if (sharePassword) {
headers["X-SHARE-PASSWORD"] = sharePassword;
}
@@ -1069,7 +1078,7 @@ export function postPublic(
try {
const errorData = JSON.parse(request.responseText);
errorMessage = errorData.message || errorMessage;
} catch (e) {
} catch (_e) {
errorMessage = request.responseText || errorMessage;
}
@@ -1114,8 +1123,8 @@ export function postPublic(
async function resourceActionPublic(hash, path, method, content, token = "") {
try {
let headers = {};
let sharePassword = localStorage.getItem("sharepass:" + hash);
const headers = {};
const sharePassword = localStorage.getItem(`sharepass:${hash}`);
if (sharePassword) {
headers["X-SHARE-PASSWORD"] = sharePassword;
}
@@ -1130,7 +1139,7 @@ async function resourceActionPublic(hash, path, method, content, token = "") {
let data = null;
try {
data = await response.json()
} catch (e) {
} catch (_e) {
// ignore
}
if (data) {
+2 -2
View File
@@ -1,6 +1,6 @@
import { fetchURL } from "./utils";
import { notify } from "@/notify"; // Import notify for error handling
import { getApiPath } from "@/utils/url.js";
import { fetchURL } from "./utils";
export default async function search(base, sources, query, largest = false, extraParams = {}) {
try {
@@ -34,7 +34,7 @@ export default async function search(base, sources, query, largest = false, extr
const apiPath = getApiPath("tools/search", params);
const res = await fetchURL(apiPath);
let data = await res.json();
const data = await res.json();
return data
} catch (err) {
+2 -3
View File
@@ -1,7 +1,6 @@
import { fetchURL, fetchJSON } from "./utils";
import { getApiPath } from "@/utils/url.js";
import { notify } from "@/notify";
import { getApiPath } from "@/utils/url.js";
import { fetchJSON, fetchURL } from "./utils";
export function get(property="") {
const path = getApiPath("settings", { property });
+2 -2
View File
@@ -1,6 +1,6 @@
import { fetchURL, fetchJSON, adjustedData } from "./utils";
import { notify } from "@/notify";
import { getApiPath, getPublicApiPath } from "@/utils/url.js";
import { adjustedData, fetchJSON, fetchURL } from "./utils";
// ============================================================================
@@ -28,7 +28,7 @@ export async function get(path, source) {
try {
const params = { path, source };
const apiPath = getApiPath("share", params);
let data = await fetchJSON(apiPath);
const data = await fetchJSON(apiPath);
return adjustedData(data);
} catch (/** @type {any} */ err) {
notify.showError(err.message || "Error fetching data");
+2 -2
View File
@@ -1,6 +1,6 @@
import { fetchURL } from "./utils";
import { notify } from "@/notify";
import { getApiPath } from "@/utils/url.js";
import { fetchURL } from "./utils";
// GET /api/tools/search
// extraParams: optional { olderThan, newerThan, useWildcard, terms, termJoin, perSourceScopes }
@@ -75,7 +75,7 @@ export async function search(base, sources, query, largest = false, extraParams
const apiPath = getApiPath("tools/search", params);
const res = await fetchURL(apiPath);
let data = await res.json();
const data = await res.json();
return data;
} catch (err) {
+14 -7
View File
@@ -19,7 +19,7 @@ export async function getAllUsers() {
// GET /api/users or /public/api/users (get single user)
export async function get(id) {
try {
let apiPath = getPublicApiPath('users', { id: id })
const apiPath = getPublicApiPath('users', { id: id })
return await fetchJSON(apiPath)
} catch (err) {
notify.showError(err.message || `Failed to fetch user with ID: ${id}`)
@@ -43,8 +43,7 @@ export async function create(user, options = {}) {
state.user?.loginMethod === 'password' &&
options.skipActorPasswordConfirm !== true &&
mergedHeaders['X-Password'] === undefined &&
err &&
err.status === 401 &&
err?.status === 401 &&
typeof err.message === 'string' &&
err.message.includes('X-Password')
@@ -124,8 +123,7 @@ export async function update(user, which = ['all'], options = {}) {
state.user?.loginMethod === 'password' &&
options.skipActorPasswordConfirm !== true &&
mergedHeaders['X-Password'] === undefined &&
err &&
err.status === 401 &&
err?.status === 401 &&
typeof err.message === 'string' &&
err.message.includes('X-Password')
@@ -168,6 +166,16 @@ export async function update(user, which = ['all'], options = {}) {
}
}
// PATCH /api/users/pinnedItems (add by default; ?action=remove to unpin)
export async function patchPinnedItem({ source, path, name, action = 'add' }) {
const params = { action }
const apiPath = getApiPath('users/pinnedItems', params)
await fetchURL(apiPath, {
method: 'PATCH',
body: JSON.stringify({ source, path, name }),
})
}
// DELETE /api/users (remove user)
// Password-login: tries without X-Password first; on 401 requiring X-Password, opens the prompt and retries.
// options.skipActorPasswordConfirm / pre-set X-Password skip that flow.
@@ -180,8 +188,7 @@ export async function remove(id, options = {}) {
state.user?.loginMethod === 'password' &&
options.skipActorPasswordConfirm !== true &&
mergedHeaders['X-Password'] === undefined &&
err &&
err.status === 401 &&
err?.status === 401 &&
typeof err.message === 'string' &&
err.message.includes('X-Password')
+9 -6
View File
@@ -1,12 +1,12 @@
import i18n from "@/i18n";
import { state } from "@/store";
import { renew } from "@/utils/auth";
import i18n from "@/i18n";
export async function fetchURL(url, opts, auth = true) {
opts = opts || {};
opts.headers = opts.headers || {};
let { headers, ...rest } = opts;
const { headers, ...rest } = opts;
let res;
try {
@@ -19,8 +19,8 @@ export async function fetchURL(url, opts, auth = true) {
...rest,
});
} catch (e) {
let message = e;
if (e == "TypeError: Failed to fetch") {
let message = e.message;
if (e instanceof TypeError && e.message === "Failed to fetch") {
message = i18n.global.t("errors.failedToConnectToServer");
}
const error = new Error(message);
@@ -33,7 +33,7 @@ export async function fetchURL(url, opts, auth = true) {
}
if (res.status < 200 || res.status > 299) {
let error = new Error(await res.text());
const error = new Error(await res.text());
error.status = res.status;
throw error;
}
@@ -52,6 +52,7 @@ export async function fetchJSON(url, opts) {
export function adjustedData(data) {
if (data.type === "directory") {
const pinnedNames = new Set(data.pinnedItems || []);
// Combine folders and files into items
data.items = [...(data.folders || []), ...(data.files || [])];
data.items = data.items.map((item) => {
@@ -59,7 +60,8 @@ export function adjustedData(data) {
if (item.isShared === undefined) {
item.isShared = false;
}
if (data.path == "/") {
item.pinned = pinnedNames.has(item.name);
if (data.path === "/") {
if (item.type === "directory") {
item.path = `/${item.name}/`
} else {
@@ -74,6 +76,7 @@ export function adjustedData(data) {
}
return item;
});
delete data.pinnedItems;
}
if (data.files) {
data.files = []
+28 -5
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
vi.mock('@/utils/constants', () => {
return {
@@ -54,10 +54,10 @@ describe('adjustedData', () => {
folders: [],
files: [],
items: [
{ isShared: false, name: "folder1", path: "/root/folder1/", source: undefined, type: "directory" },
{ isShared: false, name: "folder2", path: "/root/folder2/", source: undefined, type: "directory" },
{ isShared: false, name: "file1.txt", path: "/root/file1.txt", source: undefined, type: "file" },
{ isShared: false, name: "file2.txt", path: "/root/file2.txt", source: undefined, type: "file" },
{ isShared: false, name: "folder1", path: "/root/folder1/", source: undefined, type: "directory", pinned: false },
{ isShared: false, name: "folder2", path: "/root/folder2/", source: undefined, type: "directory", pinned: false },
{ isShared: false, name: "file1.txt", path: "/root/file1.txt", source: undefined, type: "file", pinned: false },
{ isShared: false, name: "file2.txt", path: "/root/file2.txt", source: undefined, type: "file", pinned: false },
],
path: "/root/",
};
@@ -105,5 +105,28 @@ describe('adjustedData', () => {
expect(adjustedData(input)).toEqual(expected);
});
it('marks items as pinned from directory pinnedItems names', () => {
const input = {
type: "directory",
path: "/",
pinnedItems: ["alpha.txt"],
folders: [{ name: "docs", type: "directory" }],
files: [
{ name: "alpha.txt", type: "file" },
{ name: "beta.txt", type: "file" },
],
source: "Docs",
};
const result = adjustedData(input);
expect(result.pinnedItems).toBeUndefined();
expect(result.items).toEqual([
{ isShared: false, name: "docs", path: "/docs/", source: "Docs", type: "directory", pinned: false },
{ isShared: false, name: "alpha.txt", path: "/alpha.txt", source: "Docs", type: "file", pinned: true },
{ isShared: false, name: "beta.txt", path: "/beta.txt", source: "Docs", type: "file", pinned: false },
]);
});
});
+19 -27
View File
@@ -1,6 +1,7 @@
<template>
<button
v-if="icon === 'close_back'"
type="button"
:disabled="isDisabled"
@click="actionMultiIcon"
:aria-label="label"
@@ -9,14 +10,15 @@
>
<svg
id="button-toggle-navbar"
class="ham hamRotate180 ham5"
viewBox="0 0 100 100"
width="30"
class="ham hamRotate180 ham5"
:class="{
back: multistate == 'back',
close: multistate == 'close',
back: multistate === 'back',
close: multistate === 'close',
}"
>
<title id="toggle-navbar-title">{{ $t('general.close') }}</title>
<path class="line top" d="M 30,33 H 70" />
<path class="line middle" d="M 30,50 H 70" />
<path class="line bottom" d="M 30,67 H 70" />
@@ -24,22 +26,21 @@
</button>
<button
v-else
type="button"
:disabled="isDisabled"
@click="action"
:aria-label="label"
:title="label"
class="action no-select"
@click="action"
>
<i v-if="icon == 'table_rows_narrow' || icon == 'content_copy' || icon == 'file_copy' || icon == 'copy_all'" class="material-symbols-outlined">{{ icon }}</i>
<i v-else class="material-symbols">{{ icon }}</i>
<i :class="iconClass">{{ icon }}</i>
<span>{{ label }}</span>
<span v-if="counter > 0" class="counter">{{ counter }}</span>
</button>
</template>
<script>
import { mutations, state, getters } from "@/store";
import { getters, mutations, state } from "@/store";
export default {
name: "action",
@@ -56,29 +57,20 @@ export default {
},
currentView() {
return getters.currentView();
}
},
mounted() {
this.reEvalAction();
},
watch: {
$route() {
this.reEvalAction();
},
req() {
this.reEvalAction();
},
currentView() {
this.reEvalAction();
iconClass() {
const outlinedIcons = [
'table_rows_narrow',
'content_copy',
'file_copy',
'copy_all'
];
return outlinedIcons.includes(this.icon)
? 'material-symbols-outlined'
: 'material-symbols';
},
},
methods: {
reEvalAction() {
const currentView = getters.currentView();
if (currentView == "settings") {
mutations.setActiveSettingsView(getters.currentHash());
}
},
actionMultiIcon() {
if (this.show) {
mutations.closeHovers();
+2 -1
View File
@@ -1,11 +1,12 @@
<template>
<div @click="preventDefaults" class="button-group">
<button v-if="isDisabled" disabled>
<button type="button" v-if="isDisabled" disabled>
{{ disableMessage }}
</button>
<template v-else>
<button
v-for="(btn, index) in buttons"
type="button"
:key="index"
class="clickable"
:class="{ active: activeButton === index }"
+75 -31
View File
@@ -9,7 +9,7 @@
id="context-menu"
ref="contextMenu"
v-if="showContext"
:style="centered ? {} : { top: posY + 'px', left: posX + 'px' }"
:style="centered ? {} : { top: `${posY}px`, left: `${posX}px` }"
class="no-select floating-window"
:class="{ 'dark-mode': isDarkMode, 'centered': centered }"
:key="showCreate ? 'create-mode' : 'normal-mode'"
@@ -76,7 +76,6 @@
:label="$t('general.info')"
@action="showInfoPrompt"
/>
<action
v-if="showDownload"
icon="file_download"
@@ -95,6 +94,12 @@
:label="$t('general.share')"
@action="showSharePrompt"
/>
<action
v-if="showPinAction"
icon="push_pin"
:label="pinActionLabel"
@action="togglePin"
/>
<action
v-if="showRename"
icon="edit"
@@ -190,15 +195,15 @@
</template>
<script>
import downloadFiles from "@/utils/download";
import { state, getters, mutations } from "@/store";
import { resourcesApi, usersApi } from "@/api";
import Action from "@/components/Action.vue";
import { globalVars } from "@/utils/constants.js";
import buttons from "@/utils/buttons";
import { notify } from "@/notify";
import { resourcesApi } from "@/api";
import { getters, mutations, state } from "@/store";
import { url } from "@/utils";
import buttons from "@/utils/buttons";
import { copyToClipboard } from "@/utils/clipboard";
import { globalVars } from "@/utils/constants.js";
import downloadFiles from "@/utils/download";
function isArchivePath(pathOrName) {
if (!pathOrName || typeof pathOrName !== "string") return false;
@@ -263,7 +268,7 @@ export default {
return this.hasDownload && !this.req.isDir && !this.isShare;
},
showGoToItem() {
return this.showLimitedOptions && this.selectedCount == 1;
return this.showLimitedOptions && this.selectedCount === 1;
},
permissions() {
return getters.permissions();
@@ -290,8 +295,8 @@ export default {
return getters.isShare();
},
showInfo() {
if (this.showLimitedOptions) return this.selectedCount == 1;
return !this.showCreate && this.selectedCount == 1;
if (this.showLimitedOptions) return this.selectedCount === 1;
return !this.showCreate && this.selectedCount === 1;
},
showDownload() {
if (this.showLimitedOptions) return false;
@@ -325,7 +330,20 @@ export default {
},
showRename() {
if (this.showLimitedOptions) return false;
return !this.showCreate && this.selectedCount == 1 && this.permissions.modify && !this.isSearchActive;
return !this.showCreate && this.selectedCount === 1 && this.permissions.modify && !this.isSearchActive;
},
showPinAction() {
if (this.showLimitedOptions) return false;
if (getters.isShare() || !getters.isLoggedIn()) return false;
if (this.showCreate || this.isSearchActive) return false;
if (this.selectedCount !== 1) return false;
return getters.currentView() === "listingView";
},
pinActionLabel() {
return this.isPinnedSelection ? this.$t("buttons.unpinItem") : this.$t("buttons.pinItem");
},
isPinnedSelection() {
return !!this.firstSelected?.pinned;
},
showCopy() {
if (this.showLimitedOptions) return false;
@@ -333,10 +351,10 @@ export default {
},
showCopyPath() {
if (this.showLimitedOptions) return false;
return !this.showCreate && this.selectedCount == 1 && !!state.user?.showCopyPath;
return !this.showCreate && this.selectedCount === 1 && !!state.user?.showCopyPath;
},
showOpenParentFolder() {
return !this.showCreate && this.selectedCount == 1 && (this.isSearchActive || this.showLimitedOptions);
return !this.showCreate && this.selectedCount === 1 && (this.isSearchActive || this.showLimitedOptions);
},
showMove() {
if (this.showLimitedOptions) return false;
@@ -384,20 +402,20 @@ export default {
return false;
}
const cv = getters.currentView();
return cv == "preview" || cv == "markdownViewer" || cv == "editor";
return cv === "preview" || cv === "markdownViewer" || cv === "editor";
},
showEdit() {
const cv = getters.currentView();
return cv == "markdownViewer" && this.permissions.modify;
return cv === "markdownViewer" && this.permissions.modify;
},
showDelete() {
if (this.showLimitedOptions) return false;
if (this.selectedCount == 0) {
if (this.selectedCount === 0) {
return false;
}
const cv = getters.currentView();
return (
cv != "settings" &&
cv !== "settings" &&
!this.isSearchActive &&
!!this.permissions.delete
);
@@ -410,10 +428,10 @@ export default {
},
showSave() {
const allowEdit = this.permissions.modify || (getters.isShare() && state.shareInfo.allowEdit);
return getters.currentView() == "editor" && allowEdit;
return getters.currentView() === "editor" && allowEdit;
},
showOverflow() {
return getters.currentPromptName() == "OverflowMenu";
return getters.currentPromptName() === "OverflowMenu";
},
showAccess() {
if (this.showLimitedOptions) return false;
@@ -432,7 +450,7 @@ export default {
return this.permissions.share;
},
showContext() {
return getters.currentPromptName() == "ContextMenu";
return getters.currentPromptName() === "ContextMenu";
},
onlyofficeEnabled() {
return globalVars.onlyOfficeUrl !== "";
@@ -506,7 +524,7 @@ export default {
},
goToItem() {
const item = this.firstSelected;
url.goToItem(item.source, item.path, {}, true);
url.goToItem(item.source, item.path, {}, true, getters.isShare());
mutations.closeHovers();
},
hideTooltip() {
@@ -535,13 +553,13 @@ export default {
this.showCreate = !this.showCreate;
},
shouldShowParentFolder() {
return this.isPreview && state.req.path != "/";
return this.isPreview && state.req.path !== "/";
},
showAccessPrompt() {
mutations.closeHovers();
const item = this.firstSelected;
let sourceName = item?.source || state.req.source;
let path = item?.path || state.req.path;
const sourceName = item?.source || state.req.source;
const path = item?.path || state.req.path;
mutations.showPrompt({
name: "access",
props: {
@@ -592,7 +610,7 @@ export default {
el.style.transition = 'height 0.3s, opacity 0.3s';
void el.offsetHeight; // Force reflow
// Animate to full height
el.style.height = fullHeight + 'px';
el.style.height = `${fullHeight}px`;
el.style.opacity = '1';
setTimeout(() => {
this.isAnimating = false;
@@ -603,7 +621,7 @@ export default {
leave(el, done) {
this.isAnimating = true;
el.style.transition = 'height 0.3s, opacity 0.3s';
el.style.height = el.scrollHeight + 'px';
el.style.height = `${el.scrollHeight}px`;
void el.offsetHeight;
el.style.height = '0';
el.style.opacity = '0';
@@ -626,7 +644,7 @@ export default {
mutations.showPrompt({
name: "share",
props: {
item: this.selectedCount == 1 ? this.firstSelected : state.req
item: this.selectedCount === 1 ? this.firstSelected : state.req
},
});
},
@@ -635,7 +653,7 @@ export default {
mutations.showPrompt({
name: "rename",
props: {
item: this.selectedCount == 1 ? this.firstSelected : state.req,
item: this.selectedCount === 1 ? this.firstSelected : state.req,
parentItems: []
},
});
@@ -703,6 +721,32 @@ export default {
},
});
},
async togglePin() {
const item = this.firstSelected;
if (!item?.name || getters.isShare() || !getters.isLoggedIn()) {
return;
}
mutations.closeHovers();
const source = item.source || state.req?.source || state.sources.current;
if (!source) {
return;
}
const directoryPath = state.req?.type === "directory"
? state.req.path
: url.getParentDir(item.path);
const action = item.pinned ? "remove" : "add";
try {
await usersApi.patchPinnedItem({
source,
path: directoryPath,
name: item.name,
action,
});
mutations.setReload(true);
} catch (e) {
notify.showError(e);
}
},
async copyPathToClipboard() {
const item = this.firstSelected;
const path = item?.path || "";
@@ -715,7 +759,7 @@ export default {
// If the context menu was triggered on a directory, pass its path as base
const selectedItem = this.firstSelected;
let base = null;
if (selectedItem && selectedItem.isDir) {
if (selectedItem?.isDir) {
// Pass both path and source
base = {
path: selectedItem.path,
@@ -813,7 +857,7 @@ export default {
}
buttons.success(button);
notify.showSuccessToast(this.$t("editor.fileSaved"));
} catch (e) {
} catch (_e) {
// Don't show error notification here - API layer already showed it
buttons.done(button);
}
@@ -824,7 +868,7 @@ export default {
let targetPath = state.req.path;
let targetSource = state.req.source;
const selectedItem = this.firstSelected;
if (selectedItem && selectedItem.isDir) {
if (selectedItem?.isDir) {
targetPath = selectedItem.path;
targetSource = selectedItem.source;
}
+15 -98
View File
@@ -5,18 +5,8 @@
v-for="notification in notifications"
:key="notification.id"
:class="['notification-item', notification.type]"
@mousedown="startDrag($event, notification.id)"
@touchstart="startDrag($event, notification.id)"
@mousemove="handleDrag($event, notification.id)"
@touchmove="handleDrag($event, notification.id)"
@mouseup="endDrag(notification.id)"
@touchend="endDrag(notification.id)"
@mouseenter="pauseAutoClose(notification.id)"
@mouseleave="handleMouseLeave(notification.id)"
:style="{
transform: `translateX(${notification.dragOffset || 0}px)`,
opacity: notification.dragOpacity !== undefined ? notification.dragOpacity : 1
}"
@mouseleave="resumeAutoClose(notification.id)"
>
<!-- Close button - always present on every notification, separate from optional buttons array -->
<i class="material-symbols" @click="closeNotification(notification.id)">close</i>
@@ -29,6 +19,7 @@
</div>
<div v-if="notification.buttons && notification.buttons.length > 0" class="notification-buttons">
<button
type="button"
v-for="(button, btnIndex) in notification.buttons"
:key="btnIndex"
:class="['button', button.className]"
@@ -62,35 +53,15 @@ import { notify } from "@/notify";
export default {
name: "notifications",
data: function () {
return {
notifications: [],
dragState: {
isDragging: false,
startX: 0,
currentX: 0,
notificationId: null
}
};
},
data: () => ({
notifications: []
}),
mounted() {
// Initialize notifications with drag state
this.notifications = notify.getNotifications().map(notification => ({
...notification,
dragOffset: 0,
dragOpacity: 1
}));
// Initialize notifications
this.notifications = notify.getNotifications();
// Register callback to receive notification updates
notify.setUpdateCallback((notifications) => {
this.notifications = notifications.map(notification => {
// Find existing notification to preserve drag state
const existing = this.notifications.find(n => n.id === notification.id);
return {
...notification,
dragOffset: existing?.dragOffset,
dragOpacity: existing?.dragOpacity !== undefined ? existing.dragOpacity : 1
};
});
this.notifications = notifications;
});
},
methods: {
@@ -105,66 +76,6 @@ export default {
button.action();
}
},
startDrag(event, notificationId) {
const clientX = event.type.includes('touch') ? event.touches[0].clientX : event.clientX;
this.dragState = {
isDragging: true,
startX: clientX,
currentX: clientX,
notificationId: notificationId
};
},
handleDrag(event, notificationId) {
if (!this.dragState.isDragging || this.dragState.notificationId !== notificationId) {
return;
}
event.preventDefault();
const clientX = event.type.includes('touch') ? event.touches[0].clientX : event.clientX;
this.dragState.currentX = clientX;
const deltaX = clientX - this.dragState.startX;
// Allow dragging in both directions (left and right)
const dragOffset = deltaX;
const absoluteDeltaX = Math.abs(deltaX);
const dragOpacity = Math.max(0.4, 1 - (absoluteDeltaX / 150));
// Update the notification position and opacity
const notificationIndex = this.notifications.findIndex(n => n.id === notificationId);
if (notificationIndex !== -1) {
this.notifications[notificationIndex].dragOffset = dragOffset;
this.notifications[notificationIndex].dragOpacity = dragOpacity;
}
},
endDrag(notificationId) {
if (!this.dragState.isDragging || this.dragState.notificationId !== notificationId) {
return;
}
const deltaX = this.dragState.currentX - this.dragState.startX;
const absoluteDeltaX = Math.abs(deltaX);
const notificationIndex = this.notifications.findIndex(n => n.id === notificationId);
if (notificationIndex !== -1) {
// Check if drag distance is enought to close the notification (120px or 25% of screen width)
const threshold = Math.min(120, window.innerWidth * 0.25);
if (absoluteDeltaX > threshold) {
// If the swipe is enought, close
this.closeNotification(notificationId);
} else {
// If not, returnt it back to the original position
this.notifications[notificationIndex].dragOffset = 0;
this.notifications[notificationIndex].dragOpacity = 1;
}
}
// Reset drag state
this.dragState = {
isDragging: false,
startX: 0,
currentX: 0,
notificationId: null
};
},
// Handle mouse leave for both drag and auto-close
handleMouseLeave(notificationId) {
this.endDrag(notificationId);
this.resumeAutoClose(notificationId);
},
// Hover persistence methods
pauseAutoClose(notificationId) {
notify.pauseAutoClose(notificationId);
@@ -207,10 +118,16 @@ export default {
transition: right 1s ease;
z-index: 21;
pointer-events: all;
user-select: none;
user-select: text;
overflow: hidden;
}
/* selection color for better visibility (since the selection color is the same as --primaryColor) */
.notification-item ::selection {
background: rgba(255, 255, 255, 0.8);
color: #000;
}
.notification-content-wrapper {
flex: 1;
display: flex;
+51 -47
View File
@@ -6,7 +6,7 @@ https://raw.githubusercontent.com/dzwillia/vue-simple-progress/master/src/compon
<div
class="vue-simple-progress-text"
:style="text_style"
v-if="textPosition == 'middle'"
v-if="textPosition === 'middle'"
>
{{ displayed_text }}
</div>
@@ -16,7 +16,7 @@ https://raw.githubusercontent.com/dzwillia/vue-simple-progress/master/src/compon
<div
class="vue-simple-progress-text"
:style="text_style"
v-if="textPosition == 'inside'"
v-if="textPosition === 'inside'"
>
{{ displayed_text }}
<i
@@ -32,12 +32,16 @@ https://raw.githubusercontent.com/dzwillia/vue-simple-progress/master/src/compon
</template>
<script>
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
import { mutations } from "@/store";
import { getHumanReadableFilesize } from "@/utils/filesizes.js";
// We're leaving this untouched as you can read in the beginning
var isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
const isNumber = (n) => {
const num = Number(n);
// Since 'isNaN' nd 'isFinite' are marked as unsafe. We need to do this
// to still matching the old behavior (the styling).
if (num === 0 && (n === null || n === '' || n === false)) return true;
return !Number.isNaN(num) && Number.isFinite(num);
};
export default {
@@ -120,14 +124,14 @@ export default {
pct() {
if (!this.isValNumeric) return 100;
if (this.max <= 0) return 0;
var pct = (this.val / this.max) * 100;
const pct = (this.val / this.max) * 100;
return Math.max(0, Math.min(pct.toFixed(2), 100));
},
pctBackground() {
if (this.valBackground === null) return 0;
if (!isNumber(this.valBackground)) return 0;
if (this.max <= 0) return 0;
var pct = (this.valBackground / this.max) * 100;
const pct = (this.valBackground / this.max) * 100;
return Math.max(0, Math.min(pct.toFixed(2), 100));
},
displayed_text() {
@@ -197,21 +201,21 @@ export default {
return isNumber(this.fontSize) ? this.fontSize : 13;
},
progress_style() {
var style = {
const style = {
background: this.bgColor,
position: 'relative'
};
if (this.status === 'indexing') {
style['background'] = '#fff8d6'; // Muted yellow/amber color
style.background = '#fff8d6'; // Muted yellow/amber color
}
if (this.textPosition == "middle" || this.textPosition == "inside") {
style["min-height"] = this.size_px + "px";
if (this.textPosition === "middle" || this.textPosition === "inside") {
style.minHeight = `${this.size_px}px`;
}
if (this.barBorderRadius > 0) {
style["border-radius"] = this.barBorderRadius + "px";
style.borderRadius = `${this.barBorderRadius}px`;
}
return style;
@@ -230,32 +234,32 @@ export default {
if (percentage < 1) {
percentage = 0;
}
var style = {
width: percentage + "%",
height: this.size_px + "px",
const style = {
width: `${percentage}%`,
height: `${this.size_px}px`,
background: barColor,
transition: this.barTransition,
position: this.valBackground !== null ? 'relative' : undefined,
"z-index": this.valBackground !== null ? 1 : undefined,
zIndex: this.valBackground !== null ? 1 : undefined,
};
// Add pulse animation for indexing status
if (this.status === 'indexing') {
style['animation'] = 'progress-pulse 4s ease-in-out infinite';
style['background'] = 'rgb(237 161 41)'; // orange
style.animation = 'progress-pulse 4s ease-in-out infinite';
style.background = 'rgb(237 161 41)'; // orange
}
if (this.barBorderRadius > 0) {
style["border-radius"] = this.barBorderRadius + "px";
style.borderRadius = `${this.barBorderRadius}px`;
}
if (this.textPosition == "middle") {
style["position"] = "absolute";
style["top"] = "0";
style["height"] = "100%";
style["min-width"] = "1.5em";
style["min-height"] = this.size_px + "px";
style["z-index"] = "-1";
if (this.textPosition === "middle") {
style.position = 'absolute';
style.top = '0';
style.height = '100%';
style.minWidth = '1.5em';
style.minHeight = `${this.size_px}px`;
style.zIndex = '-1';
}
return style;
@@ -265,9 +269,9 @@ export default {
if (percentage < 1) {
percentage = 0;
}
var style = {
width: percentage + "%",
height: this.size_px + "px",
const style = {
width: `${percentage}%`,
height: `${this.size_px}px`,
background: '#9e9e9e',
transition: this.barTransition,
position: 'absolute',
@@ -276,40 +280,40 @@ export default {
};
if (this.barBorderRadius > 0) {
style["border-radius"] = this.barBorderRadius + "px";
style.borderRadius = `${this.barBorderRadius}px`;
}
return style;
},
text_style() {
var style = {
const style = {
"color": this.textFgColor,
"font-size": this.text_font_size + "px",
"font-size": `${this.text_font_size}px`,
"text-align": this.textAlign,
};
if (this.textPosition === 'inside') {
style['position'] = 'absolute';
style['left'] = '0';
style['right'] = '0';
style['top'] = '50%';
style['transform'] = 'translateY(-50%)';
style['width'] = '100%';
style['padding'] = '0 0.5em';
style['box-sizing'] = 'border-box';
style['z-index'] = this.valBackground !== null ? 2 : undefined;
style.position = 'absolute';
style.left = '0';
style.right = '0';
style.top = '50%';
style.transform = 'translateY(-50%)';
style.width = '100%';
style.padding = '0 0.5em';
style.boxSizing = 'border-box';
style.zIndex = this.valBackground !== null ? 2 : undefined;
}
if (
this.textPosition == "top" ||
this.textPosition == "middle"
this.textPosition === "top" ||
this.textPosition === "middle"
)
style["padding-bottom"] = this.text_padding + "px";
style.paddingBottom = `${this.text_padding}px`;
if (
this.textPosition == "bottom" ||
this.textPosition == "middle"
this.textPosition === "bottom" ||
this.textPosition === "middle"
)
style["padding-top"] = this.text_padding + "px";
style.paddingTop = `${this.text_padding}px`;
return style;
},
},
+35 -42
View File
@@ -3,7 +3,7 @@
<!-- Search input section -->
<div class="search-input-container">
<!-- Close button visible when search is active -->
<button v-if="active" class="action" @click="close" :aria-label="$t('general.close')"
<button v-if="active" type="button" class="action" @click="close" :aria-label="$t('general.close')"
:title="$t('general.close')">
<i class="material-symbols">close</i>
</button>
@@ -109,7 +109,7 @@
:hasPreview="showPreviewImages && (s.hasPreview || false)"
:thumbnailUrl="showPreviewImages ? getThumbnailUrl(s) : ''" />
<span class="text-container">
{{ basePath(s.path, s.type == "directory") }}{{ baseName(s.path) }}
{{ basePath(s.path, s.type === "directory") }}{{ baseName(s.path) }}
<!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</span>
<div class="filesize">{{ humanSize(s.size) }}</div>
@@ -130,20 +130,20 @@
</template>
<script>
import ButtonGroup from "./ButtonGroup.vue";
import { toolsApi, resourcesApi } from "@/api";
import { getters, mutations, state } from "@/store";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { url } from "@/utils/";
import { resourcesApi, toolsApi } from "@/api";
import Icon from "@/components/files/Icon.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import SettingsItem from "@/components/settings/SettingsItem.vue";
import { globalVars } from "@/utils/constants";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import { utcStartOfDaySecondsFromDateInput } from "@/utils/moment";
import SettingsItem from "@/components/settings/SettingsItem.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import router from "@/router";
import { getters, mutations, state } from "@/store";
import { url } from "@/utils/";
import { globalVars } from "@/utils/constants";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { utcStartOfDaySecondsFromDateInput } from "@/utils/moment";
import ButtonGroup from "./ButtonGroup.vue";
var boxes = {
const boxes = {
folder: { label: "folders", icon: "folder" },
file: { label: "files", icon: "insert_drive_file" },
archive: { label: "archives", icon: "archive" },
@@ -293,7 +293,7 @@ export default {
return getters.isDarkMode();
},
showBoxes() {
return this.searchTypes == "";
return this.searchTypes === "";
},
boxes() {
return boxes;
@@ -322,7 +322,7 @@ export default {
// Construct the same full path as addSelected does
const context = url.removeTrailingSlash(this.getContext);
const pathStr = url.removeLeadingSlash(url.removeTrailingSlash(result.path));
const fullPath = context + '/' + pathStr;
const fullPath = `${context}/${pathStr}`;
return selectedPaths.has(fullPath);
});
},
@@ -340,7 +340,7 @@ export default {
if (this.selectedSource === "__all__" || (this.selectedSource === "" && this.multipleSources)) {
return "/";
}
let result = url.extractSourceFromPath(decodeURIComponent(state.route.path));
const result = url.extractSourceFromPath(decodeURIComponent(state.route.path));
if (this.selectedSource === "" || result.source === this.selectedSource) {
return result.path;
} else {
@@ -412,7 +412,7 @@ export default {
// Ensure exactly one slash between context and path
const context = url.removeTrailingSlash(this.getContext);
const path = url.removeLeadingSlash(url.removeTrailingSlash(s.path));
const fullPath = context + '/' + path;
const fullPath = `${context}/${path}`;
return url.buildItemUrl(source, fullPath, true);
},
humanSize(size) {
@@ -423,11 +423,11 @@ export default {
if (!isDir) {
result = url.removeLeadingSlash(result); // fix weird rtl thing
}
return result + "/";
return `${result}/`;
},
baseName(str) {
let parts = url.removeTrailingSlash(str).split("/");
let part = parts.pop();
const parts = url.removeTrailingSlash(str).split("/");
const part = parts.pop();
return part;
},
/** Clear query state whenever the overlay opens (open paths do not always call close()). */
@@ -449,16 +449,15 @@ export default {
this.close(event);
return;
}
this.results.length === 0;
},
addToTypes(string) {
if (this.searchTypes.includes(string)) {
return true;
}
if (string == null || string == "") {
if (string === null || string === "") {
return false;
}
this.searchTypes = this.searchTypes + string + " ";
this.searchTypes = `${this.searchTypes + string} `;
},
resetSearchFilters() {
this.searchTypes = "";
@@ -466,10 +465,10 @@ export default {
this.showPreviewImages = false;
},
removeFromTypes(string) {
if (string == null || string == "") {
if (string === null || string === "") {
return false;
}
this.searchTypes = this.searchTypes.replaceAll(string + " ", "");
this.searchTypes = this.searchTypes.replaceAll(`${string} `, "");
if (state.isMobile) {
this.$refs.input.focus();
}
@@ -482,7 +481,7 @@ export default {
},
async submit(event) {
this.results = [];
if (event != undefined) {
if (event !== undefined) {
event.preventDefault();
}
if (this.value === "" || this.value.length < globalVars.minSearchLength) {
@@ -490,11 +489,11 @@ export default {
return;
}
let searchTypesFull = this.searchTypes;
if (this.largerThan != "") {
searchTypesFull = searchTypesFull + "type:largerThan=" + this.largerThan + " ";
if (this.largerThan !== "") {
searchTypesFull = `${searchTypesFull}type:largerThan=${this.largerThan} `;
}
if (this.smallerThan != "") {
searchTypesFull = searchTypesFull + "type:smallerThan=" + this.smallerThan + " ";
if (this.smallerThan !== "") {
searchTypesFull = `${searchTypesFull}type:smallerThan=${this.smallerThan} `;
}
const dateParams = {};
const olderUnix = utcStartOfDaySecondsFromDateInput(this.modifiedOlderThan);
@@ -511,7 +510,7 @@ export default {
this.ongoing++;
// Determine which sources to search
let sourcesToSearch = [];
let sourcesToSearch;
if (this.selectedSource === "__all__" || this.selectedSource === "") {
// Search all sources
sourcesToSearch = Object.keys(this.sourceInfo);
@@ -532,7 +531,7 @@ export default {
);
this.ongoing--;
if (this.results.length == 0 && this.ongoing == 0) {
if (this.results.length === 0 && this.ongoing === 0) {
this.noneMessage = this.$t("search.noResults");
}
},
@@ -561,10 +560,10 @@ export default {
// Ensure exactly one slash between context and path
const context = url.removeTrailingSlash(this.getContext);
const path = url.removeLeadingSlash(url.removeTrailingSlash(s.path));
const fullPath = context + '/' + path;
const fullPath = `${context}/${path}`;
const modified = s.modified || "";
return resourcesApi.getPreviewURL(source, fullPath, modified);
} catch (err) {
} catch (_err) {
return "";
}
},
@@ -589,7 +588,7 @@ export default {
});
},
openInAdvancedSearch() {
let sourcesToSearch = [];
let sourcesToSearch;
if (this.selectedSource === "__all__" || this.selectedSource === "") {
sourcesToSearch = Object.keys(this.sourceInfo || {});
} else {
@@ -663,7 +662,7 @@ export default {
// Combine context (scope) with the result path - ensure exactly one slash between
const context = url.removeTrailingSlash(this.getContext);
const pathStr = url.removeLeadingSlash(url.removeTrailingSlash(s.path));
let path = context + '/' + pathStr;
const path = `${context}/${pathStr}`;
const modifiedItem = {
name: pathParts.pop(),
path: path,
@@ -746,11 +745,7 @@ export default {
-webkit-animation: SlideDown 0.5s forwards;
animation: SlideDown 0.5s forwards;
border-radius: 1em;
max-height: 100%;
border-top: none;
border-top-width: initial;
border-top-style: none;
border-top-color: initial;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border: 2px solid var(--surfaceSecondary);
@@ -799,7 +794,6 @@ export default {
.search-input-container {
background-color: rgba(100, 100, 100, 0.2);
display: flex;
height: 100%;
padding: 0.5em 0.75em;
border-radius: 1em;
border-style: unset;
@@ -910,8 +904,7 @@ export default {
text-align: left;
color: rgba(0, 0, 0, 0.6);
height: 0;
transition: 2s ease height, 2s ease padding;
transition: 2s ease width, 2s ease padding;
transition: 2s ease height, 2s ease padding, 2s ease width, 2s ease padding;
z-index: 3;
}
+3 -3
View File
@@ -23,7 +23,7 @@
import Breadcrumbs from "@/components/files/Breadcrumbs.vue";
import ListingHeader from "@/components/files/ListingHeader.vue";
import DuplicateFinderActions from "@/components/tools/DuplicateFinderActions.vue";
import { state, getters } from "@/store";
import { getters, state } from "@/store";
import { eventBus } from "@/store/eventBus";
export default {
@@ -78,7 +78,7 @@ export default {
// Check if any file has duration metadata
if (!state.req?.items) return false;
return state.req.items.some(item =>
item.type !== 'directory' && item.metadata && item.metadata.duration
item.type !== 'directory' && item.metadata?.duration
);
},
showDuplicateFinderActions() {
@@ -88,7 +88,7 @@ export default {
moveWithSidebar() {
if (getters.isStickySidebar() && getters.isSidebarVisible()) {
return {
left: state.sidebar.width + 'em',
left: `${state.sidebar.width}em`,
};
}
return {};
+12 -14
View File
@@ -44,7 +44,7 @@
</template>
<script>
import { state, getters, mutations } from "@/store";
import { getters, mutations, state } from "@/store";
import { getHumanReadableFilesize } from "@/utils/filesizes";
export default {
@@ -93,7 +93,7 @@ export default {
state.selected.forEach(index => {
if (index >= 0 && index < state.req.items.length) {
const item = state.req.items[index];
if (item && item.size) {
if (item?.size) {
total += item.size;
}
}
@@ -133,29 +133,27 @@ export default {
if (dirs === 0 && files === 0) {
return this.$t('files.lonely');
}
let parts = [];
const parts = [];
if (dirs > 0) parts.push(`${dirs} ${this.foldersLabel}`);
if (files > 0) parts.push(`${files} ${this.filesLabel}`);
return parts.join(' | ') + ' ' + sizeText;
return `${parts.join(' | ')} ${sizeText}`;
},
moveWithSidebar() {
if (getters.isStickySidebar() && getters.isSidebarVisible()) {
return {
left: state.sidebar.width + 'em',
left: `${state.sidebar.width}em`,
};
}
return {};
},
editorStatsText() {
const { lines, words, chars } = state.editorStats;
return [
[words, chars]
.map((v, i) => v != null && this.$t(i === 0 ? 'editor.words' : 'editor.chars', { count: v }))
.filter(Boolean)
.join(', '),
lines != null && this.$t('editor.lines', { count: lines })
].filter(Boolean).join(' | ');
const parts = [];
if (words !== null) parts.push(this.$t('editor.words', { count: words }));
if (chars !== null) parts.push(this.$t('editor.chars', { count: chars }));
if (lines !== null) parts.push(this.$t('editor.lines', { count: lines }));
return parts.join(' | ');
},
editorFontSize: {
get() {
@@ -220,7 +218,7 @@ export default {
const advSearch = (state.route?.path || "").startsWith("/tools/advancedSearch");
if (this.currentView === "listingView" || advSearch) {
event.preventDefault();
let newSize = Math.min(9, Math.max(1, this.gallerySize - delta));
const newSize = Math.min(9, Math.max(1, this.gallerySize - delta));
if (newSize !== this.gallerySize) {
this.gallerySize = newSize;
mutations.setGallerySize(newSize);
@@ -228,7 +226,7 @@ export default {
}
} else if (this.currentView === 'editor') {
event.preventDefault();
let newSize = Math.min(24, Math.max(8, this.editorFontSize - delta));
const newSize = Math.min(24, Math.max(8, this.editorFontSize - delta));
if (newSize !== this.editorFontSize) {
this.editorFontSize = newSize;
}
+27 -12
View File
@@ -3,14 +3,24 @@
ref="tooltipRef"
v-show="tooltip.show"
class="floating-tooltip floating-window"
:class="{ 'dark-mode': isDarkMode, 'pointer-enabled': tooltip.pointerEvents }"
:class="{
'dark-mode': isDarkMode,
'pointer-enabled': tooltip.pointerEvents,
'floating-tooltip--component': hasComponent,
}"
:style="tooltipStyle"
v-html="tooltip.content"
></div>
>
<component
v-if="hasComponent"
:is="tooltip.component"
v-bind="tooltip.componentProps || {}"
/>
<div v-else v-html="tooltip.content"></div>
</div>
</template>
<script>
import { state,getters } from "@/store";
import { getters, mutations, state } from "@/store";
export default {
name: "Tooltip",
@@ -25,6 +35,9 @@ export default {
tooltip() {
return state.tooltip;
},
hasComponent() {
return Boolean(this.tooltip.component);
},
isDarkMode() {
return getters.isDarkMode();
},
@@ -34,16 +47,14 @@ export default {
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';
style.maxHeight = "80vh";
style.overflowY = "auto";
}
return style;
@@ -52,9 +63,7 @@ export default {
watch: {
$route: {
handler() {
// hide tooltip when route changes
this.tooltip.show = false;
this.tooltip.content = "";
mutations.hideTooltip();
},
},
tooltip: {
@@ -121,6 +130,12 @@ export default {
overflow-wrap: break-word;
}
.floating-tooltip--component {
padding: 0;
max-width: min(28em, 90vw);
white-space: normal;
}
.floating-tooltip.pointer-enabled {
pointer-events: auto;
cursor: auto;
@@ -135,4 +150,4 @@ export default {
padding: 0.1em !important;
padding-left: 0.5em !important;
}
</style>
</style>
+2 -1
View File
@@ -28,6 +28,7 @@
<!-- Lock button -->
<button
v-if="lyrics.length && syncedLyrics"
type="button"
class="lyrics-lock-btn"
@click="lyricsScrollLocked = !lyricsScrollLocked"
:title="lyricsScrollLocked ? $t('player.unlockLyrics') : $t('player.lockLyrics')"
@@ -46,7 +47,7 @@
@click.stop="syncedLyrics && $emit('seek', line.timestamp)"
:role="syncedLyrics ? 'button' : undefined"
:tabindex="syncedLyrics ? 0 : undefined"
:aria-label="syncedLyrics ? 'Seek to ' + line.text : undefined"
:aria-label="syncedLyrics ? `Seek to ${line.text}` : undefined"
>
{{ line.text }}
</p>
+13 -13
View File
@@ -14,7 +14,7 @@
<li class="item" v-for="(link, index) in items" :key="index">
<router-link
:to="link.url"
:aria-label="'breadcrumb-link-' + link.name"
:aria-label="`breadcrumb-link-${link.name}`"
:title="link.name"
:key="index"
:class="{ changeAvailable: hasUpdate,
@@ -32,10 +32,10 @@
</template>
<script>
import { state, getters, mutations } from "@/store";
import { url } from "@/utils";
import { resourcesApi } from "@/api";
import { notify } from "@/notify";
import { getters, mutations, state } from "@/store";
import { url } from "@/utils";
export default {
name: "breadcrumbs",
@@ -88,9 +88,9 @@ export default {
if (!req.items || !req.path) {
return [];
}
let encodedPathString = url.encodedPath(state.req.path);
let originalParts = state.req.path.split("/");
let encodedParts = encodedPathString.split("/");
const encodedPathString = url.encodedPath(state.req.path);
const originalParts = state.req.path.split("/");
const encodedParts = encodedPathString.split("/");
// Remove empty strings from both arrays consistently
if (originalParts[0] === "") {
originalParts.shift();
@@ -100,14 +100,14 @@ export default {
originalParts.pop();
encodedParts.pop();
}
let breadcrumbs = [];
const breadcrumbs = [];
let buildRef = this.base;
let accumulatedPath = "";
for (let i = 0; i < originalParts.length; i++) {
const origPart = originalParts[i];
const encodedElement = encodedParts[i];
buildRef = buildRef + encodedElement + "/";
buildRef = `${buildRef + encodedElement}/`;
accumulatedPath = accumulatedPath ? `${accumulatedPath}/${origPart}` : origPart;
breadcrumbs.push({
@@ -207,7 +207,7 @@ export default {
// Build list of items to move from selected items
let itemsToMove = [];
for (let i of state.selected) {
for (const i of state.selected) {
if (i < 0 || i >= state.req.length) continue;
const selectedItem = state.req.items[i];
@@ -238,7 +238,7 @@ export default {
const toDir = normalizePath(item.to);
// Check if destination is inside the directory
if (toDir.startsWith(fromDir + "/")) {
if (toDir.startsWith(`${fromDir}/`)) {
return false;
}
}
@@ -255,7 +255,7 @@ export default {
const response = await resourcesApi.fetchFiles(source, targetPath);
targetDirItems = response?.items;
}
} catch (error) {
} catch (_e) {
notify.showError(this.$t("files.cannotAccesDir"));
return;
}
@@ -280,7 +280,7 @@ export default {
}
const buttonAction = () => {
url.goToItem(source, targetPath, {});
url.goToItem(source, targetPath, {}, false, getters.isShare());
};
notify.showSuccess(this.$t("prompts.moveSuccess"), {
@@ -293,7 +293,7 @@ export default {
});
mutations.closeTopPrompt();
mutations.setReload(true);
} catch (error) {
} catch (_e) {
mutations.closeTopPrompt();
notify.showError(this.$t("prompts.moveFailed"));
}
Loaded 100 of 305 files, more files were not shown because too many files have changed in this diff. Show more