mirror of
https://github.com/gtsteffaniak/filebrowser.git
synced 2026-11-25 16:09:41 -05:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6deb9b8ab | ||
|
|
215a3fd858 | ||
|
|
9c5df98b79 | ||
|
|
0382bec1cd | ||
|
|
532632de1c | ||
|
|
6c72d1b85f | ||
|
|
f4587d8ef3 | ||
|
|
3db63bd44c | ||
|
|
708a40b788 | ||
|
|
fa40a7472d | ||
|
|
548221c28c | ||
|
|
77d3ab9554 | ||
|
|
e2f27d1391 | ||
|
|
a8f2477879 | ||
|
|
d70ed3d806 | ||
|
|
786cabb666 | ||
|
|
d36c0bf8f9 | ||
|
|
8f78112a94 | ||
|
|
a4d20c8101 | ||
|
|
d0f5cc3593 | ||
|
|
e8c8ea2454 | ||
|
|
08fc72de8c | ||
|
|
09bfc919d6 | ||
|
|
ad13b56d7f | ||
|
|
6aae66551b | ||
|
|
ff72ca3061 | ||
|
|
595e167d47 | ||
|
|
9afc5f0017 | ||
|
|
6bb451758a | ||
|
|
54cdea3391 | ||
|
|
4b97b19a21 | ||
|
|
0fff81583d | ||
|
|
14ada6bba8 | ||
|
|
9b684ba40d | ||
|
|
977f64b248 | ||
|
|
95eb5da737 | ||
|
|
3bb4c099c1 |
No files matched your search
@@ -23,7 +23,6 @@ frontend/tsconfig.tsbuildinfo
|
||||
/frontend/generated
|
||||
/frontend/tests/playwright-files/demo*
|
||||
/frontend/loginAuth.json
|
||||
/frontend/sharePrepStorage.json
|
||||
/backend/vendor
|
||||
/backend/*.cov
|
||||
/backend/*test_config.yaml
|
||||
|
||||
-101
@@ -2,107 +2,6 @@
|
||||
|
||||
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.5.2
|
||||
|
||||
**Notes**:
|
||||
- [docker] upgraded ffmpeg version 8.1.1 to 8.1.2
|
||||
|
||||
**BugFixes**:
|
||||
- Fixed OnlyOffice reopening an older editor state after a document is modified (#2633) (#2578).
|
||||
- Cannot "Reset and generate new two-factor code" to reset the TOTP for a user (#2399) (#2641).
|
||||
|
||||
## v1.5.1
|
||||
|
||||
**BugFixes**:
|
||||
- fix http config section being dropped so trustedHeaders and disableRateLimit apply (#2602) (#2560)
|
||||
- fix upload shares with password (#2589) (#2573)
|
||||
- fix token when returning from preview on shares with pass (#2588) (#2465)
|
||||
- fix share undefined url after editing (#2567) (#2523)
|
||||
|
||||
## v1.5.0
|
||||
|
||||
**New Features**:
|
||||
- Added basic html viewer with relative reference support (#2522)
|
||||
- Shares can have pinned files, requires a user to have edit access to share (#2522)
|
||||
- Enhanced search
|
||||
- now uses "lazy" match by default. (#2509)
|
||||
- added missing `case sensitive` option in the UI
|
||||
- Progressive Web App (PWA) improvements
|
||||
- restored install prompt with sidebar install button (#2086)
|
||||
- camera and video capture buttons on upload (mobile-friendly `capture` inputs)
|
||||
- send files to other apps via the Web Share API (`Send to app` in the context menu)
|
||||
- App notifications for file operations (#2478)
|
||||
- optional browser notifications when uploads, chunked downloads, move/copy, or failures finish while the tab is in the background
|
||||
- single on/off toggle in Notifications settings, stored in browser local storage
|
||||
|
||||
**Notes**:
|
||||
- [docker] upgraded ffmpeg version 8.1 to 8.1.1
|
||||
|
||||
**BugFixes**:
|
||||
- fixed PWA manifest `scope` and `id` so install works when the app is served under a base URL
|
||||
- installing a public share as a PWA now opens the share URL instead of the site root (#2302)
|
||||
|
||||
## v1.4.4
|
||||
|
||||
**BugFixes**:
|
||||
- Pinning/Unpinning file resets users' scope permission (#2532)
|
||||
|
||||
## 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**:
|
||||
|
||||
+64
-7
@@ -5,22 +5,17 @@ Thank you for your interest in contributing to FileBrowser Quantum! This guide w
|
||||
## Prerequisites
|
||||
|
||||
- **Go 1.25+** (see `backend/go.mod`)
|
||||
- **Node.js 22.0.0+** with npm 9.0.0+ (see `frontend/package.json`)
|
||||
- **Node.js 20.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/ffprobe**: For media features (subtitles, thumbnails, heic)
|
||||
- **ffmpeg**: For media features (subtitles, thumbnails, heic)
|
||||
- Ubuntu/Debian: `sudo apt-get install ffmpeg`
|
||||
- macOS: `brew install ffmpeg`
|
||||
- Windows: Download from [ffmpeg.org](https://ffmpeg.org/download.html)
|
||||
|
||||
- **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`
|
||||
@@ -95,6 +90,18 @@ 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)
|
||||
@@ -149,3 +156,53 @@ 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`
|
||||
@@ -17,6 +17,8 @@
|
||||
|
||||
## Pinned
|
||||
|
||||
:loudspeaker: [New Announcement](https://github.com/gtsteffaniak/filebrowser/discussions/2048)
|
||||
|
||||
:pushpin: [Read The Official Docs](https://filebrowserquantum.com/) (currently english-only)
|
||||
|
||||
## About
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM gtstef/ffmpeg:8.1.2-decode AS ffmpeg
|
||||
FROM gtstef/ffmpeg:8.1-decode AS ffmpeg
|
||||
FROM golang:alpine AS base
|
||||
ARG VERSION
|
||||
ARG REVISION
|
||||
|
||||
@@ -19,7 +19,5 @@ 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: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
name: "playwright + files"
|
||||
|
||||
@@ -2,7 +2,7 @@ server:
|
||||
port: 8080
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
config:
|
||||
|
||||
@@ -3,7 +3,7 @@ server:
|
||||
baseURL: "/files/"
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
name: "exclude"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
server:
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
config:
|
||||
|
||||
@@ -3,7 +3,7 @@ server:
|
||||
baseURL: "/"
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ server:
|
||||
baseURL: "/subpath"
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
config:
|
||||
|
||||
@@ -3,7 +3,7 @@ server:
|
||||
baseURL: "/files/"
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
name: "playwright"
|
||||
|
||||
@@ -3,7 +3,7 @@ server:
|
||||
baseURL: "/"
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
name: "playwright + files"
|
||||
|
||||
@@ -3,7 +3,7 @@ server:
|
||||
baseURL: "/"
|
||||
logging:
|
||||
- levels: "info|error|warning|debug"
|
||||
apiFilter: 'disabled'
|
||||
apiFilter: '.*'
|
||||
sources:
|
||||
- path: "../frontend/tests/playwright-files"
|
||||
name: "playwright + files"
|
||||
|
||||
@@ -357,7 +357,7 @@ func TestOverrideDirectoryToFile(t *testing.T) {
|
||||
{Name: "Test Object", Type: "directory"},
|
||||
},
|
||||
}
|
||||
idx.UpdateMetadata(rootInfo, nil, true) // nil scanner for test
|
||||
idx.UpdateMetadata(rootInfo, nil) // 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, true) // nil scanner for test
|
||||
idx.UpdateMetadata(rootInfo, nil) // 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, true) // nil scanner for test
|
||||
idx.UpdateMetadata(rootInfo, nil) // 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, true) // nil scanner for test
|
||||
idx.UpdateMetadata(rootInfo, nil) // nil scanner for test
|
||||
|
||||
// Verify the file was replaced with a directory in the mock data
|
||||
rootInfo, exists := idx.GetMetadataInfo("/", true, false)
|
||||
|
||||
@@ -27,8 +27,6 @@ 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
|
||||
|
||||
@@ -89,7 +87,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) {
|
||||
@@ -147,7 +145,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 indexPath, "", errors.ErrAccessDenied
|
||||
return "", "", errors.ErrAccessDenied
|
||||
}
|
||||
return indexPath, userScope, nil
|
||||
}
|
||||
@@ -159,30 +157,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, _, topLevelErr := CheckPermissions(opts, access, user)
|
||||
accessRulesErr := topLevelErr != nil && topLevelErr == errors.ErrAccessDenied && indexPath != ""
|
||||
if topLevelErr != nil && !accessRulesErr {
|
||||
return items, topLevelErr
|
||||
indexPath, _, err := CheckPermissions(opts, access, user)
|
||||
if err != nil {
|
||||
return items, err
|
||||
}
|
||||
// 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,
|
||||
@@ -200,10 +198,6 @@ 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) {
|
||||
@@ -223,17 +217,16 @@ func GetDirItems(opts utils.FileOptions, access *access.Storage, user *users.Use
|
||||
// FileInfoFasterFunc is a variable that can be mocked in tests
|
||||
var FileInfoFasterFunc = fileInfoFasterImpl
|
||||
|
||||
func FileInfoFaster(opts utils.FileOptions, access *access.Storage, user *users.User, shareStore *share.Storage) (*iteminfo.ExtendedFileInfo, error) {
|
||||
return FileInfoFasterFunc(opts, access, user, shareStore)
|
||||
func FileInfoFaster(opts utils.FileOptions, access *access.Storage, user *users.User, share *share.Storage) (*iteminfo.ExtendedFileInfo, error) {
|
||||
return FileInfoFasterFunc(opts, access, user, share)
|
||||
}
|
||||
|
||||
// fileInfoFasterImpl is the actual implementation of FileInfoFaster
|
||||
func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *users.User, shareStore *share.Storage) (*iteminfo.ExtendedFileInfo, error) {
|
||||
func fileInfoFasterImpl(opts utils.FileOptions, access *access.Storage, user *users.User, share *share.Storage) (*iteminfo.ExtendedFileInfo, error) {
|
||||
response := &iteminfo.ExtendedFileInfo{}
|
||||
indexPath, userScope, topLevelErr := CheckPermissions(opts, access, user)
|
||||
accessRulesErr := topLevelErr != nil && topLevelErr == errors.ErrAccessDenied && indexPath != ""
|
||||
if topLevelErr != nil && !accessRulesErr {
|
||||
return response, topLevelErr
|
||||
indexPath, userScope, err := CheckPermissions(opts, access, user)
|
||||
if err != nil {
|
||||
return response, err
|
||||
}
|
||||
// Get index
|
||||
idx := indexing.GetIndex(opts.Source)
|
||||
@@ -253,44 +246,29 @@ 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
|
||||
response.RealPath = filepath.Join(idx.Path, indexPath)
|
||||
response.Source = opts.Source
|
||||
if shareStore != nil && user.Permissions.Share && opts.ShowSharedAttr {
|
||||
if share != nil && user.Permissions.Share && opts.ShowSharedAttr {
|
||||
for i := range response.Files {
|
||||
file := &response.Files[i]
|
||||
file.IsShared = shareStore.IsShared(response.Path+file.Name, idx.Path, user.ID)
|
||||
file.IsShared = share.IsShared(response.Path+file.Name, idx.Path, user.ID)
|
||||
}
|
||||
for i := range response.Folders {
|
||||
folder := &response.Folders[i]
|
||||
folder.IsShared = shareStore.IsShared(response.Path+folder.Name, idx.Path, user.ID)
|
||||
folder.IsShared = share.IsShared(response.Path+folder.Name, idx.Path, user.ID)
|
||||
}
|
||||
response.IsShared = shareStore.IsShared(response.Path, idx.Path, user.ID)
|
||||
response.IsShared = share.IsShared(response.Path, idx.Path, user.ID)
|
||||
}
|
||||
if info.Type == "directory" && opts.ShowPinnedItems {
|
||||
if opts.ShareHash != "" && shareStore != nil {
|
||||
if link, err := shareStore.GetByHash(opts.ShareHash); err == nil {
|
||||
if shareRelDir, err := link.ShareRelativeDir(response.Path); err == nil {
|
||||
response.PinnedItems = link.PinnedItems.NamesForDirectory(shareRelDir)
|
||||
}
|
||||
}
|
||||
} else 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 != "" {
|
||||
@@ -395,12 +373,13 @@ 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 := reDuration.FindStringSubmatch(line)
|
||||
matches := re.FindStringSubmatch(line)
|
||||
if len(matches) == 6 {
|
||||
// Hours default to 0 (if not present in the timestamps)
|
||||
h := 0
|
||||
@@ -479,12 +458,10 @@ func extractAudioMetadata(ctx context.Context, item *iteminfo.ExtendedItemInfo,
|
||||
if rawLyrics := m.Lyrics(); rawLyrics != "" {
|
||||
item.Metadata.HasLyrics = true
|
||||
} else {
|
||||
// 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")
|
||||
// Check for .lrc file
|
||||
ext := filepath.Ext(realPath)
|
||||
base := strings.TrimSuffix(realPath, ext)
|
||||
lrcPath := base + ".lrc"
|
||||
if _, err := os.Stat(lrcPath); err == nil {
|
||||
item.Metadata.HasLyrics = true
|
||||
}
|
||||
@@ -549,12 +526,9 @@ func ExtractLyrics(realPath string) ([]iteminfo.Lyric, error) {
|
||||
lyrics = parseLRC(raw)
|
||||
}
|
||||
if len(lyrics) == 0 {
|
||||
// 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")
|
||||
ext := filepath.Ext(realPath)
|
||||
base := strings.TrimSuffix(realPath, ext)
|
||||
lrcPath := base + ".lrc"
|
||||
if data, err := os.ReadFile(lrcPath); err == nil {
|
||||
lyrics = parseLRC(string(data))
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ func VerifyTotpCode(user *users.User, code string, userStore *users.Storage) err
|
||||
if !found && user.TOTPSecret == "" {
|
||||
return fmt.Errorf("OTP token not found in cache, please generate a new one")
|
||||
}
|
||||
useCache := found
|
||||
useCache := found && user.TOTPSecret == ""
|
||||
totpSecret := user.TOTPSecret // The encrypted or plaintext secret
|
||||
totpNonce := user.TOTPNonce // The nonce if encrypted, or empty if plaintext
|
||||
if useCache {
|
||||
|
||||
+20
-10
@@ -25,9 +25,10 @@ type webAuthnSession struct {
|
||||
}
|
||||
|
||||
type WebAuthnService struct {
|
||||
wa *webauthn.WebAuthn
|
||||
sessions sync.Map
|
||||
stopCh chan struct{}
|
||||
wa *webauthn.WebAuthn
|
||||
sessions sync.Map
|
||||
stopCh chan struct{}
|
||||
originMu sync.Mutex
|
||||
}
|
||||
|
||||
var webAuthnInstance *WebAuthnService
|
||||
@@ -65,15 +66,24 @@ func IsWebAuthnEnabled() bool {
|
||||
return webAuthnInstance != nil
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
}
|
||||
}
|
||||
return false
|
||||
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
|
||||
}
|
||||
|
||||
func generateSessionID() string {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -52,7 +53,6 @@ func Initialize(configFile string) {
|
||||
}
|
||||
setupFs()
|
||||
setupServer()
|
||||
setupHttp()
|
||||
setupAuth(false)
|
||||
setupSources(false)
|
||||
InitializeUserResolvers() // Initialize user package resolvers after sources are set up
|
||||
@@ -62,9 +62,6 @@ 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"
|
||||
}
|
||||
@@ -86,15 +83,6 @@ 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)
|
||||
@@ -857,7 +845,6 @@ func loadConfigWithDefaults(configFile string, generate bool) error {
|
||||
"integrations": true,
|
||||
"frontend": true,
|
||||
"userDefaults": true,
|
||||
"http": true,
|
||||
}
|
||||
|
||||
filteredConfig := make(map[string]interface{})
|
||||
@@ -974,6 +961,12 @@ 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"
|
||||
@@ -984,7 +977,7 @@ func SetDefaults(generate bool) Settings {
|
||||
s := Settings{
|
||||
Server: Server{
|
||||
Port: 80,
|
||||
NumImageProcessors: 4,
|
||||
NumImageProcessors: numCpus,
|
||||
BaseURL: "",
|
||||
Database: database,
|
||||
SourceMap: map[string]*Source{},
|
||||
|
||||
@@ -94,34 +94,6 @@ func TestConfigLoadEnvVars(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigLoadHttpSection(t *testing.T) {
|
||||
testDir := t.TempDir()
|
||||
configContent := []byte(`
|
||||
server:
|
||||
sources:
|
||||
- path: "."
|
||||
http:
|
||||
trustedHeaders:
|
||||
- X-Forwarded-For
|
||||
disableRateLimit: true
|
||||
`)
|
||||
configFile := filepath.Join(testDir, "config.yaml")
|
||||
if err := os.WriteFile(configFile, configContent, 0644); err != nil {
|
||||
t.Fatalf("failed to write test config: %v", err)
|
||||
}
|
||||
|
||||
if err := loadConfigWithDefaults(configFile, true); err != nil {
|
||||
t.Fatalf("error loading config file: %v", err)
|
||||
}
|
||||
|
||||
if len(Config.Http.TrustedHeadersArray) != 1 || Config.Http.TrustedHeadersArray[0] != "X-Forwarded-For" {
|
||||
t.Fatalf("expected trusted headers to contain X-Forwarded-For, got %v", Config.Http.TrustedHeadersArray)
|
||||
}
|
||||
if !Config.Http.DisableRateLimit {
|
||||
t.Fatal("expected http.disableRateLimit to be true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigLoadSpecificValues(t *testing.T) {
|
||||
// Create isolated test directory
|
||||
testDir := t.TempDir()
|
||||
|
||||
@@ -133,10 +133,6 @@ 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
|
||||
@@ -151,7 +147,7 @@ func ApplyUserDefaults(u *users.User) {
|
||||
u.LoginMethod = users.LoginMethod(d.Account.LoginMethod)
|
||||
}
|
||||
|
||||
if len(u.Scopes) == 0 {
|
||||
if len(u.Scopes) == 0 && u.Username != "anonymous" {
|
||||
for _, source := range Config.Server.Sources {
|
||||
if source.Config.DefaultEnabled {
|
||||
u.Scopes = append(u.Scopes, users.SourceScope{
|
||||
|
||||
@@ -20,14 +20,6 @@ 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 {
|
||||
@@ -49,8 +41,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 4.
|
||||
Socket string `json:"socket"` // socket to listen on - eg. /var/run/filebrowser.sock
|
||||
NumImageProcessors int `json:"numImageProcessors"` // number of concurrent image processing jobs used to create previews, default is number of cpu cores available.
|
||||
Socket string `json:"socket"` // socket to listen on
|
||||
TLSKey string `json:"tlsKey"` // path to TLS key
|
||||
TLSCert string `json:"tlsCert"` // path to TLS cert
|
||||
DisablePreviews bool `json:"disablePreviews"` // disable all previews thumbnails, simple icons will be used
|
||||
@@ -211,7 +203,6 @@ 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
|
||||
|
||||
@@ -3,29 +3,11 @@ 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 = ""
|
||||
|
||||
@@ -62,13 +44,3 @@ 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
|
||||
}
|
||||
@@ -57,8 +57,6 @@ 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
|
||||
ShareHash string // when set, pinned items are loaded from this share link
|
||||
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
|
||||
@@ -110,4 +108,4 @@ func HideFileByExt(filename, hideExt string) bool {
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ server:
|
||||
sources:
|
||||
- path: "/srv"
|
||||
auth:
|
||||
key: "change-me-to-a-random-string"
|
||||
totpSecret: "change-me-to-another-random-string"
|
||||
methods:
|
||||
password:
|
||||
enabled: true
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
package share
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
)
|
||||
|
||||
// PinnedItems maps share-relative directory paths to pinned item names.
|
||||
type PinnedItems map[string][]string
|
||||
|
||||
// Add records a pinned item name under shareRelDir.
|
||||
func (p PinnedItems) Add(shareRelDir, name string) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
items := p[shareRelDir]
|
||||
if slices.Contains(items, name) {
|
||||
return
|
||||
}
|
||||
p[shareRelDir] = append(items, name)
|
||||
}
|
||||
|
||||
// Remove deletes a pinned item name and prunes empty map entries.
|
||||
func (p PinnedItems) Remove(shareRelDir, name string) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
items := p[shareRelDir]
|
||||
idx := slices.Index(items, name)
|
||||
if idx < 0 {
|
||||
return
|
||||
}
|
||||
items = append(items[:idx], items[idx+1:]...)
|
||||
if len(items) == 0 {
|
||||
delete(p, shareRelDir)
|
||||
} else {
|
||||
p[shareRelDir] = items
|
||||
}
|
||||
}
|
||||
|
||||
// NamesForDirectory returns pinned item names for a share-relative directory path.
|
||||
func (p PinnedItems) NamesForDirectory(shareRelDir string) []string {
|
||||
if len(p) == 0 {
|
||||
return nil
|
||||
}
|
||||
names := p[shareRelDir]
|
||||
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 (l *Link) EnsurePinnedItems() PinnedItems {
|
||||
if l.PinnedItems == nil {
|
||||
l.PinnedItems = make(PinnedItems)
|
||||
}
|
||||
return l.PinnedItems
|
||||
}
|
||||
|
||||
// ShareRelativeDir maps a source index directory path to a share-relative directory path.
|
||||
// link.Path is the index path of the share root (e.g. "/share/").
|
||||
func (l *Link) ShareRelativeDir(indexDirPath string) (string, error) {
|
||||
shareRootIndex := utils.AddTrailingSlashIfNotExists(l.Path)
|
||||
indexDirPath = utils.AddTrailingSlashIfNotExists(indexDirPath)
|
||||
if !strings.HasPrefix(indexDirPath, shareRootIndex) {
|
||||
return "", fmt.Errorf("path is outside share scope")
|
||||
}
|
||||
|
||||
rel := strings.TrimPrefix(indexDirPath, shareRootIndex)
|
||||
if rel == "" {
|
||||
return "/", nil
|
||||
}
|
||||
return utils.AddTrailingSlashIfNotExists("/" + strings.TrimPrefix(rel, "/")), nil
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package share
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSharePinnedItemsAddRemove(t *testing.T) {
|
||||
p := make(PinnedItems)
|
||||
const dir = "/"
|
||||
const name = "vacation.jpg"
|
||||
|
||||
p.Add(dir, name)
|
||||
if len(p[dir]) != 1 || p[dir][0] != name {
|
||||
t.Fatalf("add failed: %#v", p)
|
||||
}
|
||||
|
||||
p.Add(dir, name)
|
||||
if len(p[dir]) != 1 {
|
||||
t.Fatalf("duplicate add should be ignored: %#v", p)
|
||||
}
|
||||
|
||||
p.Remove(dir, name)
|
||||
if len(p) != 0 {
|
||||
t.Fatalf("remove should prune empty entries: %#v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharePinnedNamesForDirectory(t *testing.T) {
|
||||
p := PinnedItems{
|
||||
"/photos/": {"vacation.jpg", "notes.txt"},
|
||||
}
|
||||
|
||||
names := p.NamesForDirectory("/photos/")
|
||||
if len(names) != 2 || names[0] != "vacation.jpg" || names[1] != "notes.txt" {
|
||||
t.Fatalf("unexpected names: %#v", names)
|
||||
}
|
||||
if got := p.NamesForDirectory("/missing/"); got != nil {
|
||||
t.Fatalf("expected nil for missing directory, got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareRelativeDir(t *testing.T) {
|
||||
link := &Link{CommonShare: CommonShare{Path: "/share/"}}
|
||||
|
||||
got, err := link.ShareRelativeDir("/share/")
|
||||
if err != nil {
|
||||
t.Fatalf("ShareRelativeDir root: %v", err)
|
||||
}
|
||||
if got != "/" {
|
||||
t.Fatalf("got %q, want /", got)
|
||||
}
|
||||
|
||||
got, err = link.ShareRelativeDir("/share/test [file2]/")
|
||||
if err != nil {
|
||||
t.Fatalf("ShareRelativeDir subdir: %v", err)
|
||||
}
|
||||
if got != "/test [file2]/" {
|
||||
t.Fatalf("got %q, want /test [file2]/", got)
|
||||
}
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -60,12 +60,11 @@ type CreateBody struct {
|
||||
// Link is the information needed to build a shareable link.
|
||||
type Link struct {
|
||||
CommonShare
|
||||
Downloads int `json:"downloads"`
|
||||
Hash string `json:"hash" storm:"id,index"`
|
||||
UserID uint `json:"userID"`
|
||||
Expire int64 `json:"expire"`
|
||||
PasswordHash string `json:"password_hash,omitempty"`
|
||||
PinnedItems PinnedItems `json:"pinnedItems,omitempty"`
|
||||
Downloads int `json:"downloads"`
|
||||
Hash string `json:"hash" storm:"id,index"`
|
||||
UserID uint `json:"userID"`
|
||||
Expire int64 `json:"expire"`
|
||||
PasswordHash string `json:"password_hash,omitempty"`
|
||||
// Token is a random value that will only be set when PasswordHash is set. It is
|
||||
// URL-Safe and is used to download links in password-protected shares via a
|
||||
// query arg.
|
||||
|
||||
@@ -19,17 +19,13 @@ type SearchItem struct {
|
||||
}
|
||||
|
||||
// appendNameGlobSQL adds AND (name GLOB ? OR ...) or AND (name GLOB ? AND ...) when joinAnd is true.
|
||||
func appendNameGlobSQL(query string, args []interface{}, patterns []string, joinAnd, caseExact bool) (string, []interface{}) {
|
||||
func appendNameGlobSQL(query string, args []interface{}, patterns []string, joinAnd bool) (string, []interface{}) {
|
||||
if len(patterns) == 0 {
|
||||
return query, args
|
||||
}
|
||||
nameExpr := "name"
|
||||
if !caseExact {
|
||||
nameExpr = "lower(name)"
|
||||
}
|
||||
parts := make([]string, len(patterns))
|
||||
for i := range patterns {
|
||||
parts[i] = nameExpr + " GLOB ?"
|
||||
parts[i] = "name GLOB ?"
|
||||
args = append(args, patterns[i])
|
||||
}
|
||||
join := " OR "
|
||||
@@ -42,7 +38,7 @@ func appendNameGlobSQL(query string, args []interface{}, patterns []string, join
|
||||
// SearchItems queries the database for items matching the search criteria for a single source.
|
||||
// When nameGlobPatterns is non-empty (and largest is false), rows are restricted with SQLite name GLOB ... OR ....
|
||||
// Returns rows that can be iterated to scan search results.
|
||||
func (db *IndexDB) SearchItems(source string, scope string, largest bool, nameGlobPatterns []string, nameGlobPatternsAnd, caseExact bool) (*sql.Rows, error) {
|
||||
func (db *IndexDB) SearchItems(source string, scope string, largest bool, nameGlobPatterns []string, nameGlobPatternsAnd bool) (*sql.Rows, error) {
|
||||
query := `
|
||||
SELECT path, name, size, mod_time, type, is_dir, has_preview
|
||||
FROM index_items
|
||||
@@ -58,7 +54,7 @@ func (db *IndexDB) SearchItems(source string, scope string, largest bool, nameGl
|
||||
}
|
||||
|
||||
if !largest && len(nameGlobPatterns) > 0 {
|
||||
query, args = appendNameGlobSQL(query, args, nameGlobPatterns, nameGlobPatternsAnd, caseExact)
|
||||
query, args = appendNameGlobSQL(query, args, nameGlobPatterns, nameGlobPatternsAnd)
|
||||
}
|
||||
|
||||
if largest {
|
||||
@@ -71,7 +67,7 @@ func (db *IndexDB) SearchItems(source string, scope string, largest bool, nameGl
|
||||
// SearchItemsMultiSource queries the database for items matching the search criteria across multiple sources.
|
||||
// When nameGlobPatterns is non-empty (and largest is false), restricts rows with SQLite name GLOB ... OR ....
|
||||
// Returns rows that can be iterated to scan search results.
|
||||
func (db *IndexDB) SearchItemsMultiSource(sources []string, sourceScopes map[string]string, largest bool, nameGlobPatterns []string, nameGlobPatternsAnd, caseExact bool) (*sql.Rows, error) {
|
||||
func (db *IndexDB) SearchItemsMultiSource(sources []string, sourceScopes map[string]string, largest bool, nameGlobPatterns []string, nameGlobPatternsAnd bool) (*sql.Rows, error) {
|
||||
if len(sources) == 0 {
|
||||
return nil, fmt.Errorf("at least one source is required")
|
||||
}
|
||||
@@ -123,7 +119,7 @@ func (db *IndexDB) SearchItemsMultiSource(sources []string, sourceScopes map[str
|
||||
}
|
||||
|
||||
if !largest && len(nameGlobPatterns) > 0 {
|
||||
query, args = appendNameGlobSQL(query, args, nameGlobPatterns, nameGlobPatternsAnd, caseExact)
|
||||
query, args = appendNameGlobSQL(query, args, nameGlobPatterns, nameGlobPatternsAnd)
|
||||
}
|
||||
|
||||
if largest {
|
||||
|
||||
@@ -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: 4,
|
||||
NumImageProcessors: 1,
|
||||
}
|
||||
return server, get(s.db, "server", server)
|
||||
}
|
||||
|
||||
@@ -492,13 +492,13 @@ func TestFilterRestrictedFields(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
name: "all allowed fields",
|
||||
fields: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode", "PinnedItems"},
|
||||
expected: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode", "PinnedItems"},
|
||||
fields: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode"},
|
||||
expected: []string{"DarkMode", "OtpEnabled", "Locale", "ViewMode"},
|
||||
},
|
||||
{
|
||||
name: "mixed allowed and restricted",
|
||||
fields: []string{"DarkMode", "Permissions", "Scopes", "OtpEnabled", "PinnedItems"},
|
||||
expected: []string{"DarkMode", "OtpEnabled", "PinnedItems"},
|
||||
fields: []string{"DarkMode", "Permissions", "Scopes", "OtpEnabled"},
|
||||
expected: []string{"DarkMode", "OtpEnabled"},
|
||||
},
|
||||
{
|
||||
name: "all restricted fields",
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
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])
|
||||
}
|
||||
}
|
||||
@@ -96,27 +96,24 @@ 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
|
||||
}
|
||||
@@ -128,44 +125,43 @@ 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"`
|
||||
PinnedItems PinnedItems `json:"pinnedItems,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"`
|
||||
}
|
||||
|
||||
type FileLoading struct {
|
||||
|
||||
+35
-34
@@ -4,36 +4,36 @@ go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/asdine/storm/v3 v3.2.1
|
||||
github.com/coreos/go-oidc/v3 v3.20.0
|
||||
github.com/coreos/go-oidc/v3 v3.18.0
|
||||
github.com/coreos/go-systemd/v22 v22.7.0
|
||||
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
|
||||
github.com/dsoprea/go-exif/v3 v3.0.1
|
||||
github.com/gen2brain/go-fitz v1.28.2
|
||||
github.com/go-ldap/ldap/v3 v3.4.14
|
||||
github.com/go-playground/validator/v10 v10.30.3
|
||||
github.com/go-webauthn/webauthn v0.17.4
|
||||
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/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.23
|
||||
github.com/mattn/go-sqlite3 v1.14.48
|
||||
github.com/kovidgoyal/imaging v1.8.21
|
||||
github.com/mattn/go-sqlite3 v1.14.44
|
||||
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.54.0
|
||||
golang.org/x/image v0.44.0
|
||||
golang.org/x/mod v0.38.0
|
||||
golang.org/x/net v0.57.0
|
||||
golang.org/x/crypto v0.51.0
|
||||
golang.org/x/image v0.40.0
|
||||
golang.org/x/mod v0.36.0
|
||||
golang.org/x/net v0.54.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/sys v0.44.0
|
||||
golang.org/x/time v0.15.0
|
||||
golang.org/x/tools v0.48.0
|
||||
golang.org/x/tools v0.45.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.54.0
|
||||
modernc.org/sqlite v1.50.1
|
||||
)
|
||||
|
||||
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.3 // indirect
|
||||
github.com/air-verse/air v1.65.1 // 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.1 // indirect
|
||||
github.com/ebitengine/purego v0.10.0 // 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
|
||||
@@ -116,20 +116,20 @@ require (
|
||||
github.com/fzipp/gocyclo v0.6.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/ghostiam/protogetter v0.3.20 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
|
||||
github.com/go-critic/go-critic v0.14.3 // indirect
|
||||
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 v1.0.0 // indirect
|
||||
github.com/go-openapi/jsonreference v1.0.0 // indirect
|
||||
github.com/go-openapi/spec v0.22.6 // indirect
|
||||
github.com/go-openapi/swag/conv v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/jsonutils v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/loading v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/stringutils v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/typeutils v0.27.0 // indirect
|
||||
github.com/go-openapi/swag/yamlutils v0.27.0 // 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/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
|
||||
github.com/go-openapi/swag/loading v0.26.0 // indirect
|
||||
github.com/go-openapi/swag/stringutils v0.26.0 // indirect
|
||||
github.com/go-openapi/swag/typeutils v0.26.0 // indirect
|
||||
github.com/go-openapi/swag/yamlutils v0.26.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-toolsmith/astcast v1.1.0 // indirect
|
||||
@@ -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.6 // indirect
|
||||
github.com/go-webauthn/x v0.2.5 // 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-20260713102120-857a528af641 // indirect
|
||||
github.com/golang/geo v0.0.0-20260512202753-e3c51de6d1b6 // 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
|
||||
@@ -178,6 +178,7 @@ require (
|
||||
github.com/jjti/go-spancheck v0.6.5 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/julz/importas v0.2.0 // indirect
|
||||
github.com/jupiterrider/ffi v0.7.0 // indirect
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
|
||||
github.com/kisielk/errcheck v1.10.0 // indirect
|
||||
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
|
||||
@@ -204,7 +205,7 @@ require (
|
||||
github.com/maratori/testpackage v1.1.2 // indirect
|
||||
github.com/matoous/godox v1.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.23 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.23 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/mgechev/revive v1.15.0 // indirect
|
||||
@@ -281,19 +282,19 @@ require (
|
||||
go-simpler.org/sloglint v0.12.0 // indirect
|
||||
go.augendre.info/arangolint v0.4.0 // indirect
|
||||
go.augendre.info/fatcontext v0.9.0 // indirect
|
||||
go.etcd.io/bbolt v1.5.0 // indirect
|
||||
go.etcd.io/bbolt v1.4.3 // indirect
|
||||
go.uber.org/multierr v1.10.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
|
||||
golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
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.74.2 // indirect
|
||||
modernc.org/libc v1.72.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
mvdan.cc/gofumpt v0.9.2 // indirect
|
||||
|
||||
+82
-80
@@ -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.3 h1:7NUAqofZuSf5vZbVoZpdTr/4LuKkOCj1JTiMrOdUs7A=
|
||||
github.com/air-verse/air v1.65.3/go.mod h1:OaJZSfZqf7wyjS2oP/CcEVyIt0JmZuPh5x1gdtklmmY=
|
||||
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/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=
|
||||
@@ -211,8 +211,8 @@ github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
|
||||
github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A=
|
||||
github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA=
|
||||
github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
@@ -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.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
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/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=
|
||||
@@ -283,16 +283,16 @@ github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo=
|
||||
github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gen2brain/go-fitz v1.28.2 h1:845G85N5TUgnq5oDqyYrW0JvehAkeo35UkkK2dJtW1M=
|
||||
github.com/gen2brain/go-fitz v1.28.2/go.mod h1:pY2hqAjp9Zy7qfPI2gwbJMHBFAdZpVXOLrRxD82l3Bs=
|
||||
github.com/gen2brain/go-fitz v1.24.15 h1:sJNB1MOWkqnzzENPHggFpgxTwW0+S5WF/rM5wUBpJWo=
|
||||
github.com/gen2brain/go-fitz v1.24.15/go.mod h1:SftkiVbTHqF141DuiLwBBM65zP7ig6AVDQpf2WlHamo=
|
||||
github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=
|
||||
github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE=
|
||||
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/ghostiam/protogetter v0.3.20 h1:oW7OPFit2FxZOpmMRPP9FffU4uUpfeE/rEdE1f+MzD0=
|
||||
github.com/ghostiam/protogetter v0.3.20/go.mod h1:FjIu5Yfs6FT391m+Fjp3fbAYJ6rkL/J6ySpZBfnODuI=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 h1:BP4M0CvQ4S3TGls2FvczZtj5Re/2ZzkV9VwqPHH/3Bo=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-critic/go-critic v0.14.3 h1:5R1qH2iFeo4I/RJU8vTezdqs08Egi4u5p6vOESA0pog=
|
||||
github.com/go-critic/go-critic v0.14.3/go.mod h1:xwntfW6SYAd7h1OqDzmN6hBX/JxsEKl5up/Y2bsxgVQ=
|
||||
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
|
||||
@@ -309,48 +309,48 @@ github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9
|
||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14/go.mod h1:S4eJUMUNjDkE0ZJtIZdybwyb03sGGLW6gxXT1Hs8VKA=
|
||||
github.com/go-ldap/ldap/v3 v3.4.13 h1:+x1nG9h+MZN7h/lUi5Q3UZ0fJ1GyDQYbPvbuH38baDQ=
|
||||
github.com/go-ldap/ldap/v3 v3.4.13/go.mod h1:LxsGZV6vbaK0sIvYfsv47rfh4ca0JXokCoKjZxsszv0=
|
||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s=
|
||||
github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y=
|
||||
github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY=
|
||||
github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0=
|
||||
github.com/go-openapi/spec v0.22.6 h1:Tyy1pLaNCM8GBCFLoGYLonjJi6zykqyLCjXLc19ZPic=
|
||||
github.com/go-openapi/spec v0.22.6/go.mod h1:HZvTHat+iH0PALQRWhrqIHtU/PEqxqd89fu0MxGlMeM=
|
||||
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/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||
github.com/go-openapi/swag/conv v0.27.0 h1:EKOH4feXrvdo8DbSsXSAqRT8fz1epEnS5O2IfXUOzE8=
|
||||
github.com/go-openapi/swag/conv v0.27.0/go.mod h1:pfiv0uKQTbaGApk8Zs/lZV3uSjmSpa2FO1y183YngN8=
|
||||
github.com/go-openapi/swag/jsonname v0.27.0 h1:4QVB//CKOdE8IOiBg19JNY2wfDS48MhesIquYBy2rUE=
|
||||
github.com/go-openapi/swag/jsonname v0.27.0/go.mod h1:I1YsyvvhBuZsFXSW6I7ODfdyq13p7hDil//1T9/pFFk=
|
||||
github.com/go-openapi/swag/jsonutils v0.27.0 h1:VYtd9jEQYeU4j8q5vdn5KWotF4vKywhGdMBrALtAsfE=
|
||||
github.com/go-openapi/swag/jsonutils v0.27.0/go.mod h1:U7pb8AGuwhok3RDicHeHwSG4L3PXSq6PAL98Aon632g=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.0 h1:+d7C7Ur/SsGg/UZ9G0JEovnfRqtMNZCJQGKc2h/ojoE=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.0/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY=
|
||||
github.com/go-openapi/swag/loading v0.27.0 h1:s8DA9aPEdFH6OluHUYUn3DnIuoTdyWs9RwffXBUfyeI=
|
||||
github.com/go-openapi/swag/loading v0.27.0/go.mod h1:VOz+Jg6UGGywcmRvYsI4fvtp+bd7NfioseGEPleYdA4=
|
||||
github.com/go-openapi/swag/stringutils v0.27.0 h1:Of7w/HljWsNZvuxsUAnw3n+hCOyI6HLJOxW2kQRAxio=
|
||||
github.com/go-openapi/swag/stringutils v0.27.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM=
|
||||
github.com/go-openapi/swag/typeutils v0.27.0 h1:aCf4MSGo8NLwZP8Q6t32DWLJSvl/WwNqgmEG+xJ6v2o=
|
||||
github.com/go-openapi/swag/typeutils v0.27.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ=
|
||||
github.com/go-openapi/swag/yamlutils v0.27.0 h1:bQ6eAMil5X9tdcf7dMn4t15alzG6jddnrKPuKa/zxKM=
|
||||
github.com/go-openapi/swag/yamlutils v0.27.0/go.mod h1:yRfIo7qqVkmJRQjX8exjA3AfcI8rH1KDNPsTparoCv4=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0=
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo=
|
||||
github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug=
|
||||
github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=
|
||||
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=
|
||||
github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w=
|
||||
github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M=
|
||||
github.com/go-openapi/swag/jsonutils v0.26.0 h1:FawFML2iAXsPqmERscuMPIHmFsoP1tOqWkxBaKNMsnA=
|
||||
github.com/go-openapi/swag/jsonutils v0.26.0/go.mod h1:2VmA0CJlyFqgawOaPI9psnjFDqzyivIqLYN34t9p91E=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0 h1:apqeINu/ICHouqiRZbyFvuDge5jCmmLTqGQ9V95EaOM=
|
||||
github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0/go.mod h1:AyM6QT8uz5IdKxk5akv0y6u4QvcL9GWERt0Jx/F/R8Y=
|
||||
github.com/go-openapi/swag/loading v0.26.0 h1:Apg6zaKhCJurpJer0DCxq99qwmhFddBhaMX7kilDcko=
|
||||
github.com/go-openapi/swag/loading v0.26.0/go.mod h1:dBxQ/6V2uBaAQdevN18VELE6xSpJWZxLX4txe12JwDg=
|
||||
github.com/go-openapi/swag/stringutils v0.26.0 h1:qZQngLxs5s7SLijc3N2ZO+fUq2o8LjuWAASSrJuh+xg=
|
||||
github.com/go-openapi/swag/stringutils v0.26.0/go.mod h1:sWn5uY+QIIspwPhvgnqJsH8xqFT2ZbYcvbcFanRyhFE=
|
||||
github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFuuyQIKYybfq4=
|
||||
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-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.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
|
||||
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
|
||||
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-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.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-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-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-20260713102120-857a528af641 h1:cpoobkgVGCE6bC5kJkOfwfM6hAtZuvoBjnCLECxG4AU=
|
||||
github.com/golang/geo v0.0.0-20260713102120-857a528af641/go.mod h1:Mymr9kRGDc64JPr03TSZmuIBODZ3KyswLzm1xL0HFA8=
|
||||
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/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=
|
||||
@@ -585,6 +585,8 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/julz/importas v0.2.0 h1:y+MJN/UdL63QbFJHws9BVC5RpA2iq0kpjrFajTGivjQ=
|
||||
github.com/julz/importas v0.2.0/go.mod h1:pThlt589EnCYtMnmhmRYY/qn9lCf/frPOK+WMx3xiJY=
|
||||
github.com/jupiterrider/ffi v0.7.0 h1:RKsl6Ascal+3kyAqR5Qcbp83LceQMLc1VZbPfHWoNzs=
|
||||
github.com/jupiterrider/ffi v0.7.0/go.mod h1:9dauhpOfNqrqk28fxuu0kkdeFtT9Qr4vbfigiuIXN7c=
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.2 h1:yfNQvP9YaGQR7VaWLYcfZUlRP2eo2vhExWKxD/fP6q0=
|
||||
github.com/karamaru-alpha/copyloopvar v1.2.2/go.mod h1:oY4rGZqZ879JkJMtX3RRkcXRkmUvH0x35ykgaKgsgJY=
|
||||
github.com/kisielk/errcheck v1.10.0 h1:Lvs/YAHP24YKg08LA8oDw2z9fJVme090RAXd90S+rrw=
|
||||
@@ -598,8 +600,8 @@ github.com/kovidgoyal/go-parallel v1.1.1 h1:1OzpNjtrUkBPq3UaqrnvOoB2F9RttSt811ui
|
||||
github.com/kovidgoyal/go-parallel v1.1.1/go.mod h1:BJNIbe6+hxyFWv7n6oEDPj3PA5qSw5OCtf0hcVxWJiw=
|
||||
github.com/kovidgoyal/go-shm v1.0.0 h1:HJEel9D1F9YhULvClEHJLawoRSj/1u/EDV7MJbBPgQo=
|
||||
github.com/kovidgoyal/go-shm v1.0.0/go.mod h1:Yzb80Xf9L3kaoB2RGok9hHwMIt7Oif61kT6t3+VnZds=
|
||||
github.com/kovidgoyal/imaging v1.8.23 h1:4WsboyQ/E8tic2kX49P93Rvscg33SPsCwTBG5EZZF54=
|
||||
github.com/kovidgoyal/imaging v1.8.23/go.mod h1:k3Iot3H0v2rSWXIxQISfT3e9wIryqzAHLHCuhG7z9lM=
|
||||
github.com/kovidgoyal/imaging v1.8.21 h1:95S2+dowTeKJJHNpf6lnScvIennTr2H0zQotu+ptNQw=
|
||||
github.com/kovidgoyal/imaging v1.8.21/go.mod h1:976F+zjiQeZ7sd87Pxlm0a64S/w9bImSIWg3sSk1rdQ=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -658,12 +660,12 @@ github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE=
|
||||
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
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.48 h1:7XHIgl0a8HwOaiK4E47ozLkST78rR9+OtNGx27D/TFs=
|
||||
github.com/mattn/go-sqlite3 v1.14.48/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
|
||||
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/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=
|
||||
@@ -926,8 +928,8 @@ go.augendre.info/arangolint v0.4.0/go.mod h1:l+f/b4plABuFISuKnTGD4RioXiCCgghv2xq
|
||||
go.augendre.info/fatcontext v0.9.0 h1:Gt5jGD4Zcj8CDMVzjOJITlSb9cEch54hjRRlN3qDojE=
|
||||
go.augendre.info/fatcontext v0.9.0/go.mod h1:L94brOAT1OOUNue6ph/2HnwxoNlds9aXDF2FcUntbNw=
|
||||
go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
|
||||
go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
|
||||
go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
|
||||
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
|
||||
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
|
||||
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
||||
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
||||
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
@@ -950,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.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
||||
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
||||
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=
|
||||
@@ -970,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.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
|
||||
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
|
||||
golang.org/x/image v0.40.0 h1:Tw4GyDXMo+daZN1znreBRC3VayR1aLFUyUEOLUdW1a8=
|
||||
golang.org/x/image v0.40.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=
|
||||
@@ -994,8 +996,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
|
||||
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
@@ -1034,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.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
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/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=
|
||||
@@ -1057,8 +1059,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -1105,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.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
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/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=
|
||||
@@ -1118,8 +1120,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
@@ -1172,8 +1174,8 @@ golang.org/x/tools v0.1.1-0.20210302220138-2ac05c832e1a/go.mod h1:9bzcO0MWcOuT0t
|
||||
golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
|
||||
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
|
||||
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=
|
||||
@@ -1290,20 +1292,20 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9
|
||||
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
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.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
|
||||
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
|
||||
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
|
||||
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/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.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
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/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.74.2 h1:r94QPC+Mh3WN1lSCDxQxFdIxcI+zdQROo+1pTEZGqkk=
|
||||
modernc.org/libc v1.74.2/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
|
||||
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
|
||||
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
|
||||
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=
|
||||
@@ -1312,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.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=
|
||||
modernc.org/sqlite v1.50.1/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=
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"compress/gzip"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -44,7 +46,11 @@ var (
|
||||
)
|
||||
|
||||
func randomArchiveToken() (string, error) {
|
||||
return utils.RandomHex(16)
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func stopArchiveSpoolIdleTimer(token string) {
|
||||
|
||||
@@ -221,9 +221,7 @@ 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) {
|
||||
@@ -322,7 +320,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 !config.Auth.Methods.PasswordAuth.Signup {
|
||||
if !settings.Config.Auth.Methods.PasswordAuth.Signup {
|
||||
return http.StatusMethodNotAllowed, fmt.Errorf("signup is disabled")
|
||||
}
|
||||
|
||||
@@ -342,7 +340,7 @@ func signupHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
|
||||
},
|
||||
LoginMethod: users.LoginMethodPassword,
|
||||
}
|
||||
err := storage.CreateUser(user, settings.ConvertPermissionsToUsers(config.UserDefaults.Account.Permissions))
|
||||
err := storage.CreateUser(user, settings.ConvertPermissionsToUsers(settings.Config.UserDefaults.Account.Permissions))
|
||||
if err != nil {
|
||||
logger.Debug(err.Error())
|
||||
// Return the actual error message instead of a generic one
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
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)
|
||||
})
|
||||
}
|
||||
+35
-54
@@ -10,7 +10,6 @@ import (
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
_ "net/http/pprof"
|
||||
@@ -81,40 +80,35 @@ 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", 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)))
|
||||
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))
|
||||
|
||||
// ========================================
|
||||
// Resources Routes - /api/resources/ (with public routes)
|
||||
@@ -129,7 +123,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(30*time.Second, withUserHelper(previewHandler)))
|
||||
api.HandleFunc("GET /resources/preview", withTimeout(60*time.Second, withUserHelper(previewHandler)))
|
||||
api.HandleFunc("POST /resources/pause", withUser(resourcePauseHandler))
|
||||
publicApi.HandleFunc("GET /resources", withHashFile(publicGetResourceHandler))
|
||||
publicApi.HandleFunc("GET /resources/items", withHashFile(publicItemsGetHandler))
|
||||
@@ -139,7 +133,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", withTimeout(30*time.Second, withHashFileHelper(publicPreviewHandler)))
|
||||
publicApi.HandleFunc("GET /resources/preview", withHashFile(publicPreviewHandler))
|
||||
publicApi.HandleFunc("POST /resources/pause", withHashFile(publicPauseHandler))
|
||||
// Legacy routes (backwards compatibility)
|
||||
api.HandleFunc("GET /raw", withUser(downloadHandler))
|
||||
@@ -166,7 +160,6 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
|
||||
api.HandleFunc("PATCH /share", withPermShare(sharePatchHandler))
|
||||
api.HandleFunc("DELETE /share", withPermShare(shareDeleteHandler))
|
||||
publicApi.HandleFunc("GET /share/info", withOrWithoutUser(shareInfoHandler))
|
||||
publicApi.HandleFunc("PATCH /share/pinnedItems", withPermShare(sharePatchPinnedItemsHandler))
|
||||
publicApi.HandleFunc("GET /share/image", withHashFile(getShareImage))
|
||||
|
||||
// ========================================
|
||||
@@ -206,6 +199,7 @@ 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)
|
||||
@@ -256,28 +250,16 @@ 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() {
|
||||
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
|
||||
// Determine whether to use HTTPS (TLS) or HTTP
|
||||
if config.Server.TLSCert != "" && config.Server.TLSKey != "" {
|
||||
// Load the TLS certificate and key
|
||||
cer, err := tls.LoadX509KeyPair(config.Server.TLSCert, config.Server.TLSKey)
|
||||
if err != nil {
|
||||
@@ -301,6 +283,8 @@ 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]
|
||||
@@ -319,9 +303,10 @@ 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 {
|
||||
@@ -332,6 +317,8 @@ 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 {
|
||||
@@ -357,10 +344,10 @@ 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)
|
||||
// Start HTTP server
|
||||
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||
logger.Fatalf("Server error: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -399,12 +386,6 @@ 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)
|
||||
}
|
||||
@@ -26,7 +26,7 @@ func AuthenticateLDAPUser(username, password string) (*users.User, error) {
|
||||
}
|
||||
|
||||
// Use the configured UserIdentifier if available, otherwise use the login username
|
||||
ldapCfg := config.Auth.Methods.LdapAuth
|
||||
ldapCfg := settings.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 := config.Auth.Methods.LdapAuth
|
||||
c := settings.Config.Auth.Methods.LdapAuth
|
||||
logger.Debugf("ldap: connecting to %s", c.Server)
|
||||
|
||||
var opts []ldap.DialOpt
|
||||
|
||||
+57
-74
@@ -5,13 +5,15 @@ 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
|
||||
@@ -36,49 +38,58 @@ 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")
|
||||
}
|
||||
|
||||
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)
|
||||
userscope, err := d.user.GetScopeForSourceName(source)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
}
|
||||
if !strings.HasPrefix(fileInfo.Type, "video") {
|
||||
return http.StatusNotFound, fmt.Errorf("file is not a video")
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
|
||||
track := findSubtitleTrack(fileInfo.Subtitles, name, embedded)
|
||||
if track == nil {
|
||||
return http.StatusNotFound, fmt.Errorf("subtitle track '%s' not found", name)
|
||||
idx := indexing.GetIndex(source)
|
||||
if idx == nil {
|
||||
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
|
||||
}
|
||||
|
||||
realPath, _, err := idx.GetRealPath(userscope, path)
|
||||
if err != nil {
|
||||
return http.StatusNotFound, fmt.Errorf("file not found: %v", err)
|
||||
}
|
||||
|
||||
parentDir := filepath.Dir(realPath)
|
||||
var content string
|
||||
|
||||
if !embedded {
|
||||
subtitlePath := filepath.Join(filepath.Dir(fileInfo.RealPath), filepath.Base(track.Name))
|
||||
content, err = utils.GetSubtitleSidecarContent(subtitlePath)
|
||||
content, err = utils.GetSubtitleSidecarContent(filepath.Join(parentDir, name))
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to get subtitle sidecar content: %v", err)
|
||||
}
|
||||
} else {
|
||||
if track.Index == nil {
|
||||
// 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 {
|
||||
return http.StatusNotFound, fmt.Errorf("embedded subtitle track '%s' not found", name)
|
||||
}
|
||||
content, err = ffmpeg.ExtractSubtitleContent(fileInfo.RealPath, *track.Index)
|
||||
|
||||
content, err = ffmpeg.ExtractSubtitleContent(realPath, *streamIndex)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to extract embedded subtitle: %v", err)
|
||||
}
|
||||
@@ -92,16 +103,6 @@ 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
|
||||
@@ -128,7 +129,7 @@ func metadataHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
Content: false,
|
||||
Metadata: true,
|
||||
AlbumArt: albumArt,
|
||||
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles,
|
||||
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles,
|
||||
ShowHidden: d.user.ShowHidden,
|
||||
HideFileExt: d.user.HideFileExt,
|
||||
SkipExtendedAttrs: false,
|
||||
@@ -166,7 +167,7 @@ func publicMetadataHandler(w http.ResponseWriter, r *http.Request, d *requestCon
|
||||
Content: false,
|
||||
Metadata: true,
|
||||
AlbumArt: albumArt,
|
||||
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles && d.share.ExtractEmbeddedSubtitles,
|
||||
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles && d.share.ExtractEmbeddedSubtitles,
|
||||
ShowHidden: d.share.ShowHidden,
|
||||
HideFileExt: d.user.HideFileExt,
|
||||
FollowSymlinks: false,
|
||||
@@ -196,26 +197,19 @@ func lyricsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
|
||||
if path == "" || source == "" {
|
||||
return http.StatusBadRequest, fmt.Errorf("path and source are required")
|
||||
}
|
||||
|
||||
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)
|
||||
userscope, err := d.user.GetScopeForSourceName(source)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
if !strings.HasPrefix(fileInfo.Type, "audio") {
|
||||
return http.StatusNotFound, fmt.Errorf("file is not an audio file")
|
||||
idx := indexing.GetIndex(source)
|
||||
if idx == nil {
|
||||
return http.StatusNotFound, fmt.Errorf("source %s not found", source)
|
||||
}
|
||||
|
||||
lyrics, err := files.ExtractLyrics(fileInfo.RealPath)
|
||||
realPath, _, err := idx.GetRealPath(userscope, path)
|
||||
if err != nil {
|
||||
return http.StatusNotFound, err
|
||||
}
|
||||
lyrics, err := files.ExtractLyrics(realPath)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to extract lyrics: %v", err)
|
||||
}
|
||||
@@ -237,26 +231,15 @@ func publicLyricsHandler(w http.ResponseWriter, r *http.Request, d *requestConte
|
||||
if !ok {
|
||||
return http.StatusNotFound, fmt.Errorf("source not found")
|
||||
}
|
||||
|
||||
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)
|
||||
idx := indexing.GetIndex(sourceCfg.Name)
|
||||
if idx == nil {
|
||||
return http.StatusNotFound, fmt.Errorf("source not found")
|
||||
}
|
||||
realPath, _, err := idx.GetRealPath(d.IndexPath)
|
||||
if err != nil {
|
||||
return errToStatus(err), err
|
||||
return http.StatusNotFound, errors.New("could not find real path for file")
|
||||
}
|
||||
if !strings.HasPrefix(fileInfo.Type, "audio") {
|
||||
return http.StatusNotFound, fmt.Errorf("file is not an audio file")
|
||||
}
|
||||
|
||||
lyrics, err := files.ExtractLyrics(fileInfo.RealPath)
|
||||
lyrics, err := files.ExtractLyrics(realPath)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, errors.New("failed to extract lyrics")
|
||||
}
|
||||
|
||||
+52
-17
@@ -8,7 +8,6 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -32,6 +31,7 @@ type requestContext struct {
|
||||
fileInfo iteminfo.ExtendedFileInfo
|
||||
token string
|
||||
share *share.Link
|
||||
shareValid bool
|
||||
ctx context.Context
|
||||
MaxBandwidth int
|
||||
Data interface{}
|
||||
@@ -58,7 +58,6 @@ 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)
|
||||
@@ -133,12 +132,10 @@ func withHashFileHelper(fn handleFunc) handleFunc {
|
||||
Content: getContent,
|
||||
Metadata: getMetadata,
|
||||
AlbumArt: strings.Contains(r.URL.Path, "/preview"),
|
||||
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles && link.ExtractEmbeddedSubtitles,
|
||||
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles && link.ExtractEmbeddedSubtitles,
|
||||
ShowHidden: link.ShowHidden,
|
||||
HideFileExt: link.HideFileExt,
|
||||
HideFileExt: link.HideFileExt,
|
||||
FollowSymlinks: true,
|
||||
ShowPinnedItems: true,
|
||||
ShareHash: hash,
|
||||
}, store.Access, data.shareUser, store.Share)
|
||||
if err != nil {
|
||||
logger.Errorf("error fetching file info for share. hash=%v path=%v error=%v", hash, path, err)
|
||||
@@ -230,19 +227,57 @@ 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 != "" {
|
||||
_, err := store.Share.GetByHash(hash)
|
||||
if err != nil {
|
||||
return http.StatusNotFound, fmt.Errorf("share hash not found")
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// Try to authenticate user first
|
||||
status, err := withUserHelper(nil)(w, r, data)
|
||||
if err == nil && status < 400 {
|
||||
if data.share != nil && data.user != nil {
|
||||
data.user.CustomTheme = data.share.ShareTheme
|
||||
if data.share != nil && data.shareValid {
|
||||
if data.user != nil {
|
||||
data.user.CustomTheme = data.share.ShareTheme
|
||||
}
|
||||
}
|
||||
return fn(w, r, data)
|
||||
}
|
||||
@@ -253,7 +288,7 @@ func withOrWithoutUserHelper(fn handleFunc) handleFunc {
|
||||
userFromExpiredToken := extractUserFromExpiredToken(r, data)
|
||||
if userFromExpiredToken != nil {
|
||||
data.user = userFromExpiredToken
|
||||
if data.share != nil {
|
||||
if data.share != nil && data.shareValid {
|
||||
data.user.CustomTheme = data.share.ShareTheme
|
||||
}
|
||||
setUserInResponseWriter(w, data.user)
|
||||
@@ -265,7 +300,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 {
|
||||
if data.share != nil && data.shareValid {
|
||||
data.user.CustomTheme = data.share.ShareTheme
|
||||
}
|
||||
// Call the handler function without user context
|
||||
@@ -629,8 +664,8 @@ func withoutUser(fn handleFunc) http.HandlerFunc {
|
||||
return wrapHandler(withoutUserHelper(fn))
|
||||
}
|
||||
|
||||
func loginHelper(fn handleFunc) handleFunc {
|
||||
return LoginHelper(false, fn)
|
||||
func loginHelper(fn handleFunc) http.HandlerFunc {
|
||||
return wrapHandler(LoginHelper(false, fn))
|
||||
}
|
||||
|
||||
func withSelfOrAdmin(fn handleFunc) http.HandlerFunc {
|
||||
@@ -725,7 +760,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 config.Http.TrustedHeaders["x-forwarded-for"] && xff != "" {
|
||||
if xff != "" {
|
||||
// The first IP is the original client
|
||||
ips := strings.Split(xff, ",")
|
||||
return strings.TrimSpace(ips[0])
|
||||
@@ -733,7 +768,7 @@ func getRemoteIP(r *http.Request) string {
|
||||
|
||||
// 2. Check X-Real-IP
|
||||
xri := r.Header.Get("X-Real-IP")
|
||||
if config.Http.TrustedHeaders["x-real-ip"] && xri != "" {
|
||||
if xri != "" {
|
||||
return xri
|
||||
}
|
||||
|
||||
|
||||
@@ -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 := config.Auth.Methods.OidcAuth
|
||||
oidcCfg := settings.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 := config.Auth.Methods.OidcAuth
|
||||
oidcCfg := settings.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.
|
||||
|
||||
+25
-137
@@ -11,13 +11,12 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt/v4"
|
||||
"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/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
"github.com/gtsteffaniak/go-logger/logger"
|
||||
)
|
||||
@@ -29,16 +28,8 @@ 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"`
|
||||
@@ -90,7 +81,7 @@ type OnlyOfficeJWTPayload struct {
|
||||
// @Router /api/office/config [get]
|
||||
// @Security ApiKeyAuth
|
||||
func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
if config.Integrations.OnlyOffice.Url == "" {
|
||||
if settings.Config.Integrations.OnlyOffice.Url == "" {
|
||||
return http.StatusInternalServerError, errors.New("only-office integration must be configured in settings")
|
||||
}
|
||||
|
||||
@@ -116,13 +107,13 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
|
||||
var sourceInfo *settings.Source
|
||||
var ok bool
|
||||
if hash != "" {
|
||||
sourceInfo, ok = config.Server.SourceMap[d.share.Source]
|
||||
sourceInfo, ok = settings.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 = config.Server.NameToSource[source]
|
||||
sourceInfo, ok = settings.Config.Server.NameToSource[source]
|
||||
if !ok {
|
||||
logger.Error("OnlyOffice: source not found")
|
||||
return http.StatusInternalServerError, fmt.Errorf("source not found")
|
||||
@@ -219,7 +210,7 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
|
||||
"title": d.fileInfo.Name,
|
||||
"url": downloadURL,
|
||||
"permissions": map[string]interface{}{
|
||||
"edit": utils.Ternary(config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
|
||||
"edit": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
|
||||
"download": true,
|
||||
"print": true,
|
||||
},
|
||||
@@ -236,14 +227,14 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
|
||||
"uiTheme": themeMode,
|
||||
},
|
||||
"lang": d.user.Locale,
|
||||
"mode": utils.Ternary(config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
|
||||
"mode": utils.Ternary(settings.Config.Integrations.OnlyOffice.ViewOnly, "view", canEditMode),
|
||||
},
|
||||
}
|
||||
|
||||
// Sign configuration with JWT if secret is configured
|
||||
if config.Integrations.OnlyOffice.Secret != "" {
|
||||
if settings.Config.Integrations.OnlyOffice.Secret != "" {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(clientConfig))
|
||||
signature, err := token.SignedString([]byte(config.Integrations.OnlyOffice.Secret))
|
||||
signature, err := token.SignedString([]byte(settings.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")
|
||||
@@ -258,10 +249,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 config.Server.InternalUrl != "" {
|
||||
if settings.Config.Server.InternalUrl != "" {
|
||||
// InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly
|
||||
internalURL := strings.TrimSuffix(config.Server.InternalUrl, "/")
|
||||
baseURLPath := strings.TrimPrefix(config.Server.BaseURL, "/")
|
||||
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
|
||||
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
|
||||
if baseURLPath != "" {
|
||||
baseURL = internalURL + "/" + baseURLPath
|
||||
} else {
|
||||
@@ -285,7 +276,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, config.Server.BaseURL)
|
||||
baseURL = fmt.Sprintf("%s://%s%s", scheme, host, settings.Config.Server.BaseURL)
|
||||
}
|
||||
|
||||
escapedPath := url.QueryEscape(path)
|
||||
@@ -302,10 +293,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 config.Server.InternalUrl != "" {
|
||||
if settings.Config.Server.InternalUrl != "" {
|
||||
// InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly
|
||||
internalURL := strings.TrimSuffix(config.Server.InternalUrl, "/")
|
||||
baseURLPath := strings.TrimPrefix(config.Server.BaseURL, "/")
|
||||
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
|
||||
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
|
||||
if baseURLPath != "" {
|
||||
baseURL = internalURL + "/" + baseURLPath
|
||||
} else {
|
||||
@@ -329,7 +320,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, config.Server.BaseURL)
|
||||
baseURL = fmt.Sprintf("%s://%s%s", scheme, host, settings.Config.Server.BaseURL)
|
||||
}
|
||||
|
||||
var callbackURL string
|
||||
@@ -356,97 +347,6 @@ 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
|
||||
@@ -482,7 +382,7 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques
|
||||
//
|
||||
// When the document is fully closed by all editors,
|
||||
// the document key should no longer be re-used.
|
||||
deleteOfficeId(source, path, user)
|
||||
deleteOfficeId(source, path)
|
||||
|
||||
// Send log event for document closure and clean up log context
|
||||
if logContext := getOnlyOfficeLogContext(data.Key); logContext != nil {
|
||||
@@ -592,12 +492,7 @@ func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *reques
|
||||
}
|
||||
|
||||
// Download the updated document from OnlyOffice server
|
||||
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)
|
||||
doc, err := http.Get(data.URL)
|
||||
if err != nil {
|
||||
logger.Errorf("OnlyOffice callback: failed to download updated document: %v", err)
|
||||
return returnOnlyOfficeError(w, r, 500, "failed to download updated document")
|
||||
@@ -755,21 +650,14 @@ func getOnlyOfficeId(realpath string) (string, error) {
|
||||
return "", fmt.Errorf("document key not found")
|
||||
}
|
||||
|
||||
func deleteOfficeId(source, path string, user *users.User) {
|
||||
fi, err := files.FileInfoFaster(utils.FileOptions{
|
||||
Path: path,
|
||||
Source: source,
|
||||
Expand: false,
|
||||
FollowSymlinks: true,
|
||||
}, store.Access, user, store.Share)
|
||||
key := path
|
||||
if fi != nil && fi.RealPath != "" {
|
||||
key = fi.RealPath
|
||||
func deleteOfficeId(source, path string) {
|
||||
idx := indexing.GetIndex(source)
|
||||
if idx == nil {
|
||||
logger.Errorf("deleteOfficeId: failed to find source index for user home dir creation: %s", source)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf("deleteOfficeId: failed to resolve realpath, source=%s, path=%s: %v", source, path, err)
|
||||
}
|
||||
utils.OnlyOfficeCache.Delete(key)
|
||||
realpath, _, _ := idx.GetRealPath(path)
|
||||
utils.OnlyOfficeCache.Delete(realpath)
|
||||
}
|
||||
|
||||
// parseOnlyOfficeJWT parses the JWT token from OnlyOffice callback
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/access"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/share"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
|
||||
)
|
||||
|
||||
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 TestDeleteOfficeId(t *testing.T) {
|
||||
const rawPath = "/docs/document.docx"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
resolve func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error)
|
||||
deleteKey string
|
||||
remainKey string
|
||||
}{
|
||||
{
|
||||
name: "deletes resolved realpath",
|
||||
resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) {
|
||||
return &iteminfo.ExtendedFileInfo{RealPath: "/some/path/document.docx"}, nil
|
||||
},
|
||||
deleteKey: "/some/path/document.docx",
|
||||
remainKey: rawPath,
|
||||
},
|
||||
{
|
||||
name: "fallback to raw path on error",
|
||||
resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) {
|
||||
return nil, fmt.Errorf("could not resolve path")
|
||||
},
|
||||
deleteKey: rawPath,
|
||||
remainKey: "/some/path/document.docx",
|
||||
},
|
||||
{
|
||||
name: "also deletes realpath when partially resolved before erroring",
|
||||
resolve: func(utils.FileOptions) (*iteminfo.ExtendedFileInfo, error) {
|
||||
return &iteminfo.ExtendedFileInfo{RealPath: "/some/path/document.docx"}, fmt.Errorf("access check failed")
|
||||
},
|
||||
deleteKey: "/some/path/document.docx",
|
||||
remainKey: rawPath,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
origStore := store
|
||||
store = &bolt.BoltStore{Access: &access.Storage{}, Share: &share.Storage{}}
|
||||
t.Cleanup(func() { store = origStore })
|
||||
|
||||
origFunc := files.FileInfoFasterFunc
|
||||
t.Cleanup(func() { files.FileInfoFasterFunc = origFunc })
|
||||
files.FileInfoFasterFunc = func(opts utils.FileOptions, accessStore *access.Storage, user *users.User, shareStore *share.Storage) (*iteminfo.ExtendedFileInfo, error) {
|
||||
if opts.Path != rawPath {
|
||||
t.Errorf("expected opts.Path=%q, got %q", rawPath, opts.Path)
|
||||
}
|
||||
if opts.Source != "source" {
|
||||
t.Errorf("expected opts.Source=%q, got %q", "source", opts.Source)
|
||||
}
|
||||
if !opts.FollowSymlinks {
|
||||
t.Error("expected FollowSymlinks=true")
|
||||
}
|
||||
return tt.resolve(opts)
|
||||
}
|
||||
utils.OnlyOfficeCache.Set(tt.deleteKey, "document-key")
|
||||
utils.OnlyOfficeCache.Set(tt.remainKey, "other-key")
|
||||
t.Cleanup(func() {
|
||||
utils.OnlyOfficeCache.Delete(tt.deleteKey)
|
||||
utils.OnlyOfficeCache.Delete(tt.remainKey)
|
||||
})
|
||||
deleteOfficeId("source", rawPath, &users.User{})
|
||||
if _, err := getOnlyOfficeId(tt.deleteKey); err == nil {
|
||||
t.Errorf("expected cache entry %q to be deleted", tt.deleteKey)
|
||||
}
|
||||
if _, err := getOnlyOfficeId(tt.remainKey); err != nil {
|
||||
t.Errorf("expected cache entry %q to remain, but it was deleted", tt.remainKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
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
|
||||
}
|
||||
|
||||
// sharePinnedItemPatchRequest is the JSON body for PATCH /public/api/share/pinnedItems.
|
||||
type sharePinnedItemPatchRequest struct {
|
||||
Path string `json:"path" validate:"required"` // share-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
|
||||
}
|
||||
|
||||
// normalizeShareRelativeDir returns a normalized share-relative directory path key.
|
||||
func normalizeShareRelativeDir(shareRelDir string) (string, error) {
|
||||
if shareRelDir == "" || shareRelDir == "/" {
|
||||
return "/", nil
|
||||
}
|
||||
cleanDir, err := utils.SanitizeUserPath(shareRelDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid path: %w", err)
|
||||
}
|
||||
return utils.AddTrailingSlashIfNotExists(cleanDir), 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
|
||||
}
|
||||
+14
-34
@@ -14,6 +14,7 @@ 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"
|
||||
@@ -84,22 +85,6 @@ 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 {
|
||||
@@ -136,7 +121,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 := config.Server.SourceMap[d.share.Source]
|
||||
sourceInfo, ok := settings.Config.Server.SourceMap[d.share.Source]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("source not found for share")
|
||||
}
|
||||
@@ -171,11 +156,6 @@ 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"
|
||||
@@ -212,12 +192,6 @@ 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
|
||||
}
|
||||
@@ -230,9 +204,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.
|
||||
// Also serve the original when dimensions already fit the requested preview size.
|
||||
if isImage && shouldServeOriginalPreview(ext, resizable, d.fileInfo.RealPath, previewSize, d.fileInfo.Size) {
|
||||
// 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 {
|
||||
return rawFileHandler(w, r, d.fileInfo)
|
||||
}
|
||||
|
||||
@@ -240,7 +214,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 config.Server.InternalUrl != "" {
|
||||
if settings.Config.Server.InternalUrl != "" {
|
||||
officeUrl = config.Server.InternalUrl + pathUrl
|
||||
} else {
|
||||
scheme := "http"
|
||||
@@ -250,6 +224,12 @@ 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)
|
||||
@@ -260,8 +240,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 15 seconds", d.fileInfo.Name)
|
||||
return http.StatusRequestTimeout, fmt.Errorf("preview generation timed out after 15 seconds")
|
||||
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")
|
||||
}
|
||||
|
||||
// Log detailed error information for actual server errors
|
||||
|
||||
+4
-12
@@ -8,6 +8,7 @@ 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"
|
||||
@@ -79,7 +80,7 @@ func publicDownloadHandler(w http.ResponseWriter, r *http.Request, d *requestCon
|
||||
}
|
||||
|
||||
// Get the actual source name from the share's source mapping
|
||||
sourceInfo, ok := config.Server.SourceMap[d.share.Source]
|
||||
sourceInfo, ok := settings.Config.Server.SourceMap[d.share.Source]
|
||||
if !ok {
|
||||
return http.StatusInternalServerError, fmt.Errorf("source not found for share")
|
||||
}
|
||||
@@ -367,19 +368,10 @@ 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, 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].FromPath = utils.JoinPathAsUnix(d.share.Path, req.Items[i].FromPath)
|
||||
req.Items[i].ToSource = sourceName
|
||||
req.Items[i].ToPath = utils.JoinPathAsUnix(d.share.Path, sanitizedPath)
|
||||
req.Items[i].ToPath = utils.JoinPathAsUnix(d.share.Path, req.Items[i].ToPath)
|
||||
}
|
||||
d.Data = req
|
||||
|
||||
|
||||
+13
-87
@@ -18,6 +18,7 @@ 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"
|
||||
@@ -98,12 +99,11 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
|
||||
Expand: true,
|
||||
Content: getContent,
|
||||
Metadata: getMetadata,
|
||||
ExtractEmbeddedSubtitles: config.Integrations.Media.ExtractEmbeddedSubtitles,
|
||||
ExtractEmbeddedSubtitles: settings.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,27 +146,18 @@ 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 {
|
||||
@@ -295,33 +286,8 @@ func resourceBulkDeleteHandler(w http.ResponseWriter, r *http.Request, d *reques
|
||||
if d.share != nil {
|
||||
sourceName := d.share.GetSourceName()
|
||||
if sourceName == "" {
|
||||
response.Failed = append(response.Failed, BulkDeleteItem{
|
||||
Source: item.Source,
|
||||
Path: sanitizedPath,
|
||||
Message: "source name is empty",
|
||||
})
|
||||
continue
|
||||
return http.StatusNotFound, fmt.Errorf("source not available")
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -390,15 +356,6 @@ 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,
|
||||
@@ -536,17 +493,6 @@ 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
|
||||
@@ -558,6 +504,11 @@ 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 {
|
||||
@@ -771,9 +722,6 @@ 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)
|
||||
@@ -907,28 +855,6 @@ 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)
|
||||
|
||||
@@ -8,6 +8,7 @@ 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"
|
||||
@@ -42,12 +43,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):
|
||||
//
|
||||
@@ -256,7 +257,7 @@ func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, erro
|
||||
|
||||
parsed := iteminfo.BuildSearchOptionsFromQuery(query, normalizedTerms, matchAllTerms)
|
||||
|
||||
minLen := config.Server.MinSearchLength
|
||||
minLen := settings.Config.Server.MinSearchLength
|
||||
if !largest {
|
||||
if len(normalizedTerms) > 0 {
|
||||
for _, t := range normalizedTerms {
|
||||
|
||||
+1
-82
@@ -206,12 +206,6 @@ 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 {
|
||||
@@ -221,7 +215,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, sanitizedPath)
|
||||
err = store.Share.UpdateSharePath(body.Hash, body.Path)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, err
|
||||
}
|
||||
@@ -700,78 +694,3 @@ func redirectToShare(w http.ResponseWriter, r *http.Request, d *requestContext)
|
||||
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
|
||||
return http.StatusMovedPermanently, nil
|
||||
}
|
||||
|
||||
// publicSharePatchPinnedItemsHandler adds or removes a pinned item on a share link.
|
||||
// @Summary Add or remove a pinned item on a share
|
||||
// @Description Patches one pinned item at a time for share owners. Defaults to add; pass ?action=remove to unpin.
|
||||
// @Tags Shares
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param hash query string true "Share hash"
|
||||
// @Param action query string false "add (default) or remove"
|
||||
// @Param body body sharePinnedItemPatchRequest true "Pinned item"
|
||||
// @Success 204 "No Content"
|
||||
// @Failure 400 {object} map[string]string "Bad Request"
|
||||
// @Failure 403 {object} map[string]string "Forbidden"
|
||||
// @Failure 404 {object} map[string]string "Share not found"
|
||||
// @Failure 500 {object} map[string]string "Internal Server Error"
|
||||
// @Router /public/api/share/pinnedItems [patch]
|
||||
func sharePatchPinnedItemsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
|
||||
hash := r.URL.Query().Get("hash")
|
||||
if hash == "" {
|
||||
return http.StatusBadRequest, fmt.Errorf("hash is required")
|
||||
}
|
||||
|
||||
link, err := store.Share.GetByHash(hash)
|
||||
if err != nil {
|
||||
return http.StatusNotFound, fmt.Errorf("share hash not found")
|
||||
}
|
||||
|
||||
if d.user.Username == "anonymous" || !link.UserCanEdit(d.user) {
|
||||
return http.StatusForbidden, fmt.Errorf("share pin editing is not allowed for this user")
|
||||
}
|
||||
|
||||
if link.ShareType == "upload" {
|
||||
return http.StatusForbidden, fmt.Errorf("pinning is disabled for upload shares")
|
||||
}
|
||||
|
||||
var body sharePinnedItemPatchRequest
|
||||
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.Path == "" || body.Name == "" {
|
||||
return http.StatusBadRequest, fmt.Errorf("path and name are required")
|
||||
}
|
||||
|
||||
shareRelDir, err := normalizeShareRelativeDir(body.Path)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid path: %s", body.Path)
|
||||
}
|
||||
|
||||
cleanName, err := utils.SanitizeUserPath(body.Name)
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, fmt.Errorf("invalid name: %s", body.Name)
|
||||
}
|
||||
body.Name = cleanName
|
||||
|
||||
pinned := link.EnsurePinnedItems()
|
||||
switch action {
|
||||
case "add":
|
||||
pinned.Add(shareRelDir, body.Name)
|
||||
case "remove":
|
||||
pinned.Remove(shareRelDir, body.Name)
|
||||
}
|
||||
|
||||
if err := store.Share.Save(link); err != nil {
|
||||
return http.StatusInternalServerError, fmt.Errorf("failed to save share: %w", err)
|
||||
}
|
||||
|
||||
return http.StatusNoContent, nil
|
||||
}
|
||||
+11
-45
@@ -6,7 +6,6 @@ import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -96,19 +95,8 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
favicon := staticURL + "/favicon" + faviconExt
|
||||
shareHash := ""
|
||||
data := make(map[string]interface{})
|
||||
disableNavButtons := config.Frontend.DisableNavButtons
|
||||
if d.share != nil {
|
||||
shareHash = d.share.Hash
|
||||
}
|
||||
if shareHash == "" {
|
||||
shareHash = icons.ShareHashFromHTTPPath(r.URL.Path, config.Server.BaseURL)
|
||||
}
|
||||
if shareHash != "" && d.share == nil && store != nil {
|
||||
if link, err := store.Share.GetByHash(shareHash); err == nil {
|
||||
d.share = link
|
||||
}
|
||||
}
|
||||
if d.share != nil {
|
||||
disableNavButtons := settings.Config.Frontend.DisableNavButtons
|
||||
if d.share != nil && d.shareValid {
|
||||
if d.share.Favicon != "" {
|
||||
if strings.HasPrefix(d.share.Favicon, "http") {
|
||||
favicon = d.share.Favicon
|
||||
@@ -136,6 +124,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
if shareFavicon != "" {
|
||||
favicon = shareFavicon
|
||||
}
|
||||
shareHash = d.share.Hash
|
||||
}
|
||||
// Set login icon URL
|
||||
loginIcon := staticURL + "/loginIcon"
|
||||
@@ -173,20 +162,6 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
pwaIcon256 := staticURL + "/icons/pwa-icon-256.png"
|
||||
pwaIcon512 := staticURL + "/icons/pwa-icon-512.png"
|
||||
|
||||
manifestURL := staticURL + "/site.webmanifest"
|
||||
if shareHash != "" {
|
||||
pwaStartURL := config.Server.BaseURL + "public/share/" + shareHash + "/"
|
||||
query := url.Values{}
|
||||
query.Set("start", pwaStartURL)
|
||||
if title != config.Frontend.Name {
|
||||
query.Set("name", title)
|
||||
}
|
||||
if description != config.Frontend.Description {
|
||||
query.Set("description", description)
|
||||
}
|
||||
manifestURL = staticURL + "/site.webmanifest?" + query.Encode()
|
||||
}
|
||||
|
||||
data["htmlVars"] = map[string]interface{}{
|
||||
"title": title,
|
||||
"customCSS": template.CSS(config.Frontend.Styling.CustomCSSRaw),
|
||||
@@ -208,30 +183,30 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
|
||||
"pwaIcon192": pwaIcon192,
|
||||
"pwaIcon256": pwaIcon256,
|
||||
"pwaIcon512": pwaIcon512,
|
||||
"manifestURL": manifestURL,
|
||||
"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": config.UserDefaults.UI.DarkMode,
|
||||
"darkMode": settings.Config.UserDefaults.UI.DarkMode,
|
||||
"baseURL": config.Server.BaseURL,
|
||||
"version": versionString,
|
||||
"commitSHA": commitSHAString,
|
||||
"signup": config.Auth.Methods.PasswordAuth.Signup,
|
||||
"signup": settings.Config.Auth.Methods.PasswordAuth.Signup,
|
||||
"noAuth": config.Auth.Methods.NoAuth,
|
||||
"enableThumbs": !config.Server.DisablePreviews,
|
||||
"externalLinks": externalLinks,
|
||||
"externalUrl": strings.TrimSuffix(config.Server.ExternalUrl, "/"),
|
||||
"onlyOfficeUrl": config.Integrations.OnlyOffice.Url,
|
||||
"onlyOfficeUrl": settings.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": config.Integrations.Media.ExiftoolPath != "",
|
||||
"exiftoolAvailable": settings.Config.Integrations.Media.ExiftoolPath != "",
|
||||
"muPdfAvailable": settings.Env.MuPdfAvailable,
|
||||
"updateAvailable": utils.GetUpdateAvailableUrl(),
|
||||
"disableNavButtons": disableNavButtons,
|
||||
@@ -292,21 +267,12 @@ func setContentType(w http.ResponseWriter, path string) {
|
||||
}
|
||||
}
|
||||
|
||||
// manifestHandler serves the cached PWA manifest, optionally scoped to a public share.
|
||||
// manifestHandler serves the cached PWA manifest
|
||||
func manifestHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/manifest+json")
|
||||
w.Header().Set("Cache-Control", "public, max-age=3600") // Cache for 1 hour
|
||||
|
||||
manifest := icons.CachedManifest
|
||||
if startURL := r.URL.Query().Get("start"); startURL != "" {
|
||||
name := r.URL.Query().Get("name")
|
||||
description := r.URL.Query().Get("description")
|
||||
if shareManifest, ok := icons.ManifestForShare(config.Server.BaseURL, startURL, name, description); ok {
|
||||
manifest = shareManifest
|
||||
}
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(w).Encode(manifest); err != nil {
|
||||
if err := json.NewEncoder(w).Encode(icons.CachedManifest); err != nil {
|
||||
http.Error(w, "Failed to serve manifest", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/auth"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/errors"
|
||||
"github.com/gtsteffaniak/filebrowser/backend/database/users"
|
||||
"github.com/pquerna/otp/totp"
|
||||
)
|
||||
|
||||
func otpRequest(username, password, code string) *http.Request {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/otp?username="+username, http.NoBody)
|
||||
req.Header.Set("X-Password", password)
|
||||
if code != "" {
|
||||
req.Header.Set("X-Secret", code)
|
||||
}
|
||||
return req
|
||||
}
|
||||
|
||||
func TestVerifyOTP_CachedSecretTakesPrecedence(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
|
||||
oldSecret := "SOMEOLDSECRET234"
|
||||
user := &users.User{
|
||||
ID: 1,
|
||||
Username: "test",
|
||||
NonAdminEditable: users.NonAdminEditable{Password: "testPass"},
|
||||
TOTPSecret: oldSecret,
|
||||
OtpEnabled: true,
|
||||
}
|
||||
if err := store.Users.Save(user, true, true); err != nil {
|
||||
t.Fatalf("failed to save user: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { auth.TotpCache.Delete(user.Username) })
|
||||
|
||||
d := &requestContext{user: user}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
if _, err := generateOTPHandler(rec, otpRequest(user.Username, "testPass", ""), d); err != nil {
|
||||
t.Fatalf("genration failed: %v", err)
|
||||
}
|
||||
var resp map[string]string
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
u, err := url.Parse(resp["url"])
|
||||
if err != nil {
|
||||
t.Fatalf("failed to parse url: %v", err)
|
||||
}
|
||||
newSecret := u.Query().Get("secret")
|
||||
if newSecret == oldSecret {
|
||||
t.Fatal("expected a fresh secret")
|
||||
}
|
||||
oldCode, err := totp.GenerateCode(oldSecret, time.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate old code: %v", err)
|
||||
}
|
||||
if _, verifyErr := verifyOTPHandler(httptest.NewRecorder(), otpRequest(user.Username, "testPass", oldCode), d); verifyErr == nil {
|
||||
t.Error("expected old secret to be rejected")
|
||||
}
|
||||
newCode, err := totp.GenerateCode(newSecret, time.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate new code: %v", err)
|
||||
}
|
||||
if _, verifyErr := verifyOTPHandler(httptest.NewRecorder(), otpRequest(user.Username, "testPass", newCode), d); verifyErr != nil {
|
||||
t.Fatalf("expected new secret to be accepted: %v", verifyErr)
|
||||
}
|
||||
updated, err := store.Users.Get(user.Username)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to reload user: %v", err)
|
||||
}
|
||||
if updated.TOTPSecret != newSecret {
|
||||
t.Error("expected TOTPSecret to be updated to the new secret")
|
||||
}
|
||||
if _, found := auth.TotpCache.Get(user.Username); found {
|
||||
t.Error("expected cache to be cleared after verification")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_EnforcedOtp(t *testing.T) {
|
||||
setupTestEnv(t)
|
||||
config.Auth.Key = "test-key"
|
||||
config.Auth.TokenExpirationHours = 1
|
||||
config.Auth.Methods.PasswordAuth.EnforcedOtp = true
|
||||
|
||||
user := &users.User{ID: 2, Username: "loginuser", LoginMethod: users.LoginMethodPassword}
|
||||
d := &requestContext{user: user}
|
||||
|
||||
status, err := loginHandler(httptest.NewRecorder(), otpRequest(user.Username, "", ""), d)
|
||||
if status != http.StatusForbidden || err != errors.ErrNoTotpConfigured {
|
||||
t.Fatalf("expected login without TOTP to fail, got=%d err=%v", status, err)
|
||||
}
|
||||
|
||||
user.TOTPSecret = "SOMESECRET123456"
|
||||
if _, loginErr := loginHandler(httptest.NewRecorder(), otpRequest(user.Username, "", ""), d); loginErr != nil {
|
||||
t.Fatalf("expected login with TOTP to succed, got err=%v", loginErr)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ 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"
|
||||
@@ -100,7 +101,6 @@ 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 := config.Server.SourceMap[source.Path]; ok {
|
||||
if full, ok := settings.Config.Server.SourceMap[source.Path]; ok {
|
||||
if full.Config.ResolvedRules.IndexingDisabled && link.Category != "source-minimal" {
|
||||
link.Category = "source-alt"
|
||||
}
|
||||
|
||||
+12
-20
@@ -27,9 +27,7 @@ func beginPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *request
|
||||
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
|
||||
}
|
||||
|
||||
if err := validateRequestOrigin(r); err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
registerRequestOrigin(r)
|
||||
|
||||
username := r.URL.Query().Get("username")
|
||||
password := r.Header.Get("X-Password")
|
||||
@@ -72,9 +70,7 @@ func finishPasskeyLoginHandler(w http.ResponseWriter, r *http.Request, d *reques
|
||||
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
|
||||
}
|
||||
|
||||
if err := validateRequestOrigin(r); err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
registerRequestOrigin(r)
|
||||
|
||||
sessionID := r.URL.Query().Get("session_id")
|
||||
if sessionID == "" {
|
||||
@@ -104,9 +100,7 @@ func beginPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d *
|
||||
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
|
||||
}
|
||||
|
||||
if err := validateRequestOrigin(r); err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
registerRequestOrigin(r)
|
||||
|
||||
rpID := deriveRPID(r)
|
||||
svc := auth.GetWebAuthn()
|
||||
@@ -140,9 +134,7 @@ func finishPasskeyRegistrationHandler(w http.ResponseWriter, r *http.Request, d
|
||||
return http.StatusForbidden, errors.ErrPasskeyNotEnabled
|
||||
}
|
||||
|
||||
if err := validateRequestOrigin(r); err != nil {
|
||||
return http.StatusForbidden, err
|
||||
}
|
||||
registerRequestOrigin(r)
|
||||
|
||||
sessionID := r.URL.Query().Get("session_id")
|
||||
credentialName := r.URL.Query().Get("name")
|
||||
@@ -215,9 +207,8 @@ func deriveRPID(r *http.Request) string {
|
||||
return host
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// registerRequestOrigin registers the request's origin and RP ID with the WebAuthn service.
|
||||
func registerRequestOrigin(r *http.Request) {
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
@@ -229,12 +220,13 @@ func validateRequestOrigin(r *http.Request) error {
|
||||
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 {
|
||||
if !svc.ValidateOrigin(origin) {
|
||||
return fmt.Errorf("origin %s is not in the configured whitelist", origin)
|
||||
}
|
||||
svc.EnsureOrigin(origin)
|
||||
svc.EnsureRPID(rpID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+49
-49
@@ -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
|
||||
config.Server.CacheDir = tempDir
|
||||
|
||||
// Setup config with sources - update both the local config var AND the global config
|
||||
settings.Config.Server.CacheDir = tempDir
|
||||
|
||||
// Setup config with sources - update both the local config var AND the global settings.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 config so access.Permitted can find sources
|
||||
|
||||
// CRITICAL: Also update the global settings.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,7 +2,6 @@ package icons
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
@@ -206,7 +205,6 @@ 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,8 +8,6 @@ import (
|
||||
type PWAManifest struct {
|
||||
Name string `json:"name"`
|
||||
ShortName string `json:"short_name"`
|
||||
ID string `json:"id"`
|
||||
Scope string `json:"scope"`
|
||||
Icons []PWAIcon `json:"icons"`
|
||||
StartURL string `json:"start_url"`
|
||||
Display string `json:"display"`
|
||||
@@ -42,8 +40,6 @@ func generatePWAManifest(name, description, baseURL, themeColor, pwaIcon192, pwa
|
||||
return PWAManifest{
|
||||
Name: name,
|
||||
ShortName: shortName,
|
||||
ID: baseURL,
|
||||
Scope: baseURL,
|
||||
StartURL: baseURL,
|
||||
Display: "standalone",
|
||||
BackgroundColor: "#ffffff",
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
package icons
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
|
||||
)
|
||||
|
||||
const maxManifestTextLen = 256
|
||||
|
||||
func isValidShareHash(hash string) bool {
|
||||
if len(hash) < 8 || len(hash) > 64 {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(hash, "..") || strings.Contains(hash, "/") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ShareRootFromStartURL validates a share PWA start URL and returns the share root
|
||||
// used for manifest scope/id plus the normalized start URL.
|
||||
func ShareRootFromStartURL(baseURL, startURL string) (shareRoot, normalizedStart string, ok bool) {
|
||||
if startURL == "" || !strings.HasPrefix(startURL, baseURL) {
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
rel := strings.TrimPrefix(startURL, baseURL)
|
||||
if !strings.HasPrefix(rel, "public/share/") {
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
rest := strings.TrimPrefix(rel, "public/share/")
|
||||
hash, subPath, _ := strings.Cut(rest, "/")
|
||||
if !isValidShareHash(hash) {
|
||||
return "", "", false
|
||||
}
|
||||
if subPath != "" {
|
||||
if _, err := utils.SanitizeUserPath(subPath); err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
}
|
||||
|
||||
shareRoot = baseURL + "public/share/" + hash + "/"
|
||||
normalizedStart = startURL
|
||||
if !strings.HasPrefix(normalizedStart, shareRoot) && normalizedStart != strings.TrimSuffix(shareRoot, "/") {
|
||||
return "", "", false
|
||||
}
|
||||
if normalizedStart == baseURL+"public/share/"+hash {
|
||||
normalizedStart = shareRoot
|
||||
}
|
||||
|
||||
return shareRoot, normalizedStart, true
|
||||
}
|
||||
|
||||
// ShareHashFromHTTPPath extracts a share hash from common FileBrowser share routes.
|
||||
func ShareHashFromHTTPPath(path, baseURL string) string {
|
||||
prefixes := []string{
|
||||
strings.TrimSuffix(baseURL, "/") + "/public/share/",
|
||||
"/public/share/",
|
||||
"/share/",
|
||||
}
|
||||
for _, prefix := range prefixes {
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
continue
|
||||
}
|
||||
rest := strings.TrimPrefix(path, prefix)
|
||||
hash, _, _ := strings.Cut(rest, "/")
|
||||
if isValidShareHash(hash) {
|
||||
return hash
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sanitizeManifestText(value string) string {
|
||||
if len(value) > maxManifestTextLen {
|
||||
return value[:maxManifestTextLen]
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// ManifestForShare returns a manifest scoped to a single public share link.
|
||||
func ManifestForShare(baseURL, startURL, name, description string) (PWAManifest, bool) {
|
||||
shareRoot, normalizedStart, ok := ShareRootFromStartURL(baseURL, startURL)
|
||||
if !ok {
|
||||
return PWAManifest{}, false
|
||||
}
|
||||
|
||||
manifest := CachedManifest
|
||||
manifest.StartURL = normalizedStart
|
||||
manifest.Scope = shareRoot
|
||||
manifest.ID = shareRoot
|
||||
|
||||
if name = sanitizeManifestText(strings.TrimSpace(name)); name != "" {
|
||||
manifest.Name = name
|
||||
shortName := name
|
||||
if len(shortName) > 12 {
|
||||
shortName = shortName[:12]
|
||||
}
|
||||
manifest.ShortName = shortName
|
||||
}
|
||||
if description = sanitizeManifestText(strings.TrimSpace(description)); description != "" {
|
||||
manifest.Description = description
|
||||
}
|
||||
|
||||
return manifest, true
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package icons
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestShareRootFromStartURL(t *testing.T) {
|
||||
baseURL := "/testing/"
|
||||
startURL := "/testing/public/share/abc123XYZ-_/"
|
||||
shareRoot, normalizedStart, ok := ShareRootFromStartURL(baseURL, startURL)
|
||||
if !ok {
|
||||
t.Fatal("expected valid share start URL")
|
||||
}
|
||||
if shareRoot != "/testing/public/share/abc123XYZ-_/" {
|
||||
t.Fatalf("unexpected share root: %q", shareRoot)
|
||||
}
|
||||
if normalizedStart != startURL {
|
||||
t.Fatalf("unexpected normalized start: %q", normalizedStart)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareRootFromStartURLRejectsTraversal(t *testing.T) {
|
||||
baseURL := "/testing/"
|
||||
startURL := "/testing/public/share/abc123XYZ-_/../secret/"
|
||||
_, _, ok := ShareRootFromStartURL(baseURL, startURL)
|
||||
if ok {
|
||||
t.Fatal("expected traversal path to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareHashFromHTTPPath(t *testing.T) {
|
||||
baseURL := "/testing/"
|
||||
paths := []string{
|
||||
"/testing/public/share/hash1234567890abcdef/",
|
||||
"/public/share/hash1234567890abcdef/files",
|
||||
"/share/hash1234567890abcdef/",
|
||||
}
|
||||
for _, path := range paths {
|
||||
hash := ShareHashFromHTTPPath(path, baseURL)
|
||||
if hash != "hash1234567890abcdef" {
|
||||
t.Fatalf("path %q: got hash %q", path, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareHashFromHTTPPathRejectsEmbeddedPrefix(t *testing.T) {
|
||||
baseURL := "/testing/"
|
||||
path := "/evil/route/share/hash1234567890abcdef/"
|
||||
hash := ShareHashFromHTTPPath(path, baseURL)
|
||||
if hash != "" {
|
||||
t.Fatalf("expected empty hash for non-prefixed path, got %q", hash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestForShare(t *testing.T) {
|
||||
CachedManifest = PWAManifest{
|
||||
Name: "FileBrowser Quantum",
|
||||
ShortName: "FBQ",
|
||||
StartURL: "/testing/",
|
||||
Scope: "/testing/",
|
||||
ID: "/testing/",
|
||||
}
|
||||
|
||||
manifest, ok := ManifestForShare(
|
||||
"/testing/",
|
||||
"/testing/public/share/hash1234567890abcdef/",
|
||||
"My Share",
|
||||
"Shared files",
|
||||
)
|
||||
if !ok {
|
||||
t.Fatal("expected share manifest")
|
||||
}
|
||||
if manifest.StartURL != "/testing/public/share/hash1234567890abcdef/" {
|
||||
t.Fatalf("unexpected start_url: %q", manifest.StartURL)
|
||||
}
|
||||
if manifest.Scope != "/testing/public/share/hash1234567890abcdef/" {
|
||||
t.Fatalf("unexpected scope: %q", manifest.Scope)
|
||||
}
|
||||
if manifest.Name != "My Share" {
|
||||
t.Fatalf("unexpected name: %q", manifest.Name)
|
||||
}
|
||||
}
|
||||
@@ -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, useLogicalSize bool) int64 {
|
||||
func getDiskUsage(fileInfo os.FileInfo, realPath string, useLogicalSize bool) int64 {
|
||||
// If useLogicalSize is true, return logical size (no block alignment)
|
||||
if useLogicalSize {
|
||||
if fileInfo.IsDir() {
|
||||
@@ -95,8 +95,6 @@ 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"`
|
||||
}
|
||||
@@ -540,7 +538,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)
|
||||
size := idx.getFileSizeForDisplay(ctx.FileInfo, ctx.RealPath)
|
||||
fileInfo := &iteminfo.FileInfo{
|
||||
Path: ctx.IndexPath,
|
||||
ItemInfo: iteminfo.ItemInfo{
|
||||
@@ -624,7 +622,7 @@ func (idx *Index) indexDirectory(indexPath string, opts Options, scanner *Scanne
|
||||
if err2 != nil {
|
||||
return 0, false, err2
|
||||
}
|
||||
idx.UpdateMetadata(dirFileInfo, scanner, !opts.Recursive)
|
||||
idx.UpdateMetadata(dirFileInfo, scanner)
|
||||
|
||||
// Always store the calculated directory size in the in-memory map
|
||||
// This ensures parent directories are updated after copy/move operations
|
||||
@@ -829,7 +827,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))
|
||||
size = uint64(idx.getFileSizeForDisplay(file, fullCombined))
|
||||
shouldCountSize = true
|
||||
} else {
|
||||
size, shouldCountSize = idx.handleFile(file, indexPath, fullCombined, opts.IsRoutineScan, scanner)
|
||||
@@ -1159,14 +1157,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) int64 {
|
||||
func (idx *Index) getFileSizeForDisplay(file os.FileInfo, realPath string) int64 {
|
||||
if idx.Config.UseLogicalSize {
|
||||
// Logical size mode: return actual bytes
|
||||
return file.Size()
|
||||
}
|
||||
|
||||
// Disk usage mode: use getDiskUsage helper
|
||||
return getDiskUsage(file, false)
|
||||
return getDiskUsage(file, realPath, false)
|
||||
}
|
||||
|
||||
// SyncFolderSizesToDB syncs in-memory folder sizes to the database after a scan completes
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package indexing
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -74,12 +73,11 @@ func (s *Scanner) executeScan() {
|
||||
}()
|
||||
|
||||
if s.scanPath != "/" && !s.directoryExists() {
|
||||
s.handlePathGone("pre-scan check")
|
||||
logger.Debugf("Scanner [%s] skipping: directory no longer exists", s.scanPath)
|
||||
s.removeSelf()
|
||||
return
|
||||
}
|
||||
|
||||
s.prepareScanState()
|
||||
|
||||
s.idx.mu.Lock()
|
||||
s.idx.activeScannerPath = s.scanPath
|
||||
s.idx.mu.Unlock()
|
||||
@@ -95,6 +93,12 @@ func (s *Scanner) executeScan() {
|
||||
s.fullScanCounter = 0
|
||||
}
|
||||
})
|
||||
scanMode := "full"
|
||||
if quick {
|
||||
scanMode = "quick"
|
||||
}
|
||||
logger.Debugf("[%s] scanner [%s] starting %s scan (full/quick cadence step %d of 5)", s.idx.Name, s.scanPath, scanMode, pre+1)
|
||||
|
||||
s.runIndexing(quick)
|
||||
s.updateSchedule()
|
||||
}
|
||||
@@ -169,14 +173,13 @@ func (s *Scanner) runFullScanRoot() {
|
||||
s.purgeStaleEntries(true, false) // isRoot=true, isQuickScan=false
|
||||
s.syncStatsWithDB()
|
||||
|
||||
s.resetHardlinkTracking()
|
||||
if s.processedInodes != nil {
|
||||
s.processedInodes = nil
|
||||
s.foundHardLinks = nil
|
||||
}
|
||||
|
||||
s.idx.mu.Lock()
|
||||
if s.idx.scanUpdatedPaths == nil {
|
||||
s.idx.scanUpdatedPaths = make(map[string]bool)
|
||||
} else {
|
||||
clear(s.idx.scanUpdatedPaths)
|
||||
}
|
||||
s.idx.scanUpdatedPaths = make(map[string]bool)
|
||||
s.idx.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -274,10 +277,6 @@ 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()
|
||||
@@ -295,7 +294,10 @@ func (s *Scanner) runFullScanChild() {
|
||||
}
|
||||
}
|
||||
|
||||
s.resetHardlinkTracking()
|
||||
if s.processedInodes != nil {
|
||||
s.processedInodes = nil
|
||||
s.foundHardLinks = nil
|
||||
}
|
||||
|
||||
s.idx.mu.Lock()
|
||||
for path := range s.idx.scanUpdatedPaths {
|
||||
@@ -496,45 +498,6 @@ 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
|
||||
@@ -590,10 +553,7 @@ func (s *Scanner) checkFolderModtime(folderPath string) (bool, error) {
|
||||
info, err := os.Stat(realPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
if folderPath == s.scanPath {
|
||||
s.handlePathGone("quick scan")
|
||||
}
|
||||
// Subfolder deleted — stale entries are removed by purge
|
||||
// Folder was deleted - will be caught by purge
|
||||
return false, nil
|
||||
}
|
||||
logger.Errorf("[QUICK_SCAN] Error stating %s: %v", folderPath, err)
|
||||
@@ -629,13 +589,10 @@ func (s *Scanner) checkFolderModtime(folderPath string) (bool, error) {
|
||||
}
|
||||
|
||||
// Update metadata (will be batched)
|
||||
s.idx.UpdateMetadata(dirInfo, s, true)
|
||||
s.idx.UpdateMetadata(dirInfo, s)
|
||||
|
||||
// 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()
|
||||
|
||||
@@ -644,17 +601,11 @@ 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
|
||||
// BulkInsertItems overwrites all columns — preserve size/hasPreview/hidden from cache/DB, not hardcoded defaults.
|
||||
// Use cached aggregate size: BulkInsertItems overwrites DB size;0 would corrupt LoadFolderSizes on restart.
|
||||
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{
|
||||
@@ -662,8 +613,8 @@ func (s *Scanner) checkFolderModtime(folderPath string) (bool, error) {
|
||||
Size: sizeForDB,
|
||||
ModTime: info.ModTime(),
|
||||
Type: "directory",
|
||||
Hidden: hidden,
|
||||
HasPreview: hasPreview,
|
||||
Hidden: false,
|
||||
HasPreview: false,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -213,7 +213,11 @@ 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--
|
||||
@@ -221,6 +225,7 @@ 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 {
|
||||
@@ -231,7 +236,6 @@ func (idx *Index) runSerialScanPass() {
|
||||
continue
|
||||
}
|
||||
if s.scanPath != "/" && !s.directoryExists() {
|
||||
s.removeSelf()
|
||||
continue
|
||||
}
|
||||
s.executeScan()
|
||||
@@ -279,10 +283,6 @@ 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).Truncate(time.Second)
|
||||
d := time.Until(next)
|
||||
if d < time.Second {
|
||||
d = time.Second
|
||||
}
|
||||
|
||||
@@ -67,5 +67,4 @@ 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
|
||||
}
|
||||
@@ -411,7 +411,20 @@ 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,92 +0,0 @@
|
||||
package iteminfo
|
||||
|
||||
import "strings"
|
||||
|
||||
type namePatternMode int
|
||||
|
||||
const (
|
||||
patternLazyDefault namePatternMode = iota
|
||||
patternQuotedLiteral
|
||||
patternUserGlob
|
||||
)
|
||||
|
||||
func escapeGlobLiteral(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
switch r {
|
||||
case '*', '?', '[', '\\':
|
||||
b.WriteByte('\\')
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func wrapGlobPattern(s string) string {
|
||||
return "*" + s + "*"
|
||||
}
|
||||
|
||||
// BuildNameGlobPattern converts a search term into a SQLite GLOB pattern for indexed file names.
|
||||
func BuildNameGlobPattern(term string, quoted, useWildcard, exactCase bool) string {
|
||||
if term == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
var mode namePatternMode
|
||||
switch {
|
||||
case useWildcard:
|
||||
mode = patternUserGlob
|
||||
case quoted:
|
||||
mode = patternQuotedLiteral
|
||||
default:
|
||||
mode = patternLazyDefault
|
||||
}
|
||||
|
||||
var pattern string
|
||||
switch mode {
|
||||
case patternUserGlob:
|
||||
pattern = term
|
||||
case patternQuotedLiteral:
|
||||
pattern = wrapGlobPattern(escapeGlobLiteral(term))
|
||||
case patternLazyDefault:
|
||||
parts := strings.Fields(term)
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
escaped := make([]string, len(parts))
|
||||
for i, p := range parts {
|
||||
escaped[i] = escapeGlobLiteral(p)
|
||||
}
|
||||
pattern = wrapGlobPattern(strings.Join(escaped, "*"))
|
||||
}
|
||||
|
||||
if !exactCase {
|
||||
pattern = strings.ToLower(pattern)
|
||||
}
|
||||
return pattern
|
||||
}
|
||||
|
||||
// NameGlobPatternsForSearch builds SQLite name GLOB patterns for the given search options.
|
||||
func NameGlobPatternsForSearch(opts SearchOptions, useWildcard, largest bool) []string {
|
||||
if largest || len(opts.Terms) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
exactCase := opts.Conditions["exact"]
|
||||
var patterns []string
|
||||
for _, t := range opts.Terms {
|
||||
if t == "" {
|
||||
continue
|
||||
}
|
||||
p := BuildNameGlobPattern(t, opts.Quoted, useWildcard, exactCase)
|
||||
if p != "" {
|
||||
patterns = append(patterns, p)
|
||||
}
|
||||
}
|
||||
if len(patterns) == 0 {
|
||||
return nil
|
||||
}
|
||||
return patterns
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package iteminfo
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBuildNameGlobPattern(t *testing.T) {
|
||||
tests := []struct {
|
||||
term string
|
||||
quoted bool
|
||||
useWildcard bool
|
||||
exactCase bool
|
||||
want string
|
||||
}{
|
||||
{"cons", false, false, false, "*cons*"},
|
||||
{"new folder", false, false, false, "*new*folder*"},
|
||||
{"new folder", true, false, false, "*new folder*"},
|
||||
{"new*folder", false, true, false, "new*folder"},
|
||||
{"Blade Runner", false, false, false, "*blade*runner*"},
|
||||
{"Blade Runner", false, false, true, "*Blade*Runner*"},
|
||||
{"test[1]", false, false, false, "*test\\[1]*"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := BuildNameGlobPattern(tt.term, tt.quoted, tt.useWildcard, tt.exactCase)
|
||||
if got != tt.want {
|
||||
t.Errorf("BuildNameGlobPattern(%q, quoted=%v, wildcard=%v, exact=%v) = %q, want %q",
|
||||
tt.term, tt.quoted, tt.useWildcard, tt.exactCase, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameGlobPatternsForSearch(t *testing.T) {
|
||||
opts := SearchOptions{
|
||||
Terms: []string{"house", "car"},
|
||||
}
|
||||
patterns := NameGlobPatternsForSearch(opts, false, false)
|
||||
if len(patterns) != 2 || patterns[0] != "*house*" || patterns[1] != "*car*" {
|
||||
t.Fatalf("unexpected patterns: %#v", patterns)
|
||||
}
|
||||
|
||||
optsQuoted := SearchOptions{
|
||||
Terms: []string{"new folder"},
|
||||
Quoted: true,
|
||||
}
|
||||
patterns = NameGlobPatternsForSearch(optsQuoted, false, false)
|
||||
if len(patterns) != 1 || patterns[0] != "*new folder*" {
|
||||
t.Fatalf("unexpected quoted patterns: %#v", patterns)
|
||||
}
|
||||
|
||||
optsLargest := SearchOptions{Terms: []string{"test"}}
|
||||
if p := NameGlobPatternsForSearch(optsLargest, false, true); p != nil {
|
||||
t.Fatalf("largest mode should return nil patterns, got %#v", p)
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,6 @@ type SearchOptions struct {
|
||||
// MatchAllTerms, when true and non-wildcard search, an item must contain every term (AND). When false (default), any term matches (OR).
|
||||
// For name GLOB wildcard search, name must match every pattern when true; when false, patterns are OR-combined in SQL.
|
||||
MatchAllTerms bool
|
||||
// Quoted is true when the search query was a double-quoted phrase; spaces are kept literal in name matching.
|
||||
Quoted bool
|
||||
}
|
||||
|
||||
// BuildSearchOptionsFromQuery merges optional repeated literal terms (HTTP "terms" parameters) with structured filter text ("query" prefix).
|
||||
@@ -121,7 +119,6 @@ func ParseSearch(value string) SearchOptions {
|
||||
unique = strings.TrimSuffix(unique, "\"")
|
||||
|
||||
opts.Terms = []string{unique}
|
||||
opts.Quoted = true
|
||||
return opts
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
@@ -30,7 +30,7 @@ func (idx *Index) CreateMockData(numDirs, numFilesPerDir int) {
|
||||
Files: files,
|
||||
}
|
||||
|
||||
idx.UpdateMetadata(dirInfo, nil, true) // nil scanner for mock
|
||||
idx.UpdateMetadata(dirInfo, nil) // nil scanner for mock
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+35
-18
@@ -13,35 +13,57 @@ import (
|
||||
)
|
||||
|
||||
// UpdateMetadata persists a completed directory listing to the index. The directory row's has_preview
|
||||
// reflects direct previewable children only (see GetDirInfoCore).
|
||||
func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo, scanner *Scanner, persistListedFolders bool) bool {
|
||||
// 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 {
|
||||
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 includeListedFolders {
|
||||
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
|
||||
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,
|
||||
Path: folderPath, // Store index path with trailing slash
|
||||
}
|
||||
items = append(items, folderItem)
|
||||
}
|
||||
}
|
||||
|
||||
for i := range info.Files {
|
||||
f := &info.Files[i]
|
||||
filePath := strings.TrimRight(info.Path, "/") + "/" + f.Name
|
||||
fileItem := &iteminfo.FileInfo{
|
||||
ItemInfo: f.ItemInfo,
|
||||
Path: filePath,
|
||||
// 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)
|
||||
}
|
||||
items = append(items, fileItem)
|
||||
}
|
||||
|
||||
// Use scanner-specific batch if available
|
||||
@@ -49,9 +71,6 @@ func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo, scanner *Scanner, pers
|
||||
// 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()
|
||||
|
||||
@@ -361,8 +380,6 @@ 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
|
||||
}
|
||||
|
||||
@@ -242,7 +242,7 @@ func TestUpdateFileMetadata(t *testing.T) {
|
||||
mock: true,
|
||||
}
|
||||
|
||||
success := index.UpdateMetadata(info, nil, true) // nil scanner for test
|
||||
success := index.UpdateMetadata(info, nil) // nil scanner for test
|
||||
if !success {
|
||||
t.Fatalf("expected UpdateFileMetadata to succeed")
|
||||
}
|
||||
@@ -315,73 +315,9 @@ func TestSetDirectoryInfo(t *testing.T) {
|
||||
{ItemInfo: iteminfo.ItemInfo{Name: "testfile.txt", ModTime: time.Now()}},
|
||||
},
|
||||
}
|
||||
index.UpdateMetadata(dir, nil, true) // nil scanner for test
|
||||
index.UpdateMetadata(dir, nil) // 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")
|
||||
}
|
||||
}
|
||||
+27
-12
@@ -55,11 +55,10 @@ func (idx *Index) SearchParsed(baseOpts iteminfo.SearchOptions, scope string, so
|
||||
searchOptions.Terms = []string{""}
|
||||
}
|
||||
|
||||
nameGlobPatterns := iteminfo.NameGlobPatternsForSearch(searchOptions, useWildcard, largest)
|
||||
caseExact := searchOptions.Conditions["exact"]
|
||||
globAnd := len(nameGlobPatterns) > 0 && searchOptions.MatchAllTerms
|
||||
nameGlobPatterns := nameGlobPatternsForSearch(searchOptions, useWildcard, largest)
|
||||
globAnd := useWildcard && searchOptions.MatchAllTerms
|
||||
|
||||
rows, err := idx.db.SearchItems(idx.Name, scope, largest, nameGlobPatterns, globAnd, caseExact)
|
||||
rows, err := idx.db.SearchItems(idx.Name, scope, largest, nameGlobPatterns, globAnd)
|
||||
if err != nil {
|
||||
return []*SearchResult{}
|
||||
}
|
||||
@@ -96,7 +95,7 @@ func (idx *Index) SearchParsed(baseOpts iteminfo.SearchOptions, scope string, so
|
||||
HasPreview: hasPreview,
|
||||
}
|
||||
|
||||
matches := itemMatchesSearchFilters(item, isDir, searchOptions, largest, nameGlobPatterns)
|
||||
matches := itemMatchesSearchFilters(item, isDir, searchOptions, largest, useWildcard, nameGlobPatterns)
|
||||
|
||||
if matches {
|
||||
resType := mimeType
|
||||
@@ -128,7 +127,7 @@ func (idx *Index) SearchParsed(baseOpts iteminfo.SearchOptions, scope string, so
|
||||
return sortedKeys
|
||||
}
|
||||
|
||||
func itemMatchesSearchFilters(item iteminfo.ItemInfo, isDir bool, searchOptions iteminfo.SearchOptions, largest bool, nameGlobPatterns []string) bool {
|
||||
func itemMatchesSearchFilters(item iteminfo.ItemInfo, isDir bool, searchOptions iteminfo.SearchOptions, largest, useWildcard bool, nameGlobPatterns []string) bool {
|
||||
if largest {
|
||||
largerThan := int64(searchOptions.LargerThan) * 1024 * 1024
|
||||
sizeMatches := largerThan == 0 || item.Size > largerThan
|
||||
@@ -142,7 +141,7 @@ func itemMatchesSearchFilters(item iteminfo.ItemInfo, isDir bool, searchOptions
|
||||
dateMatches := searchDateMatches(item.ModTime.Unix(), searchOptions)
|
||||
return sizeMatches && typeMatches && dateMatches
|
||||
}
|
||||
if len(nameGlobPatterns) > 0 {
|
||||
if useWildcard && len(nameGlobPatterns) > 0 {
|
||||
return item.MatchesSearchAuxiliaryFilters(searchOptions)
|
||||
}
|
||||
if searchOptions.MatchAllTerms {
|
||||
@@ -169,6 +168,23 @@ func itemMatchesSearchFilters(item iteminfo.ItemInfo, isDir bool, searchOptions
|
||||
return false
|
||||
}
|
||||
|
||||
// nameGlobPatternsForSearch builds non-empty parsed terms for SQLite name GLOB OR clauses.
|
||||
func nameGlobPatternsForSearch(opts iteminfo.SearchOptions, useWildcard, largest bool) []string {
|
||||
if largest || !useWildcard || len(opts.Terms) == 0 {
|
||||
return nil
|
||||
}
|
||||
var patterns []string
|
||||
for _, t := range opts.Terms {
|
||||
if t != "" {
|
||||
patterns = append(patterns, t)
|
||||
}
|
||||
}
|
||||
if len(patterns) == 0 {
|
||||
return nil
|
||||
}
|
||||
return patterns
|
||||
}
|
||||
|
||||
func searchDateMatches(modUnix int64, opts iteminfo.SearchOptions) bool {
|
||||
if opts.ModifiedNewerThan > 0 && modUnix < opts.ModifiedNewerThan {
|
||||
return false
|
||||
@@ -218,11 +234,10 @@ func SearchMultiSourcesParsed(baseOpts iteminfo.SearchOptions, sources []string,
|
||||
searchOptions.Terms = []string{""}
|
||||
}
|
||||
|
||||
nameGlobPatterns := iteminfo.NameGlobPatternsForSearch(searchOptions, useWildcard, largest)
|
||||
caseExact := searchOptions.Conditions["exact"]
|
||||
globAnd := len(nameGlobPatterns) > 0 && searchOptions.MatchAllTerms
|
||||
nameGlobPatterns := nameGlobPatternsForSearch(searchOptions, useWildcard, largest)
|
||||
globAnd := useWildcard && searchOptions.MatchAllTerms
|
||||
|
||||
rows, err := db.SearchItemsMultiSource(sources, normalizedScopes, largest, nameGlobPatterns, globAnd, caseExact)
|
||||
rows, err := db.SearchItemsMultiSource(sources, normalizedScopes, largest, nameGlobPatterns, globAnd)
|
||||
if err != nil {
|
||||
return []*SearchResult{}
|
||||
}
|
||||
@@ -260,7 +275,7 @@ func SearchMultiSourcesParsed(baseOpts iteminfo.SearchOptions, sources []string,
|
||||
HasPreview: hasPreview,
|
||||
}
|
||||
|
||||
matches := itemMatchesSearchFilters(item, isDir, searchOptions, largest, nameGlobPatterns)
|
||||
matches := itemMatchesSearchFilters(item, isDir, searchOptions, largest, useWildcard, nameGlobPatterns)
|
||||
|
||||
if matches {
|
||||
resType := mimeType
|
||||
|
||||
@@ -116,14 +116,6 @@ func TestParseSearch(t *testing.T) {
|
||||
Terms: []string{"thisfile"},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: `"new folder"`,
|
||||
want: iteminfo.SearchOptions{
|
||||
Conditions: map[string]bool{"exact": false},
|
||||
Terms: []string{"new folder"},
|
||||
Quoted: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "type:olderThan=2024-06-01 type:newerThan=2024-01-01 findme",
|
||||
want: iteminfo.SearchOptions{
|
||||
@@ -274,13 +266,6 @@ func TestSearchIndexes(t *testing.T) {
|
||||
{ItemInfo: iteminfo.ItemInfo{Name: "toggle.gif", Size: 65536, Type: "image/gif"}},
|
||||
},
|
||||
},
|
||||
"/media/": {
|
||||
ItemInfo: iteminfo.ItemInfo{Name: "media", Type: "directory"},
|
||||
Files: []iteminfo.ExtendedItemInfo{
|
||||
{ItemInfo: iteminfo.ItemInfo{Name: "Blade.Runner.mkv", Type: "video"}},
|
||||
{ItemInfo: iteminfo.ItemInfo{Name: "new.folder.txt", Type: "text"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Insert all directories and files into database
|
||||
@@ -477,65 +462,6 @@ func TestSearchIndexes(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
search: "Blade Runner",
|
||||
scope: "/media/",
|
||||
expectedResult: []*SearchResult{
|
||||
{
|
||||
Path: "/media/Blade.Runner.mkv",
|
||||
Type: "video",
|
||||
Size: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
search: "new folder",
|
||||
scope: "/media/",
|
||||
expectedResult: []*SearchResult{
|
||||
{
|
||||
Path: "/media/new.folder.txt",
|
||||
Type: "text",
|
||||
Size: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
search: "new folder",
|
||||
scope: "/",
|
||||
expectedResult: []*SearchResult{
|
||||
{
|
||||
Path: "/new+folder/",
|
||||
Type: "directory",
|
||||
Size: 0,
|
||||
},
|
||||
{
|
||||
Path: "/media/new.folder.txt",
|
||||
Type: "text",
|
||||
Size: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
search: `"new folder"`,
|
||||
scope: "/media/",
|
||||
expectedResult: []*SearchResult{},
|
||||
},
|
||||
{
|
||||
search: "VIDEO",
|
||||
scope: "/new/test/",
|
||||
expectedResult: []*SearchResult{
|
||||
{
|
||||
Path: "/new/test/video.MP4",
|
||||
Type: "video",
|
||||
Size: 0,
|
||||
},
|
||||
{
|
||||
Path: "/new/test/video.mp4",
|
||||
Type: "video",
|
||||
Size: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -555,59 +481,6 @@ func TestSearchIndexes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchUserGlob(t *testing.T) {
|
||||
if indexDB == nil {
|
||||
var err error
|
||||
indexDB, _, err = dbsql.NewIndexDB("test_search_glob", "OFF", 1000, 32, false)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test database: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
index := Index{
|
||||
Source: settings.Source{
|
||||
Name: "test_search_glob",
|
||||
Path: "/mock/path",
|
||||
},
|
||||
db: indexDB,
|
||||
mock: true,
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
directories := map[string]*iteminfo.FileInfo{
|
||||
"/media/": {
|
||||
ItemInfo: iteminfo.ItemInfo{Name: "media", Type: "directory"},
|
||||
Files: []iteminfo.ExtendedItemInfo{
|
||||
{ItemInfo: iteminfo.ItemInfo{Name: "NEW-folder", Type: "text"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for path, dirInfo := range directories {
|
||||
dirInfo.Path = path
|
||||
if dirInfo.ModTime.IsZero() {
|
||||
dirInfo.ModTime = now
|
||||
}
|
||||
_ = index.db.InsertItem("test_search_glob", path, dirInfo)
|
||||
for _, file := range dirInfo.Files {
|
||||
filePath := strings.TrimSuffix(path, "/") + "/" + file.Name
|
||||
fileInfo := &iteminfo.FileInfo{
|
||||
Path: filePath,
|
||||
ItemInfo: file.ItemInfo,
|
||||
}
|
||||
if fileInfo.ModTime.IsZero() {
|
||||
fileInfo.ModTime = now
|
||||
}
|
||||
_ = index.db.InsertItem("test_search_glob", filePath, fileInfo)
|
||||
}
|
||||
}
|
||||
|
||||
result := index.Search("new*folder", "/media/", "", false, DefaultSearchResults, 0, 0, true)
|
||||
if len(result) != 1 || result[0].Path != "/media/NEW-folder" {
|
||||
t.Fatalf("expected new*folder to match NEW-folder, got %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSearchLargestModeExcludesRoot(t *testing.T) {
|
||||
// Initialize the database if not already done
|
||||
if indexDB == nil {
|
||||
|
||||
@@ -2,7 +2,6 @@ package preview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
@@ -13,22 +12,6 @@ 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(
|
||||
@@ -167,26 +150,12 @@ type ResizeOptions struct {
|
||||
JpegQuality int // JPEG encoding quality (1-100), 0 means use Quality default
|
||||
}
|
||||
|
||||
func (s *Service) Resize(ctx context.Context, in io.Reader, out io.Writer, opts ResizeOptions) error {
|
||||
return s.ResizeWithSize(ctx, in, out, 0, opts)
|
||||
func (s *Service) Resize(in io.Reader, out io.Writer, opts ResizeOptions) error {
|
||||
return s.ResizeWithSize(in, out, 0, opts)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// 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 {
|
||||
// Set defaults
|
||||
if opts.ResizeMode == 0 {
|
||||
opts.ResizeMode = ResizeModeFit
|
||||
@@ -224,7 +193,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, previewDecodeOpts(true)...)
|
||||
img, err := imaging.Decode(wrappedReader, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
// Imaging library failed, try format-specific standard decoder as fallback
|
||||
// Reset reader if possible
|
||||
@@ -248,16 +217,7 @@ func (s *Service) resizeWithSize(in io.Reader, out io.Writer, fileSize int64, op
|
||||
}
|
||||
}
|
||||
|
||||
// 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())
|
||||
}
|
||||
|
||||
// Resize
|
||||
resampleFilter := opts.Quality.resampleFilter()
|
||||
switch opts.ResizeMode {
|
||||
case ResizeModeFill:
|
||||
@@ -282,7 +242,7 @@ func applyOrientationToPreviewBytes(imageBytes []byte, orientation string) []byt
|
||||
if len(imageBytes) < 100 {
|
||||
return imageBytes
|
||||
}
|
||||
img, err := imaging.Decode(bytes.NewReader(imageBytes), previewDecodeOpts(false)...)
|
||||
img, err := imaging.Decode(bytes.NewReader(imageBytes))
|
||||
if err != nil {
|
||||
return imageBytes
|
||||
}
|
||||
@@ -308,7 +268,7 @@ func applyOrientationToPreviewBytes(imageBytes []byte, orientation string) []byt
|
||||
return imageBytes
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, out, &jpeg.Options{Quality: 80}); err != nil {
|
||||
if err := jpeg.Encode(&buf, out, &jpeg.Options{Quality: 90}); err != nil {
|
||||
return imageBytes
|
||||
}
|
||||
return buf.Bytes()
|
||||
@@ -397,6 +357,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.CatmullRom)
|
||||
thumb := imaging.Fit(img, width, height, imaging.Lanczos)
|
||||
return thumb, nil
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package preview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/gif"
|
||||
@@ -248,7 +247,7 @@ func TestService_Resize(t *testing.T) {
|
||||
defer source.Close()
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
err := svc.Resize(context.Background(), source, buf, test.options)
|
||||
err := svc.Resize(source, buf, test.options)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("GetMarketSpecs() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
@@ -460,7 +459,7 @@ func TestResize_ConcurrencyLimit(t *testing.T) {
|
||||
source := newGrayJpeg(t, 100, 100)
|
||||
defer source.Close()
|
||||
out := &bytes.Buffer{}
|
||||
err := svc.Resize(context.Background(), source, out, ResizeOptions{Width: 50, Height: 50})
|
||||
err := svc.Resize(source, out, ResizeOptions{Width: 50, Height: 50})
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, out.Len(), 0)
|
||||
}
|
||||
@@ -474,7 +473,7 @@ func TestResize_ConcurrencyLimit_NoFFmpeg(t *testing.T) {
|
||||
source := newGrayJpeg(t, 100, 100)
|
||||
defer source.Close()
|
||||
out := &bytes.Buffer{}
|
||||
err := svc.Resize(context.Background(), source, out, ResizeOptions{Width: 50, Height: 50})
|
||||
err := svc.Resize(source, out, ResizeOptions{Width: 50, Height: 50})
|
||||
require.NoError(t, err)
|
||||
require.Greater(t, out.Len(), 0)
|
||||
}
|
||||
@@ -495,47 +494,12 @@ func TestCreatePreviewFromReader_UsesConcurrencyLimit(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create preview from reader
|
||||
out, err := svc.CreatePreview(context.Background(), bytes.NewReader(data), int64(len(data)), options)
|
||||
out, err := svc.CreatePreview(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(context.Background(), bytes.NewReader(data), int64(len(data)), options)
|
||||
out2, err := svc.CreatePreview(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)
|
||||
}
|
||||
@@ -87,17 +87,14 @@ func (s *Service) GenerateOfficePreview(ctx context.Context, filetype, key, titl
|
||||
return data, fmt.Errorf("error from OnlyOffice: %s", response.Error)
|
||||
}
|
||||
|
||||
thumbReq, err := http.NewRequestWithContext(ctx, http.MethodGet, response.FileURL, nil)
|
||||
// make get request to binary data response.FileURL and return the body as a byte array data
|
||||
resp, err = http.Get(response.FileURL)
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
thumbResp, err := client.Do(thumbReq)
|
||||
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)
|
||||
}
|
||||
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)
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -50,8 +49,6 @@ 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
|
||||
}
|
||||
@@ -345,13 +342,6 @@ 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 {
|
||||
@@ -365,11 +355,8 @@ func (s *Service) generateImagePreview(ctx context.Context, file iteminfo.Extend
|
||||
return nil, err
|
||||
}
|
||||
|
||||
imageBytes, err := s.CreatePreview(ctx, f, file.Size, options)
|
||||
imageBytes, err := s.CreatePreview(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)
|
||||
@@ -509,18 +496,8 @@ func GeneratePreviewWithMD5(ctx context.Context, file iteminfo.ExtendedFileInfo,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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)
|
||||
resizedBytes, err := service.CreatePreview(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)
|
||||
@@ -556,42 +533,6 @@ 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 {
|
||||
@@ -608,15 +549,15 @@ func getPreviewOptions(previewSize string) (ResizeOptions, error) {
|
||||
Width: 640,
|
||||
Height: 640,
|
||||
ResizeMode: ResizeModeFit,
|
||||
Quality: QualityMedium,
|
||||
Quality: QualityHigh,
|
||||
Format: FormatJpeg,
|
||||
}, nil
|
||||
case "small":
|
||||
return ResizeOptions{
|
||||
Width: 256,
|
||||
Height: 256,
|
||||
ResizeMode: ResizeModeFill,
|
||||
Quality: QualityLow,
|
||||
ResizeMode: ResizeModeFit,
|
||||
Quality: QualityMedium,
|
||||
Format: FormatJpeg,
|
||||
}, nil
|
||||
default:
|
||||
@@ -625,9 +566,9 @@ func getPreviewOptions(previewSize string) (ResizeOptions, error) {
|
||||
}
|
||||
|
||||
// CreatePreview resizes an image from a reader with the given options
|
||||
func (s *Service) CreatePreview(ctx context.Context, reader io.Reader, fileSize int64, options ResizeOptions) ([]byte, error) {
|
||||
func (s *Service) CreatePreview(reader io.Reader, fileSize int64, options ResizeOptions) ([]byte, error) {
|
||||
output := &bytes.Buffer{}
|
||||
if err := s.ResizeWithSize(ctx, reader, output, fileSize, options); err != nil {
|
||||
if err := s.ResizeWithSize(reader, output, fileSize, options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return output.Bytes(), nil
|
||||
|
||||
@@ -512,15 +512,6 @@ const docTemplate = `{
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized - authentication failed",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden - authentication failed",
|
||||
"schema": {
|
||||
@@ -530,15 +521,6 @@ 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": {
|
||||
@@ -3600,70 +3582,6 @@ 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.",
|
||||
@@ -4630,86 +4548,6 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/public/api/share/pinnedItems": {
|
||||
"patch": {
|
||||
"description": "Patches one pinned item at a time for share owners. Defaults to add; pass ?action=remove to unpin.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Shares"
|
||||
],
|
||||
"summary": "Add or remove a pinned item on a share",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Share hash",
|
||||
"name": "hash",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "add (default) or remove",
|
||||
"name": "action",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"description": "Pinned item",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/http.sharePinnedItemPatchRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Share not found",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
@@ -5003,9 +4841,6 @@ const docTemplate = `{
|
||||
"perUserDownloadLimit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"pinnedItems": {
|
||||
"$ref": "#/definitions/share.PinnedItems"
|
||||
},
|
||||
"quickDownload": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -5181,44 +5016,6 @@ 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.sharePinnedItemPatchRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"name": {
|
||||
"description": "item basename within path",
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"description": "share-relative parent directory",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"http.unarchiveRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -5335,13 +5132,6 @@ 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"
|
||||
@@ -5796,22 +5586,6 @@ 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": {
|
||||
@@ -6339,7 +6113,7 @@ const docTemplate = `{
|
||||
"type": "integer"
|
||||
},
|
||||
"numImageProcessors": {
|
||||
"description": "number of concurrent image processing jobs used to create previews, default is 4.",
|
||||
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
|
||||
"type": "integer"
|
||||
},
|
||||
"port": {
|
||||
@@ -6347,7 +6121,7 @@ const docTemplate = `{
|
||||
"type": "integer"
|
||||
},
|
||||
"socket": {
|
||||
"description": "socket to listen on - eg. /var/run/filebrowser.sock",
|
||||
"description": "socket to listen on",
|
||||
"type": "string"
|
||||
},
|
||||
"sources": {
|
||||
@@ -6375,9 +6149,6 @@ const docTemplate = `{
|
||||
"frontend": {
|
||||
"$ref": "#/definitions/settings.Frontend"
|
||||
},
|
||||
"http": {
|
||||
"$ref": "#/definitions/settings.Http"
|
||||
},
|
||||
"integrations": {
|
||||
"$ref": "#/definitions/settings.Integrations"
|
||||
},
|
||||
@@ -6447,10 +6218,6 @@ 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",
|
||||
@@ -7383,9 +7150,6 @@ const docTemplate = `{
|
||||
"perUserDownloadLimit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"pinnedItems": {
|
||||
"$ref": "#/definitions/share.PinnedItems"
|
||||
},
|
||||
"quickDownload": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -7446,15 +7210,6 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"share.PinnedItems": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.AuthToken": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7553,18 +7308,6 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.PinnedItems": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.Preview": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7793,9 +7536,6 @@ 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"
|
||||
|
||||
@@ -501,15 +501,6 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized - authentication failed",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden - authentication failed",
|
||||
"schema": {
|
||||
@@ -519,15 +510,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
@@ -3589,70 +3571,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/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.",
|
||||
@@ -4619,86 +4537,6 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/public/api/share/pinnedItems": {
|
||||
"patch": {
|
||||
"description": "Patches one pinned item at a time for share owners. Defaults to add; pass ?action=remove to unpin.",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Shares"
|
||||
],
|
||||
"summary": "Add or remove a pinned item on a share",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Share hash",
|
||||
"name": "hash",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "add (default) or remove",
|
||||
"name": "action",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"description": "Pinned item",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/http.sharePinnedItemPatchRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "Forbidden",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Share not found",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
@@ -4992,9 +4830,6 @@
|
||||
"perUserDownloadLimit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"pinnedItems": {
|
||||
"$ref": "#/definitions/share.PinnedItems"
|
||||
},
|
||||
"quickDownload": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -5170,44 +5005,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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.sharePinnedItemPatchRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"name": {
|
||||
"description": "item basename within path",
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"description": "share-relative parent directory",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"http.unarchiveRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -5324,13 +5121,6 @@
|
||||
"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"
|
||||
@@ -5785,22 +5575,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
@@ -6328,7 +6102,7 @@
|
||||
"type": "integer"
|
||||
},
|
||||
"numImageProcessors": {
|
||||
"description": "number of concurrent image processing jobs used to create previews, default is 4.",
|
||||
"description": "number of concurrent image processing jobs used to create previews, default is number of cpu cores available.",
|
||||
"type": "integer"
|
||||
},
|
||||
"port": {
|
||||
@@ -6336,7 +6110,7 @@
|
||||
"type": "integer"
|
||||
},
|
||||
"socket": {
|
||||
"description": "socket to listen on - eg. /var/run/filebrowser.sock",
|
||||
"description": "socket to listen on",
|
||||
"type": "string"
|
||||
},
|
||||
"sources": {
|
||||
@@ -6364,9 +6138,6 @@
|
||||
"frontend": {
|
||||
"$ref": "#/definitions/settings.Frontend"
|
||||
},
|
||||
"http": {
|
||||
"$ref": "#/definitions/settings.Http"
|
||||
},
|
||||
"integrations": {
|
||||
"$ref": "#/definitions/settings.Integrations"
|
||||
},
|
||||
@@ -6436,10 +6207,6 @@
|
||||
"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",
|
||||
@@ -7372,9 +7139,6 @@
|
||||
"perUserDownloadLimit": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"pinnedItems": {
|
||||
"$ref": "#/definitions/share.PinnedItems"
|
||||
},
|
||||
"quickDownload": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -7435,15 +7199,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"share.PinnedItems": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.AuthToken": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7542,18 +7297,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.PinnedItems": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"users.Preview": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -7782,9 +7525,6 @@
|
||||
"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"
|
||||
|
||||
@@ -193,8 +193,6 @@ definitions:
|
||||
type: boolean
|
||||
perUserDownloadLimit:
|
||||
type: boolean
|
||||
pinnedItems:
|
||||
$ref: '#/definitions/share.PinnedItems'
|
||||
quickDownload:
|
||||
type: boolean
|
||||
shareTheme:
|
||||
@@ -326,33 +324,6 @@ 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.sharePinnedItemPatchRequest:
|
||||
properties:
|
||||
name:
|
||||
description: item basename within path
|
||||
type: string
|
||||
path:
|
||||
description: share-relative parent directory
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
- path
|
||||
type: object
|
||||
http.unarchiveRequest:
|
||||
properties:
|
||||
deleteAfter:
|
||||
@@ -439,11 +410,6 @@ 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
|
||||
@@ -792,18 +758,6 @@ 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:
|
||||
@@ -1214,13 +1168,13 @@ definitions:
|
||||
type: integer
|
||||
numImageProcessors:
|
||||
description: number of concurrent image processing jobs used to create previews,
|
||||
default is 4.
|
||||
default is number of cpu cores available.
|
||||
type: integer
|
||||
port:
|
||||
description: port to listen on
|
||||
type: integer
|
||||
socket:
|
||||
description: socket to listen on - eg. /var/run/filebrowser.sock
|
||||
description: socket to listen on
|
||||
type: string
|
||||
sources:
|
||||
items:
|
||||
@@ -1241,8 +1195,6 @@ definitions:
|
||||
$ref: '#/definitions/settings.Auth'
|
||||
frontend:
|
||||
$ref: '#/definitions/settings.Frontend'
|
||||
http:
|
||||
$ref: '#/definitions/settings.Http'
|
||||
integrations:
|
||||
$ref: '#/definitions/settings.Integrations'
|
||||
server:
|
||||
@@ -1294,10 +1246,6 @@ 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:
|
||||
@@ -1981,8 +1929,6 @@ definitions:
|
||||
type: string
|
||||
perUserDownloadLimit:
|
||||
type: boolean
|
||||
pinnedItems:
|
||||
$ref: '#/definitions/share.PinnedItems'
|
||||
quickDownload:
|
||||
type: boolean
|
||||
shareTheme:
|
||||
@@ -2029,12 +1975,6 @@ definitions:
|
||||
"gallery"'
|
||||
type: string
|
||||
type: object
|
||||
share.PinnedItems:
|
||||
additionalProperties:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
type: object
|
||||
users.AuthToken:
|
||||
properties:
|
||||
Permissions:
|
||||
@@ -2105,14 +2045,6 @@ 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:
|
||||
@@ -2277,8 +2209,6 @@ 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
|
||||
@@ -2756,25 +2686,12 @@ 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:
|
||||
@@ -4898,49 +4815,6 @@ 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:
|
||||
@@ -5609,58 +5483,4 @@ paths:
|
||||
summary: Get share information by hash
|
||||
tags:
|
||||
- Shares
|
||||
/public/api/share/pinnedItems:
|
||||
patch:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Patches one pinned item at a time for share owners. Defaults to
|
||||
add; pass ?action=remove to unpin.
|
||||
parameters:
|
||||
- description: Share hash
|
||||
in: query
|
||||
name: hash
|
||||
required: true
|
||||
type: string
|
||||
- description: add (default) or remove
|
||||
in: query
|
||||
name: action
|
||||
type: string
|
||||
- description: Pinned item
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/http.sharePinnedItemPatchRequest'
|
||||
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
|
||||
"404":
|
||||
description: Share not found
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
additionalProperties:
|
||||
type: string
|
||||
type: object
|
||||
summary: Add or remove a pinned item on a share
|
||||
tags:
|
||||
- Shares
|
||||
swagger: "2.0"
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
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";
|
||||
import security from "eslint-plugin-security";
|
||||
|
||||
export default defineConfig(
|
||||
{
|
||||
ignores: [
|
||||
"**/dist/**",
|
||||
"**/node_modules/**",
|
||||
"**/public/**",
|
||||
"**/*.json",
|
||||
],
|
||||
},
|
||||
|
||||
// Defaults
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
...pluginVue.configs["flat/essential"],
|
||||
...vueI18n.configs.recommended,
|
||||
security.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",
|
||||
"@typescript-eslint/no-floating-promises": "error",
|
||||
"@typescript-eslint/no-unnecessary-condition": "off", // this one is useful, but is pretty noisy and found lot of false positives
|
||||
"@typescript-eslint/no-dynamic-delete": "warn",
|
||||
"@typescript-eslint/no-misused-promises": "error",
|
||||
"prefer-object-has-own": "error",
|
||||
"no-prototype-builtins": "error",
|
||||
"no-implied-eval": "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",
|
||||
//"vue/no-v-html": "warn",
|
||||
"vue/no-v-text-v-html-on-component": "warn",
|
||||
},
|
||||
},
|
||||
// Relax the rules a bit for tests files
|
||||
{
|
||||
files: ["tests/**/*.ts", "**/*.spec.ts", "**/*.test.ts"],
|
||||
rules: {
|
||||
"preserve-caught-error": "off",
|
||||
"no-empty-pattern": "off",
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"@typescript-eslint/no-unused-vars": ["error", { caughtErrors: "none" }],
|
||||
"no-unused-expressions": "off",
|
||||
"security/detect-non-literal-regexp": "off",
|
||||
},
|
||||
},
|
||||
);
|
||||
Generated
+1342
-1249
File diff suppressed because it is too large.
Load diff
+10
-13
@@ -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": "biome format --write .",
|
||||
"format": "prettier --write .",
|
||||
"test": "vitest run "
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -38,7 +38,8 @@
|
||||
"srt-support-for-html5-videos": "^2.6.11",
|
||||
"three": "^0.182.0",
|
||||
"vue": "^3.4.21",
|
||||
"vue-i18n": "^11.4.4",
|
||||
"vue-i18n": "^9.10.2",
|
||||
"vue-lazyload": "^3.0.0",
|
||||
"vue-router": "^4.3.0"
|
||||
},
|
||||
"overrides": {
|
||||
@@ -46,27 +47,23 @@
|
||||
"@xmldom/xmldom": "^0.8.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@intlify/eslint-plugin-vue-i18n": "^4.4.0",
|
||||
"@intlify/unplugin-vue-i18n": "^11.2.3",
|
||||
"@intlify/eslint-plugin-vue-i18n": "^3.2.0",
|
||||
"@intlify/unplugin-vue-i18n": "^4.0.0",
|
||||
"@playwright/test": "^1.54.1",
|
||||
"@types/eslint-plugin-security": "^3.0.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": "^10.4.0",
|
||||
"eslint-plugin-security": "^4.0.0",
|
||||
"eslint-plugin-vue": "^10.9.1",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-vue": "^9.24.0",
|
||||
"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": "^4.1.8",
|
||||
"vue-eslint-parser": "^10.4.0",
|
||||
"vitest": "^3.0.7",
|
||||
"vue-tsc": "^2.0.7"
|
||||
}
|
||||
}
|
||||
@@ -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 4.
|
||||
socket: "" # socket to listen on - eg. /var/run/filebrowser.sock
|
||||
numImageProcessors: 4 # number of concurrent image processing jobs used to create previews, default is number of cpu cores available.
|
||||
socket: "" # socket to listen on
|
||||
tlsKey: "" # path to TLS key
|
||||
tlsCert: "" # path to TLS cert
|
||||
disablePreviews: false # disable all previews thumbnails, simple icons will be used
|
||||
@@ -26,7 +26,6 @@ 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.
|
||||
@@ -258,6 +257,3 @@ 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).
|
||||
@@ -20,7 +20,6 @@
|
||||
<meta name="theme-color" content="{{ .htmlVars.color }}">
|
||||
|
||||
<!-- Add to home screen for Safari on iOS/iPadOS -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
<meta name="apple-mobile-web-app-title" content="assets">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="{{ .htmlVars.appIcon }}">
|
||||
@@ -52,12 +51,6 @@
|
||||
<!-- Injected variables come from backend server -->
|
||||
<script>
|
||||
window.globalVars = {{ .globalVars }};
|
||||
window.__pwaDeferredPrompt = null;
|
||||
window.addEventListener("beforeinstallprompt", function (event) {
|
||||
event.preventDefault();
|
||||
window.__pwaDeferredPrompt = event;
|
||||
window.dispatchEvent(new Event("pwa-install-available"));
|
||||
});
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
/* eslint-disable security/detect-object-injection */
|
||||
// scripts/sync-translations.js
|
||||
import fs from 'fs-extra';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as deepl from 'deepl-node';
|
||||
import fs from 'fs-extra';
|
||||
import * as glob from 'glob';
|
||||
import * as deepl from 'deepl-node';
|
||||
|
||||
// Parse command line arguments
|
||||
const args = process.argv.slice(2);
|
||||
@@ -77,7 +76,7 @@ async function translateText(text, targetLanguage, keyPath = '') {
|
||||
try {
|
||||
console.log(`Translating "${text}" from '${masterLanguageCode}' to '${targetLanguage}'...`);
|
||||
|
||||
const deeplTargetLang = deeplLangMap[targetLanguage.toLowerCase()] || targetLanguage.toUpperCase();
|
||||
let deeplTargetLang = deeplLangMap[targetLanguage.toLowerCase()] || targetLanguage.toUpperCase();
|
||||
|
||||
const result = await translator.translateText(textToTranslate, masterLanguageCode, deeplTargetLang, options);
|
||||
|
||||
@@ -105,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.hasOwn(masterObj, key)) {
|
||||
if (Object.hasOwn(obj, key)) {
|
||||
if (Object.prototype.hasOwnProperty.call(masterObj, key)) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
newObj[key] = reorderObject(obj[key], masterObj[key]);
|
||||
}
|
||||
}
|
||||
@@ -121,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.hasOwn(masterObj, key)) {
|
||||
if (Object.prototype.hasOwnProperty.call(masterObj, key)) {
|
||||
const currentPathPartsNext = [...currentPathParts, key];
|
||||
const currentKeyPath = currentPathPartsNext.join('.');
|
||||
|
||||
@@ -154,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";
|
||||
}
|
||||
@@ -169,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.hasOwn(targetObj, key) || existingTargetValue === '' || existingTargetValue === null;
|
||||
const isMissing = !Object.prototype.hasOwnProperty.call(targetObj, key) || existingTargetValue === '' || existingTargetValue === null;
|
||||
|
||||
if (isMissing) {
|
||||
if (checkOnly) {
|
||||
@@ -181,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;
|
||||
@@ -189,7 +188,7 @@ async function processKeys(masterObj, targetObj, targetLangCode, currentPathPart
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!Object.hasOwn(targetObj, key)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(targetObj, key)) {
|
||||
if (checkOnly) {
|
||||
console.log(`Would copy key "${currentKeyPath}" (non-string) from English to ${targetLangCode}.json`);
|
||||
meaningfulChanges++; // Copying non-string values is meaningful
|
||||
@@ -207,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.hasOwn(targetObj, key)) {
|
||||
if (!Object.hasOwn(masterObj, key)) {
|
||||
if (Object.prototype.hasOwnProperty.call(targetObj, key)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(masterObj, key)) {
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
@@ -260,7 +259,7 @@ async function syncAllTranslations() {
|
||||
const targetLangCode = path.basename(targetFile, '.json');
|
||||
let targetContent = {};
|
||||
let originalTargetContent = null;
|
||||
const fileExisted = await fs.pathExists(targetFile);
|
||||
let fileExisted = await fs.pathExists(targetFile);
|
||||
|
||||
if (fileExisted) {
|
||||
try {
|
||||
@@ -350,4 +349,4 @@ syncAllTranslations()
|
||||
.catch(error => {
|
||||
console.error("\n❌ An error occurred during translation synchronization:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@
|
||||
<script>
|
||||
import { onMounted } from "vue";
|
||||
import { mutations } from "@/store"; // Import your store's mutations
|
||||
|
||||
mutations.setLoading("main-app", true);
|
||||
export default {
|
||||
name: "app",
|
||||
@@ -22,3 +21,9 @@ export default {
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style>
|
||||
/* Always load styles.css */
|
||||
@import "./css/styles.css";
|
||||
@import "./css/dark.css";
|
||||
</style>
|
||||
@@ -1,5 +1,5 @@
|
||||
import { getApiPath } from '@/utils/url.js'
|
||||
import { fetchJSON } from './utils'
|
||||
import { getApiPath } from '@/utils/url.js'
|
||||
|
||||
/**
|
||||
* @param {string} source
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { notify } from "@/notify";
|
||||
import { getApiPath } from "@/utils/url.js";
|
||||
import { fetchURL } from "./utils";
|
||||
import { getApiPath } from "@/utils/url.js";
|
||||
import { notify } from "@/notify";
|
||||
|
||||
/**
|
||||
* Create an archive on the server (server-side only).
|
||||
@@ -15,7 +15,7 @@ import { fetchURL } from "./utils";
|
||||
*/
|
||||
export async function createArchive(opts) {
|
||||
const { fromSource, toSource, paths, destination, format, compression, deleteAfter } = opts;
|
||||
if (!fromSource || !Array.isArray(paths) || paths.length === 0 || !destination) {
|
||||
if (!fromSource || !paths?.length || !destination) {
|
||||
throw new Error("fromSource, paths, and destination are required");
|
||||
}
|
||||
const body = {
|
||||
|
||||
+35
-38
@@ -1,6 +1,6 @@
|
||||
import { fetchJSON, fetchURL } from '@/api/utils'
|
||||
import { notify } from '@/notify'
|
||||
import { fetchURL, fetchJSON } from '@/api/utils'
|
||||
import { getApiPath } from '@/utils/url.js'
|
||||
import { notify } from '@/notify'
|
||||
|
||||
// POST /api/auth/login
|
||||
export async function login(username, password, recaptcha, otp) {
|
||||
@@ -14,33 +14,29 @@ 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 {
|
||||
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,
|
||||
}
|
||||
});
|
||||
body = JSON.parse(bodyText);
|
||||
} catch {
|
||||
body = { message: bodyText };
|
||||
}
|
||||
|
||||
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));
|
||||
if (res.status != 200) {
|
||||
const msg = body.message || 'Forbidden';
|
||||
throw new Error(msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +54,7 @@ export async function logout() {
|
||||
// POST /api/auth/signup
|
||||
export async function signup(username, password, otp) {
|
||||
const params = { username, password, otp }
|
||||
const apiPath = getApiPath('auth/signup', params)
|
||||
let apiPath = getApiPath('auth/signup', params)
|
||||
const res = await fetch(apiPath, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -73,7 +69,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)
|
||||
@@ -84,7 +80,7 @@ export async function signup(username, password, otp) {
|
||||
export async function generateOTP(username, password) {
|
||||
const params = { username }
|
||||
try {
|
||||
const apiPath = getApiPath('auth/otp/generate', params)
|
||||
let apiPath = getApiPath('auth/otp/generate', params)
|
||||
const res = await fetch(apiPath, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
@@ -108,7 +104,7 @@ export async function generateOTP(username, password) {
|
||||
export async function verifyOTP(username, password, otp) {
|
||||
const params = { username }
|
||||
try {
|
||||
const apiPath = getApiPath('auth/otp/verify', params)
|
||||
let apiPath = getApiPath('auth/otp/verify', params)
|
||||
const res = await fetch(apiPath, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
@@ -117,7 +113,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()
|
||||
@@ -175,10 +171,10 @@ export async function createApiKey(params) {
|
||||
}
|
||||
|
||||
// DELETE /api/auth/token
|
||||
export async function deleteApiKey(params) {
|
||||
export function deleteApiKey(params) {
|
||||
try {
|
||||
const apiPath = getApiPath('auth/token', params)
|
||||
await fetchURL(apiPath, {
|
||||
fetchURL(apiPath, {
|
||||
method: 'DELETE'
|
||||
})
|
||||
} catch (err) {
|
||||
@@ -190,9 +186,7 @@ export async 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, '_')
|
||||
}
|
||||
|
||||
@@ -201,7 +195,10 @@ function base64ToArrayBuffer(base64url) {
|
||||
let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/')
|
||||
while (base64.length % 4) base64 += '='
|
||||
const binary = atob(base64)
|
||||
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i)
|
||||
}
|
||||
return bytes.buffer
|
||||
}
|
||||
|
||||
|
||||
+16
-15
@@ -10,24 +10,25 @@
|
||||
// - /api/media/ -> media.js
|
||||
// - /public/api/* -> public functions in respective files (e.g., resourcesApi.fetchFilesPublic)
|
||||
|
||||
import * as accessApi from "./access";
|
||||
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";
|
||||
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 mediaApi from "./media";
|
||||
|
||||
export {
|
||||
accessApi,
|
||||
export {
|
||||
authApi,
|
||||
mediaApi,
|
||||
officeApi,
|
||||
resourcesApi,
|
||||
settingsApi,
|
||||
shareApi,
|
||||
toolsApi,
|
||||
usersApi,
|
||||
resourcesApi,
|
||||
accessApi,
|
||||
shareApi,
|
||||
settingsApi,
|
||||
toolsApi,
|
||||
officeApi,
|
||||
mediaApi
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { fetchURL, adjustedData } from "./utils";
|
||||
import { notify } from "@/notify";
|
||||
import { state } from "@/store";
|
||||
import { getApiPath, getPublicApiPath } from "@/utils/url.js";
|
||||
import { adjustedData, fetchURL } from "./utils";
|
||||
import { state } from "@/store";
|
||||
|
||||
// GET /api/media/subtitles
|
||||
export async function getSubtitleContent(source, path, subtitleName, embedded = false) {
|
||||
@@ -45,7 +45,8 @@ export async function getLyricsPublic(path, hash, password = "") {
|
||||
});
|
||||
if (!response.ok) {
|
||||
const error = new Error(response.statusText);
|
||||
const data = await response.json();
|
||||
let data = null;
|
||||
data = await response.json();
|
||||
if (data?.message) {
|
||||
error.message = data.message;
|
||||
}
|
||||
@@ -89,7 +90,7 @@ export async function fetchDirectoryMediaMetadataPublic(path, hash, password = "
|
||||
let data = null;
|
||||
try {
|
||||
data = await response.json();
|
||||
} catch (_e) {
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
if (data?.message) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { notify } from '@/notify'
|
||||
import { getApiPath, getPublicApiPath } from '@/utils/url.js'
|
||||
import { fetchURL } from './utils'
|
||||
import { getApiPath, getPublicApiPath } from '@/utils/url.js'
|
||||
import { notify } from '@/notify'
|
||||
|
||||
// GET /api/office/config or /public/api/office/config
|
||||
export async function getConfig(req) {
|
||||
@@ -27,7 +27,7 @@ export async function getConfig(req) {
|
||||
}
|
||||
|
||||
// POST /api/office/callback or /public/api/office/callback
|
||||
export async function callback(params, hash) {
|
||||
export async function callback(params, hash = null) {
|
||||
try {
|
||||
let apiPath
|
||||
if (hash) {
|
||||
|
||||
@@ -1,16 +1,9 @@
|
||||
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 {
|
||||
notifyDownloadComplete,
|
||||
notifyDownloadError,
|
||||
} from '@/utils/appNotifications'
|
||||
import { getApiPath, getPublicApiPath } from '@/utils/url.js'
|
||||
import { adjustedData, fetchURL } from './utils'
|
||||
import { getObjectProperty } from '@/utils/object'
|
||||
|
||||
export { fetchPreviewImage } from '@/utils/previewRequests'
|
||||
|
||||
// Notify if errors occur
|
||||
export async function fetchFiles(source, path, content = false, metadata = false, skipExtendedAttrs = false) {
|
||||
@@ -58,14 +51,14 @@ export async function getItems(source, path, only = "") {
|
||||
* Registers a graceful pause for the active chunked upload at this path.
|
||||
* Call immediately before aborting the chunk XHR so the server keeps partial data.
|
||||
*/
|
||||
export async function signalUploadPause(source, path, shareHash) {
|
||||
export async function signalUploadPause(source, path, shareHash = null) {
|
||||
if (shareHash) {
|
||||
const apiPath = getPublicApiPath('resources/pause', {
|
||||
hash: shareHash,
|
||||
path: path,
|
||||
})
|
||||
const headers = {}
|
||||
const sharePassword = localStorage.getItem(`sharepass:${shareHash}`)
|
||||
const sharePassword = localStorage.getItem('sharepass:' + shareHash)
|
||||
if (sharePassword) {
|
||||
headers['X-SHARE-PASSWORD'] = sharePassword
|
||||
}
|
||||
@@ -85,7 +78,7 @@ async function resourceAction(source, path, method, content) {
|
||||
}
|
||||
try {
|
||||
const apiPath = getApiPath('resources', { path, source })
|
||||
const opts = { method }
|
||||
let opts = { method }
|
||||
if (content) {
|
||||
opts.body = content
|
||||
}
|
||||
@@ -97,7 +90,7 @@ async function resourceAction(source, path, method, content) {
|
||||
let data = null;
|
||||
try {
|
||||
data = await response.json()
|
||||
} catch (_e) {
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
if (data) {
|
||||
@@ -184,7 +177,7 @@ export async function download(format, files, shareHash = "") {
|
||||
if (shareHash) {
|
||||
filePaths = files.map((file) => file.path)
|
||||
} else {
|
||||
for (const file of files) {
|
||||
for (let file of files) {
|
||||
if (!file.source) {
|
||||
throw new Error('File source is required for downloads')
|
||||
}
|
||||
@@ -271,17 +264,11 @@ 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 }
|
||||
}
|
||||
}
|
||||
@@ -290,17 +277,20 @@ async function resolveDownloadContentLength(url) {
|
||||
if (cl) {
|
||||
const n = parseInt(cl, 10)
|
||||
if (Number.isFinite(n) && n > 0) {
|
||||
cancelBody()
|
||||
return { size: n, token }
|
||||
}
|
||||
}
|
||||
}
|
||||
cancelBody()
|
||||
return { size: 0, token }
|
||||
} catch (e) {
|
||||
cancelBody()
|
||||
throw e
|
||||
} finally {
|
||||
if (res.body && typeof res.body.cancel === 'function') {
|
||||
try {
|
||||
await res.body.cancel()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
return { size: 0, token: null }
|
||||
}
|
||||
|
||||
function archiveDisplayFileName(format, files) {
|
||||
@@ -309,20 +299,20 @@ function archiveDisplayFileName(format, files) {
|
||||
if (files.length === 1 && first.isDir) {
|
||||
const base =
|
||||
first.name ||
|
||||
(first.path?.split('/').filter(Boolean).pop()) ||
|
||||
(first.path && first.path.split('/').filter(Boolean).pop()) ||
|
||||
'download'
|
||||
return `${base}${ext}`
|
||||
return base + ext
|
||||
}
|
||||
if (first?.path) {
|
||||
if (first && 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
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -347,7 +337,7 @@ async function chunkedRangeDownloadToBlob(
|
||||
|
||||
while (offset < totalSize) {
|
||||
const download = downloadManager.findById(downloadId)
|
||||
if (download?.status === 'cancelled') {
|
||||
if (download && download.status === 'cancelled') {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -440,7 +430,7 @@ async function chunkedRangeDownloadToBlob(
|
||||
}
|
||||
} catch (readError) {
|
||||
const download = downloadManager.findById(downloadId)
|
||||
if (readError.name === 'AbortError' || (download?.status === 'cancelled')) {
|
||||
if (readError.name === 'AbortError' || (download && download.status === 'cancelled')) {
|
||||
downloadManager.setStatus(downloadId, 'cancelled')
|
||||
return null
|
||||
}
|
||||
@@ -502,7 +492,7 @@ async function downloadChunkedArchive(url, format, files, filePaths, source, sha
|
||||
|
||||
downloadManager.setStatus(downloadId, 'downloading')
|
||||
|
||||
const hasDownloadPrompt = state.prompts.some((h) => h.name === 'download')
|
||||
const hasDownloadPrompt = state.prompts && state.prompts.some((h) => h.name === 'download')
|
||||
if (!hasDownloadPrompt) {
|
||||
mutations.showPrompt({ name: 'download' })
|
||||
}
|
||||
@@ -535,7 +525,6 @@ async function downloadChunkedArchive(url, format, files, filePaths, source, sha
|
||||
|
||||
downloadManager.setStatus(downloadId, 'completed')
|
||||
downloadManager.updateProgress(downloadId, fileSize, fileSize)
|
||||
notifyDownloadComplete(fileName, fileSize)
|
||||
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link)
|
||||
@@ -543,14 +532,13 @@ async function downloadChunkedArchive(url, format, files, filePaths, source, sha
|
||||
}, 100)
|
||||
} catch (error) {
|
||||
const download = downloadManager.findById(downloadId)
|
||||
if (error.name === 'AbortError' || (download?.status === 'cancelled')) {
|
||||
if (error.name === 'AbortError' || (download && download.status === 'cancelled')) {
|
||||
downloadManager.setStatus(downloadId, 'cancelled')
|
||||
return
|
||||
}
|
||||
const message =
|
||||
error instanceof Error ? error.message || 'Unknown error' : String(error)
|
||||
downloadManager.setError(downloadId, message)
|
||||
notifyDownloadError(fileName, message)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -592,7 +580,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.some(h => h.name === 'download');
|
||||
const hasDownloadPrompt = state.prompts && state.prompts.some(h => h.name === 'download');
|
||||
|
||||
if (!hasDownloadPrompt) {
|
||||
mutations.showPrompt({ name: 'download' })
|
||||
@@ -627,7 +615,6 @@ async function downloadChunked(file, shareHash = "") {
|
||||
const dlDone = downloadManager.findById(downloadId)
|
||||
const finalSize = dlDone?.size ?? fileSize
|
||||
downloadManager.updateProgress(downloadId, finalSize, finalSize)
|
||||
notifyDownloadComplete(fileName, finalSize)
|
||||
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link)
|
||||
@@ -636,7 +623,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?.status === "cancelled")) {
|
||||
if (error.name === 'AbortError' || (download && download.status === "cancelled")) {
|
||||
downloadManager.setStatus(downloadId, "cancelled")
|
||||
// Don't throw error or show notification for user-initiated cancellation
|
||||
return;
|
||||
@@ -644,7 +631,6 @@ async function downloadChunked(file, shareHash = "") {
|
||||
const message =
|
||||
error instanceof Error ? error.message || "Unknown error" : String(error)
|
||||
downloadManager.setError(downloadId, message)
|
||||
notifyDownloadError(fileName, message)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -672,9 +658,9 @@ export function post(
|
||||
const request = new XMLHttpRequest();
|
||||
request.open("POST", apiPath, true);
|
||||
|
||||
Object.entries(headers).forEach(([header, value]) => {
|
||||
request.setRequestHeader(header, value);
|
||||
});
|
||||
for (const header in headers) {
|
||||
request.setRequestHeader(header, headers[header]);
|
||||
}
|
||||
|
||||
if (typeof onupload === "function") {
|
||||
request.upload.onprogress = (event) => {
|
||||
@@ -700,7 +686,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);
|
||||
@@ -817,7 +803,7 @@ export async function checksum(source, path, algo) {
|
||||
const apiPath = getApiPath('resources', params)
|
||||
const res = await fetchURL(apiPath)
|
||||
const data = await res.json()
|
||||
return getObjectProperty(data.checksums, algo)
|
||||
return data.checksums[algo]
|
||||
} catch (err) {
|
||||
notify.showError(err.message || 'Error fetching checksum')
|
||||
throw err
|
||||
@@ -845,10 +831,6 @@ 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')
|
||||
@@ -871,7 +853,7 @@ export function getPreviewURL(source, path, modified) {
|
||||
// POST /api/resources/archive - Create an archive
|
||||
export async function createArchive(opts) {
|
||||
const { fromSource, toSource, paths, destination, format, compression, deleteAfter } = opts;
|
||||
if (!fromSource || !Array.isArray(paths) || paths.length === 0 || !destination) {
|
||||
if (!fromSource || !paths?.length || !destination) {
|
||||
throw new Error("fromSource, paths, and destination are required");
|
||||
}
|
||||
const body = {
|
||||
@@ -958,7 +940,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) {
|
||||
@@ -967,7 +949,7 @@ export async function fetchFilesPublic(path, hash, password = "", content = fals
|
||||
(/** @type {any} */ (error)).status = response.status;
|
||||
throw error;
|
||||
}
|
||||
const data = await response.json()
|
||||
let data = await response.json()
|
||||
const adjusted = adjustedData(data);
|
||||
return adjusted
|
||||
}
|
||||
@@ -1045,7 +1027,7 @@ export function postPublic(
|
||||
if (!hash || hash === undefined || hash === null) {
|
||||
throw new Error('no hash provided')
|
||||
}
|
||||
const sharePassword = localStorage.getItem(`sharepass:${hash}`);
|
||||
let sharePassword = localStorage.getItem("sharepass:" + hash);
|
||||
if (sharePassword) {
|
||||
headers["X-SHARE-PASSWORD"] = sharePassword;
|
||||
}
|
||||
@@ -1060,10 +1042,9 @@ export function postPublic(
|
||||
const request = new XMLHttpRequest();
|
||||
request.open("POST", apiPath, true);
|
||||
|
||||
Object.entries(headers).forEach(([header, value]) => {
|
||||
request.setRequestHeader(header, value);
|
||||
});
|
||||
|
||||
for (const header in headers) {
|
||||
request.setRequestHeader(header, headers[header]);
|
||||
}
|
||||
if (typeof onupload === "function") {
|
||||
request.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) {
|
||||
@@ -1088,7 +1069,7 @@ export function postPublic(
|
||||
try {
|
||||
const errorData = JSON.parse(request.responseText);
|
||||
errorMessage = errorData.message || errorMessage;
|
||||
} catch (_e) {
|
||||
} catch (e) {
|
||||
errorMessage = request.responseText || errorMessage;
|
||||
}
|
||||
|
||||
@@ -1133,8 +1114,8 @@ export function postPublic(
|
||||
|
||||
async function resourceActionPublic(hash, path, method, content, token = "") {
|
||||
try {
|
||||
const headers = {};
|
||||
const sharePassword = localStorage.getItem(`sharepass:${hash}`);
|
||||
let headers = {};
|
||||
let sharePassword = localStorage.getItem("sharepass:" + hash);
|
||||
if (sharePassword) {
|
||||
headers["X-SHARE-PASSWORD"] = sharePassword;
|
||||
}
|
||||
@@ -1149,7 +1130,7 @@ async function resourceActionPublic(hash, path, method, content, token = "") {
|
||||
let data = null;
|
||||
try {
|
||||
data = await response.json()
|
||||
} catch (_e) {
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
if (data) {
|
||||
@@ -1174,7 +1155,7 @@ export async function bulkDeletePublic(items) {
|
||||
throw new Error('items array is required and must not be empty')
|
||||
}
|
||||
|
||||
const hash = state.shareInfo.hash;
|
||||
const hash = state.shareInfo?.hash;
|
||||
if (!hash) {
|
||||
throw new Error('share hash is required')
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
const data = await res.json();
|
||||
let data = await res.json();
|
||||
|
||||
return data
|
||||
} catch (err) {
|
||||
|
||||
Loaded 100 of 330 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user