diff --git a/CHANGELOG.md b/CHANGELOG.md
index bf77adbfec..05ef1fc3e0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,27 @@
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.1-beta
+
+ **Notes**:
+ - [docker] upgraded ffmpeg 8.0 to 8.0.1
+ - stricter access control checks on file downloads.
+ - Wrong translation on Chinese "save" button #1650
+ - Incorrect Spanish Translations in Folder Creation and Rename Actions #1626
+ - duplicate file detector has stricter partial checksum match #1617
+
+ **BugFixes**:
+ - added missing exiftool to docker image for heic conversion orientation support
+ - v1.1.0-beta - Incorrect naming of 1 file in directory-info #1621
+ - disable only office viewing settings not applying
+ - OnlyOffice integration does not work behind proxy authentication #1422
+ - Newly created users "add on" to defined scope of previous user #1628 #1518
+ - disable chown on upload / file saving #1469 #1546
+ - Uploading a file will silently overwrite any existing file with the same name #1564
+ - share file url issue
+ - Fix drag and drop and rows in normal view #1651
+ - Some text based files are not able to edit. #1567
+
## v1.1.0-beta
**New Features**:
diff --git a/_docker/Dockerfile b/_docker/Dockerfile
index 311acb10a5..42523e4ba6 100644
--- a/_docker/Dockerfile
+++ b/_docker/Dockerfile
@@ -1,4 +1,4 @@
-FROM gtstef/ffmpeg:8.0-decode AS ffmpeg
+FROM gtstef/ffmpeg:8.0.1-decode AS ffmpeg
FROM golang:alpine AS base
ARG VERSION
ARG REVISION
@@ -28,7 +28,7 @@ COPY --from=ffmpeg [ "/ffmpeg", "/ffprobe", "/usr/local/bin/" ]
ENV FILEBROWSER_FFMPEG_PATH="/usr/local/bin/"
ENV FILEBROWSER_DATABASE="/home/filebrowser/data/database.db"
ENV PATH="$PATH:/home/filebrowser"
-RUN apk --no-cache add ca-certificates mailcap tzdata curl
+RUN apk --no-cache add ca-certificates mailcap tzdata curl exiftool
RUN adduser -D -s /bin/true -u 1000 filebrowser
USER filebrowser
WORKDIR /home/filebrowser
@@ -42,6 +42,7 @@ COPY --from=nbuild --chown=filebrowser:1000 [ "/app/dist/", "./http/dist/" ]
RUN [ "filebrowser", "version" ]
RUN [ "ffmpeg", "-version" ]
RUN [ "ffprobe", "-version" ]
+RUN [ "exiftool", "-ver" ]
USER root
# exposing default port for auto discovery.
EXPOSE 80
diff --git a/backend/.air.toml b/backend/.air.toml
index d24d3396e4..0a31cdfcac 100644
--- a/backend/.air.toml
+++ b/backend/.air.toml
@@ -6,7 +6,7 @@ tmp_dir = "tmp"
bin = "tmp/filebrowser"
full_bin = "FILEBROWSER_DEVMODE=true CGO_ENABLED=1 ./tmp/filebrowser -c test_config.yaml"
include_ext = ["go", "tpl", "tmpl", "html"]
- exclude_dir = ["tmp", "vendor", "http/dist", "http/embed", "swagger/docs"]
+ exclude_dir = ["tmp", "vendor", "http/dist", "http/embed", "swagger/docs", "preview/thumbnails", "preview/heic"]
log = "air.log"
delay = 1000 # ms
@@ -14,4 +14,4 @@ tmp_dir = "tmp"
time = true
[misc]
- clean_on_exit = true
+ clean_on_exit = false
diff --git a/backend/.air.windows.toml b/backend/.air.windows.toml
index 42d949bf4b..ba5b9273c2 100644
--- a/backend/.air.windows.toml
+++ b/backend/.air.windows.toml
@@ -18,4 +18,4 @@ tmp_dir = "tmp"
time = true
[misc]
- clean_on_exit = true
+ clean_on_exit = false
diff --git a/backend/adapters/fs/files/content_test.go b/backend/adapters/fs/files/content_test.go
new file mode 100644
index 0000000000..02f8d6e06d
--- /dev/null
+++ b/backend/adapters/fs/files/content_test.go
@@ -0,0 +1,138 @@
+package files
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "unicode/utf8"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestGetContent_UTF8Truncation(t *testing.T) {
+ // Get the path to the test file
+ // The test file is in frontend/tests/playwright-files/utf8-truncated.txt
+ // We need to find it relative to the test execution directory
+ cwd, err := os.Getwd()
+ require.NoError(t, err)
+
+ // Navigate from backend/adapters/fs/files to the project root
+ // backend/adapters/fs/files -> backend/adapters/fs -> backend/adapters -> backend -> root
+ testFilePath := filepath.Join(cwd, "..", "..", "..", "..", "frontend", "tests", "playwright-files", "utf8-truncated.txt")
+
+ // Check if file exists, if not try alternative path
+ if _, err = os.Stat(testFilePath); os.IsNotExist(err) {
+ // Try from project root
+ testFilePath = filepath.Join("frontend", "tests", "playwright-files", "utf8-truncated.txt")
+ if _, err = os.Stat(testFilePath); os.IsNotExist(err) {
+ t.Skipf("Test file not found at %s, skipping test", testFilePath)
+ return
+ }
+ }
+
+ // Get absolute path
+ var absPath string
+ absPath, err = filepath.Abs(testFilePath)
+ require.NoError(t, err)
+
+ t.Run("file with UTF-8 truncation at 4096 byte boundary", func(t *testing.T) {
+ // The test file is longer than 4096 bytes, with valid UTF-8 throughout.
+ // However, when reading exactly 4096 bytes as a header, it cuts off in the
+ // middle of a multi-byte UTF-8 sequence (e6 9c, missing the last byte 88 of '月').
+ // This should trigger the truncation handling in getContent's header validation.
+ // The fix should trim the incomplete sequence from the header, allowing the
+ // header check to pass, and then the full file (which is valid UTF-8) should
+ // pass the full file validation.
+ content, err := getContent(absPath)
+
+ // Should not return an error - the header truncation is handled, and the full file is valid
+ require.NoError(t, err)
+
+ // The content should be the full valid UTF-8 file
+ require.NotEmpty(t, content, "Content should not be empty - full file is valid UTF-8")
+
+ // Verify it contains the expected text
+ require.Contains(t, content, "文件已备份", "Content should contain Chinese characters")
+ require.Contains(t, content, "2024年", "Content should contain date information")
+ })
+
+ t.Run("regular UTF-8 text file", func(t *testing.T) {
+ // Test with a simple text file to ensure normal files still work
+ tmpFile, err := os.CreateTemp("", "test-utf8-*.txt")
+ require.NoError(t, err)
+ defer os.Remove(tmpFile.Name())
+ defer tmpFile.Close()
+
+ testText := "Hello, 世界! This is a test file with UTF-8 characters.\n"
+ _, err = tmpFile.WriteString(testText)
+ require.NoError(t, err)
+ tmpFile.Close()
+
+ content, err := getContent(tmpFile.Name())
+ require.NoError(t, err)
+ require.Equal(t, testText, content)
+ })
+
+ t.Run("file smaller than header size", func(t *testing.T) {
+ // Test with a file smaller than 4096 bytes
+ tmpFile, err := os.CreateTemp("", "test-small-*.txt")
+ require.NoError(t, err)
+ defer os.Remove(tmpFile.Name())
+ defer tmpFile.Close()
+
+ testText := "Small file content"
+ _, err = tmpFile.WriteString(testText)
+ require.NoError(t, err)
+ tmpFile.Close()
+
+ content, err := getContent(tmpFile.Name())
+ require.NoError(t, err)
+ require.Equal(t, testText, content)
+ })
+
+ t.Run("file with Chinese characters at boundary", func(t *testing.T) {
+ // Create a file that's exactly 4094 bytes, ending with a complete Chinese character
+ tmpFile, err := os.CreateTemp("", "test-chinese-*.txt")
+ require.NoError(t, err)
+ defer os.Remove(tmpFile.Name())
+ defer tmpFile.Close()
+
+ // Create content that's exactly 4094 bytes, ending with complete UTF-8
+ baseText := "2024年 06月 17日 星期一 04:05:58 CST 文件已备份\n"
+ content := ""
+ for len([]byte(content)) < 4094 {
+ content += baseText
+ }
+ // Trim to exactly 4094 bytes
+ encoded := []byte(content)
+ if len(encoded) > 4094 {
+ encoded = encoded[:4094]
+ }
+ // Ensure it ends with a complete character by finding the last complete rune
+ for len(encoded) > 0 {
+ lastRune, _ := decodeLastRune(encoded)
+ if lastRune != 0xFFFD { // RuneError
+ break
+ }
+ encoded = encoded[:len(encoded)-1]
+ }
+
+ _, err = tmpFile.Write(encoded)
+ require.NoError(t, err)
+ tmpFile.Close()
+
+ result, err := getContent(tmpFile.Name())
+ require.NoError(t, err)
+ require.NotEmpty(t, result)
+ require.Equal(t, string(encoded), result)
+ })
+}
+
+// Helper function to check if last rune is valid
+func decodeLastRune(p []byte) (rune, int) {
+ if len(p) == 0 {
+ return 0, 0
+ }
+ r, size := utf8.DecodeLastRune(p)
+ return r, size
+}
diff --git a/backend/adapters/fs/files/files.go b/backend/adapters/fs/files/files.go
index f070de2b9e..85fd40d6d5 100644
--- a/backend/adapters/fs/files/files.go
+++ b/backend/adapters/fs/files/files.go
@@ -550,17 +550,12 @@ func WriteDirectory(opts utils.FileOptions) error {
}
// Ensure the parent directories exist
+ // Permissions are set by MkdirAll (subject to umask, which is usually acceptable)
err = os.MkdirAll(realPath, fileutils.PermDir)
if err != nil {
return err
}
- // Explicitly set directory permissions to bypass umask
- err = os.Chmod(realPath, fileutils.PermDir)
- if err != nil {
- return err
- }
-
return RefreshIndex(idx.Name, opts.Path, true, true)
}
@@ -580,15 +575,20 @@ func WriteFile(source, path string, in io.Reader) error {
}
var stat os.FileInfo
// Check if the destination exists and is a directory
- if stat, err = os.Stat(realPath); err == nil && stat.IsDir() {
- // If it's a directory and we're trying to create a file, remove the directory first
- err = os.RemoveAll(realPath)
- if err != nil {
- return fmt.Errorf("could not remove existing directory to create file: %v", err)
+ if stat, err = os.Stat(realPath); err == nil {
+ if stat.IsDir() {
+ // If it's a directory and we're trying to create a file, remove the directory first
+ err = os.RemoveAll(realPath)
+ if err != nil {
+ return fmt.Errorf("could not remove existing directory to create file: %v", err)
+ }
}
+ // If file exists, its permissions will be preserved (O_TRUNC doesn't change permissions)
}
// Open the file for writing (create if it doesn't exist, truncate if it does)
+ // For new files: permissions are set to fileutils.PermFile (subject to umask, which is usually acceptable)
+ // For existing files: permissions are preserved automatically (O_TRUNC doesn't change them)
file, err := os.OpenFile(realPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileutils.PermFile)
if err != nil {
return err
@@ -601,12 +601,6 @@ 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 {
- return err
- }
-
return RefreshIndex(source, path, false, false)
}
@@ -637,9 +631,31 @@ func getContent(realPath string) (string, error) {
// --- Start of new heuristic checks ---
if n > 0 {
+ // Trim header to last complete UTF-8 rune to avoid false negatives
+ // when the header read cuts off in the middle of a multi-byte sequence.
+ // We decode runes from the end until we find a valid one, trimming
+ // any incomplete sequences at the end.
+ trimmedHeader := actualHeader
+ for len(trimmedHeader) > 0 {
+ lastRune, size := utf8.DecodeLastRune(trimmedHeader)
+ if lastRune != utf8.RuneError {
+ // Found a valid complete rune
+ break
+ }
+ // RuneError occurred - this could be an incomplete sequence or invalid byte
+ // Trim the last byte and try again
+ if size == 1 && len(trimmedHeader) > 0 {
+ trimmedHeader = trimmedHeader[:len(trimmedHeader)-1]
+ } else {
+ // Shouldn't happen, but break to avoid infinite loop
+ break
+ }
+ }
+
// 1. Basic Check: Is the header valid UTF-8?
// If not, it's unlikely an editable UTF-8 text file.
- if !utf8.Valid(actualHeader) {
+ // Use trimmed header to avoid false negatives from truncated sequences
+ if len(trimmedHeader) > 0 && !utf8.Valid(trimmedHeader) {
return "", nil // Not an error, just not the text file we want
}
diff --git a/backend/adapters/fs/files/user.go b/backend/adapters/fs/files/user.go
index a1a96e693e..23f28dfc8d 100644
--- a/backend/adapters/fs/files/user.go
+++ b/backend/adapters/fs/files/user.go
@@ -6,6 +6,7 @@ import (
"path/filepath"
"github.com/gtsteffaniak/filebrowser/backend/common/settings"
+ "github.com/gtsteffaniak/filebrowser/backend/common/utils"
"github.com/gtsteffaniak/filebrowser/backend/database/users"
)
@@ -31,11 +32,14 @@ func MakeUserDirs(u *users.User, disableScopeChange bool) error {
if filepath.Base(scope.Scope) != cleanedUserName && source.Config.CreateUserDir && !disableScopeChange {
fullPath := filepath.Join(source.Path, scope.Scope, cleanedUserName)
parentDir := filepath.Join(source.Path, scope.Scope)
- // validate that scope path exists
+ // If parent directory doesn't exist and createUserDir is enabled, create it
if !Exists(parentDir) {
- return fmt.Errorf("MakeUserDirs: scope path does not exist: %s", scope.Scope)
+ if err := MakeUserDir(parentDir); err != nil {
+ return fmt.Errorf("MakeUserDirs: failed to create parent scope directory: %s - %v", scope.Scope, err)
+ }
}
- scope.Scope = filepath.Join(scope.Scope, cleanedUserName)
+ // 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)
diff --git a/backend/adapters/fs/fileutils/file.go b/backend/adapters/fs/fileutils/file.go
index de26edbc02..1fca730c2d 100644
--- a/backend/adapters/fs/fileutils/file.go
+++ b/backend/adapters/fs/fileutils/file.go
@@ -62,6 +62,13 @@ func CopyFile(source, dest string) error {
// copySingleFile handles copying a single file.
func copySingleFile(source, dest string) error {
+ // Get source file info to preserve permissions
+ srcInfo, err := os.Stat(source)
+ if err != nil {
+ return err
+ }
+ sourcePerms := srcInfo.Mode().Perm()
+
// Open the source file.
src, err := os.Open(source)
if err != nil {
@@ -75,8 +82,8 @@ func copySingleFile(source, dest string) error {
return err
}
- // Create the destination file.
- dst, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, PermFile)
+ // Create the destination file with source permissions
+ dst, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, sourcePerms)
if err != nil {
return err
}
@@ -88,11 +95,13 @@ func copySingleFile(source, dest string) error {
return err
}
- // Set the configured file permissions instead of copying from source
- err = os.Chmod(dest, PermFile)
-
+ // Preserve source file permissions
+ // Handle chmod errors gracefully (e.g., in rootless containers where chmod may be restricted)
+ err = os.Chmod(dest, sourcePerms)
if err != nil {
- return err
+ // Log but don't fail - chmod may be restricted in some environments
+ // The file was copied successfully, so we continue
+ logger.Debugf("Could not set file permissions for %s (this may be expected in restricted environments): %v", dest, err)
}
return nil
diff --git a/backend/common/settings/structs.go b/backend/common/settings/structs.go
index 1e6033d195..260a1707e3 100644
--- a/backend/common/settings/structs.go
+++ b/backend/common/settings/structs.go
@@ -57,7 +57,7 @@ type Server struct {
ExternalUrl string `json:"externalUrl"` // used by share links if set (eg. http://mydomain.com)
InternalUrl string `json:"internalUrl"` // used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080)
CacheDir string `json:"cacheDir"` // path to the cache directory, used for thumbnails and other cached files
- CacheDirCleanup *bool `json:"cacheDirCleanup"` // whether to automatically cleanup the cache directory (default: true)
+ CacheDirCleanup *bool `json:"cacheDirCleanup"` // whether to automatically cleanup the cache directory. Note: docker must also mount a persistent volume to persist the cache (default: true)
MaxArchiveSizeGB int64 `json:"maxArchiveSize"` // max pre-archive combined size of files/folder that are allowed to be archived (in GB)
Filesystem Filesystem `json:"filesystem"` // filesystem settings
// not exposed to config
diff --git a/backend/database/share/share.go b/backend/database/share/share.go
index 436d3c0828..41817bd4f5 100644
--- a/backend/database/share/share.go
+++ b/backend/database/share/share.go
@@ -25,6 +25,7 @@ type CommonShare struct {
Source string `json:"source,omitempty"` // backend source is path to maintain between name changes
Path string `json:"path,omitempty"`
DownloadURL string `json:"downloadURL,omitempty"`
+ ShareURL string `json:"shareURL,omitempty"`
DisableShareCard bool `json:"disableShareCard,omitempty"`
EnforceDarkLightMode string `json:"enforceDarkLightMode,omitempty"` // "dark" or "light"
ViewMode string `json:"viewMode,omitempty"` // default view mode for anonymous users: "list", "compact", "normal", "gallery"
diff --git a/backend/go.mod b/backend/go.mod
index dddfa9d593..2d08a1f189 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -20,7 +20,7 @@ require (
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.44.0
+ 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
diff --git a/backend/go.sum b/backend/go.sum
index 57fedf14fb..ada8adc260 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -546,12 +546,8 @@ 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.15 h1:FwKRGvmbQ04OFYF5WIalcvUontcnj1chBeHmR5I7UYg=
-github.com/kovidgoyal/imaging v1.8.15/go.mod h1:aXZHGm/gKcaXpxn1NnQiVtuz3Z2BCnXWyjF0ZGrmJ1g=
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=
@@ -895,8 +891,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
-golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=
-golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
+golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
+golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
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=
diff --git a/backend/http/duplicates.go b/backend/http/duplicates.go
index 7d731c81fc..9101b7363a 100644
--- a/backend/http/duplicates.go
+++ b/backend/http/duplicates.go
@@ -8,6 +8,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "sort"
"strings"
"sync"
"time"
@@ -48,13 +49,14 @@ type duplicatesOptions struct {
// duplicatesHandler handles requests to find duplicate files
//
-// This endpoint finds files with the same size and uses fuzzy filename matching
-// to verify potential duplicates.
+// This endpoint finds files with the same size, uses fuzzy filename matching
+// for initial grouping (fast), then verifies all final groups with checksums.
//
// It's optimized to handle large directories efficiently by:
// 1. Filtering by minimum size first
// 2. Grouping by size
-// 3. Verifying matches with fuzzy filename similarity
+// 3. Initial grouping with fuzzy filename similarity (fast)
+// 4. Final verification with checksums on all groups (accurate)
//
// @Summary Find Duplicate Files
// @Description Finds duplicate files based on size and fuzzy filename matching
@@ -79,7 +81,8 @@ func duplicatesHandler(w http.ResponseWriter, r *http.Request, d *requestContext
}
// Generate cache key from all input parameters that affect results
- cacheKey := fmt.Sprintf("%s:%s:%d:%t", index.Path, opts.combinedPath, opts.minSize, opts.useChecksum)
+ // Checksums are always enabled, so cache key doesn't need to include that flag
+ cacheKey := fmt.Sprintf("%s:%s:%d", index.Path, opts.combinedPath, opts.minSize)
// Check cache first (before acquiring mutex)
if cachedResults, ok := duplicateResultsCache.Get(cacheKey); ok {
@@ -132,8 +135,12 @@ func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []dup
}
})
- // Step 2: Process each size group to find duplicates
- duplicateGroups := []duplicateGroup{}
+ // Step 2: Process each size group to find duplicates using filename matching (fast)
+ // We'll verify with checksums later on the final groups
+ candidateGroups := []struct {
+ size int64
+ locations []fileLocation
+ }{}
totalFiles := 0
for size, locations := range sizeGroups {
@@ -141,14 +148,10 @@ func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []dup
continue // Skip files with no potential duplicates
}
- var groups [][]fileLocation
- if opts.useChecksum {
- groups = groupLocationsByChecksum(locations, index, size)
- } else {
- groups = groupLocationsByFilename(locations, index, size)
- }
+ // Use filename matching for initial grouping (fast)
+ groups := groupLocationsByFilename(locations, index, size)
- // Step 3: Only now create SearchResult objects for actual duplicates
+ // Collect candidate groups up to the limit
for _, locGroup := range groups {
if len(locGroup) < 2 {
continue
@@ -159,7 +162,31 @@ func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []dup
break
}
- // Create SearchResult objects only for these confirmed duplicates
+ candidateGroups = append(candidateGroups, struct {
+ size int64
+ locations []fileLocation
+ }{size, locGroup})
+ totalFiles += len(locGroup)
+ }
+
+ // Stop processing more size groups if we've hit the limit
+ if totalFiles >= maxTotalFiles {
+ break
+ }
+ }
+
+ // Step 3: Verify all final groups with checksums
+ duplicateGroups := []duplicateGroup{}
+ for _, candidate := range candidateGroups {
+ // Verify with checksums
+ verifiedGroups := groupLocationsByChecksum(candidate.locations, index, candidate.size)
+
+ // Create SearchResult objects only for verified duplicates
+ for _, locGroup := range verifiedGroups {
+ if len(locGroup) < 2 {
+ continue
+ }
+
resultGroup := make([]*indexing.SearchResult, 0, len(locGroup))
index.ReadOnlyOperation(func() {
dirs := index.GetDirectories()
@@ -175,7 +202,7 @@ func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []dup
// CRITICAL: Verify size matches the expected size for this group
// Index could have changed between initial grouping and now
- if file.Size != size {
+ if file.Size != candidate.size {
continue
}
@@ -200,20 +227,19 @@ func findDuplicatesInIndex(index *indexing.Index, opts *duplicatesOptions) []dup
if len(resultGroup) >= 2 {
duplicateGroups = append(duplicateGroups, duplicateGroup{
- Size: size,
+ Size: candidate.size,
Count: len(resultGroup),
Files: resultGroup,
})
- totalFiles += len(resultGroup)
}
}
-
- // Stop processing more size groups if we've hit the limit
- if totalFiles >= maxTotalFiles {
- break
- }
}
+ // Sort groups by size (largest to smallest)
+ sort.Slice(duplicateGroups, func(i, j int) bool {
+ return duplicateGroups[i].Size > duplicateGroups[j].Size
+ })
+
return duplicateGroups
}
@@ -221,9 +247,9 @@ func prepDuplicatesOptions(r *http.Request, d *requestContext) (*duplicatesOptio
source := r.URL.Query().Get("source")
scope := r.URL.Query().Get("scope")
minSizeMbStr := r.URL.Query().Get("minSizeMb")
- // Checksum feature disabled due to performance issues with large file systems
- // Always use fuzzy filename matching instead
- useChecksum := false // r.URL.Query().Get("useChecksum") == "true"
+ // Checksums are always enabled by default for final verification
+ // First pass uses filename matching for speed, then checksums verify final groups
+ useChecksum := true
// Default minimum size: 1MB
minSizeMb := int64(1)
diff --git a/backend/http/middleware.go b/backend/http/middleware.go
index 8c255801c5..3926dfaae4 100644
--- a/backend/http/middleware.go
+++ b/backend/http/middleware.go
@@ -126,7 +126,7 @@ func withHashFileHelper(fn handleFunc) handleFunc {
link.IncrementUserDownload(data.user.Username)
}
}
- file.Path = "/" + strings.TrimPrefix(strings.TrimPrefix(file.Path, link.Path), "/")
+ file.Path = utils.AddTrailingSlashIfNotExists(path)
// Set the file info in the `data` object
data.fileInfo = *file
// Call the next handler with the data
@@ -395,6 +395,16 @@ func getProxyUser(w http.ResponseWriter, r *http.Request, data *requestContext,
if data.user.Username == "" {
return http.StatusForbidden, errors.ErrUnauthorized
}
+ // 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)
+ 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")
+ }
+ data.token = signed.Key
+ }
// Call the handler function, passing in the context (or return OK if no handler)
if fn == nil {
return http.StatusOK, nil
diff --git a/backend/http/onlyOffice.go b/backend/http/onlyOffice.go
index 87239de2f6..7dcb38cff2 100644
--- a/backend/http/onlyOffice.go
+++ b/backend/http/onlyOffice.go
@@ -179,10 +179,10 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
sendOnlyOfficeLogEvent(logContext, "INFO", "config", fmt.Sprintf("OnlyOffice session started for document: %s ", path))
// Build download URL that OnlyOffice server will use
- downloadURL := buildOnlyOfficeDownloadURL(source, providedPath, d.fileInfo.Hash, d.token)
+ downloadURL := buildOnlyOfficeDownloadURL(r, source, providedPath, d.fileInfo.Hash, d.token)
// Build callback URL for OnlyOffice to notify us of changes
- callbackURL := buildOnlyOfficeCallbackURL(source, providedPath, d.fileInfo.Hash, d.token)
+ callbackURL := buildOnlyOfficeCallbackURL(r, source, providedPath, d.fileInfo.Hash, d.token)
// Build OnlyOffice client configuration
clientConfig := map[string]interface{}{
@@ -228,14 +228,37 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
}
// buildOnlyOfficeDownloadURL constructs the download URL that OnlyOffice server will use to fetch the file
-func buildOnlyOfficeDownloadURL(source, path, hash, token string) string {
+func buildOnlyOfficeDownloadURL(r *http.Request, source, path, hash, token string) string {
// Determine base URL (internal URL takes priority for OnlyOffice server communication)
- baseURL := settings.Config.Server.BaseURL
+ var baseURL string
if settings.Config.Server.InternalUrl != "" {
- // Ensure proper URL joining without double slashes
+ // InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
- baseURL = internalURL + "/" + baseURLPath
+ if baseURLPath != "" {
+ baseURL = internalURL + "/" + baseURLPath
+ } else {
+ baseURL = internalURL
+ }
+ } else {
+ // Extract scheme and host from request (respecting X-Forwarded-* headers)
+ var host string
+ var scheme string
+
+ if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
+ host = forwardedHost
+ // Use X-Forwarded-Proto if available, otherwise default to https for proxied requests
+ if forwardedProto := r.Header.Get("X-Forwarded-Proto"); forwardedProto != "" {
+ scheme = forwardedProto
+ } else {
+ scheme = "https"
+ }
+ } else {
+ // Fallback to simple approach
+ host = r.Host
+ scheme = getScheme(r)
+ }
+ baseURL = fmt.Sprintf("%s://%s%s", scheme, host, settings.Config.Server.BaseURL)
}
var downloadURL string
@@ -255,13 +278,37 @@ func buildOnlyOfficeDownloadURL(source, path, hash, token string) string {
}
// buildOnlyOfficeCallbackURL constructs the callback URL that OnlyOffice server will use to notify us of changes
-func buildOnlyOfficeCallbackURL(source, path, hash, token string) string {
- baseURL := settings.Config.Server.BaseURL
+func buildOnlyOfficeCallbackURL(r *http.Request, source, path, hash, token string) string {
+ // Determine base URL (internal URL takes priority for OnlyOffice server communication)
+ var baseURL string
if settings.Config.Server.InternalUrl != "" {
- // Ensure proper URL joining without double slashes
+ // InternalUrl is a full URL (e.g., http://localhost:8080), so use it directly
internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/")
- baseURL = internalURL + "/" + baseURLPath
+ if baseURLPath != "" {
+ baseURL = internalURL + "/" + baseURLPath
+ } else {
+ baseURL = internalURL
+ }
+ } else {
+ // Extract scheme and host from request (respecting X-Forwarded-* headers)
+ var host string
+ var scheme string
+
+ if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
+ host = forwardedHost
+ // Use X-Forwarded-Proto if available, otherwise default to https for proxied requests
+ if forwardedProto := r.Header.Get("X-Forwarded-Proto"); forwardedProto != "" {
+ scheme = forwardedProto
+ } else {
+ scheme = "https"
+ }
+ } else {
+ // Fallback to simple approach
+ host = r.Host
+ scheme = getScheme(r)
+ }
+ baseURL = fmt.Sprintf("%s://%s%s", scheme, host, settings.Config.Server.BaseURL)
}
var callbackURL string
diff --git a/backend/http/raw.go b/backend/http/raw.go
index b51f8d7035..148d1cfe3b 100644
--- a/backend/http/raw.go
+++ b/backend/http/raw.go
@@ -111,20 +111,20 @@ func addFile(path string, d *requestContext, tarWriter *tar.Writer, zipWriter *z
if idx == nil {
return fmt.Errorf("source %s is not available", source)
}
- if d.share != nil {
- _, err = files.FileInfoFaster(utils.FileOptions{
- Path: path,
- Source: source,
- Expand: false,
- }, nil)
- } else {
- _, err = files.FileInfoFaster(utils.FileOptions{
- Username: d.user.Username,
- Path: path,
- Source: source,
- Expand: false,
- }, store.Access)
+
+ // Check access control directly for each file and silently skip if access is denied
+ if d.share == nil && store.Access != nil {
+ if !store.Access.Permitted(idx.Path, path, d.user.Username) {
+ return nil // Silently skip this file/folder
+ }
}
+
+ // Verify file exists
+ _, err = files.FileInfoFaster(utils.FileOptions{
+ Path: path,
+ Source: source,
+ Expand: false,
+ }, nil)
if err != nil {
return err
}
@@ -158,6 +158,23 @@ func addFile(path string, d *requestContext, tarWriter *tar.Writer, zipWriter *z
return nil
}
+ // 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 = filepath.ToSlash(indexRelPath) // Normalize separators
+
+ if !store.Access.Permitted(idx.Path, indexRelPath, d.user.Username) {
+ // Skip this file/folder silently
+ if fileInfo.IsDir() {
+ // Skip the entire directory by returning filepath.SkipDir
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ }
+
// Prepend base folder name unless flatten is true
if !flatten {
relPath = filepath.Join(baseName, relPath)
@@ -322,6 +339,19 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
}
}
+ // Verify access control before opening the file (direct rule check)
+ if d.share == nil && store.Access != nil {
+ if !store.Access.Permitted(idx.Path, firstFilePath, d.user.Username) {
+ logger.Debugf("user %s denied access to path %s", d.user.Username, firstFilePath)
+ // Send OnlyOffice error log if this was an OnlyOffice download
+ if isOnlyOffice && logContext != nil {
+ sendOnlyOfficeLogEvent(logContext, "ERROR", "download",
+ fmt.Sprintf("OnlyOffice download failed - access denied by rule: %s", firstFilePath))
+ }
+ return http.StatusForbidden, fmt.Errorf("access denied to path %s", firstFilePath)
+ }
+ }
+
fd, err2 := os.Open(realPath)
if err2 != nil {
// Send OnlyOffice error log if this was an OnlyOffice download
@@ -480,6 +510,12 @@ func computeArchiveSize(fileList []string, d *requestContext) (int64, error) {
return 0, fmt.Errorf("source %s is not available for user %s", source, d.user.Username)
}
path = utils.JoinPathAsUnix(userScope, path)
+
+ // Check access control for each file in the archive
+ // Silently skip if access is denied (as if the file doesn't exist)
+ if store.Access != nil && !store.Access.Permitted(idx.Path, path, d.user.Username) {
+ continue // Skip this file and continue with the next one
+ }
}
// For shares, the path is already correctly resolved by publicRawHandler
realPath, isDir, err := idx.GetRealPath(path)
@@ -512,6 +548,7 @@ func createZip(d *requestContext, tmpDirPath string, filenames ...string) error
for _, fname := range filenames {
err := addFile(fname, d, nil, zipWriter, false)
if err != nil {
+ // Access control failures return nil, so any error here is a real error
logger.Errorf("Failed to add %s to ZIP: %v", fname, err)
return err
}
diff --git a/backend/http/resource.go b/backend/http/resource.go
index e2ae55363b..ccad783dd9 100644
--- a/backend/http/resource.go
+++ b/backend/http/resource.go
@@ -382,7 +382,12 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
}
fileInfo, err := files.FileInfoFaster(fileOpts, accessStore)
- if err != nil {
+ if err == nil { // File exists
+ if r.URL.Query().Get("override") != "true" {
+ logger.Debugf("resource already exists: %v", fileInfo.RealPath)
+ return http.StatusConflict, nil
+ }
+ // If overriding, delete existing thumbnails
preview.DelThumbs(r.Context(), *fileInfo)
}
err = files.WriteFile(fileOpts.Source, fileOpts.Path, r.Body)
diff --git a/backend/http/share.go b/backend/http/share.go
index b1da9d9507..85ac0ada76 100644
--- a/backend/http/share.go
+++ b/backend/http/share.go
@@ -26,10 +26,9 @@ import (
// ShareResponse represents a share with computed username field and download URL
type ShareResponse struct {
*share.Link
- Source string `json:"source"` // Override embedded field to show source name
- Username string `json:"username,omitempty"`
- DownloadURL string `json:"downloadURL,omitempty"`
- PathExists bool `json:"pathExists"`
+ Source string `json:"source"` // Override embedded field to show source name
+ Username string `json:"username,omitempty"`
+ PathExists bool `json:"pathExists"`
}
// convertToFrontendShareResponse converts shares to response format with usernames
@@ -63,14 +62,15 @@ 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)
// Create response with source name (overrides the embedded Link's source field)
responses = append(responses, &ShareResponse{
- Link: s,
- Source: sourceInfo.Name, // Override to show source name instead of backend path
- Username: username,
- DownloadURL: getDownloadURL(r, s.Hash),
- PathExists: pathExists,
+ Link: s,
+ Source: sourceInfo.Name, // Override to show source name instead of backend path
+ Username: username,
+ PathExists: pathExists,
})
}
return responses, nil
@@ -392,6 +392,7 @@ type DirectDownloadResponse struct {
Status string `json:"status"`
Hash string `json:"hash"`
DownloadURL string `json:"url"`
+ ShareURL string `json:"shareUrl"`
}
// shareDirectDownloadHandler creates a direct download link for files only.
@@ -509,7 +510,8 @@ func shareDirectDownloadHandler(w http.ResponseWriter, r *http.Request, d *reque
response := DirectDownloadResponse{
Status: "201",
Hash: existing.Hash,
- DownloadURL: getDownloadURL(r, existing.Hash),
+ DownloadURL: getShareURL(r, existing.Hash, true),
+ ShareURL: getShareURL(r, existing.Hash, false),
}
return renderJSON(w, r, response)
}
@@ -540,21 +542,26 @@ func shareDirectDownloadHandler(w http.ResponseWriter, r *http.Request, d *reque
response := DirectDownloadResponse{
Status: "200",
Hash: secureHash,
- DownloadURL: getDownloadURL(r, secureHash),
+ DownloadURL: getShareURL(r, secureHash, true),
+ ShareURL: getShareURL(r, secureHash, false),
}
return renderJSON(w, r, response)
}
-func getDownloadURL(r *http.Request, hash string) string {
- var downloadURL string
+func getShareURL(r *http.Request, hash string, isDirectDownload bool) string {
+ var shareURL string
if config.Server.ExternalUrl != "" {
- downloadURL = fmt.Sprintf("%s%spublic/api/raw?hash=%s", config.Server.ExternalUrl, config.Server.BaseURL, hash)
+ if isDirectDownload {
+ shareURL = fmt.Sprintf("%s%spublic/api/raw?hash=%s", config.Server.ExternalUrl, config.Server.BaseURL, hash)
+ } else {
+ shareURL = fmt.Sprintf("%s%spublic/share/%s", config.Server.ExternalUrl, config.Server.BaseURL, hash)
+ }
+
} else {
// Prefer X-Forwarded-Host for proxy support
var host string
var scheme string
-
if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
host = forwardedHost
// Use X-Forwarded-Proto if available, otherwise default to https for proxied requests
@@ -568,9 +575,13 @@ func getDownloadURL(r *http.Request, hash string) string {
host = r.Host
scheme = getScheme(r)
}
- downloadURL = fmt.Sprintf("%s://%s%spublic/api/raw?hash=%s", scheme, host, config.Server.BaseURL, hash)
+ if isDirectDownload {
+ shareURL = fmt.Sprintf("%s://%s%spublic/api/raw?hash=%s", scheme, host, config.Server.BaseURL, hash)
+ } else {
+ shareURL = fmt.Sprintf("%s://%s%spublic/share/%s", scheme, host, config.Server.BaseURL, hash)
+ }
}
- return downloadURL
+ return shareURL
}
// shareInfoHandler retrieves share information by hash.
@@ -590,6 +601,8 @@ func shareInfoHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
if err != nil {
return http.StatusNotFound, fmt.Errorf("share hash not found")
}
+ commonShare.DownloadURL = getShareURL(r, hash, true)
+ commonShare.ShareURL = getShareURL(r, hash, false)
return renderJSON(w, r, commonShare)
}
diff --git a/backend/indexing/indexingFiles.go b/backend/indexing/indexingFiles.go
index c3cb83a5b6..542af9862e 100644
--- a/backend/indexing/indexingFiles.go
+++ b/backend/indexing/indexingFiles.go
@@ -233,11 +233,15 @@ func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error)
}
if !dirInfo.IsDir() {
+ // Use handleFile for consistent size calculation across platforms
+ realSize, _ := idx.handleFile(dirInfo, adjustedPath, realPath)
+ size := int64(realSize)
+
fileInfo := iteminfo.FileInfo{
Path: adjustedPath,
ItemInfo: iteminfo.ItemInfo{
Name: filepath.Base(originalPath),
- Size: dirInfo.Size(),
+ Size: size,
ModTime: dirInfo.ModTime(),
},
}
@@ -376,8 +380,9 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus
idx.incrementScannerDirs()
}
} else {
- size, shouldCountSize := idx.handleFile(file, fullCombined)
- itemInfo.DetectType(realPath+"/"+file.Name(), false)
+ realFilePath := realPath + "/" + file.Name()
+ size, shouldCountSize := idx.handleFile(file, fullCombined, realFilePath)
+ itemInfo.DetectType(realFilePath, false)
// Set HasPreview flags - use cached metadata optimization only when indexing is enabled
usedCachedPreview := false
if !idx.Config.DisableIndexing && config.Recursive {
@@ -758,43 +763,6 @@ func (idx *Index) SetStatus(status IndexStatus) error {
return idx.SendSourceUpdateEvent()
}
-func (idx *Index) handleFile(file os.FileInfo, fullCombined string) (size uint64, shouldCountSize bool) {
- var realSize uint64
- var nlink uint64 = 1
- var ino uint64 = 0
- canUseSyscall := false
-
- if sys := file.Sys(); sys != nil {
- realSize, nlink, ino, canUseSyscall = getFileDetails(sys)
- }
-
- if !canUseSyscall {
- // Fallback for non-unix systems or if syscall info is unavailable
- realSize = uint64(file.Size())
- }
-
- if nlink > 1 {
- // It's a hard link
- idx.mu.Lock()
- defer idx.mu.Unlock()
- if _, exists := idx.processedInodes[ino]; exists {
- // Already seen, don't count towards global total, or directory total.
- return realSize, false
- }
- // First time seeing this inode.
- idx.processedInodes[ino] = struct{}{}
- idx.FoundHardLinks[fullCombined] = realSize
- idx.totalSize += realSize
- return realSize, true // Count size for directory total.
- }
-
- // It's a regular file.
- idx.mu.Lock()
- idx.totalSize += realSize
- idx.mu.Unlock()
- return realSize, true // Count size.
-}
-
// input should be non-index path.
func (idx *Index) MakeIndexPath(path string) string {
if path == "." || strings.HasPrefix(path, "./") {
diff --git a/backend/indexing/unix.go b/backend/indexing/unix.go
index f3d3b6ae78..22aafa9f4e 100644
--- a/backend/indexing/unix.go
+++ b/backend/indexing/unix.go
@@ -3,8 +3,11 @@
package indexing
import (
+ "os"
"strings"
"syscall"
+
+ "github.com/gtsteffaniak/go-logger/logger"
)
func CheckWindowsHidden(realpath string) bool {
@@ -24,14 +27,75 @@ func getPartitionSize(path string) (uint64, error) {
return total, nil
}
-func getFileDetails(sys any) (uint64, uint64, uint64, bool) {
- if stat, ok := sys.(*syscall.Stat_t); ok {
- // Use actual file size, not allocated blocks
- // This matches what ls -l shows and what FileInfoFaster returns
- realSize := uint64(stat.Size)
- return realSize, uint64(stat.Nlink), stat.Ino, true
+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)
+ if sys != nil {
+ if stat, ok := sys.(*syscall.Stat_t); ok {
+ // Use allocated size for `du`-like behavior
+ realSize := uint64(stat.Blocks * 512)
+ return realSize, uint64(stat.Nlink), stat.Ino, true
+ }
}
- return 0, 1, 0, false
+
+ // If file.Sys() didn't work, try direct stat syscall
+ // On Unix, we should always have a file path and be able to stat
+ if filePath == "" {
+ // No file path available - this is an error condition on Unix
+ // We cannot proceed without syscall info on Unix
+ return 0, 1, 0, false
+ }
+
+ // Perform direct stat syscall - this should always work on Unix if file exists
+ var stat syscall.Stat_t
+ err := syscall.Stat(filePath, &stat)
+ if err != nil {
+ // On Unix, if stat fails, the file likely doesn't exist or we don't have permission
+ // This is an error condition - we cannot proceed without syscall info on Unix
+ return 0, 1, 0, false
+ }
+
+ // Use allocated size for `du`-like behavior
+ realSize := uint64(stat.Blocks * 512)
+ return realSize, uint64(stat.Nlink), stat.Ino, true
+}
+
+// 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)
+func (idx *Index) handleFile(file os.FileInfo, fullCombined string, realFilePath string) (size uint64, shouldCountSize bool) {
+ var realSize uint64
+ var nlink uint64
+ var ino uint64
+ canUseSyscall := false
+
+ sys := file.Sys()
+ realSize, nlink, ino, canUseSyscall = getFileDetails(sys, realFilePath)
+
+ if !canUseSyscall {
+ logger.Errorf("Failed to get syscall info for file %s on Unix system - file may have been deleted or permission denied. Using file.Size() fallback.", realFilePath)
+ realSize = uint64(file.Size())
+ }
+
+ if nlink > 1 {
+ // It's a hard link
+ idx.mu.Lock()
+ defer idx.mu.Unlock()
+ if _, exists := idx.processedInodes[ino]; exists {
+ // Already seen, don't count towards global total, or directory total.
+ return realSize, false
+ }
+ // First time seeing this inode.
+ idx.processedInodes[ino] = struct{}{}
+ idx.FoundHardLinks[fullCombined] = realSize
+ idx.totalSize += realSize
+ return realSize, true // Count size for directory total.
+ }
+
+ // It's a regular file.
+ idx.mu.Lock()
+ idx.totalSize += realSize
+ idx.mu.Unlock()
+ return realSize, true // Count size.
}
// platform specific rules
diff --git a/backend/indexing/windows.go b/backend/indexing/windows.go
index 7eb674fd50..fe73425a9f 100644
--- a/backend/indexing/windows.go
+++ b/backend/indexing/windows.go
@@ -3,6 +3,7 @@
package indexing
import (
+ "os"
"strings"
"golang.org/x/sys/windows"
@@ -46,13 +47,27 @@ func getPartitionSize(path string) (uint64, error) {
return totalBytes, nil
}
-func getFileDetails(sys any) (uint64, uint64, uint64, bool) {
+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)
+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
+ idx.mu.Lock()
+ idx.totalSize += realSize
+ idx.mu.Unlock()
+ return realSize, true
+}
+
// input should be non-index path.
func (idx *Index) MakeIndexPathPlatform(path string) string {
split := strings.Split(path, "\\")
diff --git a/backend/preview/image_test.go b/backend/preview/image_test.go
index d648e1044e..2386c98722 100644
--- a/backend/preview/image_test.go
+++ b/backend/preview/image_test.go
@@ -276,7 +276,9 @@ func TestService_Resize(t *testing.T) {
for name, test := range testCases {
t.Run(name, func(t *testing.T) {
- svc := NewPreviewGenerator(1, "")
+ // Use a temporary directory for cache to avoid creating directories in the source tree
+ tmpDir := t.TempDir()
+ svc := NewPreviewGenerator(1, tmpDir)
source := test.source(t)
defer source.Close()
@@ -434,7 +436,9 @@ func TestService_FormatFromExtension(t *testing.T) {
for name, test := range testCases {
t.Run(name, func(t *testing.T) {
- svc := NewPreviewGenerator(1, "")
+ // Use a temporary directory for cache to avoid creating directories in the source tree
+ tmpDir := t.TempDir()
+ svc := NewPreviewGenerator(1, tmpDir)
got, err := svc.FormatFromExtension(test.ext)
require.Truef(t, errors.Is(err, test.wantErr), "error = %v, wantErr %v", err, test.wantErr)
if err != nil {
diff --git a/backend/preview/preview.go b/backend/preview/preview.go
index 55800c1b57..1d0aa0d551 100644
--- a/backend/preview/preview.go
+++ b/backend/preview/preview.go
@@ -30,6 +30,7 @@ var (
type Service struct {
fileCache diskcache.Interface
+ cacheDir string // Cache directory used for thumbnails and temp files
debug bool
docGenMutex sync.Mutex // Mutex to serialize access to doc generation
docSemaphore chan struct{} // Semaphore for document generation
@@ -44,36 +45,43 @@ func NewPreviewGenerator(concurrencyLimit int, cacheDir string) *Service {
}
// get round up half value of concurrencyLimit
ffmpegConcurrencyLimit := (concurrencyLimit + 1) / 2
+
+ actualCacheDir := cacheDir
+ if actualCacheDir == "" {
+ actualCacheDir = os.TempDir()
+ }
+
var fileCache diskcache.Interface
// Use file cache if cacheDir is specified
var err error
- fileCache, err = diskcache.NewFileCache(cacheDir)
+ fileCache, err = diskcache.NewFileCache(actualCacheDir)
if err != nil {
logger.Error("The cache dir could not be created. Make sure the user that you executed the program with has access to create directories in the local path. See ")
logger.Fatalf("failed to create file cache path, which is now require to run the server: %v", err)
}
- // Create directories recursively
- err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs"), fileutils.PermDir)
+ // Create directories recursively using the determined cache directory
+ err = os.MkdirAll(filepath.Join(actualCacheDir, "thumbnails", "docs"), fileutils.PermDir)
if err != nil {
logger.Error(err)
}
- err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "videos"), fileutils.PermDir)
+ err = os.MkdirAll(filepath.Join(actualCacheDir, "thumbnails", "videos"), fileutils.PermDir)
if err != nil {
logger.Error(err)
}
- err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "heic"), fileutils.PermDir)
+ err = os.MkdirAll(filepath.Join(actualCacheDir, "heic"), fileutils.PermDir)
if err != nil {
logger.Error(err)
}
videoService := ffmpeg.NewFFmpegService(ffmpegConcurrencyLimit, settings.Config.Integrations.Media.Debug, "")
- imageService := ffmpeg.NewFFmpegService(concurrencyLimit, settings.Config.Integrations.Media.Debug, filepath.Join(settings.Config.Server.CacheDir, "heic"))
+ imageService := ffmpeg.NewFFmpegService(concurrencyLimit, settings.Config.Integrations.Media.Debug, filepath.Join(actualCacheDir, "heic"))
settings.Env.MuPdfAvailable = docEnabled()
logger.Debugf("MuPDF Enabled : %v", settings.Env.MuPdfAvailable)
logger.Debugf("Media Enabled : %v", settings.MediaEnabled())
return &Service{
fileCache: fileCache,
+ cacheDir: actualCacheDir,
debug: settings.Config.Integrations.Media.Debug,
docSemaphore: make(chan struct{}, 1), // must be 1 because cgo thread limit
officeSem: make(chan struct{}, concurrencyLimit),
@@ -179,7 +187,7 @@ func GeneratePreviewWithMD5(ctx context.Context, file iteminfo.ExtendedFileInfo,
convertHEIC := strings.HasPrefix(file.Type, "image/heic") && settings.Config.Integrations.Media.Convert.ImagePreview[settings.HEICImagePreview]
// Generate an image from office document
if iteminfo.HasDocConvertableExtension(file.Name, file.Type) {
- tempFilePath := filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs", hash) + ".txt"
+ tempFilePath := filepath.Join(service.cacheDir, "thumbnails", "docs", hash) + ".txt"
imageBytes, err = service.GenerateImageFromDoc(ctx, file, tempFilePath, 0) // 0 for the first page
if err != nil {
return nil, fmt.Errorf("failed to create image for PDF file: %w", err)
diff --git a/backend/swagger/docs/docs.go b/backend/swagger/docs/docs.go
index 0de97e38cc..865c38c81b 100644
--- a/backend/swagger/docs/docs.go
+++ b/backend/swagger/docs/docs.go
@@ -2917,6 +2917,9 @@ const docTemplate = `{
"hash": {
"type": "string"
},
+ "shareUrl": {
+ "type": "string"
+ },
"status": {
"type": "string"
},
@@ -3063,6 +3066,9 @@ const docTemplate = `{
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -3844,7 +3850,7 @@ const docTemplate = `{
"type": "string"
},
"cacheDirCleanup": {
- "description": "whether to automatically cleanup the cache directory (default: true)",
+ "description": "whether to automatically cleanup the cache directory. Note: docker must also mount a persistent volume to persist the cache (default: true)",
"type": "boolean"
},
"database": {
@@ -4348,6 +4354,9 @@ const docTemplate = `{
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4478,6 +4487,9 @@ const docTemplate = `{
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4614,6 +4626,9 @@ const docTemplate = `{
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
diff --git a/backend/swagger/docs/swagger.json b/backend/swagger/docs/swagger.json
index a5da183c87..75a5858b44 100644
--- a/backend/swagger/docs/swagger.json
+++ b/backend/swagger/docs/swagger.json
@@ -2906,6 +2906,9 @@
"hash": {
"type": "string"
},
+ "shareUrl": {
+ "type": "string"
+ },
"status": {
"type": "string"
},
@@ -3052,6 +3055,9 @@
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -3833,7 +3839,7 @@
"type": "string"
},
"cacheDirCleanup": {
- "description": "whether to automatically cleanup the cache directory (default: true)",
+ "description": "whether to automatically cleanup the cache directory. Note: docker must also mount a persistent volume to persist the cache (default: true)",
"type": "boolean"
},
"database": {
@@ -4337,6 +4343,9 @@
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4467,6 +4476,9 @@
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
@@ -4603,6 +4615,9 @@
"description": "type of share: normal, upload, max",
"type": "string"
},
+ "shareURL": {
+ "type": "string"
+ },
"sidebarLinks": {
"description": "customizable sidebar links",
"type": "array",
diff --git a/backend/swagger/docs/swagger.yaml b/backend/swagger/docs/swagger.yaml
index ed531499fc..eb379636db 100644
--- a/backend/swagger/docs/swagger.yaml
+++ b/backend/swagger/docs/swagger.yaml
@@ -16,6 +16,8 @@ definitions:
properties:
hash:
type: string
+ shareUrl:
+ type: string
status:
type: string
url:
@@ -115,6 +117,8 @@ definitions:
shareType:
description: 'type of share: normal, upload, max'
type: string
+ shareURL:
+ type: string
sidebarLinks:
description: customizable sidebar links
items:
@@ -695,7 +699,8 @@ definitions:
files
type: string
cacheDirCleanup:
- description: 'whether to automatically cleanup the cache directory (default:
+ description: 'whether to automatically cleanup the cache directory. Note:
+ docker must also mount a persistent volume to persist the cache (default:
true)'
type: boolean
database:
@@ -1073,6 +1078,8 @@ definitions:
shareType:
description: 'type of share: normal, upload, max'
type: string
+ shareURL:
+ type: string
sidebarLinks:
description: customizable sidebar links
items:
@@ -1164,6 +1171,8 @@ definitions:
shareType:
description: 'type of share: normal, upload, max'
type: string
+ shareURL:
+ type: string
sidebarLinks:
description: customizable sidebar links
items:
@@ -1259,6 +1268,8 @@ definitions:
shareType:
description: 'type of share: normal, upload, max'
type: string
+ shareURL:
+ type: string
sidebarLinks:
description: customizable sidebar links
items:
diff --git a/frontend/public/config.generated.yaml b/frontend/public/config.generated.yaml
index 69bbb5cecb..1a5fe79e4e 100644
--- a/frontend/public/config.generated.yaml
+++ b/frontend/public/config.generated.yaml
@@ -49,7 +49,7 @@ server:
externalUrl: "" # used by share links if set (eg. http://mydomain.com)
internalUrl: "" # used by integrations if set, this is the base domain that an integration service will use to communicate with filebrowser (eg. http://localhost:8080)
cacheDir: "tmp" # path to the cache directory, used for thumbnails and other cached files
- cacheDirCleanup: true # whether to automatically cleanup the cache directory (default: true)
+ cacheDirCleanup: true # whether to automatically cleanup the cache directory. Note: docker must also mount a persistent volume to persist the cache (default: true)
maxArchiveSize: 50 # max pre-archive combined size of files/folder that are allowed to be archived (in GB)
filesystem: # filesystem settings
createFilePermission: "644" # Unix permissions like 644, 755, 2755 (default: 644) validate:required,file_permission
diff --git a/frontend/src/api/files.js b/frontend/src/api/files.js
index 3407ae34fc..9c02611772 100644
--- a/frontend/src/api/files.js
+++ b/frontend/src/api/files.js
@@ -81,7 +81,7 @@ export async function put(source, path, content = '') {
return await resourceAction(source, path, 'PUT', content)
}
-export function download(format, files, shareHash = "") {
+export async function download(format, files, shareHash = "") {
if (format !== 'zip') {
format = 'tar.gz'
}
@@ -102,13 +102,53 @@ export function download(format, files, shareHash = "") {
})
const url = window.origin + apiPath
- // Create a temporary element to trigger the download
+
+ // 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 filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
+ if (filenameMatch && filenameMatch[1]) {
+ filename = filenameMatch[1].replace(/['"]/g, '')
+ }
+ } else {
+ // Fallback: use format extension
+ filename = `download.${format}`
+ }
+
+ // Create a blob URL and trigger download
+ const blobUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
- link.href = url
- link.setAttribute('download', '') // Ensures it triggers a download
+ link.href = blobUrl
+ link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
- document.body.removeChild(link) // Clean up
+ document.body.removeChild(link)
+ // Clean up the blob URL
+ window.URL.revokeObjectURL(blobUrl)
+
}
export function post(
diff --git a/frontend/src/api/public.js b/frontend/src/api/public.js
index f4c543bd46..a63bd32b28 100644
--- a/frontend/src/api/public.js
+++ b/frontend/src/api/public.js
@@ -1,7 +1,6 @@
import { adjustedData } from "./utils";
import { notify } from "@/notify";
-import { getApiPath, getPublicApiPath, encodedPath, doubleEncode } from "@/utils/url.js";
-import { globalVars } from "@/utils/constants";
+import { getPublicApiPath, encodedPath, doubleEncode } from "@/utils/url.js";
import { state } from "@/store";
// ============================================================================
@@ -92,19 +91,6 @@ export function getPreviewURL(path,size="small") {
}
}
-// Get the shareable URL for a share
-/**
- * @param {{ hash: string }} share
- * @returns {string}
- */
-export function getShareURL(share) {
- if (globalVars.externalUrl) {
- const apiPath = getApiPath(`public/share/${share.hash}`)
- return globalVars.externalUrl + apiPath;
- }
- return window.origin + getApiPath(`public/share/${share.hash}`);
-}
-
export function post(
hash,
diff --git a/frontend/src/components/StatusBar.vue b/frontend/src/components/StatusBar.vue
index 203aa26e8a..46b4f3792c 100644
--- a/frontend/src/components/StatusBar.vue
+++ b/frontend/src/components/StatusBar.vue
@@ -4,12 +4,10 @@