Compare commits

...
18 Commits
Author SHA1 Message Date
Graham Steffaniak 0219b891a2 Fix search url encoding path (#1810) 2026-01-05 17:12:45 -06:00
Graham Steffaniak eee7b7828f Share album art (#1809) 2026-01-05 17:00:27 -06:00
Graham Steffaniak 7f40776c28 Fix symlink delete (#1806) 2026-01-05 15:34:08 -06:00
Graham Steffaniak 9ddafd2df7 Fix stop scanner (#1804) 2026-01-05 13:59:47 -06:00
Graham Steffaniak 82da2c31ff Fix files source name issue (#1803) 2026-01-05 13:26:03 -06:00
Graham Steffaniak 783b9962bb fix exclusion to never exclude root (#1802) 2026-01-05 12:57:07 -06:00
Graham Steffaniak 65d2e4a05b added download permission check (#1801) 2026-01-05 10:45:39 -06:00
Graham Steffaniak 2ad25a0459 improved ui listing view performance (#1796) 2026-01-05 09:23:06 -06:00
Graham Steffaniak eedf63a8de Fix fileperm writing (#1795) 2026-01-04 16:45:23 -06:00
Graham Steffaniak 58b1d53bbb updated share file fixes (#1794) 2026-01-04 14:56:41 -06:00
SmilingPie 5d7d94d86a fix(frontend): fix preview page sorting (#1787) 2026-01-03 10:09:29 -06:00
Graham SteffaniakandKevin B. 9723799e4f Beta/v1.1.5 (#1781)
Co-authored-by: Kevin B. <kurami32_kbm@proton.me>
2025-12-31 13:19:00 -06:00
Graham Steffaniak 3e5f0312f3 updated token claim process (#1774) 2025-12-31 11:13:10 -06:00
MrPanda376 131c3a3686 Bug fix: file permissions not working (#1762) 2025-12-28 15:43:20 -06:00
ATUR 7e5a579dde fix(http): handle Close() errors in archive creation (#1745) 2025-12-20 14:10:37 -06:00
Adam ABICHOU cb2d4dc518 Move custom CSS and user-selected theme styles to the end of the body… (#1744) 2025-12-20 13:53:20 -06:00
Graham SteffaniakandKevin B. 8587ffc092 Beta/v1.1.4 (#1724)
Co-authored-by: Kevin B. <kurami32_kbm@proton.me>
2025-12-15 11:14:40 -06:00
Graham Steffaniak de6fefad4e Beta/v1.1.3 (#1695) 2025-12-02 09:55:48 -06:00
103 changed files with 2512 additions and 1073 deletions

No files matched your search

+41 -5
View File
@@ -59,7 +59,7 @@ jobs:
images: |
gtstef/filebrowser
ghcr.io/gtsteffaniak/filebrowser
- name: Modify tags (strip 'v' and add 'beta'/'stable' if needed)
- name: Modify tags (strip 'v' and add version tags)
id: modify-json
run: |
JSON='${{ steps.meta.outputs.json }}'
@@ -68,13 +68,31 @@ jobs:
sub(":v"; ":") # Strip the 'v'
| select(test(":latest") | not)
) |
if any(.tags[]; test("beta")) then
# Find all version tags with suffix (X.Y.Z-suffix) and add major.minor and major tags
.tags += [
.tags[]
| select(test(":[0-9]+\\.[0-9]+\\.[0-9]+-"))
| split(":")
| .[-1] as $version
| ($version | split("-")) as $version_split
| ($version_split[0] | split(".")) as $version_parts
| ($version_split[1:] | join("-")) as $suffix
| ($version_parts | "\(.[0]).\(.[1])") as $major_minor
| ($version_parts[0]) as $major
| "gtstef/filebrowser:\($major_minor)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major_minor)-\($suffix)",
"gtstef/filebrowser:\($major)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major)-\($suffix)"
] |
# Add suffix-only tags for beta (only if tag ends with -beta)
if any(.tags[]; split(":")[-1] | endswith("-beta")) then
.tags += [
"gtstef/filebrowser:beta",
"ghcr.io/gtsteffaniak/filebrowser:beta"
]
else . end |
if any(.tags[]; test("stable")) then
# Add suffix-only tags for stable (and latest) (only if tag ends with -stable)
if any(.tags[]; split(":")[-1] | endswith("-stable")) then
.tags += [
"gtstef/filebrowser:stable",
"ghcr.io/gtsteffaniak/filebrowser:stable",
@@ -136,13 +154,31 @@ jobs:
| select(test(":latest") | not) # Remove the "latest" tag
| . + "-slim" # Append "-slim" to the versioned tag
) |
if any(.tags[]; test("beta")) then
# Find all version tags with suffix (X.Y.Z-suffix-slim) and add major.minor and major tags
.tags += [
.tags[]
| select(test(":[0-9]+\\.[0-9]+\\.[0-9]+-"))
| split(":")
| .[-1] as $version
| ($version | split("-")) as $version_split
| ($version_split[0] | split(".")) as $version_parts
| ($version_split[1:] | join("-")) as $suffix
| ($version_parts | "\(.[0]).\(.[1])") as $major_minor
| ($version_parts[0]) as $major
| "gtstef/filebrowser:\($major_minor)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major_minor)-\($suffix)",
"gtstef/filebrowser:\($major)-\($suffix)",
"ghcr.io/gtsteffaniak/filebrowser:\($major)-\($suffix)"
] |
# Add suffix-only tags for beta-slim (only if tag ends with -beta-slim)
if any(.tags[]; split(":")[-1] | endswith("-beta-slim")) then
.tags += [
"gtstef/filebrowser:beta-slim",
"ghcr.io/gtsteffaniak/filebrowser:beta-slim"
]
else . end |
if any(.tags[]; test("stable")) then
# Add suffix-only tags for stable-slim (only if tag ends with -stable-slim)
if any(.tags[]; split(":")[-1] | endswith("-stable-slim")) then
.tags += [
"gtstef/filebrowser:stable-slim",
"ghcr.io/gtsteffaniak/filebrowser:stable-slim"
+67
View File
@@ -2,6 +2,73 @@
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.1.6-beta
**Notes**:
- "showHidden" is now a backend attribute. Shares will NOT show hidden files by default unless configured to.
- improved listing view UI performance, especially for folders with many items. (#1773)
**BugFixes**:
- SortBy config is not respected when navigating next/previous (#1786)
- unauthenticated users unable to preview files (#1792)
- File permission not correctly applied( #1790)
- API Key loses "download" permission after creation despite being enabled (#1799)
- never exclude root folder (#1749)
- sources with "files" name not showing after 1.1.x update (#1772)
- Symbolic links can't be deleted from webui. (#1566)
- panic: close of closed channel during indexing (#1771)
- Public sharing returns 404 errors for album art (#1792)
- Directories with some symbols in their name "fail to open" (#1808)
## v1.1.5-beta
**Notes**:
- Major git container tag request #1756
**BugFixes**:
- Sharing broken if source `disableIndexing: true` (#1742)
- Password protected share permission issues (#1729) (#1606) (#1593)
- Sidebar Sliding left (#1737)
- file permissions not working (#1762)
- handle Close() errors in archive creation (#1745)
- Move custom CSS and user-selected theme styles to the end of the body (#1744)
## v1.1.4-beta
**New Features**:
- toggle to show searching results with thumbnails #1545
**Notes**:
- file list has loading spinner to help prevent double click issues and give better feedback
- improved cacheDir startup checks
- warning for slow read/write speeds below 50MB/s
- warning for low free space below 20GB
- warning if read/write latency is slow
- fatal for any errors reading or writing to the directory
- links to official docs for more info
- access rule changes:
- denied folders won't show up in parent directory listing view (#1684)
- tools will respect access rules
- shares will check access rules based on user that created the share
**BugFixes**:
- passwords with special characters not working properly (#1648)
- encoded filename navigation issue (#1711)
- Fix/Improve some behaviors in nextPrevious (#1707)
- Files recognized as folder if they have the same name as previously deleted folders #1697
- multi logger support issue #1701
## v1.1.3-beta
**Notes**:
- continue create user dir scope even if filesystem path creation fails #1509
- access control cache is cleared more aggresively to ensure no delay
- removed default .ico favicon in favor of .svg
**BugFixes**:
- indexing used size increases over time #1685
- download progress is not shown #1687
## v1.1.2-beta
**Notes**:
+3 -1
View File
@@ -7,6 +7,7 @@ COPY [ "./_docker/src/settings/", "./" ]
WORKDIR /app/frontend
COPY [ "./_docker/src/settings/frontend/", "./" ]
COPY [ "./frontend/tests/", "./tests" ]
COPY [ "./frontend/tests/playwright-files", "/tests/playwright-files" ]
WORKDIR /app/backend/
COPY [ "./backend/filebrowser*", "./"]
@@ -17,4 +18,5 @@ COPY [ "./backend/http/embed/", "./http/dist/"]
# Run tests
ENV FILEBROWSER_PLAYWRIGHT_TEST=true
RUN ./filebrowser set -u testuser1,testuser1
RUN ./filebrowser & sleep 2 && cd ../frontend && npx playwright test
RUN ./filebrowser set rule -f /tests/playwright-files -p / -r user -v admin -allow -c config.yaml
RUN ./filebrowser set rule -f /tests/playwright-files -p /excluded -r user -v admin -c config.yaml
+5
View File
@@ -13,6 +13,11 @@ server:
config:
disableIndexing: true
defaultEnabled: true
- path: "/tests/playwright-files"
name: "access"
config:
defaultEnabled: true
denyByDefault: true
frontend:
name: "Graham's Filebrowser"
disableDefaultLinks: true
+56 -34
View File
@@ -28,17 +28,19 @@ import (
func FileInfoFaster(opts utils.FileOptions, access *access.Storage) (*iteminfo.ExtendedFileInfo, error) {
response := &iteminfo.ExtendedFileInfo{}
index := indexing.GetIndex(opts.Source)
if index == nil {
idx := indexing.GetIndex(opts.Source)
if idx == nil {
return response, fmt.Errorf("could not get index: %v ", opts.Source)
}
if !strings.HasPrefix(opts.Path, "/") {
opts.Path = "/" + opts.Path
}
realPath, isDir, err := index.GetRealPath(opts.Path)
if err != nil {
realPath, isDir, err := idx.GetRealPath(opts.Path)
if err != nil && opts.FollowSymlinks {
return response, fmt.Errorf("could not get real path for requested path: %v, error: %v", opts.Path, err)
}
if !strings.HasSuffix(opts.Path, "/") && isDir {
opts.Path = opts.Path + "/"
}
@@ -46,43 +48,53 @@ func FileInfoFaster(opts utils.FileOptions, access *access.Storage) (*iteminfo.E
var info *iteminfo.FileInfo
// Check if path is viewable (allows filesystem access without indexing)
isViewable := index.IsViewable(isDir, opts.Path)
isViewable := idx.IsViewable(isDir, opts.Path)
// For non-viewable paths, verify they are indexed
// Skip this check if indexing is disabled for the entire source
if !isViewable && !index.Config.DisableIndexing {
err = index.RefreshFileInfo(opts)
if !isViewable && !idx.Config.DisableIndexing {
err = idx.RefreshFileInfo(opts)
if err != nil {
return response, fmt.Errorf("path not accessible: %v", err)
}
}
if isDir {
info, err = index.GetFsDirInfo(opts.Path)
if err != nil {
return response, err
}
} else {
// For files, get info from parent directory to ensure HasPreview is set correctly
info, err = index.GetFsDirInfo(opts.Path)
if err != nil {
return response, err
}
info, err = idx.GetFsInfo(opts.Path, opts.FollowSymlinks)
if err != nil {
fmt.Println("Graham 2: ", err)
return response, err
}
response.FileInfo = *info
response.RealPath = realPath
response.Source = opts.Source
if access != nil && !access.Permitted(index.Path, opts.Path, opts.Username) {
// User doesn't have access to the current folder, but check if they have access to any subitems
// This allows specific allow rules on subfolders/files to work even when parent is denied
err := access.CheckChildItemAccess(response, index, opts.Username)
if access != nil {
err := access.CheckChildItemAccess(response, idx, opts.Username)
if err != nil {
return response, err
}
}
// Filter hidden files if ShowHidden is false
if !opts.ShowHidden && isDir {
filteredFiles := []iteminfo.ExtendedItemInfo{}
for _, file := range response.Files {
if !file.Hidden {
filteredFiles = append(filteredFiles, file)
}
}
response.Files = filteredFiles
filteredFolders := []iteminfo.ItemInfo{}
for _, folder := range response.Folders {
if !folder.Hidden {
filteredFolders = append(filteredFolders, folder)
}
}
response.Folders = filteredFolders
}
// For directories, populate metadata for audio/video files ONLY if explicitly requested
// This avoids expensive ffprobe calls on every directory listing
if isDir && opts.Metadata {
@@ -103,7 +115,7 @@ func FileInfoFaster(opts utils.FileOptions, access *access.Storage) (*iteminfo.E
if isItemAudio || isItemVideo {
// Get the real path for this file
itemRealPath, _, _ := index.GetRealPath(opts.Path, fileItem.Name)
itemRealPath, _, _ := idx.GetRealPath(opts.Path, fileItem.Name)
// Capture loop variables in local copies to avoid closure issues
item := fileItem
@@ -150,7 +162,7 @@ func FileInfoFaster(opts utils.FileOptions, access *access.Storage) (*iteminfo.E
// Extract content/metadata when explicitly requested OR for single file audio/video requests
isAudioVideo := strings.HasPrefix(info.Type, "audio") || strings.HasPrefix(info.Type, "video")
if opts.Content || opts.Metadata || (!isDir && isAudioVideo) {
processContent(response, index, opts)
processContent(response, idx, opts)
}
if settings.Config.Integrations.OnlyOffice.Secret != "" && info.Type != "directory" && iteminfo.IsOnlyOffice(info.Name) {
@@ -349,6 +361,10 @@ func DeleteFiles(source, absPath string, absDirPath string, isDir bool) error {
return err
}
// Clear cache entries
indexing.RealPathCache.Delete(absPath)
indexing.IsDirCache.Delete(absPath + ":isdir")
// Remove metadata from index
if isDir {
// Recursively remove directory and all subdirectories from index
@@ -402,6 +418,8 @@ func RefreshIndex(source string, path string, isDir bool, recursive bool) error
if !Exists(realPath) {
// Directory no longer exists, remove it from the index
// This clears both Directories and DirectoriesLedger maps
indexing.RealPathCache.Delete(realPath)
indexing.IsDirCache.Delete(realPath + ":isdir")
idx.DeleteMetadata(path, true, false)
return nil
}
@@ -474,16 +492,11 @@ func MoveResource(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string
// Handle SOURCE cleanup (treat as deletion)
if !srcIdx.Config.DisableIndexing {
// Remove metadata from source index
if isSrcDir {
// Recursively remove directory and all subdirectories from source index
srcIdx.DeleteMetadata(srcIndexPath, true, true)
} else {
// Remove file from source parent's file list
srcIdx.DeleteMetadata(srcIndexPath, false, false)
}
// Refresh the source parent directory to recalculate sizes and update counts
go RefreshIndex(sourceIndex, srcParentPath, true, false) //nolint:errcheck
}
@@ -491,16 +504,11 @@ func MoveResource(isSrcDir bool, sourceIndex, destIndex, realsrc, realdst string
if !dstIdx.Config.DisableIndexing {
if isSrcDir {
go func() {
// When moving a folder, refresh the folder itself recursively FIRST
// Must complete before parent refresh to avoid race condition
RefreshIndex(destIndex, realdst, true, true) //nolint:errcheck
// THEN refresh the parent directory so it sees the newly indexed child
parentDir := filepath.Dir(realdst)
RefreshIndex(destIndex, parentDir, true, false) //nolint:errcheck
}()
} else {
// If moving a file, just refresh the parent directory
parentDir := filepath.Dir(realdst)
go RefreshIndex(destIndex, parentDir, true, false) //nolint:errcheck
}
@@ -588,6 +596,13 @@ func WriteDirectory(opts utils.FileOptions) error {
return err
}
// Explicitly set directory permissions to bypass umask
err = os.Chmod(realPath, fileutils.PermDir)
if err != nil {
// Handle chmod error gracefully
logger.Debugf("Could not set file permissions for %s (this may be expected in restricted environments): %v", realPath, err)
}
return RefreshIndex(idx.Name, opts.Path, true, true)
}
@@ -633,6 +648,13 @@ func WriteFile(source, path string, in io.Reader) error {
return err
}
// Explicitly set file permissions to bypass umask
err = os.Chmod(realPath, fileutils.PermFile)
if err != nil {
// Handle chmod error gracefully
logger.Debugf("Could not set file permissions for %s (this may be expected in restricted environments): %v", realPath, err)
}
return RefreshIndex(source, path, false, false)
}
+13 -6
View File
@@ -8,6 +8,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/database/users"
"github.com/gtsteffaniak/go-logger/logger"
)
// MakeUserDir makes the user directory according to settings.
@@ -26,7 +27,8 @@ func MakeUserDirs(u *users.User, disableScopeChange bool) error {
for i, scope := range u.Scopes {
source, ok := settings.Config.Server.SourceMap[scope.Name]
if !ok {
return fmt.Errorf("MakeUserDirs: source not found: %s", scope.Name)
logger.Errorf("MakeUserDirs: source not found: %s", scope.Name)
continue
}
// create directory and append user name
if filepath.Base(scope.Scope) != cleanedUserName && source.Config.CreateUserDir && !disableScopeChange {
@@ -35,31 +37,36 @@ func MakeUserDirs(u *users.User, disableScopeChange bool) error {
// If parent directory doesn't exist and createUserDir is enabled, create it
if !Exists(parentDir) {
if err := MakeUserDir(parentDir); err != nil {
return fmt.Errorf("MakeUserDirs: failed to create parent scope directory: %s - %v", scope.Scope, err)
logger.Errorf("MakeUserDirs: failed to create parent scope directory: %s - %v", scope.Scope, err)
continue
}
}
// Use JoinPathAsUnix to ensure scope remains in Unix format (forward slashes)
scope.Scope = utils.JoinPathAsUnix(scope.Scope, cleanedUserName)
err := MakeUserDir(fullPath)
if err != nil {
return fmt.Errorf("MakeUserDirs: failed to create user home dir: %s", err)
logger.Errorf("MakeUserDirs: failed to create user home dir: %s", err)
// Continue to next scope even if this one failed
}
} else if filepath.Base(scope.Scope) == cleanedUserName && source.Config.CreateUserDir {
// create directory exactly as specified
fullPath := filepath.Join(source.Path, scope.Scope)
parentDir := filepath.Dir(fullPath)
if !Exists(parentDir) {
return fmt.Errorf("MakeUserDirs: scope folder does not exist: %s", parentDir)
logger.Errorf("MakeUserDirs: scope folder does not exist: %s", parentDir)
continue
}
err := MakeUserDir(fullPath)
if err != nil {
return fmt.Errorf("create user: failed to create user home dir: %s", err)
logger.Errorf("create user: failed to create user home dir: %s", err)
// Continue to next scope even if this one failed
}
} else {
// just assigning scope to path provided, so just check that it exists
path := filepath.Join(source.Path, scope.Scope)
if !Exists(path) {
return fmt.Errorf("MakeUserDirs: scope folder does not exist: %s", path)
logger.Errorf("MakeUserDirs: scope folder does not exist: %s", path)
continue
}
}
u.Scopes[i] = scope
@@ -0,0 +1,31 @@
//go:build !windows
package fileutils
import (
"syscall"
)
// GetPartitionSize returns the filesystem size for Unix systems
func GetPartitionSize(path string) (uint64, error) {
var stat syscall.Statfs_t
err := syscall.Statfs(path, &stat)
if err != nil {
return 0, err
}
// Total size in bytes: Blocks * Block size
total := uint64(stat.Blocks) * uint64(stat.Bsize)
return total, nil
}
// GetFreeSpace returns the available free space for Unix systems
func GetFreeSpace(path string) (uint64, error) {
var stat syscall.Statfs_t
err := syscall.Statfs(path, &stat)
if err != nil {
return 0, err
}
// Available free space in bytes: Available blocks * Block size
free := uint64(stat.Bavail) * uint64(stat.Bsize)
return free, nil
}
@@ -0,0 +1,35 @@
//go:build windows
package fileutils
import (
"golang.org/x/sys/windows"
)
// GetPartitionSize returns the filesystem size for Windows systems
func GetPartitionSize(path string) (uint64, error) {
pathPtr, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, err
}
var freeBytes, totalBytes, totalFreeBytes uint64
err = windows.GetDiskFreeSpaceEx(pathPtr, &freeBytes, &totalBytes, &totalFreeBytes)
if err != nil {
return 0, err
}
return totalBytes, nil
}
// GetFreeSpace returns the available free space for Windows systems
func GetFreeSpace(path string) (uint64, error) {
pathPtr, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, err
}
var freeBytes, totalBytes, totalFreeBytes uint64
err = windows.GetDiskFreeSpaceEx(pathPtr, &freeBytes, &totalBytes, &totalFreeBytes)
if err != nil {
return 0, err
}
return freeBytes, nil
}
+5
View File
@@ -22,6 +22,11 @@ func (auther JSONAuth) Auth(r *http.Request, userStore *users.Storage) (*users.U
username := r.URL.Query().Get("username")
recaptcha := r.URL.Query().Get("recaptcha")
password := r.Header.Get("X-Password")
// URL-decode password to support special characters in headers
password, err := url.QueryUnescape(password)
if err != nil {
return nil, fmt.Errorf("invalid password encoding: %v", err)
}
totpCode := r.Header.Get("X-Secret")
// If ReCaptcha is enabled, check the code.
-4
View File
@@ -17,9 +17,6 @@ func validateAccessRules() {
}
// Get all sources
for sourcePath := range settings.Config.Server.SourceMap {
// Clear cache before migration to ensure we get fresh data
store.Access.ClearCacheForSource(sourcePath)
// Get all rules for this source
rules, err := store.Access.GetAllRules(sourcePath)
if err != nil {
@@ -65,7 +62,6 @@ func validateAccessRules() {
// After migration, clear cache
if migratedCount > 0 {
store.Access.ClearCacheForSource(sourcePath)
logger.Infof("Migrated %d access rules for source %s", migratedCount, sourcePath)
}
}
+156 -59
View File
@@ -60,10 +60,17 @@ func runCLI() bool {
setCmd := flag.NewFlagSet("set", flag.ExitOnError)
var user, dbConfig string
var asAdmin bool
var fsPath, indexPath, ruleCategory, value string
var allow bool
setCmd.StringVar(&user, "u", "", "Comma-separated username and password: \"set -u <username>,<password>\"")
setCmd.BoolVar(&asAdmin, "a", false, "Create a user as admin user, used in combination with -u")
setCmd.StringVar(&dbConfig, "c", "config.yaml", "Path to the config file, default: config.yaml")
setCmd.StringVar(&fsPath, "f", "", "Real filesystem path (e.g. /mnt/storage) for rule command")
setCmd.StringVar(&indexPath, "p", "", "Index path (e.g. /secret) for rule command")
setCmd.StringVar(&ruleCategory, "r", "", "Rule category: 'user', 'group', or 'all' (for deny only)")
setCmd.StringVar(&value, "v", "", "Value: username or groupname (not required if ruleCategory is 'all')")
setCmd.BoolVar(&allow, "allow", false, "Allow access (default: false, which means deny)")
// Parse subcommand flags only if a subcommand is specified
if len(os.Args) > 1 {
@@ -72,72 +79,38 @@ func runCLI() bool {
createConfig(configPath)
return false
case "set":
err := setCmd.Parse(os.Args[2:])
if err != nil {
setCmd.PrintDefaults()
if len(os.Args) < 3 {
fmt.Printf("error: missing subcommand for 'set'. Use 'set user' or 'set rule'\n")
os.Exit(1)
}
userInfo := strings.Split(user, ",")
if len(userInfo) < 2 {
fmt.Printf("not enough info to create user: \"set -u username,password\", only provided %v\n", userInfo)
setCmd.PrintDefaults()
os.Exit(1)
}
username := userInfo[0]
password := userInfo[1]
_ = getStore(dbConfig) // ignore bool check
user, err := store.Users.Get(username)
if err != nil {
newUser := users.User{
Username: username,
LoginMethod: users.LoginMethodPassword,
NonAdminEditable: users.NonAdminEditable{
Password: password,
},
}
for _, source := range settings.Config.Server.SourceMap {
if source.Config.DefaultEnabled {
newUser.Scopes = append(newUser.Scopes, users.SourceScope{
Name: source.Name,
Scope: source.Config.DefaultUserScope,
})
}
}
subcommand := os.Args[2]
// Create the user logic
if asAdmin {
logger.Infof("Creating user as admin: %s\n", username)
} else {
logger.Infof("Creating non-admin user: %s\n", username)
}
newUser.Permissions = settings.ConvertPermissionsToUsers(settings.Config.UserDefaults.Permissions)
newUser.Permissions.Admin = asAdmin
err = storage.CreateUser(newUser, newUser.Permissions)
// New pattern: subcommand-based (e.g., "set user" or "set rule")
// Parse flags starting from os.Args[3:] to skip the subcommand
err := setCmd.Parse(os.Args[3:])
if err != nil {
setCmd.PrintDefaults()
os.Exit(1)
}
switch subcommand {
case "-u":
err := setUser(dbConfig, asAdmin)
if err != nil {
logger.Errorf("could not create user: %v", err)
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
return false
case "rule":
err := setRule(dbConfig, fsPath, indexPath, ruleCategory, value, allow)
if err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
return false
default:
fmt.Printf("error: unknown subcommand '%s' for 'set'. Use 'set user' or 'set rule'\n", subcommand)
os.Exit(1)
}
if user.LoginMethod != users.LoginMethodPassword {
logger.Fatalf("user %s is not allowed to login with password authentication, cannot set password", username)
}
user.Password = password
user.TOTPSecret = "" // reset TOTP secret if it exists
user.TOTPNonce = "" // reset TOTP nonce if it exists
user.LoginMethod = users.LoginMethodPassword
if asAdmin {
user.Permissions.Admin = true
}
// Ensure version is set for existing users being updated
if user.Version == 0 {
user.Version = 1
}
err = store.Users.Save(user, true, false)
if err != nil {
logger.Errorf("could not update user: %v", err)
}
fmt.Printf("successfully updated user: %s\n", username)
return false
case "version":
fmt.Printf(`FileBrowser Quantum - A modern web-based file manager
@@ -151,6 +124,130 @@ func runCLI() bool {
return true
}
func setRule(dbConfig, fsPath, indexPath, ruleCategory, value string, allow bool) error {
// Validate required parameters
if fsPath == "" {
return fmt.Errorf("real filesystem path is required: use -f <fsPath>")
}
if indexPath == "" {
return fmt.Errorf("index path is required: use -p <indexPath>")
}
if ruleCategory == "" {
return fmt.Errorf("ruleCategory is required: use -r <user|group|all>")
}
if ruleCategory != "all" && value == "" {
return fmt.Errorf("value is required when ruleCategory is 'user' or 'group': use -v <username|groupname>")
}
// Initialize store and settings
_ = getStore(dbConfig) // ignore bool check
// Apply the rule based on allow flag and ruleCategory
var err error
if allow {
switch ruleCategory {
case "user":
err = store.Access.AllowUser(fsPath, indexPath, value)
case "group":
err = store.Access.AllowGroup(fsPath, indexPath, value)
default:
return fmt.Errorf("invalid ruleCategory for allow: must be 'user' or 'group'")
}
} else {
switch ruleCategory {
case "user":
err = store.Access.DenyUser(fsPath, indexPath, value)
case "group":
err = store.Access.DenyGroup(fsPath, indexPath, value)
case "all":
err = store.Access.DenyAll(fsPath, indexPath)
default:
return fmt.Errorf("invalid ruleCategory: must be 'user', 'group', or 'all'")
}
}
if err != nil {
return fmt.Errorf("failed to add or update rule: %w", err)
}
action := "deny"
if allow {
action = "allow"
}
if ruleCategory == "all" {
fmt.Printf("successfully added %s rule for all users on index path '%s' in filesystem path '%s'\n", action, indexPath, fsPath)
} else {
fmt.Printf("successfully added %s rule for %s '%s' on index path '%s' in filesystem path '%s'\n", action, ruleCategory, value, indexPath, fsPath)
}
return nil
}
func setUser(dbConfig string, asAdmin bool) error {
if len(os.Args) < 4 {
return fmt.Errorf("missing username and password for 'set user'. Use 'set -u username,password'")
}
userInfo := strings.Split(os.Args[3], ",")
if len(userInfo) < 2 {
return fmt.Errorf("not enough info to create user: \"set -u username,password\", only provided %v", userInfo)
}
username := userInfo[0]
password := userInfo[1]
_ = getStore(dbConfig) // ignore bool check
user, err := store.Users.Get(username)
if err != nil {
newUser := users.User{
Username: username,
LoginMethod: users.LoginMethodPassword,
NonAdminEditable: users.NonAdminEditable{
Password: password,
},
}
for _, source := range settings.Config.Server.SourceMap {
if source.Config.DefaultEnabled {
newUser.Scopes = append(newUser.Scopes, users.SourceScope{
Name: source.Name,
Scope: source.Config.DefaultUserScope,
})
}
}
// Create the user logic
if asAdmin {
logger.Infof("Creating user as admin: %s\n", username)
} else {
logger.Infof("Creating non-admin user: %s\n", username)
}
newUser.Permissions = settings.ConvertPermissionsToUsers(settings.Config.UserDefaults.Permissions)
newUser.Permissions.Admin = asAdmin
err = storage.CreateUser(newUser, newUser.Permissions)
if err != nil {
return fmt.Errorf("could not create user: %v", err)
}
fmt.Printf("successfully created user")
return nil
}
if user.LoginMethod != users.LoginMethodPassword {
return fmt.Errorf("user %s is not allowed to login with password authentication, cannot set password", username)
}
user.Password = password
user.TOTPSecret = "" // reset TOTP secret if it exists
user.TOTPNonce = "" // reset TOTP nonce if it exists
user.LoginMethod = users.LoginMethodPassword
if asAdmin {
user.Permissions.Admin = true
}
// Ensure version is set for existing users being updated
if user.Version == 0 {
user.Version = 1
}
err = store.Users.Save(user, true, false)
if err != nil {
return fmt.Errorf("could not update user: %v", err)
}
fmt.Printf("successfully updated user: %s\n", username)
return nil
}
// UserDefaults defines default settings for new users.
type UserDefaults struct {
Permissions users.Permissions `yaml:"permissions"`
+125 -9
View File
@@ -3,6 +3,7 @@ package settings
import (
"bytes"
"fmt"
"io"
"log"
"os"
"path/filepath"
@@ -87,17 +88,132 @@ func setupFs() {
}
fileutils.SetFsPermissions(os.FileMode(filePermOctal), os.FileMode(dirPermOctal))
// try writing to cache dir
absCacheDir, err := filepath.Abs(Config.Server.CacheDir)
// Perform mandatory cache directory speed test
testCacheDirSpeed()
logger.Infof("cache directory setup successfully: %v", Config.Server.CacheDir)
}
// testCacheDirSpeed performs a mandatory speed test on the cache directory by writing,
// reading, and deleting a 10MB test file. Reports write and read performance in MB/s.
func testCacheDirSpeed() {
msgPrfx := "cacheDir"
failSuffix := "Please review documentation to ensure a valid cache directory is configured https://filebrowserquantum.com/en/docs/configuration/server/#cachedir"
const testFileSize = 10 * 1024 * 1024 // 10MB
// Ensure cache directory exists
err := os.MkdirAll(Config.Server.CacheDir, fileutils.PermDir)
if err != nil {
logger.Errorf("error getting absolute path for 'server.cacheDir: %v': %v", Config.Server.CacheDir, err)
}
cacheDir := filepath.Join(absCacheDir, "init_test")
err = os.MkdirAll(cacheDir, fileutils.PermDir)
if err != nil {
logger.Errorf("Unable to write to 'server.cacheDir: %v', please ensure the cache directory is writable: %v", absCacheDir, err)
logger.Fatalf("%s failed to create cache directory: %v\n%s", msgPrfx, err, failSuffix)
}
testFileName := filepath.Join(Config.Server.CacheDir, "speed_test.tmp")
// Create test data (10MB of zeros)
testData := make([]byte, testFileSize)
// Test write performance
writeStart := time.Now()
file, err := os.Create(testFileName)
if err != nil {
logger.Fatalf("%s failed to create test file: %v\n%s", msgPrfx, err, failSuffix)
}
written, err := file.Write(testData)
if err != nil {
file.Close()
os.Remove(testFileName)
logger.Fatalf("%s failed to write test file: %v\n%s", msgPrfx, err, failSuffix)
}
err = file.Sync() // Ensure data is written to disk
if err != nil {
file.Close()
os.Remove(testFileName)
logger.Fatalf("%s failed to sync test file to disk: %v\n%s", msgPrfx, err, failSuffix)
}
err = file.Close()
if err != nil {
os.Remove(testFileName)
logger.Fatalf("%s failed to close test file: %v\n%s", msgPrfx, err, failSuffix)
}
writeDuration := time.Since(writeStart)
writeSpeedMBs := float64(written) / (1024 * 1024) / writeDuration.Seconds()
// Test read performance
readStart := time.Now()
file, err = os.Open(testFileName)
if err != nil {
os.Remove(testFileName)
logger.Fatalf("%s failed to open test file for reading: %v\n%s", msgPrfx, err, failSuffix)
}
readData := make([]byte, testFileSize)
readBytes, err := io.ReadFull(file, readData)
if err != nil {
file.Close()
os.Remove(testFileName)
logger.Fatalf("%s failed to read test file: %v\n%s", msgPrfx, err, failSuffix)
}
err = file.Close()
if err != nil {
os.Remove(testFileName)
logger.Fatalf("%s failed to close test file after reading: %v\n%s", msgPrfx, err, failSuffix)
}
readDuration := time.Since(readStart)
readSpeedMBs := float64(readBytes) / (1024 * 1024) / readDuration.Seconds()
// Verify data integrity
if readBytes != written {
os.Remove(testFileName)
logger.Fatalf("%s data integrity check failed: wrote %d bytes but read %d bytes\n%s", msgPrfx, written, readBytes, failSuffix)
}
// Clean up test file
err = os.Remove(testFileName)
if err != nil {
logger.Fatalf("%s failed to remove test file: %v\n%s", msgPrfx, err, failSuffix)
}
// Log performance results
writeDurationMs := writeDuration.Seconds() * 1000
readDurationMs := readDuration.Seconds() * 1000
const highLatencyThresholdMs = 1000.0 // 1 second for 10MB file indicates high latency
if writeSpeedMBs < 50 {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s slow write speed detected: %.2f MB/s (%.2f ms)\n%s\n%s", msgPrfx, writeSpeedMBs, writeDurationMs, failSuffix, slowSuffix)
} else if writeDurationMs > highLatencyThresholdMs {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s high write latency detected: %.2f ms for 10MB file (speed: %.2f MB/s). This may indicate network storage or I/O issues.\n%s\n%s", msgPrfx, writeDurationMs, writeSpeedMBs, failSuffix, slowSuffix)
} else {
logger.Debugf("%s write speed: %.2f MB/s (%.2f ms)", msgPrfx, writeSpeedMBs, writeDurationMs)
}
if readSpeedMBs < 50 {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s slow read speed detected: %.2f MB/s (%.2f ms)\n%s\n%s", msgPrfx, readSpeedMBs, readDurationMs, failSuffix, slowSuffix)
} else if readDurationMs > highLatencyThresholdMs {
slowSuffix := " Ensure you configure a faster cache directory via the `server.cacheDir` configuration option."
logger.Warningf("%s high read latency detected: %.2f ms for 10MB file (speed: %.2f MB/s). This may indicate network storage or I/O issues.\n%s\n%s", msgPrfx, readDurationMs, readSpeedMBs, failSuffix, slowSuffix)
} else {
logger.Debugf("%s read speed : %.2f MB/s (%.2f ms)", msgPrfx, readSpeedMBs, readDurationMs)
}
// check cache directory disk free space
freeSpace, err := fileutils.GetFreeSpace(Config.Server.CacheDir)
if err != nil {
logger.Fatalf("%s failed to get free space for cache directory: %v\n%s", msgPrfx, err, failSuffix)
}
freeSpaceGB := float64(freeSpace) / (1024 * 1024 * 1024)
logger.Debugf("%s cache directory has %.2f GB of free space", msgPrfx, freeSpaceGB)
const minRecommendedGB = 20.0
if freeSpaceGB < minRecommendedGB {
logger.Warningf("%s only has %.2f GB of free space, this is less than the %.0f GB minimum recommended free space.\n%s", msgPrfx, freeSpaceGB, minRecommendedGB, failSuffix)
}
}
func setupFrontend(generate bool) {
@@ -643,7 +759,7 @@ func loadCustomFavicon() {
allowedFormats := []string{".ico", ".png", ".svg"}
// Set default embedded favicon path
Env.FaviconEmbeddedPath = "img/icons/favicon.ico"
Env.FaviconEmbeddedPath = "img/icons/favicon.svg"
// Check if a custom favicon path is configured
if Config.Frontend.Favicon == "" {
+2
View File
@@ -55,4 +55,6 @@ type FileOptions struct {
Metadata bool // whether to get metadata
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)
FollowSymlinks bool // whether to follow symlinks
}
+31 -111
View File
@@ -153,18 +153,12 @@ func ClearCache() {
rulesCache = cache.NewCache[map[string]FrontendAccessRule](1 * time.Minute)
}
// ClearCacheForSource clears the cache for a specific source
func (s *Storage) ClearCacheForSource(sourcePath string) {
// Clear all caches related to this source
accessCache.Delete(accessChangedKey + sourcePath)
rulesCache.Delete(accessChangedKey + sourcePath)
versionCache.Delete("version:" + sourcePath)
// Clear all permission caches for this source
// We need to iterate through all permission cache keys and remove those for this source
// Since we can't iterate through cache keys, we'll just increment the version
// which will invalidate all permission caches for this source
s.incrementSourceVersion(sourcePath)
// clearAllCaches clears ALL caches. This should be called whenever rules are created, updated, or deleted.
func (s *Storage) clearAllCaches() {
accessCache.ClearAll()
versionCache.ClearAll()
permissionCache.ClearAll()
rulesCache.ClearAll()
}
// RemoveRuleByPath removes a rule by its exact path from the internal storage
@@ -180,18 +174,11 @@ func (s *Storage) RemoveRuleByPath(sourcePath, indexPath string) {
// Remove the rule by exact path match (don't normalize)
if _, exists := rulesBySource[indexPath]; exists {
delete(rulesBySource, indexPath)
// If no rules left for this source, remove the source entry
if len(rulesBySource) == 0 {
delete(s.AllRules, sourcePath)
}
// Invalidate caches
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
// Save to database
s.clearAllCaches()
err := s.SaveToDB()
if err != nil {
logger.Errorf("error saving access rules to database: %v", err)
@@ -233,9 +220,7 @@ func (s *Storage) DenyUser(sourcePath, indexPath, username string) error {
return errors.ErrExist
}
rule.Deny.Users[username] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return s.SaveToDB()
}
@@ -254,9 +239,7 @@ func (s *Storage) AllowUser(sourcePath, indexPath, username string) error {
return errors.ErrExist
}
rule.Allow.Users[username] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return s.SaveToDB()
}
@@ -273,9 +256,7 @@ func (s *Storage) DenyGroup(sourcePath, indexPath, groupname string) error {
return errors.ErrExist
}
rule.Deny.Groups[groupname] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return s.SaveToDB()
}
@@ -292,9 +273,7 @@ func (s *Storage) AllowGroup(sourcePath, indexPath, groupname string) error {
return errors.ErrExist
}
rule.Allow.Groups[groupname] = struct{}{}
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return s.SaveToDB()
}
@@ -307,19 +286,17 @@ func (s *Storage) DenyAll(sourcePath, indexPath string) error {
return errors.ErrExist
}
rule.DenyAll = true
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return s.SaveToDB()
}
// Permitted checks if a username is permitted for a given sourcePath and indexPath, recursively checking parent directories.
func (s *Storage) Permitted(sourcePath, indexPath, username string) bool {
// SECURITY: All paths MUST start with "/" - reject any path that doesn't
// This prevents path normalization bypass attacks
// Ensure leading slash
if !strings.HasPrefix(indexPath, "/") {
return false
indexPath = "/" + indexPath
}
indexPath = utils.AddTrailingSlashIfNotExists(indexPath)
// Get current version for the sourcePath
versionKey := "version:" + sourcePath
@@ -659,11 +636,7 @@ func (s *Storage) RemoveAllowUser(sourcePath, indexPath, username string) (bool,
if exists {
delete(rule.Allow.Users, username)
}
removed := false
if exists {
s.incrementSourceVersion(sourcePath)
removed = true
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
@@ -672,8 +645,7 @@ func (s *Storage) RemoveAllowUser(sourcePath, indexPath, username string) (bool,
}
}
if removed {
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return exists, s.SaveToDB()
}
return false, nil
@@ -692,11 +664,7 @@ func (s *Storage) RemoveAllowGroup(sourcePath, indexPath, groupname string) (boo
if exists {
delete(rule.Allow.Groups, groupname)
}
removed := false
if exists {
s.incrementSourceVersion(sourcePath)
removed = true
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
@@ -705,8 +673,7 @@ func (s *Storage) RemoveAllowGroup(sourcePath, indexPath, groupname string) (boo
}
}
if removed {
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return exists, s.SaveToDB()
}
return exists, nil
@@ -725,11 +692,7 @@ func (s *Storage) RemoveDenyUser(sourcePath, indexPath, username string) (bool,
if exists {
delete(rule.Deny.Users, username)
}
removed := false
if exists {
s.incrementSourceVersion(sourcePath)
removed = true
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
@@ -738,8 +701,7 @@ func (s *Storage) RemoveDenyUser(sourcePath, indexPath, username string) (bool,
}
}
if removed {
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return exists, s.SaveToDB()
}
return false, nil
@@ -758,11 +720,7 @@ func (s *Storage) RemoveDenyGroup(sourcePath, indexPath, groupname string) (bool
if exists {
delete(rule.Deny.Groups, groupname)
}
removed := false
if exists {
s.incrementSourceVersion(sourcePath)
removed = true
}
removed := exists
// If rule is now empty, remove it
if len(rule.Allow.Users) == 0 && len(rule.Allow.Groups) == 0 && len(rule.Deny.Users) == 0 && len(rule.Deny.Groups) == 0 {
delete(s.AllRules[sourcePath], normalizedPath)
@@ -771,8 +729,7 @@ func (s *Storage) RemoveDenyGroup(sourcePath, indexPath, groupname string) (bool
}
}
if removed {
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return exists, s.SaveToDB()
}
return exists, nil
@@ -790,7 +747,6 @@ func (s *Storage) RemoveDenyAll(sourcePath, indexPath string) (bool, error) {
removed := false
if rule.DenyAll {
rule.DenyAll = false
s.incrementSourceVersion(sourcePath)
removed = true
}
// If rule is now empty, remove it
@@ -801,8 +757,7 @@ func (s *Storage) RemoveDenyAll(sourcePath, indexPath string) (bool, error) {
}
}
if removed {
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return true, s.SaveToDB()
}
return false, nil
@@ -834,12 +789,8 @@ func (s *Storage) RemoveAllRulesForUser(username string) error {
}
}
}
for sp := range changedSourcePaths {
s.incrementSourceVersion(sp)
accessCache.Set(accessChangedKey+sp, "false")
rulesCache.Delete(accessChangedKey + sp)
}
if changed {
s.clearAllCaches()
return s.SaveToDB()
}
return nil
@@ -871,12 +822,8 @@ func (s *Storage) RemoveAllRulesForGroup(groupname string) error {
}
}
}
for sp := range changedSourcePaths {
s.incrementSourceVersion(sp)
accessCache.Set(accessChangedKey+sp, "false")
rulesCache.Delete(accessChangedKey + sp)
}
if changed {
s.clearAllCaches()
return s.SaveToDB()
}
return nil
@@ -1084,25 +1031,11 @@ func (s *Storage) GetAllRulesByGroups(sourcePath string) map[string]map[string]F
return allGroupRules
}
// incrementSourceVersion increments the version of a sourcePath to invalidate caches.
func (s *Storage) incrementSourceVersion(sourcePath string) {
key := "version:" + sourcePath
version := 0
if v, ok := versionCache.Get(key); ok {
version = v
}
versionCache.Set(key, version+1)
}
// HasAnyVisibleItems checks if a user has access to any items in a given parent path.
// This is used to determine if a user should see a folder's contents even when
// they don't have direct access to the parent folder.
func (s *Storage) HasAnyVisibleItems(sourcePath, parentPath string, itemNames []string, username string) bool {
// Ensure parentPath has trailing slash for proper path construction
if !strings.HasSuffix(parentPath, "/") {
parentPath = parentPath + "/"
}
parentPath = utils.AddTrailingSlashIfNotExists(parentPath)
// Check if user has access to any of the items
for _, itemName := range itemNames {
indexPath := parentPath + itemName
@@ -1164,9 +1097,7 @@ func (s *Storage) RemoveUserCascade(sourcePath, indexPath, username string, allo
}
if changed {
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return removedCount, s.SaveToDB()
}
@@ -1223,9 +1154,7 @@ func (s *Storage) RemoveGroupCascade(sourcePath, indexPath, groupname string, al
}
if changed {
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
return removedCount, s.SaveToDB()
}
@@ -1272,11 +1201,7 @@ func (s *Storage) UpdateRules(sourcePath, oldPath, newPath string) (int, error)
}
if updated > 0 {
// Invalidate caches
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
if err := s.SaveToDB(); err != nil {
return updated, err
}
@@ -1307,12 +1232,7 @@ func (s *Storage) UpdateRulePath(sourcePath, oldPath, newPath string) error {
// Remove the old rule and add it with the new path
delete(rulesBySource, oldPath)
rulesBySource[newPath] = rule
// Invalidate caches
s.incrementSourceVersion(sourcePath)
accessCache.Set(accessChangedKey+sourcePath, "false")
rulesCache.Delete(accessChangedKey + sourcePath)
s.clearAllCaches()
logger.Debugf("access rule path updated: source=%s, fromPath=%s, toPath=%s", sourcePath, oldPath, newPath)
return s.SaveToDB()
}
+1 -1
View File
@@ -22,7 +22,7 @@ func (s *Storage) CheckChildItemAccess(response *iteminfo.ExtendedFileInfo, inde
parentPath := index.MakeIndexPath(response.Path)
// Check if user has access to any items
if !s.HasAnyVisibleItems(index.Path, parentPath, allItemNames, username) {
if !s.HasAnyVisibleItems(index.Path, parentPath, allItemNames, username) && len(allItemNames) > 0 {
return errors.ErrAccessDenied
}
+1
View File
@@ -41,6 +41,7 @@ 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)
}
type CreateBody struct {
CommonShare
+1 -1
View File
@@ -117,7 +117,7 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
user.Scopes = adjustedScopes
err = files.MakeUserDirs(user, true)
if err != nil {
return err
logger.Error(err.Error())
}
}
// converting scopes to map of paths intead of names (names can change)
+10 -7
View File
@@ -17,13 +17,16 @@ const (
)
type AuthToken struct {
Key string `json:"key"`
Name string `json:"name"`
Created int64 `json:"createdAt"`
Expires int64 `json:"expiresAt"`
BelongsTo uint `json:"belongsTo"`
Permissions Permissions `json:"Permissions"`
jwt.RegisteredClaims `json:"-"`
MinimalAuthToken
Key string `json:"key,omitempty"`
Name string `json:"name,omitempty"`
BelongsTo uint `json:"belongsTo,omitempty"`
Permissions Permissions `json:"Permissions,omitempty"`
}
// MinimalAuthToken is used for tokens that only include JWT standard claims
type MinimalAuthToken struct {
jwt.RegisteredClaims `swaggerignore:"true"`
}
type Permissions struct {
+29 -28
View File
@@ -4,27 +4,27 @@ go 1.25.0
require (
github.com/asdine/storm/v3 v3.2.1
github.com/coreos/go-oidc/v3 v3.16.0
github.com/coreos/go-oidc/v3 v3.17.0
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
github.com/dsoprea/go-exif/v3 v3.0.1
github.com/gen2brain/go-fitz v1.24.15
github.com/go-playground/validator/v10 v10.28.0
github.com/goccy/go-yaml v1.18.0
github.com/go-playground/validator/v10 v10.29.0
github.com/goccy/go-yaml v1.19.0
github.com/golang-jwt/jwt/v4 v4.5.2
github.com/google/go-cmp v0.7.0
github.com/gtsteffaniak/go-cache v1.0.0
github.com/gtsteffaniak/go-logger v0.2.3
github.com/gtsteffaniak/go-cache v1.1.0
github.com/gtsteffaniak/go-logger v0.2.4
github.com/kovidgoyal/imaging v1.7.2
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.45.0
golang.org/x/image v0.33.0
golang.org/x/mod v0.30.0
golang.org/x/oauth2 v0.33.0
golang.org/x/sys v0.38.0
golang.org/x/crypto v0.46.0
golang.org/x/image v0.34.0
golang.org/x/mod v0.31.0
golang.org/x/oauth2 v0.34.0
golang.org/x/sys v0.39.0
golang.org/x/time v0.14.0
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.40.1
@@ -105,16 +105,16 @@ require (
github.com/go-critic/go-critic v0.14.2 // indirect
github.com/go-errors/errors v1.5.1 // indirect
github.com/go-jose/go-jose/v4 v4.1.3 // indirect
github.com/go-openapi/jsonpointer v0.22.3 // indirect
github.com/go-openapi/jsonreference v0.21.3 // indirect
github.com/go-openapi/spec v0.22.1 // indirect
github.com/go-openapi/swag/conv v0.25.3 // indirect
github.com/go-openapi/swag/jsonname v0.25.3 // indirect
github.com/go-openapi/swag/jsonutils v0.25.3 // indirect
github.com/go-openapi/swag/loading v0.25.3 // indirect
github.com/go-openapi/swag/stringutils v0.25.3 // indirect
github.com/go-openapi/swag/typeutils v0.25.3 // indirect
github.com/go-openapi/swag/yamlutils v0.25.3 // indirect
github.com/go-openapi/jsonpointer v0.22.4 // indirect
github.com/go-openapi/jsonreference v0.21.4 // indirect
github.com/go-openapi/spec v0.22.2 // indirect
github.com/go-openapi/swag/conv v0.25.4 // indirect
github.com/go-openapi/swag/jsonname v0.25.4 // indirect
github.com/go-openapi/swag/jsonutils v0.25.4 // indirect
github.com/go-openapi/swag/loading v0.25.4 // indirect
github.com/go-openapi/swag/stringutils v0.25.4 // indirect
github.com/go-openapi/swag/typeutils v0.25.4 // indirect
github.com/go-openapi/swag/yamlutils v0.25.4 // 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
@@ -130,7 +130,7 @@ require (
github.com/godoc-lint/godoc-lint v0.10.1 // indirect
github.com/gofrs/flock v0.13.0 // indirect
github.com/gohugoio/hugo v0.149.1 // indirect
github.com/golang/geo v0.0.0-20251117194806-05dcfdd28b33 // indirect
github.com/golang/geo v0.0.0-20251209161508-25c597310d4b // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golangci/asciicheck v0.5.0 // indirect
github.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32 // indirect
@@ -164,6 +164,7 @@ require (
github.com/kisielk/errcheck v1.9.0 // indirect
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
github.com/kovidgoyal/go-shm v1.0.0 // indirect
github.com/kulti/thelper v0.7.1 // indirect
github.com/kunwardeep/paralleltest v1.0.15 // indirect
github.com/lasiar/canonicalheader v1.1.2 // indirect
@@ -193,7 +194,7 @@ require (
github.com/moricho/tparallel v0.3.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/nakabonne/nestif v0.3.1 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/nishanths/exhaustive v0.12.0 // indirect
github.com/nishanths/predeclared v0.2.2 // indirect
github.com/nunnatsa/ginkgolinter v0.21.2 // indirect
@@ -263,17 +264,17 @@ require (
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-20250819193227-8b4c13bb791b // indirect
golang.org/x/exp v0.0.0-20251209150349-8475f28825e9 // indirect
golang.org/x/exp/typeparams v0.0.0-20251023183803-a4bb9ffd2546 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sync v0.18.0 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/tools v0.39.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/text v0.32.0 // indirect
golang.org/x/tools v0.40.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
honnef.co/go/tools v0.6.1 // indirect
modernc.org/libc v1.66.10 // indirect
modernc.org/libc v1.67.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
mvdan.cc/gofumpt v0.9.2 // indirect
+63 -2
View File
@@ -197,6 +197,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/coreos/go-oidc/v3 v3.16.0 h1:qRQUCFstKpXwmEjDQTIbyY/5jF00+asXzSkmkoa/mow=
github.com/coreos/go-oidc/v3 v3.16.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8=
github.com/coreos/go-oidc/v3 v3.17.0 h1:hWBGaQfbi0iVviX4ibC7bk8OKT5qNr4klBaCHVNvehc=
github.com/coreos/go-oidc/v3 v3.17.0/go.mod h1:wqPbKFrVnE90vty060SB40FCJ8fTHTxSwyXJqZH+sI8=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
@@ -294,27 +296,48 @@ github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-openapi/jsonpointer v0.22.3 h1:dKMwfV4fmt6Ah90zloTbUKWMD+0he+12XYAsPotrkn8=
github.com/go-openapi/jsonpointer v0.22.3/go.mod h1:0lBbqeRsQ5lIanv3LHZBrmRGHLHcQoOXQnf88fHlGWo=
github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4=
github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80=
github.com/go-openapi/jsonreference v0.21.3 h1:96Dn+MRPa0nYAR8DR1E03SblB5FJvh7W6krPI0Z7qMc=
github.com/go-openapi/jsonreference v0.21.3/go.mod h1:RqkUP0MrLf37HqxZxrIAtTWW4ZJIK1VzduhXYBEeGc4=
github.com/go-openapi/jsonreference v0.21.4 h1:24qaE2y9bx/q3uRK/qN+TDwbok1NhbSmGjjySRCHtC8=
github.com/go-openapi/jsonreference v0.21.4/go.mod h1:rIENPTjDbLpzQmQWCj5kKj3ZlmEh+EFVbz3RTUh30/4=
github.com/go-openapi/spec v0.22.1 h1:beZMa5AVQzRspNjvhe5aG1/XyBSMeX1eEOs7dMoXh/k=
github.com/go-openapi/spec v0.22.1/go.mod h1:c7aeIQT175dVowfp7FeCvXXnjN/MrpaONStibD2WtDA=
github.com/go-openapi/spec v0.22.2 h1:KEU4Fb+Lp1qg0V4MxrSCPv403ZjBl8Lx1a83gIPU8Qc=
github.com/go-openapi/spec v0.22.2/go.mod h1:iIImLODL2loCh3Vnox8TY2YWYJZjMAKYyLH2Mu8lOZs=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag/conv v0.25.3 h1:PcB18wwfba7MN5BVlBIV+VxvUUeC2kEuCEyJ2/t2X7E=
github.com/go-openapi/swag/conv v0.25.3/go.mod h1:n4Ibfwhn8NJnPXNRhBO5Cqb9ez7alBR40JS4rbASUPU=
github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4=
github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU=
github.com/go-openapi/swag/jsonname v0.25.3 h1:U20VKDS74HiPaLV7UZkztpyVOw3JNVsit+w+gTXRj0A=
github.com/go-openapi/swag/jsonname v0.25.3/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag=
github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI=
github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag=
github.com/go-openapi/swag/jsonutils v0.25.3 h1:kV7wer79KXUM4Ea4tBdAVTU842Rg6tWstX3QbM4fGdw=
github.com/go-openapi/swag/jsonutils v0.25.3/go.mod h1:ILcKqe4HC1VEZmJx51cVuZQ6MF8QvdfXsQfiaCs0z9o=
github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA=
github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY=
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.3 h1:/i3E9hBujtXfHy91rjtwJ7Fgv5TuDHgnSrYjhFxwxOw=
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.3/go.mod h1:8kYfCR2rHyOj25HVvxL5Nm8wkfzggddgjZm6RgjT8Ao=
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo=
github.com/go-openapi/swag/loading v0.25.3 h1:Nn65Zlzf4854MY6Ft0JdNrtnHh2bdcS/tXckpSnOb2Y=
github.com/go-openapi/swag/loading v0.25.3/go.mod h1:xajJ5P4Ang+cwM5gKFrHBgkEDWfLcsAKepIuzTmOb/c=
github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s=
github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE=
github.com/go-openapi/swag/stringutils v0.25.3 h1:nAmWq1fUTWl/XiaEPwALjp/8BPZJun70iDHRNq/sH6w=
github.com/go-openapi/swag/stringutils v0.25.3/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0=
github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8=
github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0=
github.com/go-openapi/swag/typeutils v0.25.3 h1:2w4mEEo7DQt3V4veWMZw0yTPQibiL3ri2fdDV4t2TQc=
github.com/go-openapi/swag/typeutils v0.25.3/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE=
github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw=
github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE=
github.com/go-openapi/swag/yamlutils v0.25.3 h1:LKTJjCn/W1ZfMec0XDL4Vxh8kyAnv1orH5F2OREDUrg=
github.com/go-openapi/swag/yamlutils v0.25.3/go.mod h1:Y7QN6Wc5DOBXK14/xeo1cQlq0EA0wvLoSv13gDQoCao=
github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw=
github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc=
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4=
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg=
github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls=
@@ -327,6 +350,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.28.0 h1:Q7ibns33JjyW48gHkuFT91qX48KG0ktULL6FgHdG688=
github.com/go-playground/validator/v10 v10.28.0/go.mod h1:GoI6I1SjPBh9p7ykNE/yj3fFYbyDOpwMn5KXd+m2hUU=
github.com/go-playground/validator/v10 v10.29.0 h1:lQlF5VNJWNlRbRZNeOIkWElR+1LL/OuHcc0Kp14w1xk=
github.com/go-playground/validator/v10 v10.29.0/go.mod h1:D6QxqeMlgIPuT02L66f2ccrZ7AGgHkzKmmTMZhk/Kc4=
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=
@@ -361,6 +386,8 @@ github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/goccy/go-yaml v1.19.0 h1:EmkZ9RIsX+Uq4DYFowegAuJo8+xdX3T/2dwNPXbxEYE=
github.com/goccy/go-yaml v1.19.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/godoc-lint/godoc-lint v0.10.1 h1:ZPUVzlDtJfA+P688JfPJPkI/SuzcBr/753yGIk5bOPA=
github.com/godoc-lint/godoc-lint v0.10.1/go.mod h1:KleLcHu/CGSvkjUH2RvZyoK1MBC7pDQg4NxMYLcBBsw=
github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
@@ -389,6 +416,8 @@ github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgR
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20251117194806-05dcfdd28b33 h1:1iCpF+lKihFpyN/Ujqvy9cWVlB516bGZItvb3l9HOSo=
github.com/golang/geo v0.0.0-20251117194806-05dcfdd28b33/go.mod h1:Mymr9kRGDc64JPr03TSZmuIBODZ3KyswLzm1xL0HFA8=
github.com/golang/geo v0.0.0-20251209161508-25c597310d4b h1:6y9D6yfaR5FyqoNoV2S+XJyhzeMUlkdIeUX1Ssj0FJQ=
github.com/golang/geo v0.0.0-20251209161508-25c597310d4b/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=
@@ -490,10 +519,12 @@ github.com/gostaticanalysis/nilerr v0.1.2/go.mod h1:A19UHhoY3y8ahoL7YKz6sdjDtduw
github.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M=
github.com/gostaticanalysis/testutil v0.5.0 h1:Dq4wT1DdTwTGCQQv3rl3IvD5Ld0E6HiY+3Zh0sUGqw8=
github.com/gostaticanalysis/testutil v0.5.0/go.mod h1:OLQSbuM6zw2EvCcXTz1lVq5unyoNft372msDY0nY5Hs=
github.com/gtsteffaniak/go-cache v1.0.0 h1:CuZw6eI/be6Oi3oR94Jb5LhcZShMCs6+1wvS7WGN8oQ=
github.com/gtsteffaniak/go-cache v1.0.0/go.mod h1:rHUZvf4huhMX/bnNK4/oQ3sNAE2fYC2jFpAWZiBPWac=
github.com/gtsteffaniak/go-cache v1.1.0 h1:ni/2cJpCxpGmaMZd92iTDIGOy+yUcMcxQuW7bSKhkCE=
github.com/gtsteffaniak/go-cache v1.1.0/go.mod h1:rHUZvf4huhMX/bnNK4/oQ3sNAE2fYC2jFpAWZiBPWac=
github.com/gtsteffaniak/go-logger v0.2.3 h1:8nSC5xSMnMYQI61tsBS1tARpnkv/rOh5lzEXtAG72Nw=
github.com/gtsteffaniak/go-logger v0.2.3/go.mod h1:rapapTju4D7bwt6h4JOdZNUXDjnp0WkTBd6TN5yWglI=
github.com/gtsteffaniak/go-logger v0.2.4 h1:CGioQehoo84xufxtS57gqEAYcXdLc5hzA71CPvGQ/3s=
github.com/gtsteffaniak/go-logger v0.2.4/go.mod h1:rapapTju4D7bwt6h4JOdZNUXDjnp0WkTBd6TN5yWglI=
github.com/hairyhenderson/go-codeowners v0.7.0 h1:s0W4wF8bdsBEjTWzwzSlsatSthWtTAF2xLgo4a4RwAo=
github.com/hairyhenderson/go-codeowners v0.7.0/go.mod h1:wUlNgQ3QjqC4z8DnM5nnCYVq/icpqXJyJOukKx5U8/Q=
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 h1:CUW5RYIcysz+D3B+l1mDeXrQ7fUvGGCwJfdASSzbrfo=
@@ -550,8 +581,12 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kovidgoyal/go-parallel v1.1.1 h1:1OzpNjtrUkBPq3UaqrnvOoB2F9RttSt811uiUXyI7ok=
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.7.2 h1:mmT6k6Az3mC6dbqdZ6Q9KQCdZFWTAQ+q97NyGZgJ/2c=
github.com/kovidgoyal/imaging v1.7.2/go.mod h1:GdkCORjfZMMGFY0Pb7TDmRhj7PDhxF/QShKukSCj0VU=
github.com/kovidgoyal/imaging v1.8.17 h1:IDc7lbN2Qrn8s50y7Zt355HhOc+jUpvsScYAaGCW8vs=
github.com/kovidgoyal/imaging v1.8.17/go.mod h1:uD4XKN42lLV9du0TsPkwi53yw23vz/qDmfpiDWCSUCE=
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=
@@ -641,6 +676,8 @@ github.com/nakabonne/nestif v0.3.1 h1:wm28nZjhQY5HyYPx+weN3Q65k6ilSBxDb8v5S81B81
github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/niklasfasching/go-org v1.9.1 h1:/3s4uTPOF06pImGa2Yvlp24yKXZoTYM+nsIlMzfpg/0=
github.com/niklasfasching/go-org v1.9.1/go.mod h1:ZAGFFkWvUQcpazmi/8nHqwvARpr1xpb+Es67oUGX/48=
github.com/nishanths/exhaustive v0.12.0 h1:vIY9sALmw6T/yxiASewa4TQcFsVYZQQRUQJhKRf3Swg=
@@ -901,6 +938,8 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
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=
@@ -913,6 +952,8 @@ golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EH
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b h1:DXr+pvt3nC887026GRP39Ej11UATqWDmWuS99x26cD0=
golang.org/x/exp v0.0.0-20250819193227-8b4c13bb791b/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4=
golang.org/x/exp v0.0.0-20251209150349-8475f28825e9 h1:MDfG8Cvcqlt9XXrmEiD4epKn7VJHZO84hejP9Jmp0MM=
golang.org/x/exp v0.0.0-20251209150349-8475f28825e9/go.mod h1:EPRbTFwzwjXj9NpYyyrvenVh9Y+GFeEvMNh7Xuz7xgU=
golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20230203172020-98cc5a0785f9/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/exp/typeparams v0.0.0-20251023183803-a4bb9ffd2546 h1:HDjDiATsGqvuqvkDvgJjD1IgPrVekcSXVVE21JwvzGE=
@@ -921,6 +962,8 @@ golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMx
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.33.0 h1:LXRZRnv1+zGd5XBUVRFmYEphyyKJjQjCRiOuAP3sZfQ=
golang.org/x/image v0.33.0/go.mod h1:DD3OsTYT9chzuzTQt+zMcOlBHgfoKQb1gry8p76Y1sc=
golang.org/x/image v0.34.0 h1:33gCkyw9hmwbZJeZkct8XyR11yH889EQt/QH4VmXMn8=
golang.org/x/image v0.34.0/go.mod h1:2RNFBZRB+vnwwFil8GkMdRvrJOFd1AzdZI6vOY+eJVU=
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=
@@ -948,6 +991,8 @@ golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
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=
@@ -992,6 +1037,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
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=
@@ -1000,6 +1047,8 @@ golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4Iltr
golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
golang.org/x/oauth2 v0.33.0 h1:4Q+qn+E5z8gPRJfmRy7C2gGG3T4jIprK6aSYgTXGRpo=
golang.org/x/oauth2 v0.33.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -1017,6 +1066,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1072,6 +1123,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -1090,6 +1143,8 @@ golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
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=
@@ -1147,6 +1202,8 @@ golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58
golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
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=
@@ -1266,8 +1323,10 @@ honnef.co/go/tools v0.6.1 h1:R094WgE8K4JirYjBaOpz/AvTyUu/3wbmAoskKN/pxTI=
honnef.co/go/tools v0.6.1/go.mod h1:3puzxxljPCe8RGJX7BIy1plGbxEOZni5mR2aXe3/uk4=
modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=
modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=
modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=
modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
@@ -1276,6 +1335,8 @@ modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
modernc.org/libc v1.67.1 h1:bFaqOaa5/zbWYJo8aW0tXPX21hXsngG2M7mckCnFSVk=
modernc.org/libc v1.67.1/go.mod h1:QvvnnJ5P7aitu0ReNpVIEyesuhmDLQ8kaEoyMjIFZJA=
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=
+121 -24
View File
@@ -7,10 +7,47 @@ import (
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/gtsteffaniak/filebrowser/backend/auth"
"github.com/gtsteffaniak/filebrowser/backend/database/users"
"github.com/gtsteffaniak/go-cache/cache"
)
var (
ApiTokenUserCache = cache.NewCache[uint](24 * time.Hour) // API token to user ID mapping gets cached for 24 hours
)
// getUserFromApiToken finds the user ID associated with a given API token
func getUserFromApiToken(token string) (uint, error) {
// Check cache first
if cached, ok := ApiTokenUserCache.Get(token); ok {
return cached, nil
}
// Get all users
allUsers, err := store.Users.Gets()
if err != nil {
return 0, fmt.Errorf("failed to get all users: %w", err)
}
// Iterate through all users and their API keys
for _, user := range allUsers {
if user.ApiKeys == nil {
continue
}
for _, apiKey := range user.ApiKeys {
if apiKey.Key == token {
// Cache the result
ApiTokenUserCache.Set(token, user.ID)
return user.ID, nil
}
}
}
// Token not found
return 0, fmt.Errorf("token not found")
}
// createApiKeyHandler creates an API key for the user.
// @Summary Create API key
// @Description Create an API key with specified name, duration, and permissions.
@@ -30,6 +67,7 @@ func createApiKeyHandler(w http.ResponseWriter, r *http.Request, d *requestConte
name := r.URL.Query().Get("name")
durationStr := r.URL.Query().Get("days")
permissionsStr := r.URL.Query().Get("permissions")
minimal := r.URL.Query().Get("minimal") == "true"
if !d.user.Permissions.Api {
return http.StatusForbidden, fmt.Errorf("user does not have permission to create api keys")
@@ -41,18 +79,25 @@ func createApiKeyHandler(w http.ResponseWriter, r *http.Request, d *requestConte
if durationStr == "" {
return http.StatusBadRequest, fmt.Errorf("api duration must be valid")
}
if permissionsStr == "" {
return http.StatusBadRequest, fmt.Errorf("api permissions must be valid")
}
// Parse permissions from the query parameter
permissions := users.Permissions{
Api: strings.Contains(permissionsStr, "api") && d.user.Permissions.Api,
Admin: strings.Contains(permissionsStr, "admin") && d.user.Permissions.Admin,
Modify: strings.Contains(permissionsStr, "modify") && d.user.Permissions.Modify,
Delete: strings.Contains(permissionsStr, "delete") && d.user.Permissions.Delete,
Create: strings.Contains(permissionsStr, "create") && d.user.Permissions.Create,
Share: strings.Contains(permissionsStr, "share") && d.user.Permissions.Share,
Realtime: strings.Contains(permissionsStr, "realtime") && d.user.Permissions.Realtime,
// For full tokens (minimal=false), permissions are required in the claim
// For minimal tokens (minimal=true), permissions are not in the token
var permissions users.Permissions
if !minimal {
if permissionsStr == "" {
return http.StatusBadRequest, fmt.Errorf("api permissions must be valid for full tokens")
}
// Parse permissions from the query parameter
permissions = users.Permissions{
Api: strings.Contains(permissionsStr, "api") && d.user.Permissions.Api,
Admin: strings.Contains(permissionsStr, "admin") && d.user.Permissions.Admin,
Modify: strings.Contains(permissionsStr, "modify") && d.user.Permissions.Modify,
Delete: strings.Contains(permissionsStr, "delete") && d.user.Permissions.Delete,
Create: strings.Contains(permissionsStr, "create") && d.user.Permissions.Create,
Share: strings.Contains(permissionsStr, "share") && d.user.Permissions.Share,
Realtime: strings.Contains(permissionsStr, "realtime") && d.user.Permissions.Realtime,
Download: strings.Contains(permissionsStr, "download") && d.user.Permissions.Download,
}
}
// Convert the duration string to an int64
@@ -64,7 +109,7 @@ func createApiKeyHandler(w http.ResponseWriter, r *http.Request, d *requestConte
// Here we assume the duration is in seconds; convert to time.Duration
duration := time.Duration(durationInt) * time.Hour * 24
// get request body like:
token, err := makeSignedTokenAPI(d.user, name, duration, permissions)
token, err := makeSignedTokenAPI(d.user, name, duration, permissions, minimal)
if err != nil {
if strings.Contains(err.Error(), "key already exists with same name") {
return http.StatusConflict, err
@@ -117,7 +162,8 @@ type AuthTokenMin struct {
Name string `json:"name"`
Created int64 `json:"created"`
Expires int64 `json:"expires"`
Permissions users.Permissions `json:"Permissions"`
Permissions users.Permissions `json:"Permissions,omitempty"`
Minimal bool `json:"minimal"`
}
// listApiKeysHandler lists all API keys or retrieves details for a specific key.
@@ -142,24 +188,75 @@ func listApiKeysHandler(w http.ResponseWriter, r *http.Request, d *requestContex
if !ok {
return http.StatusNotFound, fmt.Errorf("api key not found")
}
// Determine if token is minimal by parsing the JWT claim
// For minimal tokens, the JWT claim doesn't have BelongsTo even though the database record does
minimal := false
if keyInfo.Key != "" {
keyFunc := func(token *jwt.Token) (interface{}, error) {
return []byte(config.Auth.Key), nil
}
var claim users.AuthToken
token, err := jwt.ParseWithClaims(keyInfo.Key, &claim, keyFunc)
if err == nil && token.Valid {
// If the parsed claim doesn't have BelongsTo, it's a minimal token
minimal = claim.BelongsTo == 0
}
}
modifiedKey := AuthTokenMin{
Key: keyInfo.Key,
Name: key,
Created: keyInfo.Created,
Expires: keyInfo.Expires,
Permissions: keyInfo.Permissions,
Key: keyInfo.Key,
Name: key,
Created: 0,
Expires: 0,
Minimal: minimal,
}
// Safely access IssuedAt and ExpiresAt (they're pointers)
if keyInfo.IssuedAt != nil {
modifiedKey.Created = keyInfo.IssuedAt.Unix()
}
if keyInfo.ExpiresAt != nil {
modifiedKey.Expires = keyInfo.ExpiresAt.Unix()
}
// Only include Permissions for full tokens (not minimal tokens)
if !minimal {
modifiedKey.Permissions = keyInfo.Permissions
}
return renderJSON(w, r, modifiedKey)
}
modifiedList := map[string]AuthTokenMin{}
for key, value := range d.user.ApiKeys {
modifiedList[key] = AuthTokenMin{
Key: value.Key,
Created: value.Created,
Expires: value.Expires,
Permissions: value.Permissions,
// Determine if token is minimal by parsing the JWT claim
// For minimal tokens, the JWT claim doesn't have BelongsTo even though the database record does
minimal := false
if value.Key != "" {
keyFunc := func(token *jwt.Token) (interface{}, error) {
return []byte(config.Auth.Key), nil
}
var claim users.AuthToken
token, err := jwt.ParseWithClaims(value.Key, &claim, keyFunc)
if err == nil && token.Valid {
// If the parsed claim doesn't have BelongsTo, it's a minimal token
minimal = claim.BelongsTo == 0
}
}
modifiedKey := AuthTokenMin{
Key: value.Key,
Created: 0,
Expires: 0,
Minimal: minimal,
}
// Safely access IssuedAt and ExpiresAt (they're pointers)
if value.IssuedAt != nil {
modifiedKey.Created = value.IssuedAt.Unix()
}
if value.ExpiresAt != nil {
modifiedKey.Expires = value.ExpiresAt.Unix()
}
// Only include Permissions for full tokens (not minimal tokens)
if !minimal {
modifiedKey.Permissions = value.Permissions
}
modifiedList[key] = modifiedKey
}
return renderJSON(w, r, modifiedList)
+95 -28
View File
@@ -1,6 +1,9 @@
package http
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
libError "errors"
"fmt"
@@ -111,10 +114,14 @@ func setupProxyUser(r *http.Request, data *requestContext, proxyUser string) (*u
// loginHandler handles user authentication via password.
// @Summary User login
// @Description Authenticate a user with a username and password.
// @Description Authenticate a user with a username and password. The password must be URL-encoded and sent in the X-Password header to support special characters (e.g., ^, %, £, €, etc.).
// @Tags Auth
// @Accept json
// @Produce json
// @Param username query string true "Username"
// @Param recaptcha query string false "ReCaptcha response token (if enabled)"
// @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 403 {object} map[string]string "Forbidden - authentication failed"
// @Failure 500 {object} map[string]string "Internal server error"
@@ -249,7 +256,7 @@ func renewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (in
func printToken(w http.ResponseWriter, r *http.Request, user *users.User) (int, error) {
expires := time.Hour * time.Duration(config.Auth.TokenExpirationHours)
signed, err := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions)
signed, err := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions, false)
if err != nil {
if strings.Contains(err.Error(), "key already exists with same name") {
return http.StatusConflict, err
@@ -287,41 +294,78 @@ func printToken(w http.ResponseWriter, r *http.Request, user *users.User) (int,
return 0, nil
}
func makeSignedTokenAPI(user *users.User, name string, duration time.Duration, perms users.Permissions) (users.AuthToken, error) {
func makeSignedTokenAPI(user *users.User, name string, duration time.Duration, perms users.Permissions, minimal bool) (users.AuthToken, error) {
_, ok := user.ApiKeys[name]
if ok {
return users.AuthToken{}, fmt.Errorf("key already exists with same name %v ", name)
}
now := time.Now()
expires := now.Add(duration)
claim := users.AuthToken{
Permissions: perms,
Created: now.Unix(),
Expires: expires.Unix(),
Name: name,
BelongsTo: user.ID,
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(expires),
Issuer: "FileBrowser Quantum",
var tokenString string
var err error
if minimal {
// Create minimal token with only JWT standard claims
minimalClaim := users.MinimalAuthToken{
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(expires),
Issuer: "FileBrowser Quantum",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, minimalClaim)
tokenString, err = token.SignedString([]byte(config.Auth.Key))
if err != nil {
return users.AuthToken{}, err
}
} else {
// Create full token with permissions and user ID
fullClaim := users.AuthToken{
MinimalAuthToken: users.MinimalAuthToken{
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(expires),
Issuer: "FileBrowser Quantum",
},
},
Name: name,
Permissions: perms,
BelongsTo: user.ID,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, fullClaim)
tokenString, err = token.SignedString([]byte(config.Auth.Key))
if err != nil {
return users.AuthToken{}, err
}
}
// Create the AuthToken to store in database (always includes permissions and user ID)
storedClaim := users.AuthToken{
MinimalAuthToken: users.MinimalAuthToken{
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(expires),
Issuer: "FileBrowser Quantum",
},
},
Key: tokenString,
Name: name,
Permissions: perms,
BelongsTo: user.ID,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
tokenString, err := token.SignedString([]byte(config.Auth.Key))
if err != nil {
return claim, err
}
claim.Key = tokenString
if strings.HasPrefix(name, "WEB_TOKEN") {
// don't add to api tokens, its a short lived web token
return claim, err
return storedClaim, nil
}
// Perform the user update
err = store.Users.AddApiKey(user.ID, name, claim)
err = store.Users.AddApiKey(user.ID, name, storedClaim)
if err != nil {
return claim, err
return storedClaim, err
}
return claim, err
return storedClaim, nil
}
func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) {
@@ -329,8 +373,34 @@ func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) {
return 200, nil
}
if r.URL.Query().Get("token") == l.Token {
return 200, nil
tokenParam := r.URL.Query().Get("token")
if tokenParam != "" {
// Verify the token signature if it's in the new signed format
if strings.Contains(tokenParam, ".") {
parts := strings.Split(tokenParam, ".")
if len(parts) == 2 {
payload := parts[0]
signature := parts[1]
// Verify HMAC signature
mac := hmac.New(sha256.New, []byte(config.Auth.Key))
mac.Write([]byte(payload))
expectedSignature := base64.URLEncoding.EncodeToString(mac.Sum(nil))
// Use constant-time comparison to prevent timing attacks
if hmac.Equal([]byte(signature), []byte(expectedSignature)) {
// Token signature is valid, now check if it matches stored token
if tokenParam == l.Token {
return 200, nil
}
}
}
} else {
// Legacy token format (plain base64) - direct comparison
if tokenParam == l.Token {
return 200, nil
}
}
}
password := r.Header.Get("X-SHARE-PASSWORD")
@@ -338,9 +408,6 @@ func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) {
if err != nil {
return http.StatusUnauthorized, err
}
if password == "" {
return http.StatusUnauthorized, nil
}
if err := bcrypt.CompareHashAndPassword([]byte(l.PasswordHash), []byte(password)); err != nil {
if libError.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return http.StatusUnauthorized, nil
+19 -3
View File
@@ -14,6 +14,7 @@ import (
"unicode"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/database/sql"
"github.com/gtsteffaniak/filebrowser/backend/indexing"
"github.com/gtsteffaniak/go-cache/cache"
@@ -78,6 +79,16 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext
if index == nil {
return http.StatusBadRequest, fmt.Errorf("index not found for source %s", opts.source)
}
userscope, err := settings.GetScopeFromSourceName(d.user.Scopes, index.Name)
if err != nil {
return http.StatusForbidden, err
}
userscope = strings.TrimRight(userscope, "/")
scopePath := utils.JoinPathAsUnix(userscope, opts.searchScope)
fullPath := index.MakeIndexPath(scopePath)
if !store.Access.Permitted(index.Path, fullPath, d.user.Username) {
return http.StatusForbidden, fmt.Errorf("user is not allowed to access this location")
}
// Generate cache key from all input parameters that affect results
// Checksums are always enabled, so cache key doesn't need to include that flag
@@ -101,7 +112,7 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext
// Find duplicates using index-native approach to minimize memory allocation
// This avoids creating SearchResult objects until we know the final limited set
duplicateGroups := findDuplicatesInIndex(index, opts)
duplicateGroups := findDuplicatesInIndex(index, opts, d.user.Username)
// Cache the results before returning
duplicateResultsCache.Set(cacheKey, duplicateGroups)
@@ -115,7 +126,7 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext
// 2. Querying SQLite for size groups with 2+ files
// 3. Processing each size group sequentially (only one in memory at a time)
// 4. Only creating SearchResult objects for final verified duplicates
func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []duplicateGroup {
func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions, username string) []duplicateGroup {
// Create temporary SQLite database for streaming in cache directory
tempDB, err := sql.NewTempDB("duplicates", &sql.TempDBConfig{
@@ -256,8 +267,12 @@ func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []dup
continue
}
// Construct full path
// Construct full path (index-relative)
fullPath := filepath.Join(loc.DirPath, file.Name)
// Check access control using index-relative path
if store.Access != nil && !store.Access.Permitted(index.Path, fullPath, username) {
continue // Silently skip this file
}
// Remove the user scope from path
adjustedPath := strings.TrimPrefix(fullPath, opts.combinedPath)
@@ -305,6 +320,7 @@ func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []dup
func prepDuplicatesOptions(r *http.Request, d *requestContext) (*duplicatesOptions, error) {
source := r.URL.Query().Get("source")
scope := r.URL.Query().Get("scope")
minSizeMbStr := r.URL.Query().Get("minSizeMb")
// Checksums are always enabled by default for final verification
// First pass uses filename matching for speed, then checksums verify final groups
+1 -4
View File
@@ -189,7 +189,7 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
publicRoutes.Handle("GET /static/", http.HandlerFunc(staticAssetHandler))
// Standard browser favicon and manifest routes
router.HandleFunc("GET /favicon.ico", http.HandlerFunc(staticAssetHandler))
router.HandleFunc("GET /favicon.svg", http.HandlerFunc(staticAssetHandler))
router.HandleFunc("GET /site.webmanifest", http.HandlerFunc(staticAssetHandler))
router.HandleFunc("GET /manifest.json", http.HandlerFunc(staticAssetHandler))
@@ -211,9 +211,6 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch
Handler: muxWithMiddleware(router),
}
listenAddress := config.Server.ListenAddress
if listenAddress == "0.0.0.0" {
listenAddress = "localhost"
}
go func() {
// Determine whether to use HTTPS (TLS) or HTTP
if config.Server.TLSCert != "" && config.Server.TLSKey != "" {
+27 -7
View File
@@ -100,13 +100,20 @@ func withHashFileHelper(fn handleFunc) handleFunc {
if link.DisableFileViewer || reachedDownloadsLimit {
getContent = false
}
shareCreatedByUser, err := store.Users.Get(link.UserID)
if err != nil {
return http.StatusNotFound, fmt.Errorf("user for share no longer exists")
}
file, err := FileInfoFasterFunc(utils.FileOptions{
Path: utils.JoinPathAsUnix(link.Path, path),
Source: link.Source,
Username: shareCreatedByUser.Username,
Expand: true,
Content: getContent,
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles && link.ExtractEmbeddedSubtitles,
}, nil)
ShowHidden: link.ShowHidden,
FollowSymlinks: true,
}, store.Access)
if err != nil {
logger.Errorf("error fetching file info for share. hash=%v path=%v error=%v", hash, path, err)
return errToStatus(err), fmt.Errorf("error fetching share from server")
@@ -352,21 +359,34 @@ func withUserHelper(fn handleFunc) handleFunc {
if isProxyUser {
return getProxyUser(w, r, data, fn, proxyUser)
}
// JWT library automatically validates expiration - if expired, it returns an error
return http.StatusUnauthorized, fmt.Errorf("error processing token, %v", err)
}
if !token.Valid {
return http.StatusUnauthorized, fmt.Errorf("invalid token")
}
if auth.IsRevokedApiKey(data.token) || tk.Expires < time.Now().Unix() {
if auth.IsRevokedApiKey(data.token) {
if isProxyUser {
return getProxyUser(w, r, data, fn, proxyUser)
}
return http.StatusUnauthorized, fmt.Errorf("token expired or revoked")
return http.StatusUnauthorized, fmt.Errorf("token revoked")
}
// Check if the token is about to expire and send a header to renew it
if tk.Expires < time.Now().Add(time.Minute*30).Unix() {
// ExpiresAt should always be set in valid tokens created by our system
// If it's nil, the token is invalid
if tk.ExpiresAt == nil {
return http.StatusUnauthorized, fmt.Errorf("invalid token: missing expiration")
}
// Check if token is about to expire for renewal header
if tk.ExpiresAt.Unix() < time.Now().Add(time.Minute*30).Unix() {
w.Header().Add("X-Renew-Token", "true")
} // Retrieve the user from the store and store it in the context
}
// Check if token is minimal/stateful (no BelongsTo in claim)
if tk.BelongsTo == 0 {
tk.BelongsTo, err = getUserFromApiToken(data.token)
if err != nil {
return http.StatusUnauthorized, err
}
}
data.user, err = store.Users.Get(tk.BelongsTo)
if err != nil {
logger.Errorf("Failed to get user with ID %v: %v", tk.BelongsTo, err)
@@ -398,7 +418,7 @@ func getProxyUser(w http.ResponseWriter, r *http.Request, data *requestContext,
// Generate a token for proxy users if they don't have one
if data.token == "" {
expires := time.Hour * time.Duration(config.Auth.TokenExpirationHours)
signed, err := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions)
signed, err := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions, false)
if err != nil {
logger.Errorf("Failed to generate token for proxy user %s: %v", proxyUser, err)
return http.StatusInternalServerError, fmt.Errorf("failed to generate token")
+13 -2
View File
@@ -101,7 +101,7 @@ func TestWithAdminHelper(t *testing.T) {
data := &requestContext{
user: tc.user,
}
token, err := makeSignedTokenAPI(tc.user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), time.Hour*2, tc.user.Perm)
token, err := makeSignedTokenAPI(tc.user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), time.Hour*2, tc.user.Perm, false)
if err != nil {
t.Fatalf("Error making token for request: %v", err)
}
@@ -140,6 +140,16 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
const passwordBcrypt = "$2y$10$TFAmdCbyd/mEZDe5fUeZJu.MaJQXRTwdqb/IQV.eTn6dWrF58gCSe" // bcrypt hashed password
// Create and save a dummy user with ID 1 (all shares use UserID: 1)
dummyUser := &users.User{
ID: 1,
Username: "testuser",
Permissions: users.Permissions{Admin: false},
}
if err := store.Users.Save(dummyUser, true, true); err != nil {
t.Fatal("failed to save dummy user:", err)
}
testCases := []struct {
name string
share *share.Link
@@ -151,7 +161,8 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
{
name: "Public share, no auth required",
share: &share.Link{
Hash: "public_hash",
Hash: "public_hash",
UserID: 1,
CommonShare: share.CommonShare{
Source: "/srv",
},
+1 -1
View File
@@ -301,7 +301,7 @@ func loginWithOidcUser(w http.ResponseWriter, r *http.Request, username string,
expires := time.Hour * time.Duration(config.Auth.TokenExpirationHours)
// Generate a signed token for the user
signed, err2 := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions)
signed, err2 := makeSignedTokenAPI(user, "WEB_TOKEN_"+utils.InsecureRandomIdentifier(4), expires, user.Permissions, false)
if err2 != nil {
// Handle potential errors during token generation
if strings.Contains(err2.Error(), "key already exists with same name") {
+5 -4
View File
@@ -109,10 +109,11 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
path = utils.JoinPathAsUnix(userScope, path)
logger.Debugf("OnlyOffice user request: resolved path=%s", path)
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Username: d.user.Username,
Path: path,
Source: source,
Expand: false,
Username: d.user.Username,
Path: path,
Source: source,
Expand: false,
FollowSymlinks: true,
}, store.Access)
if err != nil {
logger.Errorf("OnlyOffice: failed to get file info for source=%s, path=%s: %v", source, path, err)
+11 -7
View File
@@ -238,9 +238,11 @@ func publicPreviewHandler(w http.ResponseWriter, r *http.Request, d *requestCont
return http.StatusNotFound, fmt.Errorf("source not available")
}
fileInfo, err := FileInfoFasterFunc(utils.FileOptions{
Path: utils.JoinPathAsUnix(d.share.Path, d.fileInfo.Path),
Source: source,
Metadata: true,
Path: utils.JoinPathAsUnix(d.share.Path, d.fileInfo.Path),
Source: source,
Metadata: true,
AlbumArt: true,
ShowHidden: d.share.ShowHidden,
}, nil)
if err != nil {
return http.StatusNotFound, fmt.Errorf("resource not available")
@@ -314,10 +316,12 @@ func publicDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestConte
}
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Username: d.user.Username,
Path: indexPath,
Source: source,
Expand: false,
Username: d.user.Username,
FollowSymlinks: true,
Path: indexPath,
Source: source,
Expand: false,
ShowHidden: d.share.ShowHidden,
}, nil)
if err != nil {
return http.StatusNotFound, fmt.Errorf("resource not available")
+19 -11
View File
@@ -145,9 +145,10 @@ func addFile(path string, d *requestContext, tarWriter *tar.Writer, zipWriter *z
// Verify file exists
_, err = files.FileInfoFaster(utils.FileOptions{
Path: path,
Source: source,
Expand: false,
Path: path,
Source: source,
Expand: false,
FollowSymlinks: true,
}, nil)
if err != nil {
return err
@@ -184,11 +185,8 @@ func addFile(path string, d *requestContext, tarWriter *tar.Writer, zipWriter *z
// Check access control for each file/folder during walk
if d.share == nil {
// Construct the index-relative path for this file/folder
// relPath is relative to realPath, so we need to join it with the original path
indexRelPath := filepath.Join(path, relPath)
indexRelPath := utils.JoinPathAsUnix(path, relPath)
indexRelPath = filepath.ToSlash(indexRelPath) // Normalize separators
if !store.Access.Permitted(idx.Path, indexRelPath, d.user.Username) {
// Skip this file/folder silently
if fileInfo.IsDir() {
@@ -552,7 +550,7 @@ func computeArchiveSize(fileList []string, d *requestContext) (int64, error) {
indexPath := idx.MakeIndexPath(realPath)
info, ok := idx.GetReducedMetadata(indexPath, isDir)
if !ok {
info, err = idx.GetFsDirInfo(indexPath)
info, err = idx.GetFsInfo(indexPath, false)
if err != nil {
return 0, fmt.Errorf("failed to get file info for %s : %v", path, err)
}
@@ -570,7 +568,6 @@ func createZip(d *requestContext, tmpDirPath string, filenames ...string) error
defer file.Close()
zipWriter := zip.NewWriter(file)
defer zipWriter.Close()
for _, fname := range filenames {
err := addFile(fname, d, nil, zipWriter, false)
@@ -581,6 +578,11 @@ func createZip(d *requestContext, tmpDirPath string, filenames ...string) error
}
}
// Close the ZIP writer and check for errors
if err := zipWriter.Close(); err != nil {
return fmt.Errorf("failed to finalize ZIP archive: %w", err)
}
return nil
}
@@ -592,9 +594,7 @@ func createTarGz(d *requestContext, tmpDirPath string, filenames ...string) erro
defer file.Close()
gzWriter := gzip.NewWriter(file)
defer gzWriter.Close()
tarWriter := tar.NewWriter(gzWriter)
defer tarWriter.Close()
for _, fname := range filenames {
err := addFile(fname, d, tarWriter, nil, false)
@@ -604,6 +604,14 @@ func createTarGz(d *requestContext, tmpDirPath string, filenames ...string) erro
}
}
// Close writers in reverse order and check for errors
if err := tarWriter.Close(); err != nil {
return fmt.Errorf("failed to finalize TAR archive: %w", err)
}
if err := gzWriter.Close(); err != nil {
return fmt.Errorf("failed to finalize GZIP compression: %w", err)
}
return nil
}
+18 -12
View File
@@ -89,12 +89,14 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
getContent := r.URL.Query().Get("content") == "true"
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Username: d.user.Username,
FollowSymlinks: true,
Path: scopePath,
Source: source,
Expand: true,
Content: getContent,
Metadata: true,
ExtractEmbeddedSubtitles: settings.Config.Integrations.Media.ExtractEmbeddedSubtitles,
ShowHidden: d.user.ShowHidden,
}, store.Access)
if err != nil {
return errToStatus(err), err
@@ -172,10 +174,11 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon
}
userscope = strings.TrimRight(userscope, "/")
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Username: d.user.Username,
Path: utils.JoinPathAsUnix(userscope, path),
Source: source,
Expand: false,
Username: d.user.Username,
Path: utils.JoinPathAsUnix(userscope, path),
Source: source,
Expand: false,
ShowHidden: d.user.ShowHidden,
}, store.Access)
if err != nil {
return errToStatus(err), err
@@ -248,10 +251,11 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
isDirParam := r.URL.Query().Get("isDir")
isDir := isDirParam == "true" || strings.HasSuffix(unescapedPath, "/")
fileOpts := utils.FileOptions{
Username: d.user.Username,
Path: path,
Source: source,
Expand: false,
Username: d.user.Username,
Path: path,
Source: source,
Expand: false,
FollowSymlinks: true,
}
idx := indexing.GetIndex(source)
if idx == nil {
@@ -614,10 +618,12 @@ func patchAction(ctx context.Context, params patchActionParams) error {
srcPath = strings.TrimSuffix(srcPath, "/")
}
fileInfo, err := files.FileInfoFaster(utils.FileOptions{
Username: params.d.user.Username,
Path: srcPath,
Source: params.srcIndex,
IsDir: params.isSrcDir,
Username: params.d.user.Username,
FollowSymlinks: true,
Path: srcPath,
Source: params.srcIndex,
IsDir: params.isSrcDir,
ShowHidden: params.d.user.ShowHidden,
}, store.Access)
if err != nil {
+11 -2
View File
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/indexing"
)
@@ -77,14 +78,22 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
// Perform the search using the provided query and user scope
response := index.Search(searchOptions.query, searchOptions.combinedPath, searchOptions.sessionId, searchOptions.largest, indexing.DefaultSearchResults)
// Remove the user scope from the path (modifying in place is safe - these are fresh allocations)
// Filter out items that are not permitted according to access rules
filteredResponse := make([]*indexing.SearchResult, 0, len(response))
for _, result := range response {
indexPath := utils.JoinPathAsUnix(searchOptions.combinedPath, result.Path)
if store.Access != nil && !store.Access.Permitted(index.Path, indexPath, d.user.Username) {
continue // Silently skip this file/folder
}
// Remove the user scope from the path (modifying in place is safe - these are fresh allocations)
result.Path = strings.TrimPrefix(result.Path, searchOptions.combinedPath)
if result.Path == "" {
result.Path = "/"
}
filteredResponse = append(filteredResponse, result)
}
return renderJSON(w, r, response)
return renderJSON(w, r, filteredResponse)
}
func prepSearchOptions(r *http.Request, d *requestContext) (*searchOptions, error) {
+40 -26
View File
@@ -1,7 +1,9 @@
package http
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
@@ -62,8 +64,8 @@ func convertToFrontendShareResponse(r *http.Request, shares []*share.Link) ([]*S
pathExists := utils.CheckPathExists(filepath.Join(sourceInfo.Path, s.Path))
s.CommonShare.HasPassword = s.HasPassword()
s.DownloadURL = getShareURL(r, s.Hash, true)
s.ShareURL = getShareURL(r, s.Hash, false)
s.DownloadURL = getShareURL(r, s.Hash, true, s.Token)
s.ShareURL = getShareURL(r, s.Hash, false, s.Token)
// Create response with source name (overrides the embedded Link's source field)
responses = append(responses, &ShareResponse{
@@ -283,11 +285,21 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
stringHash := ""
var token string
if len(hash) > 0 {
tokenBuffer := make([]byte, 24)
if _, err = rand.Read(tokenBuffer); err != nil {
// Generate a cryptographically secure token similar to JWT
// Create a random payload
payloadBuffer := make([]byte, 24)
if _, err = rand.Read(payloadBuffer); err != nil {
return http.StatusInternalServerError, err
}
token = base64.URLEncoding.EncodeToString(tokenBuffer)
payload := base64.URLEncoding.EncodeToString(payloadBuffer)
// Sign the payload with HMAC-SHA256 using the same secret key as JWT tokens
mac := hmac.New(sha256.New, []byte(config.Auth.Key))
mac.Write([]byte(payload))
signature := base64.URLEncoding.EncodeToString(mac.Sum(nil))
// Combine payload and signature: payload.signature (similar to JWT format)
token = payload + "." + signature
stringHash = string(hash)
}
if s != nil {
@@ -352,17 +364,13 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
if err != nil {
return http.StatusForbidden, err
}
scopePath := utils.JoinPathAsUnix(userscope, body.Path)
scopePath = utils.AddTrailingSlashIfNotExists(scopePath)
body.Path = scopePath
providedPath := body.Path
body.Path = utils.JoinPathAsUnix(userscope, providedPath)
body.Path = utils.AddTrailingSlashIfNotExists(body.Path)
// validate path exists as file or folder
_, exists := idx.GetReducedMetadata(body.Path, true) // true to check if it exists
if !exists {
// could be a file instead
_, exists := idx.GetReducedMetadata(utils.GetParentDirectoryPath(body.Path), true)
if !exists {
return http.StatusForbidden, fmt.Errorf("path not found: %s", body.Path)
}
_, _, err = idx.GetRealPath(body.Path)
if err != nil {
return http.StatusForbidden, fmt.Errorf("path not found: %s", providedPath)
}
if body.ShareType == "upload" && !body.AllowCreate {
body.AllowCreate = true
@@ -510,8 +518,8 @@ func shareDirectDownloadHandler(w http.ResponseWriter, r *http.Request, d *reque
response := DirectDownloadResponse{
Status: "201",
Hash: existing.Hash,
DownloadURL: getShareURL(r, existing.Hash, true),
ShareURL: getShareURL(r, existing.Hash, false),
DownloadURL: getShareURL(r, existing.Hash, true, existing.Token),
ShareURL: getShareURL(r, existing.Hash, false, existing.Token),
}
return renderJSON(w, r, response)
}
@@ -542,18 +550,23 @@ func shareDirectDownloadHandler(w http.ResponseWriter, r *http.Request, d *reque
response := DirectDownloadResponse{
Status: "200",
Hash: secureHash,
DownloadURL: getShareURL(r, secureHash, true),
ShareURL: getShareURL(r, secureHash, false),
DownloadURL: getShareURL(r, secureHash, true, shareLink.Token),
ShareURL: getShareURL(r, secureHash, false, shareLink.Token),
}
return renderJSON(w, r, response)
}
func getShareURL(r *http.Request, hash string, isDirectDownload bool) string {
func getShareURL(r *http.Request, hash string, isDirectDownload bool, token string) string {
var shareURL string
tokenParam := ""
if token != "" && isDirectDownload {
tokenParam = fmt.Sprintf("&token=%s", url.QueryEscape(token))
}
if config.Server.ExternalUrl != "" {
if isDirectDownload {
shareURL = fmt.Sprintf("%s%spublic/api/raw?hash=%s", config.Server.ExternalUrl, config.Server.BaseURL, hash)
shareURL = fmt.Sprintf("%s%spublic/api/raw?hash=%s%s", config.Server.ExternalUrl, config.Server.BaseURL, hash, tokenParam)
} else {
shareURL = fmt.Sprintf("%s%spublic/share/%s", config.Server.ExternalUrl, config.Server.BaseURL, hash)
}
@@ -576,7 +589,7 @@ func getShareURL(r *http.Request, hash string, isDirectDownload bool) string {
scheme = getScheme(r)
}
if isDirectDownload {
shareURL = fmt.Sprintf("%s://%s%spublic/api/raw?hash=%s", scheme, host, config.Server.BaseURL, hash)
shareURL = fmt.Sprintf("%s://%s%spublic/api/raw?hash=%s%s", scheme, host, config.Server.BaseURL, hash, tokenParam)
} else {
shareURL = fmt.Sprintf("%s://%s%spublic/share/%s", scheme, host, config.Server.BaseURL, hash)
}
@@ -596,13 +609,14 @@ func getShareURL(r *http.Request, hash string, isDirectDownload bool) string {
// @Router /public/api/shareinfo [get]
func shareInfoHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
hash := r.URL.Query().Get("hash")
// Get the file link by hash
commonShare, err := store.Share.GetCommonShareByHash(hash)
// Get the file link by hash (need full Link to get Token)
shareLink, err := store.Share.GetByHash(hash)
if err != nil {
return http.StatusNotFound, fmt.Errorf("share hash not found")
}
commonShare.DownloadURL = getShareURL(r, hash, true)
commonShare.ShareURL = getShareURL(r, hash, false)
commonShare := shareLink.CommonShare
commonShare.DownloadURL = getShareURL(r, hash, true, shareLink.Token)
commonShare.ShareURL = getShareURL(r, hash, false, shareLink.Token)
return renderJSON(w, r, commonShare)
}
+6 -1
View File
@@ -73,6 +73,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
staticURL := config.Server.BaseURL + "public/static"
description := config.Frontend.Description
title := config.Frontend.Name
disableSidebar := false
// Use custom favicon if configured and validated, otherwise fall back to default
favicon := staticURL + "/favicon"
@@ -104,6 +105,9 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
userSelectedTheme = theme.CssRaw
}
}
if d.share.DisableSidebar {
disableSidebar = true
}
}
// Set login icon URL
loginIcon := staticURL + "/loginIcon"
@@ -148,6 +152,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont
"enableHeicConversion": config.Integrations.Media.Convert.ImagePreview[settings.HEICImagePreview] && settings.MediaEnabled(),
"eventBasedThemes": !config.Frontend.Styling.DisableEventBasedThemes,
"loginIcon": loginIcon,
"disableSidebar": disableSidebar,
}
// Marshal each variable to JSON strings for direct template usage
@@ -210,7 +215,7 @@ func staticAssetHandler(w http.ResponseWriter, r *http.Request) {
// Handle special routes that need path mapping
var assetPath string
switch path {
case "favicon.ico", "favicon":
case "favicon.svg", "favicon":
// Handle custom favicon from filesystem
if settings.Env.FaviconIsCustom {
http.ServeFile(w, r, settings.Env.FaviconPath)
+7 -3
View File
@@ -10,11 +10,13 @@ import (
// generateOTPHandler handles the generation of a new TOTP secret and QR code.
// @Summary Generate OTP
// @Description Generates a new TOTP secret and QR code for the authenticated user.
// @Description Generates a new TOTP secret and QR code for the authenticated user. The password must be URL-encoded and sent in the X-Password header to support special characters.
// @Tags OTP
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param username query string true "Username"
// @Param X-Password header string true "URL-encoded password"
// @Success 200 {object} map[string]string "OTP secret generated successfully."
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/auth/otp/generate [post]
@@ -33,12 +35,14 @@ func generateOTPHandler(w http.ResponseWriter, r *http.Request, d *requestContex
// verifyOTPHandler handles the verification of a TOTP code.
// @Summary Verify OTP
// @Description Verifies the provided TOTP code for the authenticated user.
// @Description Verifies the provided TOTP code for the authenticated user. The password must be URL-encoded and sent in the X-Password header to support special characters.
// @Tags OTP
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param code query string true "TOTP code to verify"
// @Param username query string true "Username"
// @Param X-Password header string true "URL-encoded password"
// @Param X-Secret header string true "TOTP code to verify"
// @Success 200 {object} HttpResponse "OTP token is valid."
// @Failure 401 {object} map[string]string "Unauthorized - invalid TOTP token"
// @Router /api/auth/otp/verify [post]
+32 -7
View File
@@ -215,7 +215,32 @@ func (idx *Index) indexDirectory(adjustedPath string, config actionConfig) error
return nil
}
func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error) {
func (idx *Index) GetFsInfo(adjustedPath string, followSymlinks bool) (*iteminfo.FileInfo, error) {
// If not following symlinks, check if it's a symlink first
if !followSymlinks {
realPath := filepath.Join(idx.Path, adjustedPath)
symlinkInfo, err := os.Lstat(realPath)
if err != nil {
return nil, err
}
// If it's a symlink, return info about the symlink itself (not the target)
if symlinkInfo.Mode()&os.ModeSymlink != 0 {
realSize, _ := idx.handleFile(symlinkInfo, adjustedPath, realPath)
size := int64(realSize)
fileInfo := iteminfo.FileInfo{
Path: adjustedPath,
ItemInfo: iteminfo.ItemInfo{
Name: filepath.Base(strings.TrimSuffix(adjustedPath, "/")),
Size: size,
ModTime: symlinkInfo.ModTime(),
Type: "symlink",
},
}
return &fileInfo, nil
}
}
realPath, isDir, err := idx.GetRealPath(adjustedPath)
if err != nil {
return nil, err
@@ -234,11 +259,8 @@ func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error)
}
if !dirInfo.IsDir() {
// Use handleFile for consistent size calculation across platforms
// API calls (GetFsDirInfo) should not update totalSize, so pass false for isRoutineScan
realSize, _ := idx.handleFile(dirInfo, adjustedPath, realPath, false)
realSize, _ := idx.handleFile(dirInfo, adjustedPath, realPath)
size := int64(realSize)
fileInfo := iteminfo.FileInfo{
Path: adjustedPath,
ItemInfo: iteminfo.ItemInfo{
@@ -365,7 +387,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
}
} else {
realFilePath := realPath + "/" + file.Name()
size, shouldCountSize := idx.handleFile(file, fullCombined, realFilePath, config.IsRoutineScan)
size, shouldCountSize := idx.handleFile(file, fullCombined, realFilePath)
itemInfo.DetectType(realFilePath, false)
usedCachedPreview := false
if !idx.Config.DisableIndexing && config.Recursive {
@@ -399,7 +421,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
}
}
}
if totalSize == 0 && idx.Config.Conditionals.ZeroSizeFolders {
if totalSize == 0 && idx.Config.Conditionals.ZeroSizeFolders && combinedPath != "/" {
return nil, errors.ErrNotIndexed
}
dirFileInfo := &iteminfo.FileInfo{
@@ -527,6 +549,9 @@ func setFilePreviewFlags(fileInfo *iteminfo.ItemInfo, realPath string) {
// IsViewable checks if a path has viewable:true (allows FS access without indexing)
func (idx *Index) IsViewable(isDir bool, adjustedPath string) bool {
if adjustedPath == "/" {
return true
}
rules := idx.Config.ResolvedConditionals
baseName := filepath.Base(strings.TrimSuffix(adjustedPath, "/"))
+69 -35
View File
@@ -3,6 +3,7 @@ package indexing
import (
"os"
"strings"
"sync"
"time"
"github.com/gtsteffaniak/go-logger/logger"
@@ -22,15 +23,21 @@ type Scanner struct {
lastScanned time.Time
quickScanTime int
fullScanTime int
numDirs uint64 // Local count for this path
numFiles uint64 // Local count for this path
scannerSize uint64 // Size contributed by this scanner (for delta calculation)
// size tracking
numDirs uint64 // Local count for this path
numFiles uint64 // Local count for this path
size uint64 // Size contributed by this scanner (for delta calculation)
previousNumDirs uint64 // Previous numDirs value (preserved across scans)
previousNumFiles uint64 // Previous numFiles value (preserved across scans)
previousSize uint64 // Previous size value (preserved across scans)
// Reference back to parent index
idx *Index
// Control
stopChan chan struct{}
stopOnce sync.Once // Ensures stop() is only executed once
}
// start begins the scanner's main loop
@@ -121,31 +128,17 @@ func (s *Scanner) runRootScan(quick bool) {
IsRoutineScan: true,
}
// Reset counters for full scan
// Store previous values before scanning (preserved across scans)
prevNumDirs := s.previousNumDirs
prevNumFiles := s.previousNumFiles
prevSize := s.previousSize
// Reset counters for full scan (they will be incremented during indexing)
if !quick {
s.numDirs = 0
s.numFiles = 0
}
// Track size before scan for delta calculation
previousScannerSize := s.scannerSize
s.idx.mu.Lock()
if previousScannerSize > 0 {
if s.idx.totalSize >= previousScannerSize {
s.idx.totalSize -= previousScannerSize
} else {
// Safety check: if totalSize is less than previousScannerSize, something is wrong
// Reset to 0 to avoid underflow
logger.Warningf("[%s] Scanner [%s] WARNING: totalSize (%d) < previousScannerSize (%d), resetting totalSize to 0", s.idx.Name, s.scanPath, s.idx.totalSize, previousScannerSize)
s.idx.totalSize = 0
}
}
indexSizeBefore := s.idx.totalSize
s.idx.mu.Unlock()
logger.Debugf("[%s] Scanner [%s] START: indexSizeBefore=%d, previousScannerSize=%d (quick=%v)", s.idx.Name, s.scanPath, indexSizeBefore, previousScannerSize, quick)
s.filesChanged = false
startTime := time.Now()
@@ -154,12 +147,30 @@ func (s *Scanner) runRootScan(quick bool) {
logger.Errorf("Root scanner error: %v", err)
}
// Calculate delta for this scanner
// Root scanner gets values directly from index metadata - simple!
s.idx.mu.RLock()
indexSizeAfter := s.idx.totalSize
rootDirInfo, exists := s.idx.Directories["/"]
s.idx.mu.RUnlock()
newScannerSize := indexSizeAfter - indexSizeBefore
s.scannerSize = newScannerSize
newNumDirs := prevNumDirs
newNumFiles := prevNumFiles
newsize := prevSize
if exists && rootDirInfo != nil {
for _, file := range rootDirInfo.Files {
newsize += uint64(file.Size)
newNumFiles++
}
for range rootDirInfo.Folders {
newNumDirs++
}
}
// Update scanner with new values
s.size = newsize
// Update previous values for next scan (preserve history - don't reset on new scans)
s.previousNumDirs = newNumDirs
s.previousNumFiles = newNumFiles
s.previousSize = newsize
scanDuration := int(time.Since(startTime).Seconds())
if quick {
s.quickScanTime = scanDuration
@@ -178,26 +189,46 @@ func (s *Scanner) runChildScan(quick bool) {
IsRoutineScan: true,
}
// Reset counters for full scan
// Store previous values before scanning (preserved across scans)
prevSize := s.previousSize
// Reset counters for full scan (they will be incremented during indexing)
if !quick {
s.numDirs = 0
s.numFiles = 0
}
s.idx.mu.RLock()
indexSizeBefore := s.idx.totalSize
s.idx.mu.RUnlock()
s.filesChanged = false
startTime := time.Now()
err := s.idx.indexDirectory(s.scanPath, config)
if err != nil {
logger.Errorf("Scanner [%s] error: %v", s.scanPath, err)
}
// Calculate new values after scan
newNumDirs := s.numDirs
newNumFiles := s.numFiles
// For child scanners, calculate size from the directory info
// Since child scanners don't modify totalSize, we get it from the directory metadata
s.idx.mu.RLock()
indexSizeAfter := s.idx.totalSize
dirInfo, exists := s.idx.Directories[s.scanPath]
s.idx.mu.RUnlock()
newScannerSize := indexSizeAfter - indexSizeBefore
s.scannerSize = newScannerSize
newsize := prevSize
if exists && dirInfo != nil {
newsize = uint64(dirInfo.Size)
}
// Update scanner with new values
s.size = newsize
// Update previous values for next scan (preserve history - don't reset on new scans)
s.previousNumDirs = newNumDirs
s.previousNumFiles = newNumFiles
s.previousSize = newsize
scanDuration := int(time.Since(startTime).Seconds())
if quick {
s.quickScanTime = scanDuration
@@ -375,6 +406,9 @@ func (s *Scanner) removeSelf() {
}
// stop gracefully stops the scanner
// This method is idempotent and safe to call multiple times
func (s *Scanner) stop() {
close(s.stopChan)
s.stopOnce.Do(func() {
close(s.stopChan)
})
}
+7 -1
View File
@@ -178,7 +178,7 @@ func (idx *Index) SendSourceUpdateEvent() error {
logger.Debug("Skipping source update event for mock index.")
return nil
}
reducedIndex, err := GetIndexInfo(idx.Name, false)
reducedIndex, err := GetIndexInfo(idx.Name, true)
if err != nil {
logger.Errorf("[%s] Error getting index info: %v", idx.Name, err)
return err
@@ -284,6 +284,7 @@ func (idx *Index) aggregateStatsFromScanners() {
var totalFiles uint64 = 0
var totalQuickScanTime = 0
var totalFullScanTime = 0
var totalSizeFromScanners uint64 = 0 // Sum of all scanner sizes
var mostRecentScan time.Time
allScannedAtLeastOnce := true
@@ -292,6 +293,7 @@ func (idx *Index) aggregateStatsFromScanners() {
totalFiles += scanner.numFiles
totalQuickScanTime += scanner.quickScanTime
totalFullScanTime += scanner.fullScanTime
totalSizeFromScanners += scanner.size
if scanner.lastScanned.After(mostRecentScan) {
mostRecentScan = scanner.lastScanned
}
@@ -299,6 +301,10 @@ func (idx *Index) aggregateStatsFromScanners() {
allScannedAtLeastOnce = false
}
}
// Update totalSize by summing all scanner sizes (root scanner handles this)
// This ensures totalSize is always the sum of all scanner contributions
idx.totalSize = totalSizeFromScanners
idx.NumDirs = totalDirs
idx.NumFiles = totalFiles
idx.QuickScanTime = totalQuickScanTime
+7 -2
View File
@@ -5,6 +5,7 @@ import (
"path/filepath"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
"github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo"
@@ -21,7 +22,6 @@ func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo) bool {
// DeleteMetadata removes the specified path from the index.
// If recursive is true and the path is a directory, it will also remove all subdirectories.
// NOTE: path should already be an index path (with trailing slash for directories)
func (idx *Index) DeleteMetadata(path string, isDir bool, recursive bool) bool {
idx.mu.Lock()
defer idx.mu.Unlock()
@@ -32,6 +32,11 @@ func (idx *Index) DeleteMetadata(path string, isDir bool, recursive bool) bool {
indexPath = utils.AddTrailingSlashIfNotExists(path)
}
// Clear cache entries
joinedPath := filepath.Join(idx.Path, indexPath)
RealPathCache.Delete(joinedPath)
IsDirCache.Delete(joinedPath + ":isdir")
if !isDir {
// For files, remove from parent directory's Files slice
parentPath := utils.AddTrailingSlashIfNotExists(filepath.Dir(strings.TrimSuffix(path, "/")))
@@ -194,7 +199,7 @@ func GetIndexInfo(sourceName string, forceCacheRefresh bool) (ReducedIndex, erro
_, ok = utils.DiskUsageCache.Get(cacheKey)
if !ok {
// Only fetch disk total if not cached (this is expensive, so we cache it)
totalBytes, err := getPartitionSize(sourcePath)
totalBytes, err := fileutils.GetPartitionSize(sourcePath)
if err != nil {
idx.mu.Lock()
idx.Status = UNAVAILABLE
+2 -28
View File
@@ -15,18 +15,6 @@ func CheckWindowsHidden(realpath string) bool {
return false
}
// getFilesystemSize returns the filesystem size (fallback method)
func getPartitionSize(path string) (uint64, error) {
var stat syscall.Statfs_t
err := syscall.Statfs(path, &stat)
if err != nil {
return 0, err
}
// Total size in bytes: Blocks * Block size
total := stat.Blocks * uint64(stat.Bsize)
return total, nil
}
func getFileDetails(sys any, filePath string) (uint64, uint64, uint64, bool) {
// On Unix, we should always be able to get syscall info
// First try from file.Sys() if available (fast path)
@@ -62,8 +50,7 @@ func getFileDetails(sys any, filePath string) (uint64, uint64, uint64, bool) {
// handleFile processes a file and returns its size and whether it should be counted
// On Unix, always uses syscall to get allocated size (du-like behavior)
// isRoutineScan: if true, updates the global totalSize; if false (API calls), only returns size
func (idx *Index) handleFile(file os.FileInfo, fullCombined string, realFilePath string, isRoutineScan bool) (size uint64, shouldCountSize bool) {
func (idx *Index) handleFile(file os.FileInfo, fullCombined string, realFilePath string) (size uint64, shouldCountSize bool) {
var realSize uint64
var nlink uint64
var ino uint64
@@ -88,21 +75,8 @@ func (idx *Index) handleFile(file os.FileInfo, fullCombined string, realFilePath
// First time seeing this inode.
idx.processedInodes[ino] = struct{}{}
idx.FoundHardLinks[fullCombined] = realSize
// Only update totalSize during routine scans (not API calls)
if isRoutineScan {
idx.totalSize += realSize
}
return realSize, true // Count size for directory total.
}
// It's a regular file.
// Only update totalSize during routine scans (not API calls)
if isRoutineScan {
idx.mu.Lock()
idx.totalSize += realSize
idx.mu.Unlock()
}
return realSize, true // Count size.
return realSize, true // Count size for directory total.
}
// platform specific rules
+1 -31
View File
@@ -34,41 +34,11 @@ func CheckWindowsHidden(realpath string) bool {
return false
}
func getPartitionSize(path string) (uint64, error) {
pathPtr, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, err
}
var freeBytes, totalBytes, totalFreeBytes uint64
err = windows.GetDiskFreeSpaceEx(pathPtr, &freeBytes, &totalBytes, &totalFreeBytes)
if err != nil {
return 0, err
}
return totalBytes, nil
}
func getFileDetails(sys any, filePath string) (uint64, uint64, uint64, bool) {
// On Windows, os.FileInfo.Sys() returns *syscall.Win32FileAttributeData,
// which does not contain inode or link count information.
// We return false to indicate that we should use the fallback mechanism.
// filePath parameter is ignored on Windows
return 0, 1, 0, false
}
// handleFile processes a file and returns its size and whether it should be counted
// On Windows, uses file.Size() directly (no syscall support for allocated size)
// isRoutineScan: if true, updates the global totalSize; if false (API calls), only returns size
func (idx *Index) handleFile(file os.FileInfo, fullCombined string, realFilePath string, isRoutineScan bool) (size uint64, shouldCountSize bool) {
func (idx *Index) handleFile(file os.FileInfo, fullCombined string, realFilePath string) (size uint64, shouldCountSize bool) {
// On Windows, just use the actual file size
realSize := uint64(file.Size())
// Windows doesn't support hard links in the same way, so always count size
// Only update totalSize during routine scans (not API calls)
if isRoutineScan {
idx.mu.Lock()
idx.totalSize += realSize
idx.mu.Unlock()
}
return realSize, true
}
+82 -11
View File
@@ -466,7 +466,7 @@ const docTemplate = `{
},
"/api/auth/login": {
"post": {
"description": "Authenticate a user with a username and password.",
"description": "Authenticate a user with a username and password. The password must be URL-encoded and sent in the X-Password header to support special characters (e.g., ^, %, £, €, etc.).",
"consumes": [
"application/json"
],
@@ -477,6 +477,34 @@ const docTemplate = `{
"Auth"
],
"summary": "User login",
"parameters": [
{
"type": "string",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "ReCaptcha response token (if enabled)",
"name": "recaptcha",
"in": "query"
},
{
"type": "string",
"description": "URL-encoded password",
"name": "X-Password",
"in": "header",
"required": true
},
{
"type": "string",
"description": "TOTP code (if 2FA is enabled)",
"name": "X-Secret",
"in": "header"
}
],
"responses": {
"200": {
"description": "JWT token for authentication",
@@ -610,7 +638,7 @@ const docTemplate = `{
},
"/api/auth/otp/generate": {
"post": {
"description": "Generates a new TOTP secret and QR code for the authenticated user.",
"description": "Generates a new TOTP secret and QR code for the authenticated user. The password must be URL-encoded and sent in the X-Password header to support special characters.",
"consumes": [
"application/json"
],
@@ -621,6 +649,22 @@ const docTemplate = `{
"OTP"
],
"summary": "Generate OTP",
"parameters": [
{
"type": "string",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "URL-encoded password",
"name": "X-Password",
"in": "header",
"required": true
}
],
"responses": {
"200": {
"description": "OTP secret generated successfully.",
@@ -650,7 +694,7 @@ const docTemplate = `{
},
"/api/auth/otp/verify": {
"post": {
"description": "Verifies the provided TOTP code for the authenticated user.",
"description": "Verifies the provided TOTP code for the authenticated user. The password must be URL-encoded and sent in the X-Password header to support special characters.",
"consumes": [
"application/json"
],
@@ -664,10 +708,24 @@ const docTemplate = `{
"parameters": [
{
"type": "string",
"description": "TOTP code to verify",
"name": "code",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "URL-encoded password",
"name": "X-Password",
"in": "header",
"required": true
},
{
"type": "string",
"description": "TOTP code to verify",
"name": "X-Secret",
"in": "header",
"required": true
}
],
"responses": {
@@ -2903,6 +2961,9 @@ const docTemplate = `{
"key": {
"type": "string"
},
"minimal": {
"type": "boolean"
},
"name": {
"type": "string"
}
@@ -3066,6 +3127,10 @@ const docTemplate = `{
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4354,6 +4419,10 @@ const docTemplate = `{
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4487,6 +4556,10 @@ const docTemplate = `{
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4626,6 +4699,10 @@ const docTemplate = `{
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4675,12 +4752,6 @@ const docTemplate = `{
"belongsTo": {
"type": "integer"
},
"createdAt": {
"type": "integer"
},
"expiresAt": {
"type": "integer"
},
"key": {
"type": "string"
},
+82 -11
View File
@@ -455,7 +455,7 @@
},
"/api/auth/login": {
"post": {
"description": "Authenticate a user with a username and password.",
"description": "Authenticate a user with a username and password. The password must be URL-encoded and sent in the X-Password header to support special characters (e.g., ^, %, £, €, etc.).",
"consumes": [
"application/json"
],
@@ -466,6 +466,34 @@
"Auth"
],
"summary": "User login",
"parameters": [
{
"type": "string",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "ReCaptcha response token (if enabled)",
"name": "recaptcha",
"in": "query"
},
{
"type": "string",
"description": "URL-encoded password",
"name": "X-Password",
"in": "header",
"required": true
},
{
"type": "string",
"description": "TOTP code (if 2FA is enabled)",
"name": "X-Secret",
"in": "header"
}
],
"responses": {
"200": {
"description": "JWT token for authentication",
@@ -599,7 +627,7 @@
},
"/api/auth/otp/generate": {
"post": {
"description": "Generates a new TOTP secret and QR code for the authenticated user.",
"description": "Generates a new TOTP secret and QR code for the authenticated user. The password must be URL-encoded and sent in the X-Password header to support special characters.",
"consumes": [
"application/json"
],
@@ -610,6 +638,22 @@
"OTP"
],
"summary": "Generate OTP",
"parameters": [
{
"type": "string",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "URL-encoded password",
"name": "X-Password",
"in": "header",
"required": true
}
],
"responses": {
"200": {
"description": "OTP secret generated successfully.",
@@ -639,7 +683,7 @@
},
"/api/auth/otp/verify": {
"post": {
"description": "Verifies the provided TOTP code for the authenticated user.",
"description": "Verifies the provided TOTP code for the authenticated user. The password must be URL-encoded and sent in the X-Password header to support special characters.",
"consumes": [
"application/json"
],
@@ -653,10 +697,24 @@
"parameters": [
{
"type": "string",
"description": "TOTP code to verify",
"name": "code",
"description": "Username",
"name": "username",
"in": "query",
"required": true
},
{
"type": "string",
"description": "URL-encoded password",
"name": "X-Password",
"in": "header",
"required": true
},
{
"type": "string",
"description": "TOTP code to verify",
"name": "X-Secret",
"in": "header",
"required": true
}
],
"responses": {
@@ -2892,6 +2950,9 @@
"key": {
"type": "string"
},
"minimal": {
"type": "boolean"
},
"name": {
"type": "string"
}
@@ -3055,6 +3116,10 @@
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4343,6 +4408,10 @@
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4476,6 +4545,10 @@
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4615,6 +4688,10 @@
"shareURL": {
"type": "string"
},
"showHidden": {
"description": "show hidden files in share (true = show, false = hide)",
"type": "boolean"
},
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4664,12 +4741,6 @@
"belongsTo": {
"type": "integer"
},
"createdAt": {
"type": "integer"
},
"expiresAt": {
"type": "integer"
},
"key": {
"type": "string"
},
+64 -8
View File
@@ -9,6 +9,8 @@ definitions:
type: integer
key:
type: string
minimal:
type: boolean
name:
type: string
type: object
@@ -119,6 +121,9 @@ definitions:
type: string
shareURL:
type: string
showHidden:
description: show hidden files in share (true = show, false = hide)
type: boolean
sidebarLinks:
description: customizable sidebar links
items:
@@ -1080,6 +1085,9 @@ definitions:
type: string
shareURL:
type: string
showHidden:
description: show hidden files in share (true = show, false = hide)
type: boolean
sidebarLinks:
description: customizable sidebar links
items:
@@ -1173,6 +1181,9 @@ definitions:
type: string
shareURL:
type: string
showHidden:
description: show hidden files in share (true = show, false = hide)
type: boolean
sidebarLinks:
description: customizable sidebar links
items:
@@ -1270,6 +1281,9 @@ definitions:
type: string
shareURL:
type: string
showHidden:
description: show hidden files in share (true = show, false = hide)
type: boolean
sidebarLinks:
description: customizable sidebar links
items:
@@ -1308,10 +1322,6 @@ definitions:
$ref: '#/definitions/users.Permissions'
belongsTo:
type: integer
createdAt:
type: integer
expiresAt:
type: integer
key:
type: string
name:
@@ -1871,7 +1881,28 @@ paths:
post:
consumes:
- application/json
description: Authenticate a user with a username and password.
description: Authenticate a user with a username and password. The password
must be URL-encoded and sent in the X-Password header to support special characters
(e.g., ^, %, £, €, etc.).
parameters:
- description: Username
in: query
name: username
required: true
type: string
- description: ReCaptcha response token (if enabled)
in: query
name: recaptcha
type: string
- description: URL-encoded password
in: header
name: X-Password
required: true
type: string
- description: TOTP code (if 2FA is enabled)
in: header
name: X-Secret
type: string
produces:
- application/json
responses:
@@ -1966,6 +1997,19 @@ paths:
consumes:
- application/json
description: Generates a new TOTP secret and QR code for the authenticated user.
The password must be URL-encoded and sent in the X-Password header to support
special characters.
parameters:
- description: Username
in: query
name: username
required: true
type: string
- description: URL-encoded password
in: header
name: X-Password
required: true
type: string
produces:
- application/json
responses:
@@ -1990,11 +2034,23 @@ paths:
post:
consumes:
- application/json
description: Verifies the provided TOTP code for the authenticated user.
description: Verifies the provided TOTP code for the authenticated user. The
password must be URL-encoded and sent in the X-Password header to support
special characters.
parameters:
- description: TOTP code to verify
- description: Username
in: query
name: code
name: username
required: true
type: string
- description: URL-encoded password
in: header
name: X-Password
required: true
type: string
- description: TOTP code to verify
in: header
name: X-Secret
required: true
type: string
produces:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

+4 -2
View File
@@ -160,8 +160,6 @@
transform: scale(1.0);
}
}
{{ .htmlVars.customCSS }}
{{ .htmlVars.userSelectedTheme }}
</style>
</head>
@@ -187,6 +185,10 @@
{{end}}
<script type="module" src="/src/main.ts"></script>
<style>
{{ .htmlVars.customCSS }}
{{ .htmlVars.userSelectedTheme }}
</style>
</body>
</html>
+14 -49
View File
@@ -98,61 +98,26 @@ export async function download(format, files, shareHash = "") {
files: fileargs,
algo: format,
hash: shareHash,
...(state.share.token && { token: state.share.token })
...(state.share.token && { token: state.share.token }),
sessionId: state.sessionId
})
const url = window.origin + apiPath
// Use fetch to capture errors in the console
const response = await fetch(url, {
credentials: 'same-origin',
headers: {
"sessionId": state.sessionId,
},
})
if (!response.ok) {
const errorText = await response.text()
const error = new Error(`Download failed: ${response.status} ${response.statusText}`)
console.error('Download API error:', {
status: response.status,
statusText: response.statusText,
body: errorText,
url: url
})
throw error
}
// Get the blob from the response
const blob = await response.blob()
// Determine filename from Content-Disposition header or use default
let filename = 'download'
const contentDisposition = response.headers.get('Content-Disposition')
if (contentDisposition) {
const utf8 = contentDisposition.split("filename*=utf-8''")[1]
if (utf8) {
filename = decodeURIComponent(utf8.split(';')[0].trim())
} else {
const ascii = contentDisposition.split('filename="')[1]
if (ascii) {
filename = ascii.split('"')[0]
}
}
} else {
filename = `download.${format}`
}
// Create a blob URL and trigger download
const blobUrl = window.URL.createObjectURL(blob)
// Create a direct link and trigger the download
// This allows the browser to handle the download natively with:
// - Native download progress indicator
// - Shows up in browser's download menu
// - Doesn't load entire file into memory first
const link = document.createElement('a')
link.href = blobUrl
link.setAttribute('download', filename)
link.href = url
link.style.display = 'none'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
// Clean up the blob URL
window.URL.revokeObjectURL(blobUrl)
// Clean up after a short delay
setTimeout(() => {
document.body.removeChild(link)
}, 100)
}
export function post(
-1
View File
@@ -91,7 +91,6 @@ export function getPreviewURL(path,size="small") {
}
}
export function post(
hash,
path,
+3 -3
View File
@@ -18,7 +18,7 @@ export async function generateOTP(username, password) {
const res = await fetch(apiPath, {
method: 'POST',
headers: {
'X-Password': password,
'X-Password': encodeURIComponent(password),
}
})
return await res.json()
@@ -35,7 +35,7 @@ export async function verifyOtp(username, password, otp) {
const res = await fetch(apiPath, {
method: 'POST',
headers: {
'X-Password': password,
'X-Password': encodeURIComponent(password),
'X-Secret': otp,
}
})
@@ -65,7 +65,7 @@ export async function login(username, password, recaptcha, otp) {
method: 'POST',
credentials: 'same-origin', // Ensure cookies can be set during login
headers: {
'X-Password': password,
'X-Password': encodeURIComponent(password),
'X-Secret': otp,
}
});
+67 -94
View File
@@ -1,12 +1,8 @@
<template>
<div
id="search"
:class="{ active, ongoing, 'dark-mode': isDarkMode }"
@click="clearContext"
>
<div id="search" :class="{ active, ongoing, 'dark-mode': isDarkMode }" @click="clearContext">
<!-- Search input section -->
<div id="search-input" @click="open" :class="{'halloween-eyes': eventTheme === 'halloween'}">
<div id="halloween-eyes" v-if="eventTheme=== 'halloween' && active">
<div id="search-input" @click="open" :class="{ 'halloween-eyes': eventTheme === 'halloween' }">
<div id="halloween-eyes" v-if="eventTheme === 'halloween' && active">
<div class="eye left">
<div class="pupil"></div>
</div>
@@ -15,44 +11,23 @@
</div>
</div>
<!-- Close button visible when search is active -->
<button
v-if="active"
class="action"
@click="close"
:aria-label="$t('general.close')"
:title="$t('general.close')"
>
<button v-if="active" class="action" @click="close" :aria-label="$t('general.close')"
:title="$t('general.close')">
<i class="material-icons">close</i>
</button>
<!-- Search icon when search is not active -->
<i v-else class="material-icons">search</i>
<!-- Input field for search -->
<input
id="main-input"
class="main-input"
:class="{ 'halloween-theme': eventTheme === 'halloween' }"
type="text"
@keyup.exact="keyup"
@input="submit"
ref="input"
:autofocus="active"
v-model.trim="value"
aria-label="search input"
:placeholder="$t('general.search', { suffix: '...' })"
/>
<input id="main-input" class="main-input" :class="{ 'halloween-theme': eventTheme === 'halloween' }" type="text"
@keyup.exact="keyup" @input="submit" ref="input" :autofocus="active" v-model.trim="value"
aria-label="search input" :placeholder="$t('general.search', { suffix: '...' })" />
</div>
<!-- Search results for desktop -->
<div v-show="active" id="results" class="fb-shadow" ref="result">
<div v-show="active" id="results" class="fb-shadow" ref="result">
<div class="inputWrapper">
<select
v-if="multipleSources"
class="searchContext button input"
aria-label="search-path"
v-model="selectedSource"
:value="selectedSource"
@change="updateSource"
>
<select v-if="multipleSources" class="searchContext button input" aria-label="search sources dropdown"
v-model="selectedSource" :value="selectedSource" @change="updateSource">
<option v-for="(info, name) in sourceInfo" :key="info" :value="name">
{{ name }}
</option>
@@ -66,50 +41,36 @@
<div v-if="!disableSearchOptions">
<div v-if="active">
<div v-if="isMobile">
<ButtonGroup
:buttons="toggleOptionButton"
@button-clicked="enableOptions"
@remove-button-clicked="disableOptions"
/>
<ButtonGroup :buttons="toggleOptionButton" @button-clicked="enableOptions"
@remove-button-clicked="disableOptions" />
</div>
<transition name="expand">
<div v-show="showOptions" class="search-options">
<!-- Button groups for filtering search results -->
<ButtonGroup
:buttons="folderSelect"
@button-clicked="addToTypes"
@remove-button-clicked="removeFromTypes"
@disableAll="folderSelectClicked()"
@enableAll="resetButtonGroups()"
/>
<ButtonGroup
:buttons="typeSelect"
@button-clicked="addToTypes"
@remove-button-clicked="removeFromTypes"
:isDisabled="isTypeSelectDisabled"
/>
<ButtonGroup :buttons="folderSelect" @button-clicked="addToTypes"
@remove-button-clicked="removeFromTypes" @disableAll="folderSelectClicked()"
@enableAll="resetButtonGroups()" />
<ButtonGroup :buttons="typeSelect" @button-clicked="addToTypes" @remove-button-clicked="removeFromTypes"
:isDisabled="isTypeSelectDisabled" />
<!-- Inputs for filtering by file size -->
<div class="sizeConstraints">
<div class="sizeInputWrapper">
<p>{{ $t("search.smallerThan") }}</p>
<input
class="sizeInput"
v-model="smallerThan"
type="number"
min="0"
:placeholder="$t('general.number')"
/><p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<input class="sizeInput" v-model="smallerThan" type="number" min="0"
:placeholder="$t('general.number')" />
<p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="sizeInputWrapper">
<p>{{ $t("search.largerThan") }}</p>
<input
class="sizeInput"
v-model="largerThan"
type="number"
:placeholder="$t('general.number')"
/><p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
<input class="sizeInput" v-model="largerThan" type="number" :placeholder="$t('general.number')" />
<p>MB</p> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
</div>
<!-- Toggle for showing preview images -->
<div class="search-option-item">
<ToggleSwitch v-model="showPreviewImages" :name="$t('search.showPreviewImages')"
:description="$t('search.showPreviewImagesDescription')" />
</div>
</div>
</transition>
</div>
@@ -121,27 +82,22 @@
<!-- Message when no results are found -->
<div class="searchPrompt" v-show="isEmpty && !isRunning">
<p>{{ noneMessage }}</p>
<i
class="no-select material-symbols-outlined tooltip-info-icon"
@mouseenter="showHelpTooltip"
@mouseleave="hideTooltip"
>
<i class="no-select material-symbols-outlined tooltip-info-icon" @mouseenter="showHelpTooltip"
@mouseleave="hideTooltip">
help
</i>
</div>
<!-- List of search results -->
<ul v-show="results.length > 0">
<li
v-for="(s, k) in results"
:key="k"
class="search-entry clickable"
:class="{ active: activeStates[k] }"
:aria-label="baseName(s.path)"
>
<li v-for="(s, k) in results" :key="k" class="search-entry clickable"
:class="{ active: activeStates[k], 'large-icons': showPreviewImages }" :aria-label="baseName(s.path)">
<a :href="getRelative(s.path)" @contextmenu="addSelected(event, s)">
<Icon :mimetype="s.type" :filename="s.name" />
<Icon :mimetype="s.type" :filename="baseName(s.path)"
:hasPreview="showPreviewImages && (s.hasPreview || false)"
:thumbnailUrl="showPreviewImages ? getThumbnailUrl(s) : ''" />
<span class="text-container">
{{ basePath(s.path, s.type == "directory") }}{{ baseName(s.path) }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
{{ basePath(s.path, s.type == "directory") }}{{ baseName(s.path) }}
<!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</span>
<div class="filesize">{{ humanSize(s.size) }}</div>
</a>
@@ -154,11 +110,12 @@
<script>
import ButtonGroup from "./ButtonGroup.vue";
import { search } from "@/api";
import { search, filesApi } from "@/api";
import { getters, mutations, state } from "@/store";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { url } from "@/utils/";
import Icon from "@/components/files/Icon.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import { globalVars } from "@/utils/constants";
var boxes = {
@@ -175,6 +132,7 @@ export default {
components: {
ButtonGroup,
Icon,
ToggleSwitch,
},
name: "search",
data: function () {
@@ -184,6 +142,7 @@ export default {
noneMessage: this.$t("search.typeToSearch", { minSearchLength: globalVars.minSearchLength }),
searchTypes: "",
isTypeSelectDisabled: false,
showPreviewImages: false,
folderSelect: [
{ label: this.$t("search.onlyFolders"), value: "type:folder" },
{ label: this.$t("search.onlyFiles"), value: "type:file" },
@@ -407,14 +366,8 @@ export default {
this.submit();
},
getRelative(path) {
// double encode # to fix issue with # in path
// replace all # with %23
path = path.replaceAll('#', "%23");
if (path.startsWith("/")) {
path = path.slice(1); // remove leading slash
}
const context = url.removeTrailingSlash(this.getContext)
const encodedPath = encodeURIComponent(context + "/" + path).replaceAll("%2F", "/");
const encodedPath = url.encodePath(context + "/" + path)
let fullpath = encodedPath;
fullpath = globalVars.baseURL+"files/" + this.selectedSource + encodedPath;
return fullpath;
@@ -478,6 +431,7 @@ export default {
resetSearchFilters() {
this.searchTypes = "";
this.hiddenOptions = true;
this.showPreviewImages = false;
},
removeFromTypes(string) {
if (string == null || string == "") {
@@ -537,6 +491,19 @@ export default {
clearContext() {
mutations.closeHovers();
},
getThumbnailUrl(s) {
if (!s.hasPreview) {
return "";
}
try {
const source = this.selectedSource || state.sources.current;
const path = s.path;
const modified = s.modified || "";
return filesApi.getPreviewURL(source, path, modified);
} catch (err) {
return "";
}
},
addSelected(event, s) {
const pathParts = url.removeTrailingSlash(s.path).split("/");
let path = this.getContext + url.removeTrailingSlash(s.path);
@@ -558,6 +525,7 @@ export default {
.sizeInputWrapper {
border: 1px solid #ccc;
}
.main-input {
width: 100%;
}
@@ -599,7 +567,7 @@ export default {
color: white;
}
#results > #result-list {
#results>#result-list {
max-height: 80vh;
width: 35em;
overflow: scroll;
@@ -713,6 +681,12 @@ export default {
background-color: var(--surfacePrimary);
}
/* Toggle switch styling in search options */
.search-option-item {
margin: 1em;
}
.text-container {
margin-left: 0.25em;
white-space: nowrap;
@@ -743,7 +717,7 @@ body.rtl #search #result {
direction: ltr;
}
#search #result > div > *:first-child {
#search #result>div>*:first-child {
margin-top: 0;
}
@@ -753,7 +727,7 @@ body.rtl #search #result {
}
/* Search Results */
body.rtl #search #result ul > * {
body.rtl #search #result ul>* {
direction: ltr;
text-align: left;
}
@@ -970,7 +944,7 @@ body.rtl #search .boxes h3 {
}
#result-list {
width:100vw !important;
width: 100vw !important;
max-width: 100vw !important;
left: 0;
top: 4em;
@@ -981,5 +955,4 @@ body.rtl #search .boxes h3 {
flex-direction: column;
}
}
</style>
+28 -21
View File
@@ -7,25 +7,25 @@
>
<i
v-if="hasMotion && isFile"
class="material-icons"
class="material-icons icon-optimized"
:class="{ larger: showLarger, smaller: !showLarger }"
>animation</i
>
<i
v-else-if="!isFile"
class="material-icons"
class="material-icons icon-optimized"
:class="{ larger: showLarger, smaller: !showLarger }"
>folder</i
>
<img
:key="imageTargetSrc"
:src="imageDisplaySrc"
class="icon"
class="icon icon-optimized"
ref="thumbnail"
/>
</span>
<span v-else>
<i :class="[classes, { active: active, clickable: clickable }]" class="icon"> {{ materialIcon }} </i>
<i :class="[classes, { active: active, clickable: clickable }]" class="icon icon-optimized"> {{ materialIcon }} </i>
</span>
</template>
@@ -93,17 +93,17 @@ export default {
return false;
}
const simpleType = this.getIconForType().simpleType;
if (simpleType === "video" && !state.user.preview?.video) {
if (simpleType === "video" && !getters.previewPerms().video) {
return false;
}
if (simpleType === "image" && !state.user.preview?.image) {
if (simpleType === "image" && !getters.previewPerms().image) {
return false;
}
// office files
if ((simpleType === "document" || simpleType === "text") && !state.user.preview?.office) {
if ((simpleType === "document" || simpleType === "text") && !getters.previewPerms().office) {
return false;
}
if (!state.user.preview.folder && this.mimetype == "directory") {
if (!getters.previewPerms().folder && this.mimetype == "directory") {
return false;
}
return this.imageState !== 'error' && !this.disablePreviewExt && !this.officeFileDisabled
@@ -153,7 +153,7 @@ export default {
return this.imageTargetSrc;
},
showLargeIcon() {
return getters.viewMode() === "gallery" && state.user.preview.highQuality;
return getters.viewMode() === "gallery" && getters.previewPerms().highQuality;
},
showLarger() {
return getters.viewMode() === "gallery" || getters.viewMode() === "normal";
@@ -161,10 +161,9 @@ export default {
hasMotion() {
return (
this.getIconForType().simpleType === "video" &&
state.user.preview?.video &&
getters.previewPerms().video &&
globalVars.mediaAvailable &&
// @ts-ignore
state.user.preview.motionVideoPreview
getters.previewPerms().motionVideoPreview
);
},
isMaterialIcon() {
@@ -206,8 +205,7 @@ export default {
if (this.imageState == "loaded") {
mutations.setPreviewSource(imageUrl);
}
// @ts-ignore
if (!state.user.preview.motionVideoPreview || !this.hasMotion) {
if (!getters.previewPerms().motionVideoPreview || !this.hasMotion) {
return;
}
@@ -226,7 +224,7 @@ export default {
return;
}
// Set the thumbnail or popup preview
if (state.user.preview.popup) {
if (getters.previewPerms().popup) {
mutations.setPreviewSource(sequence[index]);
} else {
this.currentThumbnail = sequence[index];
@@ -272,7 +270,6 @@ export default {
showLargeIcon() {
this.updateImageTargetSrc();
},
// UPDATED: Load image when URL changes, let hasPreviewImage control display
imageTargetSrc: {
handler(newSrc) {
// Check all conditions EXCEPT imageState to avoid circular dependency
@@ -283,17 +280,17 @@ export default {
return;
}
const simpleType = this.getIconForType().simpleType;
// Check user preview settings
if (simpleType === "video" && !state.user.preview?.video) {
// Check preview settings (share or user)
if (simpleType === "video" && !getters.previewPerms().video) {
return;
}
if (simpleType === "image" && !state.user.preview?.image) {
if (simpleType === "image" && !getters.previewPerms().image) {
return;
}
if ((simpleType === "document" || simpleType === "text") && !state.user.preview?.office) {
if ((simpleType === "document" || simpleType === "text") && !getters.previewPerms().office) {
return;
}
if (!state.user.preview.folder && this.mimetype === "directory") {
if (!getters.previewPerms().folder && this.mimetype === "directory") {
return;
}
if (this.disablePreviewExt || this.officeFileDisabled) {
@@ -319,6 +316,13 @@ export default {
</script>
<style>
/* Performance optimization for icons */
.icon-optimized {
will-change: auto;
transform: translateZ(0);
backface-visibility: hidden;
}
.larger {
position: absolute;
opacity: 0.5;
@@ -354,6 +358,9 @@ export default {
border-radius: 0.2em;
padding: 0.1em;
background: var(--iconBackground);
/* Performance optimization */
will-change: auto;
transform: translateZ(0);
}
.icon.active {
background: var(--background);
+34 -8
View File
@@ -7,6 +7,7 @@
hiddenFile: isHiddenNotSelected && this && !this.isDraggedOver,
'half-selected': isDraggedOver,
'drag-hover': isDraggedOver,
'out-of-view': !isInView && !isSelected,
}"
:id="getID"
role="button"
@@ -89,6 +90,7 @@ export default {
data() {
return {
isThumbnailInView: false,
isInView: false, // Track if item is in viewport
touches: 0,
touchStartX: 0,
touchStartY: 0,
@@ -96,6 +98,7 @@ export default {
isSwipe: false,
isDraggedOver: false,
contextTimeout: null,
observer: null, // Store observer reference
};
},
props: [
@@ -209,14 +212,21 @@ export default {
},
},
mounted() {
// Prevent default navigation for left-clicks
const observer = new IntersectionObserver(this.handleIntersect, {
// Set up IntersectionObserver with larger margins for smoother rendering
this.observer = new IntersectionObserver(this.handleIntersect, {
root: null,
rootMargin: "0px",
threshold: 0.1, // Adjust threshold as needed
rootMargin: "1500px", // Start rendering 1500px before entering viewport for smooth scrolling
threshold: 0,
});
observer.observe(this.$el);
this.observer.observe(this.$el);
},
beforeUnmount() {
// Clean up observer
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
},
methods: {
/** @param {MouseEvent} event */
@@ -287,12 +297,12 @@ export default {
* @param {IntersectionObserverEntry[]} entries
* @param {IntersectionObserver} observer
*/
handleIntersect(entries, observer) {
handleIntersect(entries) {
entries.forEach((entry) => {
// Update both view state and thumbnail state
this.isInView = entry.isIntersecting;
if (entry.isIntersecting) {
this.isThumbnailInView = true;
// Stop observing once thumbnail is in view
observer.unobserve(entry.target);
}
});
},
@@ -634,6 +644,22 @@ export default {
-webkit-touch-callout: none; /* Disable the default long press preview */
}
/* Disable transitions and hide content for out-of-view items for better performance */
.listing-item.out-of-view {
transition: none !important;
}
.listing-item.out-of-view * {
transition: none !important;
opacity: 0 !important;
pointer-events: none !important;
}
/* Ensure items maintain their height even when content is hidden */
.listing-item > div {
min-height: 1em; /* Forces layout calculation even with hidden content */
}
.hiddenFile {
opacity: 0.5;
}
+53 -114
View File
@@ -19,11 +19,11 @@
<!-- Previous button -->
<button
v-if="enabled && hasPrevious"
@click.stop="handlePrevClick"
@click.prevent="handlePrevClick"
@mousedown="startDrag($event, 'previous')"
@touchstart="handleTouchStart($event, 'previous')"
@touchmove="handleButtonTouchMove"
@touchend="handleTouchEnd"
@touchend.prevent="handleTouchEnd"
@mouseover="setHoverNav(true)"
@mouseleave="setHoverNav(false)"
class="nav-button nav-previous"
@@ -35,7 +35,7 @@
active: dragState.atFullExtent && dragState.type === 'previous',
'dark-mode': isDarkMode,
'media-mode': isMediaQueueMode,
}"
}"
:style="dragState.type === 'previous' ? { transform: `translateY(-50%) translate(${dragState.deltaX}px, 0)` } : {}"
:aria-label="$t('general.previous')"
:title="$t('general.previous')"
@@ -48,11 +48,11 @@
<!-- Next button -->
<button
v-if="enabled && hasNext"
@click.stop="handleNextClick"
@click.prevent="handleNextClick"
@mousedown="startDrag($event, 'next')"
@touchstart="handleTouchStart($event, 'next')"
@touchmove="handleButtonTouchMove"
@touchend="handleTouchEnd"
@touchend.prevent="handleTouchEnd"
@mouseover="setHoverNav(true)"
@mouseleave="setHoverNav(false)"
class="nav-button nav-next"
@@ -144,6 +144,10 @@ export default {
const view = getters.currentView();
return view;
},
isMediaFile() {
const previewType = getters.previewType();
return previewType === 'audio' || previewType === 'video';
},
isMediaQueueMode() {
const previewType = getters.previewType();
const isMediaView = previewType === 'audio' || previewType === 'video';
@@ -527,27 +531,15 @@ export default {
return;
}
// Check if any media element is currently playing
const mediaElements = document.querySelectorAll('audio, video');
let mediaActive = false;
mediaElements.forEach(media => {
if (!media.paused ||
document.activeElement === media) {
mediaActive = true;
}
});
// If media is playing don't handle arrow keys and let use fastfoward and rewind of the player
if (mediaActive) {
return;
}
// Don't handle arrow keys when playing media or when editing a file on the editor
const blockedViews = ['audio', 'video', 'editor'];
if (blockedViews.includes(this.currentView)) {
return;
}
// If we're in plyr, don't handle arrow keys to use fast-forward/rewind shortcuts, even if the media is paused.
if (this.isMediaFile) {
return;
}
// If we're in the editor, don't handle arrow keys to avoid change of file mistakenly.
const blockedViews = ['editor'];
if (blockedViews.includes(this.currentView)) {
return;
}
const { key } = event;
@@ -666,14 +658,6 @@ export default {
tapTimeout: null,
triggered: false
};
// Set a longer timeout to allow for drag intent detection
this.touchState.tapTimeout = setTimeout(() => {
// If we haven't moved significantly and not dragging, treat as tap
if (!this.touchState.hasMoved && !this.dragState.isDragging) {
this.handleButtonTap(buttonType);
}
}, 300); // Increased to 300ms to allow for drag detection
}
}
},
@@ -760,13 +744,20 @@ export default {
handleTouchEnd() {
// Handle touch end for buttons
if (this.touchState.isButtonTouch) {
const touchDuration = Date.now() - this.touchState.startTime;
// Only navigate on release if we didn't move our finger significantly (not a drag)
if (!this.touchState.hasMoved &&
!this.dragState.triggered &&
!this.touchState.triggered) {
// If it was a short touch without movement, and we haven't already navigated, treat as tap
if (!this.touchState.hasMoved && touchDuration < 300 && this.touchState.tapTimeout) {
clearTimeout(this.touchState.tapTimeout);
this.touchState.tapTimeout = null;
this.handleButtonTap(this.touchState.buttonType);
// Mark as triggered to prevent double navigation
this.touchState.triggered = true;
// Navigate based on button type
if (this.touchState.buttonType === 'previous' && this.hasPrevious) {
this.prev();
} else if (this.touchState.buttonType === 'next' && this.hasNext) {
this.next();
}
}
// Reset touch state
@@ -789,33 +780,6 @@ export default {
}
},
// Handle immediate button tap (mobile-friendly)
handleButtonTap(buttonType) {
// Prevent double navigation if already triggered
if (this.touchState.triggered) {
return;
}
// Clear any pending timeouts
if (this.touchState.tapTimeout) {
clearTimeout(this.touchState.tapTimeout);
this.touchState.tapTimeout = null;
}
// Mark as triggered to prevent double navigation
this.touchState.triggered = true;
// Navigate immediately on tap
if (buttonType === 'previous' && this.hasPrevious) {
this.prev();
} else if (buttonType === 'next' && this.hasNext) {
this.next();
}
// Reset touch state
this.resetTouchState();
},
resetTouchState() {
if (this.touchState.tapTimeout) {
clearTimeout(this.touchState.tapTimeout);
@@ -884,8 +848,13 @@ export default {
// Only show file list if user released at full extent
if (this.dragState.atFullExtent) {
this.showFileList(this.dragState.type);
this.dragState.triggered = true; // Mark that drag triggered an action
}
// We check if there was any movement (deltaX != 0) to distinguish from a simple click
if (this.dragState.deltaX !== 0) {
this.dragState.wasDrag = true;
}
this.resetDragState();
this.resetTouchState();
},
@@ -901,10 +870,17 @@ export default {
threshold: this.dragState.threshold,
atFullExtent: false,
triggered: false,
wasDrag: this.dragState.wasDrag,
};
},
handlePrevClick() {
// If a drag was not at the maximum, don't navigate and return the button to its initial position
if (this.dragState.wasDrag) {
this.dragState.wasDrag = false;
this.resetDragState();
return;
}
// Only navigate if this wasn't a drag
if (!this.dragState.triggered) {
this.prev();
@@ -913,6 +889,12 @@ export default {
},
handleNextClick() {
// If a drag was not at the maximum, don't navigate and return the button to its initial position
if (this.dragState.wasDrag) {
this.dragState.wasDrag = false;
this.resetDragState();
return;
}
// Only navigate if this wasn't a drag
if (!this.dragState.triggered) {
this.next();
@@ -923,29 +905,13 @@ export default {
showFileList(type) {
// Hide navigation buttons when showing file list
mutations.setNavigationShow(false);
// Determine what list to show based on drag type
if (type === 'previous') {
// Show parent directories for navigating up
this.showParentDirectories();
} else if (type === 'next') {
if (type === 'previous' || type === 'next') {
// Show current listing items for quick jumping
this.showCurrentListing();
}
},
showParentDirectories() {
// Show files in the current directory (same directory as the previewed file)
const currentItems = this.getCurrentListingItems();
mutations.showHover({
name: "file-list",
props: {
fileList: currentItems,
mode: "navigate-siblings",
title: this.$t("prompts.quickJump")
}
});
},
showCurrentListing() {
const currentItems = this.getCurrentListingItems();
mutations.showHover({
@@ -958,35 +924,6 @@ export default {
});
},
getParentDirectories() {
// Build array of parent directories from current path
const currentPath = state.req.path || "/";
const pathParts = currentPath.split("/").filter(part => part);
const parentDirs = [];
// Add root
parentDirs.push({
name: "/",
path: "/",
source: state.req.source,
isDirectory: true
});
// Add each level up to current
let buildPath = "";
for (let i = 0; i < pathParts.length; i++) {
buildPath += "/" + pathParts[i];
parentDirs.push({
name: pathParts[i],
path: buildPath,
source: state.req.source,
isDirectory: true
});
}
return parentDirs.reverse(); // Show deepest first
},
getCurrentListingItems() {
// Get items from the current navigation listing (files in same directory)
const listing = state.navigation.listing || [];
@@ -999,6 +936,7 @@ export default {
originalItem: item
}));
},
handleGlobalMouseMove(event) {
// Check if mouse is in the nav zone areas to show navigation buttons
if (!this.enabled) return;
@@ -1076,6 +1014,7 @@ export default {
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
opacity: 1;
margin-top: 2em;
user-select: none;
}
.nav-button.dark-mode {
+242 -36
View File
@@ -1,51 +1,88 @@
<template>
<div class="card-title">
<h2>{{ $t('api.title') }}:</h2> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="card-title">
<h2>{{ $t('api.title') }}</h2> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</div>
<div class="card-content">
<div class="card-content api-content">
<!-- API Key Section -->
<div class="api-section">
<button
class="action copy-clipboard"
:data-clipboard-text="info.key"
class="action copy-clipboard api-key-button"
:data-clipboard-text="name"
:aria-label="$t('buttons.copyToClipboard')"
:title="$t('buttons.copyToClipboard')"
>
{{ $t('api.keyName') }}{{ name }}
<span class="api-key-name">{{ name }}</span>
<i class="material-icons">content_paste</i>
</button>
<h3>{{ $t('api.createdAt') }}</h3>
{{ formatTime(info.created) }}
<h3>{{ $t('api.expiresAt') }}</h3>
{{ formatTime(info.expires) }}
<h3>{{ $t('api.permissions') }}</h3>
<table>
<tbody>
<tr v-for="(isEnabled, permission) in info.Permissions" :key="permission">
<td>{{ permission }}</td>
<td>{{ isEnabled ? '✓' : '✗' }}</td> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</tr>
</tbody>
</table>
</div>
<div class="card-action">
<button
class="button button--flat button--grey"
@click="closeHovers"
:aria-label="$t('general.close')"
:title="$t('general.close')"
class="action copy-clipboard api-key-value-button"
:data-clipboard-text="info.key"
:aria-label="$t('api.clickToCopyKey')"
:title="$t('api.clickToCopyKey')"
>
{{ $t('general.close') }}
</button>
<button
class="button button--flat button--red"
@click="deleteApi"
:title="$t('general.delete')"
>
{{ $t('general.delete') }}
<span class="api-key-value">{{ $t('api.clickToCopyKey') }}</span>
<i class="material-icons">content_paste</i>
</button>
</div>
<!-- Information Section -->
<div class="api-section">
<h3 class="section-title">{{ $t('general.info') }}</h3>
<div class="info-item">
<span class="info-label">{{ $t('api.createdAt') }}</span>
<span class="info-value">{{ formatTime(info.created) }}</span>
</div>
<div class="info-item">
<span class="info-label">{{ $t('api.expiresAt') }}</span>
<span class="info-value">{{ formatTime(info.expires) }}</span>
</div>
</div>
<!-- Token Type or Permissions Section -->
<div class="api-section" v-if="info.minimal">
<h3 class="section-title">{{ $t('api.tokenType') }}</h3>
<div class="info-item">
<span class="info-label">{{ $t('api.minimalDescription') }}</span>
</div>
<p class="minimal-info">{{ $t('api.minimalInfo') }}</p>
</div>
<div class="api-section" v-else>
<h3 class="section-title">{{ $t('api.permissions') }}</h3>
<div class="permissions-grid">
<div
v-for="(isEnabled, permission) in info.Permissions"
:key="permission"
class="permission-item"
>
<span class="permission-name">{{ permission }}</span>
<span class="permission-status" :class="{ enabled: isEnabled, disabled: !isEnabled }">
{{ isEnabled ? '✓' : '✗' }} <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</span>
</div>
</div>
</div>
</div>
<div class="card-action">
<button
class="button button--flat button--grey"
@click="closeHovers"
:aria-label="$t('general.close')"
:title="$t('general.close')"
>
{{ $t('general.close') }}
</button>
<button
class="button button--flat button--red"
@click="deleteApi"
:title="$t('general.delete')"
>
{{ $t('general.delete') }}
</button>
</div>
</template>
<script>
@@ -94,3 +131,172 @@ export default {
},
};
</script>
<style scoped>
.api-content {
max-height: 70vh;
overflow-y: auto;
}
.api-section {
margin-bottom: 2em;
}
.api-section:last-child {
margin-bottom: 0;
}
.section-title {
font-size: 0.95em;
font-weight: 600;
color: var(--textPrimary);
margin: 0 0 0.75em 0;
padding-bottom: 0.5em;
border-bottom: 1px solid var(--divider);
}
.api-key-title {
margin-top: 1.5em;
}
.api-key-button,
.api-key-value-button {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 0.75em 1em;
margin-top: 0.5em;
background-color: var(--surfaceSecondary);
border: 1px solid var(--divider);
border-radius: 4px;
transition: background-color 0.2s;
cursor: pointer;
}
.api-key-button:hover,
.api-key-value-button:hover {
background-color: var(--surfaceTertiary);
}
.api-key-name {
font-family: monospace;
font-size: 0.9em;
font-weight: 500;
color: var(--textPrimary);
word-break: break-all;
flex: 1;
margin-right: 0.5em;
}
.api-key-value {
font-size: 0.9em;
font-weight: 500;
color: var(--textSecondary);
flex: 1;
margin-right: 0.5em;
font-style: italic;
}
.api-key-button .material-icons,
.api-key-value-button .material-icons {
font-size: 1.2em;
color: var(--textSecondary);
flex-shrink: 0;
}
.info-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75em 0.5em;
border-radius: 4px;
transition: background-color 0.2s;
}
.info-item:hover {
background-color: var(--surfaceSecondary);
}
.info-label {
font-weight: 500;
color: var(--textSecondary);
font-size: 0.9em;
}
.info-value {
color: var(--textPrimary);
font-size: 0.9em;
text-align: right;
}
.minimal-info {
font-style: italic;
color: var(--textSecondary);
margin-top: 0.75em;
padding: 0.75em;
background-color: var(--surfaceSecondary);
border-radius: 4px;
line-height: 1.5;
font-size: 0.9em;
}
.permissions-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 0.5em;
margin-top: 0.5em;
}
.permission-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75em;
background-color: var(--surfaceSecondary);
border: 1px solid var(--divider);
border-radius: 4px;
transition: background-color 0.2s;
}
.permission-item:hover {
background-color: var(--surfaceTertiary);
}
.permission-name {
font-size: 0.9em;
color: var(--textPrimary);
flex: 1;
}
.permission-status {
font-size: 1.1em;
font-weight: 600;
min-width: 1.5em;
text-align: center;
}
.permission-status.enabled {
color: #4caf50;
}
.permission-status.disabled {
color: #f44336;
}
/* Responsive adjustments */
@media (max-width: 768px) {
.permissions-grid {
grid-template-columns: 1fr;
}
.info-item {
flex-direction: column;
align-items: flex-start;
gap: 0.25em;
}
.info-value {
text-align: left;
}
}
</style>
+39 -11
View File
@@ -5,7 +5,7 @@
<div class="card-content">
<!-- API Key Name Input -->
<p>{{ $t('api.keyName') }}</p>
<p>{{ $t('general.name') }}</p>
<input v-focus class="input" type="text" v-model.trim="apiName"
:placeholder="$t('api.keyNamePlaceholder')" />
@@ -20,11 +20,24 @@
</select>
</div>
<!-- Permissions Input -->
<p>{{ $t('api.permissionNote') }}</p>
<!-- Minimal Token Option -->
<div class="settings-items">
<ToggleSwitch v-for="(isEnabled, permission) in permissions" :key="permission" class="item"
v-model="permissions[permission]" :name="permission" />
<ToggleSwitch
v-model="minimal"
name="minimal"
class="item"
:title="$t('api.minimalDescription')"
:description="$t('api.minimalInfo')"
/>
</div>
<!-- Permissions Input (only shown for full tokens) -->
<div v-if="!minimal">
<p>{{ $t('api.permissionNote') }}</p>
<div class="settings-items">
<ToggleSwitch v-for="(isEnabled, permission) in permissions" :key="permission" class="item"
v-model="permissions[permission]" :name="permission" />
</div>
</div>
</div>
@@ -53,6 +66,7 @@ export default {
apiName: "",
duration: 1,
unit: "days",
minimal: false, // false = full token (default), true = minimal token
};
},
components: {
@@ -76,17 +90,21 @@ export default {
},
async createAPIKey() {
try {
// Filter to get keys of permissions set to true and join them as a comma-separated string
const permissionsString = Object.keys(this.permissions)
.filter((key) => this.permissions[key])
.join(",");
const params = {
name: this.apiName,
days: this.durationInDays,
permissions: permissionsString,
minimal: this.minimal,
};
// Only include permissions for full tokens (not minimal tokens)
if (!this.minimal) {
// Filter to get keys of permissions set to true and join them as a comma-separated string
const permissionsString = Object.keys(this.permissions)
.filter((key) => this.permissions[key])
.join(",");
params.permissions = permissionsString;
}
await usersApi.createApiKey(params);
// Emit event to refresh API keys list
eventBus.emit('apiKeysChanged');
@@ -103,4 +121,14 @@ export default {
.sizeInputWrapper {
display: flex !important;
}
.description {
font-size: 0.9em;
color: #666;
margin-top: 0.5em;
}
.info-text {
font-style: italic;
color: #666;
margin-top: 0.5em;
}
</style>
+29 -8
View File
@@ -19,7 +19,11 @@
<div v-if="!isDisplayMode" aria-label="filelist-path" class="searchContext button clickable">{{ $t('general.path', { suffix: ':' }) }}
{{ sourcePath.path }}</div>
<ul class="file-list">
<div v-if="loading" class="loading-spinner">
<i class="material-icons spin">sync</i>
</div>
<ul v-else class="file-list">
<li @click="itemClick" @touchstart="touchstart" @dblclick="next" role="button" tabindex="0"
:aria-label="item.name" :aria-selected="selected == item.path" :key="item.name" v-for="item in items"
:data-path="item.path" class="file-item">
@@ -92,6 +96,7 @@ export default {
selectedSource: null,
current: window.location.pathname,
currentSource: initialSource,
loading: false,
};
},
computed: {
@@ -140,10 +145,13 @@ export default {
mounted() {
if (this.isDisplayMode) {
// Display mode: use provided fileList
this.fillOptionsFromList();
this.withLoading(async () => {
await new Promise(resolve => setTimeout(resolve, 0)); // Make it async
this.fillOptionsFromList();
});
} else if (this.browseShare) {
// Browse a specific share
publicApi.fetchPub("/", this.browseShare).then(this.fillOptions);
this.withLoading(() => publicApi.fetchPub("/", this.browseShare).then(this.fillOptions));
} else {
// Normal browse mode: fetch files
const sourceToUse = this.currentSource;
@@ -155,13 +163,26 @@ export default {
};
// Fetch the initial data for the source
if (this.currentSource !== state.req.source) {
filesApi.fetchFiles(sourceToUse, pathToUse).then(this.fillOptions);
this.withLoading(() => filesApi.fetchFiles(sourceToUse, pathToUse).then(this.fillOptions));
} else {
this.fillOptions(initialReq);
}
}
},
methods: {
// Helper method to ensure loading spinner shows for minimum 200ms
async withLoading(operation) {
const startTime = Date.now();
this.loading = true;
try {
await operation();
} finally {
const elapsed = Date.now() - startTime;
const remaining = Math.max(0, 200 - elapsed);
await new Promise(resolve => setTimeout(resolve, remaining));
this.loading = false;
}
},
resetToSource(newSource) {
// Use current path if browsing the same source as current, otherwise start at root
const newPath = newSource === state.req.source ? state.req.path : "/";
@@ -172,7 +193,7 @@ export default {
this.selected = null;
this.selectedSource = null;
// Fetch files for the new source
filesApi.fetchFiles(newSource, newPath).then(this.fillOptions);
this.withLoading(() => filesApi.fetchFiles(newSource, newPath).then(this.fillOptions));
},
resetToShare(newHash) {
// Reset to the share root
@@ -182,7 +203,7 @@ export default {
this.selected = null;
this.selectedSource = null;
// Fetch files for the share
publicApi.fetchPub("/", newHash).then(this.fillOptions);
this.withLoading(() => publicApi.fetchPub("/", newHash).then(this.fillOptions));
},
fillOptions(req) {
// Sets the current path and resets
@@ -234,10 +255,10 @@ export default {
if (this.browseShare || getters.isShare()) {
// Browsing a share - use public API
const hashToUse = this.browseShare || state.shareInfo?.hash;
publicApi.fetchPub(path, hashToUse).then(this.fillOptions);
this.withLoading(() => publicApi.fetchPub(path, hashToUse).then(this.fillOptions));
} else {
this.source = sourceToUse;
filesApi.fetchFiles(sourceToUse, path).then(this.fillOptions);
this.withLoading(() => filesApi.fetchFiles(sourceToUse, path).then(this.fillOptions));
}
},
+3 -3
View File
@@ -23,10 +23,10 @@
<button
class="button button--flat"
@click="submit"
:aria-label="$t('general.submit')"
:title="$t('general.submit')"
:aria-label="$t('general.login')"
:title="$t('general.login')"
>
{{ $t("general.submit") }}
{{ $t("general.login") }}
</button>
</div>
</template>
+3 -3
View File
@@ -7,14 +7,14 @@
<p>{{ $t("prompts.renameMessage") }}</p>
<div v-if="item.type !== 'directory'" class="filename-inputs">
<input class="input filename-input" :class="{ 'form-invalid': !validation.valid }" v-focus type="text" @keyup.enter="submit"
<input aria-label="New Name" class="input filename-input" :class="{ 'form-invalid': !validation.valid }" v-focus type="text" @keyup.enter="submit"
v-model.trim="fileName" @input="updateFullName" />
<span class="extension-separator">.</span> <!--eslint-disable-line @intlify/vue-i18n/no-raw-text-->
<input class="input extension-input" type="text" @keyup.enter="submit" v-model.trim="fileExtension"
@input="updateFullName" />
</div>
<input v-else class="input" :class="{ 'form-invalid': !validation.valid }" v-focus type="text" @keyup.enter="submit"
<input v-else class="input" aria-label="New Name" :class="{ 'form-invalid': !validation.valid }" v-focus type="text" @keyup.enter="submit"
v-model.trim="name" />
<p v-if="!validation.valid && name.length > 0" class="validation-error">
<span v-if="validation.reason === 'conflict'">
@@ -32,7 +32,7 @@
{{ $t("general.cancel") }}
</button>
<button @click="submit" class="button button--flat" :disabled="!canRename"
type="submit" :aria-label="$t('general.rename')" :title="$t('general.rename')">
type="submit" :aria-label="$t('general.submit')" :title="$t('general.submit')">
{{ $t("general.rename") }}
</button>
</div>
@@ -202,6 +202,8 @@
:description="$t('share.keepAfterExpirationDescription')" />
<ToggleSwitch v-if="shareType === 'normal'" class="item" v-model="disableThumbnails"
:name="$t('share.disableThumbnails')" :description="$t('share.disableThumbnailsDescription')" />
<ToggleSwitch v-if="shareType === 'normal'" class="item" v-model="showHidden"
:name="$t('profileSettings.showHiddenFiles')" :description="$t('profileSettings.showHiddenFilesDescription')" />
<ToggleSwitch class="item" v-model="disableNavButtons" :name="$t('share.hideNavButtons')"
:description="$t('share.hideNavButtonsDescription')" />
<ToggleSwitch class="item" v-model="disableShareCard" :name="$t('share.disableShareCard')"
@@ -367,6 +369,7 @@ export default {
maxBandwidth: "",
disableFileViewer: false,
disableThumbnails: false,
showHidden: false,
enableAllowedUsernames: false,
allowedUsernames: "",
keepAfterExpiration: false,
@@ -485,6 +488,7 @@ export default {
this.disableAnonymous = this.link.disableAnonymous || false;
this.disableThumbnails = this.link.disableThumbnails || false;
this.disableFileViewer = this.link.disableFileViewer || false;
this.showHidden = this.link.showHidden || false;
this.enableAllowedUsernames = Array.isArray(this.link.allowedUsernames) && this.link.allowedUsernames.length > 0;
this.allowedUsernames = this.enableAllowedUsernames ? this.link.allowedUsernames.join(", ") : "";
this.keepAfterExpiration = this.link.keepAfterExpiration || false;
@@ -600,6 +604,7 @@ export default {
shareTheme: this.shareTheme,
disableFileViewer: this.disableFileViewer,
disableThumbnails: this.disableThumbnails,
showHidden: this.showHidden,
allowedUsernames: this.enableAllowedUsernames ? this.allowedUsernames.split(',').map(u => u.trim()) : [],
keepAfterExpiration: this.keepAfterExpiration,
hash: '',
@@ -698,6 +703,7 @@ export default {
this.disableAnonymous = link.disableAnonymous || false;
this.disableThumbnails = link.disableThumbnails || false;
this.disableFileViewer = link.disableFileViewer || false;
this.showHidden = link.showHidden || false;
this.enableAllowedUsernames = Array.isArray(link.allowedUsernames) && link.allowedUsernames.length > 0;
this.allowedUsernames = this.enableAllowedUsernames ? link.allowedUsernames.join(", ") : "";
this.keepAfterExpiration = link.keepAfterExpiration || false;
+45 -1
View File
@@ -44,7 +44,11 @@ body.rtl #listingView {
background: var(--item-secondary);
color: var(--textPrimary);
border-color: var(--divider);
background: var(--surfacePrimary)
background: var(--surfacePrimary);
/* Performance optimizations */
contain: layout style paint;
content-visibility: auto;
will-change: auto;
}
.listing-item div:last-of-type {
@@ -66,6 +70,8 @@ body.rtl #listingView {
.listing-item i {
font-size: 4em;
vertical-align: bottom;
/* Performance optimization for icon rendering */
transform: translateZ(0);
}
.listing-item img {
@@ -166,6 +172,11 @@ body.rtl #listingView {
transition: width 0.25s ease-out, height 0.25s ease-out, box-shadow 0.2s ease-in-out, transform 0.1s ease-in-out;
}
/* Disable transitions during resize for better performance */
#listingView.resizing .listing-item {
transition: none !important;
}
#listingView.gallery .listing-item .text {
color: white;
text-shadow: 0 0 2px black;
@@ -521,6 +532,39 @@ body.rtl #listingView {
transition: width 0.25s ease-out, height 0.25s ease-out;
}
/* Large icon styling for search results when preview images are enabled - matches icons view */
.search-entry.large-icons i.icon,
.search-entry.large-icons .image-preview,
.search-entry.large-icons .image-preview img.icon {
display: flex;
align-items: center;
justify-content: center;
transition: width 0.25s ease-out, height 0.25s ease-out;
padding: 0;
}
.search-entry.large-icons i.icon {
font-size: var(--icons-view-icon-size, 50px) !important;
line-height: 1 !important;
background: var(--iconBackground) !important;
}
.search-entry.large-icons .image-preview {
flex-shrink: 0;
}
.search-entry.large-icons .image-preview img.icon {
margin: 0;
object-fit: cover;
width: 50px;
height: 50px;
}
.search-entry.large-icons .image-preview {
width: unset !important;
height: unset !important;
}
#listingView.gallery .folder-items,
#listingView.gallery .file-items {
display: grid;
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "عرض الخيارات",
"searchContext": "سياق البحث: {context}",
"notEnoughCharacters": "أحرف غير كافية للبحث (الحد الأدنى {minSearchLength})",
"typeToSearch": "ابدأ الكتابة {minSearchLength} أو أكثر لبدء البحث."
"typeToSearch": "ابدأ الكتابة {minSearchLength} أو أكثر لبدء البحث.",
"showPreviewImages": "عرض صور المعاينة",
"showPreviewImagesDescription": "عرض معاينات الصور المصغرة لنتائج البحث عند توفرها، وإظهار أيقونات أكبر لجميع النتائج."
},
"settings": {
"administrator": "Administrator",
@@ -446,7 +448,6 @@
},
"api": {
"title": "مفاتيح واجهة برمجة التطبيقات (API):",
"keyName": "اسم مفتاح API:",
"createdAt": "تم الإنشاء في:",
"expiresAt": "تنتهي في:",
"permissions": "الأذونات:",
@@ -461,13 +462,16 @@
"createKeySuccess": "تم إنشاء مفتاح API بنجاح.",
"description": "تعتمد مفاتيح API على المستخدم الذي أنشأها. انظر",
"swaggerLinkText": "صفحة التبختر",
"name": "الاسم",
"created": "تم إنشاؤها",
"expires": "تنتهي صلاحيتها",
"actions": "الإجراءات",
"enabled": "ممكّنة",
"disabled": "معاق",
"apiKeyDeleted": "تم حذف مفتاح API!"
"apiKeyDeleted": "تم حذف مفتاح API!",
"tokenType": "نوع الرمز المميز:",
"clickToCopyKey": "انقر لنسخ المفتاح (مخفي)",
"minimalDescription": "الحد الأدنى من الرمز المميز",
"minimalInfo": "يستثني تخصيصات الرمز المميز لإنشاء طول رمز مميز أصغر. تتطابق الأذونات الدقيقة مع المستخدم المرتبط."
},
"index": {
"assessment": "التقييم",
+8 -4
View File
@@ -301,7 +301,9 @@
"showOptions": "Zobrazit možnosti",
"searchContext": "Kontext vyhledávání: {context}",
"notEnoughCharacters": "Nedostatek znaků pro vyhledávání (min. {minSearchLength})",
"typeToSearch": "Pro zahájení vyhledávání začněte psát {minSearchLength} nebo více znaků."
"typeToSearch": "Pro zahájení vyhledávání začněte psát {minSearchLength} nebo více znaků.",
"showPreviewImages": "Zobrazit náhledové obrázky",
"showPreviewImagesDescription": "Zobrazení miniaturních náhledů výsledků vyhledávání, pokud jsou k dispozici, a zobrazení větších ikon u všech výsledků."
},
"profileSettings": {
"setDateFormat": "Nastavit formát data",
@@ -506,7 +508,6 @@
},
"api": {
"title": "API klíče",
"keyName": "Název API klíče:",
"createdAt": "Vytvořeno:",
"expiresAt": "Platnost do:",
"permissions": "Oprávnění:",
@@ -521,13 +522,16 @@
"createKeySuccess": "API klíč byl úspěšně vytvořen.",
"description": "API klíče jsou vázané na uživatele, který je vytvořil. Viz",
"swaggerLinkText": "stránka swagger",
"name": "Název",
"created": "Vytvořeno",
"expires": "Vyprší",
"actions": "Akce",
"enabled": "Povoleno",
"disabled": "Zakázáno",
"apiKeyDeleted": "Klíč API smazán!"
"apiKeyDeleted": "Klíč API smazán!",
"tokenType": "Typ tokenu:",
"clickToCopyKey": "Kliknutím zkopírujete klíč (skrytý)",
"minimalDescription": "Minimální žeton",
"minimalInfo": "Vyloučí přizpůsobení tokenu pro vytvoření menší délky tokenu. Přesná shoda oprávnění s přidruženým uživatelem."
},
"index": {
"assessment": "Vyhodnocení",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Optionen anzeigen",
"searchContext": "Suche im Kontext: {context}",
"notEnoughCharacters": "Nicht genügend Zeichen für die Suche (min {minSearchLength})",
"typeToSearch": "Beginnen Sie mit der Eingabe von {minSearchLength} oder mehr Zeichen, um die Suche zu starten."
"typeToSearch": "Beginnen Sie mit der Eingabe von {minSearchLength} oder mehr Zeichen, um die Suche zu starten.",
"showPreviewImages": "Vorschaubilder anzeigen",
"showPreviewImagesDescription": "Zeigen Sie eine Miniaturvorschau für Suchergebnisse an, wenn verfügbar, und zeigen Sie größere Symbole für alle Ergebnisse an."
},
"settings": {
"administrator": "Administrator",
@@ -446,7 +448,6 @@
},
"api": {
"title": "API-Schlüssel",
"keyName": "API-Schlüsselname:",
"createdAt": "Erstellt am:",
"expiresAt": "Läuft ab am:",
"permissions": "Berechtigungen:",
@@ -461,13 +462,16 @@
"createKeySuccess": "API-Schlüssel erfolgreich erstellt.",
"description": "Die API-Schlüssel basieren auf dem Benutzer, der sie erstellt. Siehe",
"swaggerLinkText": "Angeberseite",
"name": "Name",
"created": "Erstellt",
"expires": "Läuft ab",
"actions": "Aktionen",
"enabled": "Aktiviert",
"disabled": "Deaktiviert",
"apiKeyDeleted": "API-Schlüssel gelöscht!"
"apiKeyDeleted": "API-Schlüssel gelöscht!",
"tokenType": "Token-Typ:",
"clickToCopyKey": "Zum Kopieren des Schlüssels anklicken (ausgeblendet)",
"minimalDescription": "Minimale Wertmarke",
"minimalInfo": "Schließt Token-Anpassungen aus, um eine geringere Token-Länge zu erreichen. Genaue Übereinstimmung der Berechtigungen mit dem zugehörigen Benutzer."
},
"index": {
"assessment": "Bewertung",
+8 -4
View File
@@ -233,7 +233,9 @@
"showOptions": "Εμφάνιση επιλογών",
"searchContext": "Πλαίσιο αναζήτησης: {context}",
"notEnoughCharacters": "Δεν υπάρχουν αρκετοί χαρακτήρες για αναζήτηση (min {minSearchLength})",
"typeToSearch": "Αρχίστε να πληκτρολογείτε {minSearchLength} ή περισσότερους χαρακτήρες για να ξεκινήσετε την αναζήτηση."
"typeToSearch": "Αρχίστε να πληκτρολογείτε {minSearchLength} ή περισσότερους χαρακτήρες για να ξεκινήσετε την αναζήτηση.",
"showPreviewImages": "Εμφάνιση εικόνων προεπισκόπησης",
"showPreviewImagesDescription": "Εμφάνιση προεπισκοπήσεων μικρογραφιών για τα αποτελέσματα αναζήτησης, όταν είναι διαθέσιμα, και εμφάνιση μεγαλύτερων εικονιδίων για όλα τα αποτελέσματα."
},
"settings": {
"administrator": "Διαχειριστής",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Κλειδιά API:",
"keyName": "Όνομα κλειδιού API:",
"createdAt": "Δημιουργήθηκε στο:",
"expiresAt": "Λήγει στις:",
"permissions": "Άδειες:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Το κλειδί API δημιουργήθηκε με επιτυχία.",
"description": "Τα κλειδιά API βασίζονται στον χρήστη που τα δημιουργεί. Βλέπε",
"swaggerLinkText": "σελίδα swagger",
"name": "Όνομα",
"created": "Δημιουργήθηκε",
"expires": "Λήγει",
"actions": "Δράσεις",
"enabled": "Ενεργοποιημένο",
"disabled": "Άτομα με ειδικές ανάγκες",
"apiKeyDeleted": "Το κλειδί API διαγράφηκε!"
"apiKeyDeleted": "Το κλειδί API διαγράφηκε!",
"tokenType": "Τύπος κουπονιού:",
"clickToCopyKey": "Κάντε κλικ για να αντιγράψετε το κλειδί (κρυφό)",
"minimalDescription": "Ελάχιστο Token",
"minimalInfo": "Εξαιρεί τις προσαρμογές token για τη δημιουργία μικρότερου μήκους token. Ακριβής αντιστοιχία δικαιωμάτων με τον σχετικό χρήστη."
},
"index": {
"assessment": "Αξιολόγηση",
+8 -4
View File
@@ -67,7 +67,7 @@
"scope": "Scope{suffix}",
"rules": "Rules{suffix}",
"downloads": "Downloads{suffix}",
"submit": "Login{suffix}",
"submit": "Submit{suffix}",
"navigation": "Navigation{suffix}",
"metadata": "Metadata{suffix}",
"loading": "Loading{suffix}",
@@ -412,6 +412,8 @@
"noResults": "No results found in indexed search.",
"smallerThan": "Smaller than:",
"largerThan": "Larger than:",
"showPreviewImages": "Show preview images",
"showPreviewImagesDescription": "Display thumbnail previews for search results when available, and show larger icons for all results.",
"helpText1": "Search occurs on each character you type (3 character minimum for search terms).",
"helpText2": "The index: Search utilizes the index which automatically gets updated on the configured interval (default: 5 minutes). Searching when the program has just started may result in incomplete results."
},
@@ -618,7 +620,6 @@
},
"api": {
"title": "API Keys",
"keyName": "API Key Name:",
"createdAt": "Created At:",
"expiresAt": "Expires At:",
"permissions": "Permissions:",
@@ -634,12 +635,15 @@
"apiKeyDeleted": "API key deleted!",
"description": "API keys are based on the user that creates them. See",
"swaggerLinkText": "swagger page",
"name": "Name",
"created": "Created",
"expires": "Expires",
"actions": "Actions",
"enabled": "Enabled",
"disabled": "Disabled"
"disabled": "Disabled",
"tokenType": "Token Type:",
"minimalDescription": "Minimal Token",
"minimalInfo": "Excludes token customizations to create a smaller token length. Exact permissions match the associated user.",
"clickToCopyKey": "Click to copy key (hidden)"
},
"index": {
"unknown": "Unknown",
+8 -4
View File
@@ -230,7 +230,9 @@
"noResults": "No pudimos encontrar lo que buscas...",
"searchContext": "Buscar en: {context}",
"notEnoughCharacters": "Escribe al menos {minSearchLength} letras para empezar a buscar",
"typeToSearch": "Escribe {minSearchLength} letras o más para iniciar la búsqueda"
"typeToSearch": "Escribe {minSearchLength} letras o más para iniciar la búsqueda",
"showPreviewImages": "Mostrar imágenes de previsualización",
"showPreviewImagesDescription": "Mostrar vistas previas en miniatura de los resultados de búsqueda cuando estén disponibles, y mostrar iconos más grandes para todos los resultados."
},
"settings": {
"scopes": "Fuentes y carpetas que el usuario tendrá acceso",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Gestión de claves API",
"keyName": "Nombre de la API: ",
"createdAt": "Creado en:",
"expiresAt": "Expira el:",
"permissions": "Permisos:",
@@ -457,7 +458,6 @@
"days": "Días",
"months": "Meses",
"swaggerLinkText": "documentación de Swagger.",
"name": "Nombre",
"created": "Creado",
"expires": "Expira el:",
"actions": "Acciones",
@@ -467,7 +467,11 @@
"createKeyFailed": "Hubo un error al crear la API",
"createKeySuccess": "¡Clave API creada con exito!",
"description": "Las claves API solo podrán tener los permisos que tu usuario tenga. Para más info mira la",
"apiKeyDeleted": "Clave API borrada"
"apiKeyDeleted": "Clave API borrada",
"tokenType": "Tipo de ficha:",
"clickToCopyKey": "Haga clic para copiar la clave (oculta)",
"minimalDescription": "Ficha mínima",
"minimalInfo": "Excluye las personalizaciones de token para crear una longitud de token menor. Los permisos exactos coinciden con los del usuario asociado."
},
"index": {
"assessment": "Tipo",
+9 -5
View File
@@ -58,7 +58,7 @@
"itemSelected": "élément sélectionné",
"itemsSelected": "éléments sélectionnés",
"myFiles": "Mes dossiers{suffix}",
"newFile": "Nouveau dossier{suffix}",
"newFile": "Nouveau Fichier{suffix}",
"newFolder": "Nouveau dossier{suffix}",
"duration": "Durée de l'accord{suffix}",
"sortByDuration": "Trier par durée"
@@ -230,7 +230,9 @@
"showOptions": "Afficher les options",
"searchContext": "Contexte de la recherche : {context}",
"notEnoughCharacters": "Pas assez de caractères pour effectuer une recherche (min {minSearchLength})",
"typeToSearch": "Commencez à taper {minSearchLength} ou plus de caractères pour lancer la recherche."
"typeToSearch": "Commencez à taper {minSearchLength} ou plus de caractères pour lancer la recherche.",
"showPreviewImages": "Afficher les images de prévisualisation",
"showPreviewImagesDescription": "Afficher les vignettes des résultats de la recherche lorsqu'elles sont disponibles, et afficher des icônes plus grandes pour tous les résultats."
},
"settings": {
"scopes": "Définir les sources autorisées et la portée de l'utilisateur au sein de celles-ci",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Clés API :",
"keyName": "Nom de la clé API :",
"createdAt": "Créée le :",
"expiresAt": "Expire le :",
"permissions": "Permissions :",
@@ -461,13 +462,16 @@
"createKeySuccess": "Clé API créée avec succès.",
"description": "Les clés API sont basées sur l'utilisateur qui les a créées. Voir les",
"swaggerLinkText": "page swagger",
"name": "Nom",
"created": "Créée",
"expires": "Expiration",
"actions": "Actions",
"enabled": "Activée",
"disabled": "Désactivée",
"apiKeyDeleted": "Clé API supprimée !"
"apiKeyDeleted": "Clé API supprimée !",
"tokenType": "Type de jeton :",
"clickToCopyKey": "Cliquez pour copier la clé (cachée)",
"minimalDescription": "Jeton minimal",
"minimalInfo": "Exclut les personnalisations du jeton afin de réduire la longueur du jeton. Les autorisations correspondent exactement à celles de l'utilisateur associé."
},
"index": {
"assessment": "Évaluation",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "הצג אפשרויות",
"searchContext": "הקשר החיפוש: {context}",
"notEnoughCharacters": "אין מספיק תווים לחיפוש (מינימום {minSearchLength})",
"typeToSearch": "התחל להקליד {minSearchLength} או יותר תווים כדי להתחיל בחיפוש."
"typeToSearch": "התחל להקליד {minSearchLength} או יותר תווים כדי להתחיל בחיפוש.",
"showPreviewImages": "הצג תמונות מקדימות",
"showPreviewImagesDescription": "הצג תצוגה מקדימה של תמונות ממוזערות עבור תוצאות החיפוש, כאשר הן זמינות, והצג סמלים גדולים יותר עבור כל התוצאות."
},
"settings": {
"administrator": "מנהל ראשי",
@@ -446,7 +448,6 @@
},
"api": {
"title": "מפתחות API",
"keyName": "שם מפתח API:",
"createdAt": "נוצר ב:",
"expiresAt": "תוקף ב:",
"permissions": "הרשאות:",
@@ -461,13 +462,16 @@
"createKeySuccess": "מפתח API נוצר בהצלחה.",
"description": "מפתחות API מבוססים על המשתמש שיצר אותם. ראה",
"swaggerLinkText": "דף סוואגר",
"name": "שם",
"created": "נוצר",
"expires": "תוקף",
"actions": "פעולות",
"enabled": "מופעל",
"disabled": "נכה",
"apiKeyDeleted": "מפתח API נמחק!"
"apiKeyDeleted": "מפתח API נמחק!",
"tokenType": "סוג האסימון:",
"clickToCopyKey": "לחץ כדי להעתיק את המפתח (מוסתר)",
"minimalDescription": "אסימון מינימלי",
"minimalInfo": "לא כולל התאמות אישיות של אסימונים ליצירת אורך אסימון קטן יותר. ההרשאות תואמות במדויק למשתמש המשויך."
},
"index": {
"assessment": "הערכה",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Beállítások megjelenítése",
"searchContext": "Keresési kontextus: {context}",
"notEnoughCharacters": "Nincs elég karakter a kereséshez (min {minSearchLength})",
"typeToSearch": "A keresés megkezdéséhez írja be a {minSearchLength} vagy több karaktert."
"typeToSearch": "A keresés megkezdéséhez írja be a {minSearchLength} vagy több karaktert.",
"showPreviewImages": "Előnézeti képek megjelenítése",
"showPreviewImagesDescription": "A keresési találatok miniatűr előnézeteinek megjelenítése, ha rendelkezésre állnak, és nagyobb ikonok megjelenítése az összes találathoz."
},
"settings": {
"administrator": "Adminisztrátor",
@@ -446,7 +448,6 @@
},
"api": {
"title": "API-kulcsok:",
"keyName": "API-kulcs neve:",
"createdAt": "Létrehozva:",
"expiresAt": "Lejár:",
"permissions": "Engedélyek:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Sikeresen létrehozott API-kulcs.",
"description": "Az API-kulcsok a létrehozó felhasználó alapján készülnek. Lásd",
"swaggerLinkText": "swagger oldal",
"name": "Név",
"created": "Létrehozva",
"expires": "Lejárat:",
"actions": "Tevékenységek",
"enabled": "Engedélyezve",
"disabled": "Mozgáskorlátozottak",
"apiKeyDeleted": "API kulcs törölve!"
"apiKeyDeleted": "API kulcs törölve!",
"tokenType": "Token típus:",
"clickToCopyKey": "Kattintson a kulcs másolásához (rejtett)",
"minimalDescription": "Minimal Token",
"minimalInfo": "Kizárja a token testreszabásokat, hogy kisebb tokenhosszúságot hozzon létre. A jogosultságok pontosan megegyeznek a hozzárendelt felhasználóval."
},
"index": {
"assessment": "Értékelés",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Mostra opzioni",
"searchContext": "Contesto di ricerca: {context}",
"notEnoughCharacters": "Non ci sono abbastanza caratteri per la ricerca (min {minSearchLength})",
"typeToSearch": "Iniziare a digitare {minSearchLength} o più caratteri per avviare la ricerca."
"typeToSearch": "Iniziare a digitare {minSearchLength} o più caratteri per avviare la ricerca.",
"showPreviewImages": "Mostra le immagini di anteprima",
"showPreviewImagesDescription": "Visualizzare le anteprime dei risultati della ricerca, se disponibili, e mostrare icone più grandi per tutti i risultati."
},
"settings": {
"administrator": "Amministratore",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Chiavi API:",
"keyName": "Nome della chiave API:",
"createdAt": "Creato a:",
"expiresAt": "Scade a:",
"permissions": "Permessi:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Chiave API creata con successo.",
"description": "Le chiavi API si basano sull'utente che le crea. Vedere",
"swaggerLinkText": "pagina swagger",
"name": "Nome",
"created": "Creato",
"expires": "Scadenza",
"actions": "Azioni",
"enabled": "Abilitato",
"disabled": "Disabili",
"apiKeyDeleted": "Chiave API cancellata!"
"apiKeyDeleted": "Chiave API cancellata!",
"tokenType": "Tipo di gettone:",
"clickToCopyKey": "Fare clic per copiare la chiave (nascosta)",
"minimalDescription": "Gettone minimo",
"minimalInfo": "Esclude le personalizzazioni del token per creare un token di lunghezza inferiore. Le autorizzazioni corrispondono esattamente all'utente associato."
},
"index": {
"assessment": "Valutazione",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "オプションを表示",
"searchContext": "検索コンテキスト:{context}",
"notEnoughCharacters": "検索する文字数が不足しています(最小:{minSearchLength}文字)",
"typeToSearch": "検索を開始するには、{minSearchLength}文字以上を入力してください。"
"typeToSearch": "検索を開始するには、{minSearchLength}文字以上を入力してください。",
"showPreviewImages": "プレビュー画像を表示する",
"showPreviewImagesDescription": "検索結果のサムネイルプレビューを表示し、すべての検索結果に対して大きなアイコンを表示します。"
},
"settings": {
"administrator": "管理者",
@@ -446,7 +448,6 @@
},
"api": {
"title": "APIキー:",
"keyName": "APIキー名",
"createdAt": "で作成された:",
"expiresAt": "有効期限",
"permissions": "許可:",
@@ -461,13 +462,16 @@
"createKeySuccess": "APIキーが正常に作成されました。",
"description": "APIキーは、それを作成したユーザーに基づいています。参照:",
"swaggerLinkText": "Swaggerページ",
"name": "名前",
"created": "作成日時",
"expires": "有効期限",
"actions": "操作",
"enabled": "有効",
"disabled": "無効",
"apiKeyDeleted": "APIキーが削除されました!"
"apiKeyDeleted": "APIキーが削除されました!",
"tokenType": "トークン・タイプ",
"clickToCopyKey": "クリックしてキーをコピー (非表示)",
"minimalDescription": "ミニマル・トークン",
"minimalInfo": "トークン長を小さくするためのトークンのカスタマイズを除く。関連するユーザーとパーミッションが完全に一致します。"
},
"index": {
"assessment": "評価",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "옵션 표시",
"searchContext": "컨텍스트 검색: {context}",
"notEnoughCharacters": "검색할 문자가 부족합니다(최소 {minSearchLength})",
"typeToSearch": "검색을 시작하려면 {minSearchLength} 을 입력하세요."
"typeToSearch": "검색을 시작하려면 {minSearchLength} 을 입력하세요.",
"showPreviewImages": "미리 보기 이미지 표시",
"showPreviewImagesDescription": "가능한 경우 검색 결과의 썸네일 미리 보기를 표시하고 모든 결과에 대해 더 큰 아이콘을 표시합니다."
},
"settings": {
"administrator": "관리자",
@@ -446,7 +448,6 @@
},
"api": {
"title": "API 키:",
"keyName": "API 키 이름:",
"createdAt": "만든 곳:",
"expiresAt": "만료일:",
"permissions": "권한:",
@@ -461,13 +462,16 @@
"createKeySuccess": "API 키가 성공적으로 생성되었습니다.",
"description": "API 키는 키를 생성한 사용자를 기준으로 합니다. 참조",
"swaggerLinkText": "스웨거 페이지",
"name": "이름",
"created": "생성됨",
"expires": "만료",
"actions": "작업",
"enabled": "활성화됨",
"disabled": "장애인",
"apiKeyDeleted": "API 키가 삭제되었습니다!"
"apiKeyDeleted": "API 키가 삭제되었습니다!",
"tokenType": "토큰 유형:",
"clickToCopyKey": "키를 복사하려면 클릭(숨김)",
"minimalDescription": "최소 토큰",
"minimalInfo": "더 작은 토큰 길이를 만들기 위해 토큰 사용자 지정을 제외합니다. 연결된 사용자와 정확한 권한이 일치합니다."
},
"index": {
"assessment": "평가",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Opties weergeven",
"searchContext": "Zoek context: {context}",
"notEnoughCharacters": "Niet genoeg tekens om te zoeken (min {minSearchLength})",
"typeToSearch": "Begin met het typen van {minSearchLength} of meer tekens om te beginnen met zoeken."
"typeToSearch": "Begin met het typen van {minSearchLength} of meer tekens om te beginnen met zoeken.",
"showPreviewImages": "Voorbeeldafbeeldingen tonen",
"showPreviewImagesDescription": "Toon miniatuurvoorbeelden voor zoekresultaten indien beschikbaar, en toon grotere pictogrammen voor alle resultaten."
},
"settings": {
"administrator": "Administrator",
@@ -446,7 +448,6 @@
},
"api": {
"title": "API-sleutels",
"keyName": "API-sleutelnaam:",
"createdAt": "Gemaakt op:",
"expiresAt": "Verloopt op:",
"permissions": "Toestemmingen:",
@@ -461,13 +462,16 @@
"createKeySuccess": "API-sleutel succesvol aangemaakt.",
"description": "API-sleutels zijn gebaseerd op de gebruiker die ze aanmaakt. Zie",
"swaggerLinkText": "swagger pagina",
"name": "Naam",
"created": "Gemaakt",
"expires": "Verloopt op",
"actions": "Acties",
"enabled": "Ingeschakeld",
"disabled": "Uitgeschakeld",
"apiKeyDeleted": "API-sleutel verwijderd!"
"apiKeyDeleted": "API-sleutel verwijderd!",
"tokenType": "Type penning:",
"clickToCopyKey": "Klik om sleutel te kopiëren (verborgen)",
"minimalDescription": "Minimaal token",
"minimalInfo": "Sluit tokenaanpassingen uit om een kleinere tokenlengte te creëren. Exacte overeenkomst met de rechten van de bijbehorende gebruiker."
},
"index": {
"assessment": "Beoordeling",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Pokaż opcje",
"searchContext": "Kontekst wyszukiwania: {context}",
"notEnoughCharacters": "Za mało znaków do wyszukania (min. {minSearchLength})",
"typeToSearch": "Zacznij wpisywać {minSearchLength} lub więcej znaków, aby rozpocząć wyszukiwanie."
"typeToSearch": "Zacznij wpisywać {minSearchLength} lub więcej znaków, aby rozpocząć wyszukiwanie.",
"showPreviewImages": "Pokaż obrazy podglądu",
"showPreviewImagesDescription": "Wyświetlaj podglądy miniatur wyników wyszukiwania, jeśli są dostępne, i wyświetlaj większe ikony dla wszystkich wyników."
},
"settings": {
"administrator": "Administrator",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Klucze API:",
"keyName": "Nazwa klucza API:",
"createdAt": "Utworzono w:",
"expiresAt": "Wygasa w:",
"permissions": "Uprawnienia:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Klucz API został pomyślnie utworzony.",
"description": "Klucze API są oparte na użytkowniku, który je utworzył. Zobacz",
"swaggerLinkText": "strona swagger",
"name": "Nazwa",
"created": "Utworzony",
"expires": "Wygasa",
"actions": "Działania",
"enabled": "Włączone",
"disabled": "Wyłączony",
"apiKeyDeleted": "Klucz API został usunięty!"
"apiKeyDeleted": "Klucz API został usunięty!",
"tokenType": "Typ tokena:",
"clickToCopyKey": "Kliknij, aby skopiować klucz (ukryty)",
"minimalDescription": "Minimalny token",
"minimalInfo": "Wyklucza dostosowania tokenu w celu utworzenia tokenu o mniejszej długości. Dokładne dopasowanie uprawnień do powiązanego użytkownika."
},
"index": {
"assessment": "Ocena",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Mostrar opções",
"searchContext": "Contexto da pesquisa: {context}",
"notEnoughCharacters": "Não há caracteres suficientes para pesquisar (mín. {minSearchLength})",
"typeToSearch": "Comece a digitar {minSearchLength} ou mais caracteres para iniciar a busca."
"typeToSearch": "Comece a digitar {minSearchLength} ou mais caracteres para iniciar a busca.",
"showPreviewImages": "Mostrar imagens de visualização",
"showPreviewImagesDescription": "Exibir visualizações em miniatura dos resultados da pesquisa, quando disponíveis, e mostrar ícones maiores para todos os resultados."
},
"settings": {
"administrator": "Administrador",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Chaves de API:",
"keyName": "Nome da chave da API:",
"createdAt": "Criado em:",
"expiresAt": "Expira em:",
"permissions": "Permissões:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Chave de API criada com sucesso.",
"description": "As chaves de API são baseadas no usuário que as cria. Veja",
"swaggerLinkText": "página do swagger",
"name": "Nome",
"created": "Criado",
"expires": "Expirações",
"actions": "Ações",
"enabled": "Ativado",
"disabled": "Desativado",
"apiKeyDeleted": "Chave de API excluída!"
"apiKeyDeleted": "Chave de API excluída!",
"tokenType": "Tipo de token:",
"clickToCopyKey": "Clique para copiar a chave (oculto)",
"minimalDescription": "Token mínimo",
"minimalInfo": "Exclui personalizações de token para criar um comprimento de token menor. As permissões exatas correspondem ao usuário associado."
},
"index": {
"assessment": "Avaliação",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Mostrar opções",
"searchContext": "Contexto de pesquisa: {context}",
"notEnoughCharacters": "Não há caracteres suficientes para pesquisar (min {minSearchLength})",
"typeToSearch": "Comece a escrever {minSearchLength} ou mais caracteres para iniciar a pesquisa."
"typeToSearch": "Comece a escrever {minSearchLength} ou mais caracteres para iniciar a pesquisa.",
"showPreviewImages": "Mostrar imagens de pré-visualização",
"showPreviewImagesDescription": "Apresentar pré-visualizações em miniatura dos resultados da pesquisa, quando disponíveis, e mostrar ícones maiores para todos os resultados."
},
"settings": {
"administrator": "Administrador",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Chaves da API",
"keyName": "Nome da chave da API:",
"createdAt": "Criado em:",
"expiresAt": "Expira em:",
"permissions": "Permissões:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Chave API criada com sucesso.",
"description": "As chaves da API são baseadas no utilizador que as cria. Veja",
"swaggerLinkText": "página do swagger",
"name": "Nome",
"created": "Criado",
"expires": "Expirações",
"actions": "Acções",
"enabled": "Ativado",
"disabled": "Desativado",
"apiKeyDeleted": "Chave API eliminada!"
"apiKeyDeleted": "Chave API eliminada!",
"tokenType": "Tipo de ficha:",
"clickToCopyKey": "Clique para copiar a chave (oculto)",
"minimalDescription": "Token mínimo",
"minimalInfo": "Exclui personalizações de token para criar um comprimento de token menor. As permissões exactas correspondem ao utilizador associado."
},
"index": {
"assessment": "Avaliação",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Afișare opțiuni",
"searchContext": "Context de căutare: {context}",
"notEnoughCharacters": "Nu sunt suficiente caractere pentru căutare (min {minSearchLength})",
"typeToSearch": "Începeți să tastați {minSearchLength} sau mai multe caractere pentru a începe căutarea."
"typeToSearch": "Începeți să tastați {minSearchLength} sau mai multe caractere pentru a începe căutarea.",
"showPreviewImages": "Afișați imagini de previzualizare",
"showPreviewImagesDescription": "Afișați previzualizări în miniatură pentru rezultatele căutării, atunci când sunt disponibile, și afișați pictograme mai mari pentru toate rezultatele."
},
"settings": {
"administrator": "Administrator",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Chei API:",
"keyName": "Nume cheie API:",
"createdAt": "Creat la:",
"expiresAt": "Expiră la:",
"permissions": "Permisiuni:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Cheie API creată cu succes.",
"description": "Cheile API sunt bazate pe utilizatorul care le creează. A se vedea",
"swaggerLinkText": "pagina swagger",
"name": "Nume și prenume",
"created": "Creat",
"expires": "Expiră",
"actions": "Acțiuni",
"enabled": "Activat",
"disabled": "Dezactivat",
"apiKeyDeleted": "Cheie API ștearsă!"
"apiKeyDeleted": "Cheie API ștearsă!",
"tokenType": "Tip de jeton:",
"clickToCopyKey": "Faceți clic pentru a copia cheia (ascuns)",
"minimalDescription": "Token minim",
"minimalInfo": "Exclude personalizările tokenului pentru a crea o lungime mai mică a tokenului. Potrivirea exactă a permisiunilor cu cele ale utilizatorului asociat."
},
"index": {
"assessment": "Evaluare",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Показать параметры",
"searchContext": "Контекст поиска: {context}",
"notEnoughCharacters": "Недостаточно символов для поиска (мин. {minSearchLength})",
"typeToSearch": "Начните вводить {minSearchLength} или более символов, чтобы начать поиск."
"typeToSearch": "Начните вводить {minSearchLength} или более символов, чтобы начать поиск.",
"showPreviewImages": "Показать изображения для предварительного просмотра",
"showPreviewImagesDescription": "Показывайте миниатюры для результатов поиска, если они доступны, и отображайте более крупные значки для всех результатов."
},
"settings": {
"administrator": "Администратор",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Ключи API",
"keyName": "Имя ключа API:",
"createdAt": "Создан:",
"expiresAt": "Истекает:",
"permissions": "Разрешения:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Ключ API успешно создан.",
"description": "Ключи API зависят от пользователя, который их создает. См.",
"swaggerLinkText": "страница swagger",
"name": "Имя",
"created": "Создано",
"expires": "Срок действия:",
"actions": "Действия",
"enabled": "Включено",
"disabled": "Отключено",
"apiKeyDeleted": "Ключ API удален!"
"apiKeyDeleted": "Ключ API удален!",
"tokenType": "Тип токена:",
"clickToCopyKey": "Нажмите, чтобы скопировать ключ (скрыто)",
"minimalDescription": "Минимальный токен",
"minimalInfo": "Исключение настроек токена для создания токена меньшей длины. Точное совпадение разрешений со связанным пользователем."
},
"index": {
"assessment": "Оценка",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Zobraziť možnosti",
"searchContext": "Kontext vyhľadávania: {context}",
"notEnoughCharacters": "Nedostatok znakov na vyhľadávanie (min. {minSearchLength})",
"typeToSearch": "Začnite písať {minSearchLength} alebo viac znakov, aby ste začali vyhľadávať."
"typeToSearch": "Začnite písať {minSearchLength} alebo viac znakov, aby ste začali vyhľadávať.",
"showPreviewImages": "Zobraziť náhľad obrázkov",
"showPreviewImagesDescription": "Zobrazenie miniatúrnych náhľadov výsledkov vyhľadávania, ak sú k dispozícii, a zobrazenie väčších ikon pre všetky výsledky."
},
"settings": {
"administrator": "Administrátor",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Kľúče API:",
"keyName": "Názov kľúča API:",
"createdAt": "Vytvorené v:",
"expiresAt": "Platnosť končí na:",
"permissions": "Oprávnenia:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Kľúč API bol úspešne vytvorený.",
"description": "Kľúče API sú založené na používateľovi, ktorý ich vytvoril. Pozri .",
"swaggerLinkText": "swagger stránka",
"name": "Názov",
"created": "Vytvorené",
"expires": "Platnosť končí na",
"actions": "Činnosti",
"enabled": "Povolené",
"disabled": "Bezbariérový",
"apiKeyDeleted": "Kľúč API odstránený!"
"apiKeyDeleted": "Kľúč API odstránený!",
"tokenType": "Typ žetónu:",
"clickToCopyKey": "Kliknutím skopírujete kľúč (skrytý)",
"minimalDescription": "Minimálny žetón",
"minimalInfo": "Vylúči prispôsobenie tokenu na vytvorenie menšej dĺžky tokenu. Presná zhoda oprávnení s priradeným používateľom."
},
"index": {
"assessment": "Hodnotenie",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Visa alternativ",
"searchContext": "Sök kontext: {context}",
"notEnoughCharacters": "Inte tillräckligt med tecken för att söka (min {minSearchLength})",
"typeToSearch": "Börja skriva {minSearchLength} eller fler tecken för att påbörja sökningen."
"typeToSearch": "Börja skriva {minSearchLength} eller fler tecken för att påbörja sökningen.",
"showPreviewImages": "Visa förhandsgranskningsbilder",
"showPreviewImagesDescription": "Visa förhandsvisningar av miniatyrbilder för sökresultat när det är tillgängligt och visa större ikoner för alla resultat."
},
"settings": {
"administrator": "Administratör",
@@ -446,7 +448,6 @@
},
"api": {
"title": "API-nycklar",
"keyName": "Namn på API-nyckel:",
"createdAt": "Skapad på:",
"expiresAt": "Upphör att gälla kl:",
"permissions": "Behörighet:",
@@ -461,13 +462,16 @@
"createKeySuccess": "API-nyckel skapad framgångsrikt.",
"description": "API-nycklar baseras på den användare som skapar dem. Se även",
"swaggerLinkText": "swagger-sida",
"name": "Namn",
"created": "Skapad",
"expires": "Upphör att gälla",
"actions": "Åtgärder",
"enabled": "Aktiverad",
"disabled": "Inaktiverad",
"apiKeyDeleted": "API-nyckel raderad!"
"apiKeyDeleted": "API-nyckel raderad!",
"tokenType": "Token typ:",
"clickToCopyKey": "Klicka för att kopiera nyckel (dold)",
"minimalDescription": "Minimal symbol",
"minimalInfo": "Utesluter anpassningar av token för att skapa en kortare tokenlängd. Exakta behörigheter som matchar den associerade användaren."
},
"index": {
"assessment": "Bedömning",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Seçenekleri Göster",
"searchContext": "Arama Bağlamı: {context}",
"notEnoughCharacters": "Arama yapmak için yeterli karakter yok (min {minSearchLength})",
"typeToSearch": "Aramaya başlamak için {minSearchLength} veya daha fazla karakter yazmaya başlayın."
"typeToSearch": "Aramaya başlamak için {minSearchLength} veya daha fazla karakter yazmaya başlayın.",
"showPreviewImages": "Önizleme resimlerini göster",
"showPreviewImagesDescription": "Kullanılabilir olduğunda arama sonuçları için küçük resim önizlemelerini görüntüleyin ve tüm sonuçlar için daha büyük simgeler gösterin."
},
"settings": {
"administrator": "Yönetici",
@@ -446,7 +448,6 @@
},
"api": {
"title": "API Anahtarları:",
"keyName": "API Anahtar Adı:",
"createdAt": "Oluşturuldu:",
"expiresAt": "Son kullanma tarihi:",
"permissions": "İzinler:",
@@ -461,13 +462,16 @@
"createKeySuccess": "API anahtarı başarıyla oluşturuldu.",
"description": "API anahtarları, onları oluşturan kullanıcıyı temel alır. Bkz.",
"swaggerLinkText": "swagger sayfası",
"name": "İsim",
"created": "Oluşturuldu",
"expires": "Sona erdi",
"actions": "Eylemler",
"enabled": "Etkin",
"disabled": "Engelli",
"apiKeyDeleted": "API anahtarı silindi!"
"apiKeyDeleted": "API anahtarı silindi!",
"tokenType": "Jeton Tipi:",
"clickToCopyKey": "Anahtarı kopyalamak için tıklayın (gizli)",
"minimalDescription": "Minimal Belirteç",
"minimalInfo": "Daha küçük bir belirteç uzunluğu oluşturmak için belirteç özelleştirmelerini hariç tutar. İlişkili kullanıcı ile tam izin eşleşmesi."
},
"index": {
"assessment": "Değerlendirme",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "Показати параметри",
"searchContext": "Пошуковий контекст: {context}",
"notEnoughCharacters": "Недостатньо символів для пошуку (мінімум {minSearchLength})",
"typeToSearch": "Почніть вводити {minSearchLength} або більше символів, щоб почати пошук."
"typeToSearch": "Почніть вводити {minSearchLength} або більше символів, щоб почати пошук.",
"showPreviewImages": "Показати попередній перегляд зображень",
"showPreviewImagesDescription": "Відображати попередній перегляд мініатюр для результатів пошуку, якщо вони доступні, і показувати більші іконки для всіх результатів."
},
"settings": {
"administrator": "Адміністратор",
@@ -446,7 +448,6 @@
},
"api": {
"title": "Ключі API",
"keyName": "Ім'я ключа API:",
"createdAt": "Створено в Ат:",
"expiresAt": "Термін дії закінчується о:",
"permissions": "Дозвольте:",
@@ -461,13 +462,16 @@
"createKeySuccess": "Ключ API створено успішно.",
"description": "Ключі API залежать від користувача, який їх створює. Дивіться",
"swaggerLinkText": "сторінка swagger",
"name": "Ім'я",
"created": "Створено",
"expires": "Закінчується",
"actions": "Дії",
"enabled": "Увімкнено",
"disabled": "Інваліди",
"apiKeyDeleted": "Ключ API видалено!"
"apiKeyDeleted": "Ключ API видалено!",
"tokenType": "Тип жетона:",
"clickToCopyKey": "Натисніть, щоб скопіювати ключ (приховано)",
"minimalDescription": "Мінімальний маркер",
"minimalInfo": "Виключає налаштування токенів для створення меншої довжини токенів. Точна відповідність дозволів асоційованому користувачеві."
},
"index": {
"assessment": "Оцінка",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "显示选项",
"searchContext": "搜索上下文:{context}",
"notEnoughCharacters": "搜索字符数不足(最少{minSearchLength})",
"typeToSearch": "开始键入{minSearchLength} 或更多字符开始搜索。"
"typeToSearch": "开始键入{minSearchLength} 或更多字符开始搜索。",
"showPreviewImages": "显示预览图像",
"showPreviewImagesDescription": "在可用时显示搜索结果的缩略图预览,并为所有结果显示更大的图标。"
},
"settings": {
"scopes": "定义允许的来源及其中的用户范围",
@@ -446,7 +448,6 @@
},
"api": {
"title": "应用程序接口密钥",
"keyName": "API 密钥名称:",
"createdAt": "创建于",
"expiresAt": "有效期至",
"permissions": "权限",
@@ -461,13 +462,16 @@
"createKeySuccess": "API 密钥创建成功。",
"description": "API 密钥基于创建密钥的用户。请参见",
"swaggerLinkText": "跩頁",
"name": "名称",
"created": "创建",
"expires": "到期",
"actions": "行动",
"enabled": "已启用",
"disabled": "残疾",
"apiKeyDeleted": "API 密钥已删除!"
"apiKeyDeleted": "API 密钥已删除!",
"tokenType": "令牌类型:",
"clickToCopyKey": "点击复制密钥(隐藏)",
"minimalDescription": "最小令牌",
"minimalInfo": "不包括令牌定制,以创建较小的令牌长度。权限与相关用户完全匹配。"
},
"index": {
"assessment": "评估",
+8 -4
View File
@@ -230,7 +230,9 @@
"showOptions": "顯示選項",
"searchContext": "搜尋範圍:{context}",
"notEnoughCharacters": "搜尋字元不足 (最少{minSearchLength})",
"typeToSearch": "開始輸入{minSearchLength} 或更多字元以開始搜尋。"
"typeToSearch": "開始輸入{minSearchLength} 或更多字元以開始搜尋。",
"showPreviewImages": "顯示預覽影像",
"showPreviewImagesDescription": "在可用的情況下,顯示搜尋結果的縮圖預覽,並顯示所有結果的較大圖示。"
},
"settings": {
"administrator": "管理員",
@@ -446,7 +448,6 @@
},
"api": {
"title": "API 金鑰",
"keyName": "API 金鑰名稱:",
"createdAt": "創建於",
"expiresAt": "到期日::",
"permissions": "權限:",
@@ -461,13 +462,16 @@
"createKeySuccess": "API 金鑰已成功建立。",
"description": "API 金鑰以建立金鑰的使用者為基礎。請參閱",
"swaggerLinkText": "跩頁",
"name": "名稱",
"created": "創建",
"expires": "到期",
"actions": "行動",
"enabled": "已啟用",
"disabled": "殘障",
"apiKeyDeleted": "API 金鑰已刪除!"
"apiKeyDeleted": "API 金鑰已刪除!",
"tokenType": "代幣類型:",
"clickToCopyKey": "按一下以複製鑰匙 (隱藏)",
"minimalDescription": "最小代幣",
"minimalInfo": "排除令牌自訂,以建立較小的令牌長度。與關聯使用者完全相容的權限。"
},
"index": {
"assessment": "評估",
+41 -3
View File
@@ -52,7 +52,13 @@ export const getters = {
if (getters.isShare()) {
source = getters.currentHash();
}
const path = state.route.path;
let path = state.route.path;
// If current request is a file, use parent directory's preferences
if (state.req?.type && state.req.type !== 'directory') {
path = path.substring(0, path.lastIndexOf('/')+1) || '/';
}
if (state.displayPreferences?.[source]?.[path]) {
return state.displayPreferences[source][path];
}
@@ -188,7 +194,7 @@ export const getters = {
return { dirs, files }
},
isSidebarVisible: () => {
if (state.shareInfo?.disableSidebar) {
if (globalVars.disableSidebar) {
return false
}
const cv = getters.currentView()
@@ -199,7 +205,7 @@ export const getters = {
if (getters.currentPromptName() && !getters.isStickySidebar()) {
visible = false
}
if (previewViews.includes(cv) && !state.user.preview?.disableHideSidebar) {
if (previewViews.includes(cv) && !getters.previewPerms().disableHideSidebar) {
visible = false
}
if (state.shareInfo?.singleFileShare) {
@@ -549,5 +555,37 @@ export const getters = {
admin: state.user?.permissions?.admin,
api: state.user?.permissions?.api,
};
},
previewPerms: () => {
if (getters.isShare()) {
// For shares, use defaults for preview settings (shares don't have per-share preview config)
return {
video: state.user?.preview?.video ?? true,
image: state.user?.preview?.image ?? true,
office: state.user?.preview?.office ?? true,
folder: state.user?.preview?.folder ?? true,
popup: state.user?.preview?.popup ?? true,
highQuality: state.user?.preview?.highQuality ?? false,
motionVideoPreview: state.user?.preview?.motionVideoPreview ?? false,
disableHideSidebar: state.user?.preview?.disableHideSidebar ?? false,
autoplayMedia: state.user?.preview?.autoplayMedia ?? false,
defaultMediaPlayer: false,
showHidden: state.shareInfo?.showHidden !== undefined ? state.shareInfo.showHidden : false,
};
}
// For regular users, use their preview settings -- unless is share
return {
video: state.user?.preview?.video ?? true,
image: state.user?.preview?.image ?? true,
office: state.user?.preview?.office ?? true,
folder: state.user?.preview?.folder ?? true,
popup: state.user?.preview?.popup ?? true,
highQuality: state.user?.preview?.highQuality ?? false,
motionVideoPreview: state.user?.preview?.motionVideoPreview ?? false,
disableHideSidebar: state.user?.preview?.disableHideSidebar ?? false,
autoplayMedia: state.user?.preview?.autoplayMedia ?? false,
defaultMediaPlayer: state.user?.preview?.defaultMediaPlayer ?? false,
showHidden: false, // Backend handles this now, but kept for API compatibility
};
}
};
+4 -3
View File
@@ -499,9 +499,6 @@ export const mutations = {
emitStateChanged();
return
}
if (!state.user.showHidden) {
value.items = value.items.filter((item) => !item.hidden);
}
let sortby = "name"
let asc = true
const sorting = getters.sorting();
@@ -682,6 +679,10 @@ export const mutations = {
return;
}
// Sort listing according to sorting preferences
const sorting = getters.sorting();
listing = sortedItems(listing, sorting.by, sorting.asc);
// Find current item index in the listing
for (let i = 0; i < listing.length; i++) {
if (listing[i].name === currentItem.name) {
+3 -2
View File
@@ -154,10 +154,11 @@ export function extractSourceFromPath(url) {
}
export function buildItemUrl(source, path) {
const encodedPath = encodePath(path);
if (getters.isShare()) {
return `/public/share/${state.shareInfo.hash}${path}`;
return `/public/share/${state.shareInfo.hash}${encodedPath}`;
}
return `/files/${source}${path}`;
return `/files/${source}${encodedPath}`;
}
export function encodedPath(path) {
+88 -34
View File
@@ -30,7 +30,6 @@ import MarkdownViewer from "./files/MarkdownViewer.vue";
import { state, mutations, getters } from "@/store";
import { url } from "@/utils";
import router from "@/router";
import { globalVars } from "@/utils/constants";
import { extractSourceFromPath } from "@/utils/url";
export default {
@@ -204,6 +203,10 @@ export default {
this.attemptedPasswordLogin = this.sharePassword !== "";
// Reset password validation state on wrong password
mutations.setShareData({ passwordValid: false });
// Clear error for upload shares so upload interface can be shown once password is correct
if (state.shareInfo?.shareType === "upload") {
this.error = null;
}
this.showPasswordPrompt();
} else {
router.push({ name: "error" });
@@ -234,46 +237,104 @@ export default {
}
shareInfo.hash = hash;
mutations.setShareInfo(shareInfo);
if (shareInfo.shareType == "upload") {
return;
}
if (shareInfo.themeColor) {
document.documentElement.style.setProperty("--primaryColor", shareInfo.themeColor);
}
if (shareInfo.hasPassword && this.sharePassword === "") {
this.sharePassword = localStorage.getItem("sharepass:" + this.shareHash);
if (this.sharePassword === null || this.sharePassword === "") {
this.showPasswordPrompt();
return;
}
}
// Parse share route
// Parse share route to get shareHash and shareSubPath
let urlPath = getters.routePath('public/share')
let parts = urlPath.split("/");
this.shareHash = parts[1]
this.shareSubPath = "/" + parts.slice(2).join("/");
// Handle password
if (this.sharePassword === "") {
this.sharePassword = localStorage.getItem("sharepass:" + this.shareHash);
} else {
// Check for password requirement (applies to both regular and upload shares)
if (shareInfo.hasPassword) {
if (this.sharePassword === "") {
this.sharePassword = localStorage.getItem("sharepass:" + this.shareHash);
if (this.sharePassword === null || this.sharePassword === "") {
this.showPasswordPrompt();
return;
}
}
// Store password in localStorage
localStorage.setItem("sharepass:" + this.shareHash, this.sharePassword);
}
if (shareInfo.themeColor) {
document.documentElement.style.setProperty("--primaryColor", shareInfo.themeColor);
}
// Handle password (same for both regular and upload shares)
if (this.sharePassword === null) {
this.sharePassword = "";
}
// For upload shares, validate password on startup and return early
// Password validation happens via fetchPub call, which will throw 401 if incorrect
// A 501 error means browsing is disabled (expected for upload shares) and indicates auth succeeded
if (shareInfo.shareType == "upload") {
// Initialize password validation state
if (shareInfo.hasPassword) {
mutations.setShareData({ passwordValid: false });
try {
await publicApi.fetchPub(this.shareSubPath, this.shareHash, this.sharePassword, false);
// If we get here, password is valid (unlikely for upload shares, but handle it)
mutations.setShareData({ passwordValid: true });
this.error = null; // Clear any previous errors
} catch (e) {
// 501 means browsing is disabled for upload shares - this is expected and means auth succeeded
if (e.status === 501) {
// Password is valid, mark as validated
mutations.setShareData({ passwordValid: true });
this.error = null; // Clear any previous errors
} else if (e.status === 401) {
// Password is invalid, show prompt
this.attemptedPasswordLogin = true;
mutations.setShareData({ passwordValid: false });
this.showPasswordPrompt();
return;
} else {
// For other errors, re-throw to be handled by fetchData()
throw e;
}
}
} else {
// No password required, mark as validated
mutations.setShareData({ passwordValid: true });
this.error = null; // Clear any previous errors
}
return;
}
// For regular shares, validate password on startup (similar to upload shares)
if (shareInfo.hasPassword) {
mutations.setShareData({ passwordValid: false });
try {
await publicApi.fetchPub(this.shareSubPath, this.shareHash, this.sharePassword, false);
// Password is valid
mutations.setShareData({ passwordValid: true });
this.error = null; // Clear any previous errors
} catch (e) {
if (e.status === 401) {
// Password is invalid, show prompt
this.attemptedPasswordLogin = true;
mutations.setShareData({ passwordValid: false });
this.showPasswordPrompt();
return;
} else {
// For other errors, re-throw to be handled by fetchData()
throw e;
}
}
} else {
// No password required, mark as validated
mutations.setShareData({ passwordValid: true });
this.error = null; // Clear any previous errors
}
mutations.resetSelected();
mutations.setMultiple(false);
if (state.shareInfo?.singleFileShare) {
mutations.setSidebarVisible(true);
}
// Initialize password validation state for password-protected shares
if (state.shareInfo?.isPasswordProtected) {
mutations.setShareData({ passwordValid: false });
}
// Fetch share data
let file = await publicApi.fetchPub(this.shareSubPath, this.shareHash, this.sharePassword);
file.hash = this.shareHash;
@@ -329,16 +390,9 @@ export default {
// Clear share data when accessing files
mutations.clearShareData();
const routePath = url.removeTrailingSlash(getters.routePath(`${globalVars.baseURL}files`));
const rootRoute =
routePath == "/files" ||
routePath == "/files/" ||
routePath == "" ||
routePath == "/";
const routePath = url.removeTrailingSlash(getters.routePath());
// lets redirect if multiple sources and user went to /files/
if (rootRoute) {
if (routePath == "/files") {
// Check if user has custom sidebar links with sources
let targetPath = `/files/${state.sources.current}`;
for (const link of state.user?.sidebarLinks || []) {
+1 -1
View File
@@ -132,7 +132,7 @@ export default {
if (!state.user || state.user?.username == "") {
return false;
}
return state.user.preview.popup;
return getters.previewPerms().popup;
},
},
watch: {
+1 -1
View File
@@ -48,7 +48,7 @@
<div v-if="globalVars.recaptcha" id="globalVars.recaptcha"></div>
<input class="button button--block" type="submit"
:value="createMode ? $t('general.signup') : $t('general.submit')" />
:value="createMode ? $t('general.signup') : $t('general.login')" />
<p @click="toggleMode" v-if="signup" aria-label="sign up toggle">
{{ createMode ? $t("login.loginInstead") : $t("login.createAnAccount") }}
</p>
+59 -7
View File
@@ -181,7 +181,8 @@
</div>
<!-- Upload Share Target -->
<div v-else class="upload-share-embed">
<!-- Only show upload interface if password is validated (or no password required) -->
<div v-else-if="!shareInfo.hasPassword || state.share?.passwordValid" class="upload-share-embed">
<Upload :initialItems="null" />
</div>
</template>
@@ -218,6 +219,10 @@ export default {
rectangleEnd: { x: 0, y: 0 },
rectangleSelection: [],
cssVariables: {},
rafId: null, // For requestAnimationFrame
selectionUpdatePending: false, // Flag to batch updates
isResizing: false, // Track resize state
resizeTimeout: null, // Timeout for resize end detection
};
},
watch: {
@@ -489,10 +494,10 @@ export default {
window.addEventListener("click", this.clickClear);
window.addEventListener("keyup", this.clearCtrKey);
window.addEventListener("dragover", this.preventDefault);
document.addEventListener('mousemove', this.updateRectangleSelection);
document.addEventListener('mousemove', this.updateRectangleSelection, { passive: true });
document.addEventListener('mouseup', this.endRectangleSelection);
this.$el.addEventListener('mousedown', this.startRectangleSelection);
this.$el.addEventListener("touchmove", this.handleTouchMove);
this.$el.addEventListener("touchmove", this.handleTouchMove, { passive: true });
this.$el.addEventListener("contextmenu", this.openContext);
// Adjust contextmenu listener based on browser
@@ -516,6 +521,16 @@ export default {
}
},
beforeUnmount() {
// Cancel any pending animation frames
if (this.rafId) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = null;
}
// Remove event listeners before destroying this page.
window.removeEventListener("keydown", this.keyEvent);
window.removeEventListener("resize", this.windowsResize);
@@ -1056,9 +1071,32 @@ export default {
showMultipleSelection();
},
windowsResize: throttle(function () {
// Mark as resizing to disable transitions
if (!this.isResizing) {
this.isResizing = true;
if (this.$refs.listingView) {
this.$refs.listingView.classList.add('resizing');
}
}
// Clear existing timeout
if (this.resizeTimeout) {
clearTimeout(this.resizeTimeout);
}
// Do the resize work
this.colunmsResize();
this.width = window.innerWidth;
mutations.setMobile();
// Re-enable transitions after resize is complete
this.resizeTimeout = setTimeout(() => {
this.isResizing = false;
if (this.$refs.listingView) {
this.$refs.listingView.classList.remove('resizing');
}
}, 150); // Wait 150ms after last resize event
// Listing element is not displayed
if (this.$refs.listingView == null) return;
}, 100),
@@ -1174,13 +1212,27 @@ export default {
y: event.clientY - listingRect.top
};
this.updateSelectedItemsInRectangle(event.ctrlKey || event.metaKey);
// Use requestAnimationFrame to batch updates
if (!this.selectionUpdatePending) {
this.selectionUpdatePending = true;
this.rafId = requestAnimationFrame(() => {
this.updateSelectedItemsInRectangle(event.ctrlKey || event.metaKey);
this.selectionUpdatePending = false;
});
}
},
endRectangleSelection(event) {
if (!this.isRectangleSelecting) return;
// Cancel any pending animation frame
if (this.rafId) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
this.isRectangleSelecting = false;
this.selectionUpdatePending = false;
this.updateSelectedItemsInRectangle(event.ctrlKey || event.metaKey);
// Clear rectangle after a short delay
@@ -1204,8 +1256,8 @@ export default {
const rectangleSelectedIndexes = [];
// Get all item elements
const itemElements = this.$el.querySelectorAll('.listing-item');
// Get all item elements - use querySelectorAll with specific selector for better performance
const itemElements = this.$el.querySelectorAll('.listing-item[data-index]');
itemElements.forEach((element) => {
const elementRect = element.getBoundingClientRect();
@@ -1232,7 +1284,7 @@ export default {
}
});
// Update selection based on modifier keys (ctrl/meta)
// Batch DOM updates to minimize reflows
if (isAdditive) {
// only add more items to the current selection without reset selection
const newSelection = [...state.selected];
+2 -2
View File
@@ -103,10 +103,10 @@ export default {
return this.previewType == 'image' || this.pdfConvertable;
},
autoPlay() {
return state.user.preview.autoplayMedia;
return getters.previewPerms().autoplayMedia;
},
useDefaultMediaPlayer() {
return state.user.preview.defaultMediaPlayer === true;
return getters.previewPerms().defaultMediaPlayer === true;
},
isMobileSafari() {
const userAgent = window.navigator.userAgent;
+9 -6
View File
@@ -19,7 +19,7 @@
<table aria-label="API Keys">
<thead>
<tr>
<th>{{ $t("api.name") }}</th>
<th>{{ $t("general.name") }}</th>
<th>{{ $t("api.created") }}</th>
<th>{{ $t("api.expires") }}</th>
<th>{{ $t("settings.permissions-name") }}</th>
@@ -31,12 +31,15 @@
<td>{{ name }}</td>
<td>{{ formatTime(link.created) }}</td>
<td>{{ formatTime(link.expires) }}</td>
<td>
<td v-if="!link.minimal">
<span v-for="(value, permission) in link.Permissions" :key="permission"
:title="`${permission}: ${value ? $t('api.enabled') : $t('api.disabled')}`" class="clickable"
@click.prevent="infoPrompt(name, link)">
{{ showResult(value) }}
</span>
:title="`${permission}: ${value ? $t('api.enabled') : $t('api.disabled')}`" class="clickable"
@click.prevent="infoPrompt(name, link)">
{{ showResult(value) }}
</span>
</td>
<td v-else>
<span>-</span> <!-- eslint-disable-line @intlify/vue-i18n/no-raw-text -->
</td>
<td class="small">
<button class="action" @click.prevent="infoPrompt(name, link)">
Whitespace-only changes.
@@ -1,6 +1,5 @@
import { test, expect, checkForNotification } from "../test-setup";
test("info from listing", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
+9 -10
View File
@@ -1,4 +1,5 @@
import { Browser, firefox, expect, Page } from "@playwright/test";
import { openContextMenuHelper } from "./test-setup";
// Perform authentication and store auth state
async function globalSetup() {
@@ -57,14 +58,12 @@ async function globalSetup() {
localStorage.setItem('shareHashFile', hash);
}, shareHashFile);
// Create a share of folder "/share"
// Create a share of root folder "/"
await page.goto("http://127.0.0.1/files/playwright%20%2B%20files", { timeout: 500 });
await page.locator('a[aria-label="share"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="share"]').click({ button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('1');
await openContextMenuHelper(page);
await page.locator('button[aria-label="Share"]').click();
await expect(page.locator('div[aria-label="share-path"]')).toHaveText('Path: /share/');
await expect(page.locator('div[aria-label="share-path"]')).toHaveText('Path: /');
// Toggle "Allow creating and uploading files and folders" setting
await page.locator('input[aria-label="allow creating and uploading files and folders toggle"]').waitFor({ state: 'attached' });
await page.locator('input[aria-label="allow creating and uploading files and folders toggle"] + .slider').click();
@@ -75,14 +74,14 @@ async function globalSetup() {
await page.locator('button[aria-label="Share-Confirm"]').click();
await expect(page.locator("div[aria-label='share-prompt'] .card-content table tbody tr:not(:has(th))")).toHaveCount(1);
const shareHashShare = await page.locator("div[aria-label='share-prompt'] .card-content table tbody tr:not(:has(th)) td").first().textContent();
if (!shareHashShare) {
throw new Error("Failed to retrieve shareHash");
const rootShareHash = await page.locator("div[aria-label='share-prompt'] .card-content table tbody tr:not(:has(th)) td").first().textContent();
if (!rootShareHash) {
throw new Error("Failed to retrieve rootShareHash");
}
// Store shareHash in localStorage
await page.evaluate((hash) => {
localStorage.setItem('shareHashShare', hash);
}, shareHashShare);
localStorage.setItem('rootShareHash', hash);
}, rootShareHash);
await context.storageState({ path: "./loginAuth.json" });
await browser.close();
@@ -18,7 +18,7 @@ test("info from search", async({ page, checkForErrors, context }) => {
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('#search').click()
await page.locator('#main-input').fill('file.tar.gz');
await expect(page.locator('#result-list')).toHaveCount(1);
await expect(page.locator('#result-list ul li.search-entry')).toHaveCount(1);
await page.locator('li[aria-label="file.tar.gz"]').click({ button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('1');
@@ -32,7 +32,7 @@ test("open from search", async({ page, checkForErrors, context }) => {
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('#search').click()
await page.locator('#main-input').fill('file.tar.gz');
await expect(page.locator('#result-list')).toHaveCount(1);
await expect(page.locator('#result-list ul li.search-entry')).toHaveCount(1);
await page.locator('li[aria-label="file.tar.gz"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - file.tar.gz");
await expect(page.locator('#previewer')).toContainText('Preview is not available for this file.');
@@ -99,8 +99,12 @@ test("delete file", async({ page, checkForErrors, context }) => {
await expect(page.locator('div[aria-label="delete-path"]')).toHaveText('/deleteme.txt');
await page.locator('button[aria-label="Confirm-Delete"]').click();
await checkForNotification(page, "Deleted successfully!");
checkForErrors();
// verify its no longer in index via search
await page.locator('#search').click()
await page.locator('#main-input').fill('deleteme.txt');
await expect(page.locator('#result-list ul li.search-entry')).toHaveCount(0);
checkForErrors();
})
test("delete nested file prompt", async({ page, checkForErrors, context }) => {
@@ -115,3 +119,52 @@ test("delete nested file prompt", async({ page, checkForErrors, context }) => {
await expect(page.locator('div[aria-label="delete-path"]')).toHaveText('/folder#hash/file#.sh');
checkForErrors();
})
test("rename file", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="renameme.txt"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="renameme.txt"]').click({ button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('1');
await page.locator('button[aria-label="Rename"]').click();
await page.locator('input[aria-label="New Name"]').waitFor({ state: 'visible' });
await page.locator('input[aria-label="New Name"]').fill('renamed.txt');
await page.locator('button[aria-label="Submit"]').click();
await checkForNotification(page, "Item renamed successfully!");
// verify its no longer in index via search
await page.locator('#search').click()
await page.locator('#main-input').fill('renameme.txt');
await expect(page.locator('#result-list ul li.search-entry')).toHaveCount(0);
checkForErrors();
})
test("create a file with the same name as a directory", async({ page, checkForErrors, openContextMenu, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await openContextMenu();
await page.locator('button[aria-label="New file"]').click();
await page.locator('button[aria-label="Create"]').click();
await page.locator('input[aria-label="FileName Field"]').waitFor({ state: 'visible' });
await page.locator('input[aria-label="FileName Field"]').fill('mytest');
await page.locator('button[aria-label="Create"]').click();
await page.locator('a[aria-label="mytest"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="mytest"]').click({ button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('1');
await page.locator('button[aria-label="Delete"]').click();
await expect(page.locator('.card-content')).toHaveText('Are you sure you want to delete this file/folder?/mytest');
await expect(page.locator('div[aria-label="delete-path"]')).toHaveText('/mytest');
await page.locator('button[aria-label="Confirm-Delete"]').click();
await checkForNotification(page, "Deleted successfully!");
await openContextMenu();
await page.locator('button[aria-label="New folder"]').click();
await page.locator('input[aria-label="New Folder Name"]').waitFor({ state: 'visible' });
await page.locator('input[aria-label="New Folder Name"]').fill('mytest');
await page.locator('button[aria-label="Create"]').click();
await page.locator('a[aria-label="mytest"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="mytest"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - mytest");
checkForErrors();
})
@@ -61,4 +61,4 @@ test("share download single file", async ({ page, checkForErrors, context }) =>
await page.locator('button[aria-label="Download"]').click();
await checkForNotification(page, "Downloading...");
checkForErrors(0,1); // redirect errors are expected
});
});
@@ -0,0 +1,41 @@
import { test, expect, checkForNotification } from '../test-setup'
test("access rules - deny folder does not show in folder listing", async ({ page, checkForErrors, context }) => {
await page.goto("/files/access");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
// expect the excluded folder to not be visible
await expect(page.locator('div[aria-label="excluded"]')).toBeHidden();
checkForErrors();
});
test("access rules - deny folder has access denied message", async ({ page, checkForErrors, context }) => {
await page.goto("/files/access");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
const msg = "403: access denied"
await checkForNotification(page, msg);
// expect the excluded folder to have an access denied message
checkForErrors(1,1); // expect 1 api error
});
test("navigate from search item", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('#search').click()
await page.locator('#search-sources-dropdown').click()
await page.locator('#search-sources-dropdown option[value="access"]').click()
await page.locator('#main-input').fill('showme.txt');
await expect(page.locator('#result-list')).toHaveCount(0);
checkForErrors()
});
test("share access controls exist", async ({ page, checkForErrors, context }) => {
const rootShareHash = await page.evaluate(() => localStorage.getItem('rootShareHash'));
if (!rootShareHash) {
throw new Error("Share hash not found in localStorage");
}
await page.goto("/files/share/" + rootShareHash );
await expect(page).toHaveTitle("Graham's Filebrowser - Share - playwright-files");
// expect the excluded folder to not be visible
await expect(page.locator('div[aria-label="excluded"]')).toBeHidden();
checkForErrors();
});
@@ -4,7 +4,7 @@ test("check default sidebar links are added to sidebar", async ({ page, checkFor
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
// sidebar should have two items
await expect(page.locator('.sidebar-links .inner-card').locator('a')).toHaveCount(2);
await expect(page.locator('.sidebar-links .inner-card').locator('a')).toHaveCount(3);
// check items exist
await page.locator('a[aria-label="playwright + files"]').waitFor({ state: 'visible' });
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more