From 9ff92e079f695d8a7d3175d0a84bed2fd7642397 Mon Sep 17 00:00:00 2001 From: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com> Date: Wed, 17 Sep 2025 09:12:43 -0500 Subject: [PATCH] Beta/v0.8.6 (#1233) Co-authored-by: Max Co-authored-by: Kurami Co-authored-by: Alexander Noyle --- CHANGELOG.md | 19 + _docker/src/proxy/backend/config.yaml | 2 + backend/adapters/fs/diskcache/file_cache.go | 4 +- backend/adapters/fs/files/file_test.go | 174 ++++++++ backend/adapters/fs/files/files.go | 155 +++++-- backend/adapters/fs/files/mime.go | 5 +- backend/common/settings/config.go | 8 +- backend/common/settings/generator.go | 55 +++ backend/common/settings/settings.go | 2 +- backend/common/settings/structs.go | 4 +- backend/database/share/extended.go | 96 +++++ backend/database/storage/storage.go | 3 +- backend/ffmpeg/image.go | 6 +- backend/http/httpRouter.go | 2 + backend/http/onlyOffice.go | 163 +++++++- backend/http/preview.go | 16 +- backend/http/raw.go | 3 +- backend/http/resource.go | 6 +- backend/http/share.go | 6 +- backend/http/static.go | 7 + backend/indexing/indexingFiles.go | 125 ++++-- backend/indexing/indexingSchedule.go | 7 +- backend/indexing/iteminfo/conditions.go | 156 ++++++- backend/indexing/iteminfo/fileinfo.go | 1 + backend/indexing/mutate.go | 61 +++ backend/preview/preview.go | 20 +- backend/swagger/docs/docs.go | 2 +- backend/swagger/docs/swagger.json | 2 +- backend/swagger/docs/swagger.yaml | 3 +- frontend/public/config.generated.yaml | 3 +- frontend/src/components/ContextMenu.vue | 9 +- .../src/components/files/ShareInfoCard.vue | 35 +- frontend/src/components/prompts/Share.vue | 9 +- frontend/src/components/prompts/UserEdit.vue | 384 ++++++++++++++++-- frontend/src/components/settings/UserForm.vue | 351 ---------------- frontend/src/components/sidebar/General.vue | 2 +- frontend/src/components/sidebar/Sidebar.vue | 19 +- frontend/src/css/base.css | 1 - frontend/src/css/dark.css | 15 - frontend/src/css/header.css | 14 - frontend/src/i18n/ar.json | 6 +- frontend/src/i18n/cz.json | 6 +- frontend/src/i18n/de.json | 6 +- frontend/src/i18n/el.json | 6 +- frontend/src/i18n/en.json | 4 +- frontend/src/i18n/es.json | 6 +- frontend/src/i18n/fr.json | 6 +- frontend/src/i18n/he.json | 6 +- frontend/src/i18n/hu.json | 6 +- frontend/src/i18n/it.json | 6 +- frontend/src/i18n/ja.json | 6 +- frontend/src/i18n/ko.json | 6 +- frontend/src/i18n/nl-be.json | 6 +- frontend/src/i18n/pl.json | 6 +- frontend/src/i18n/pt-br.json | 6 +- frontend/src/i18n/pt.json | 6 +- frontend/src/i18n/ro.json | 6 +- frontend/src/i18n/ru.json | 6 +- frontend/src/i18n/sk.json | 6 +- frontend/src/i18n/sv-se.json | 6 +- frontend/src/i18n/tr.json | 6 +- frontend/src/i18n/ua.json | 6 +- frontend/src/i18n/zh-cn.json | 6 +- frontend/src/i18n/zh-tw.json | 6 +- frontend/src/store/getters.js | 9 +- frontend/src/store/mutations.js | 5 + frontend/src/store/state.js | 1 + frontend/src/utils/url.js | 7 +- frontend/src/views/Files.vue | 10 + frontend/src/views/bars/Default.vue | 14 +- frontend/src/views/files/OnlyOfficeEditor.vue | 325 ++++++++++++++- frontend/src/views/files/plyrViewer.vue | 79 +++- frontend/src/views/settings/Shares.vue | 7 + .../playwright/general/user-actions.spec.ts | 12 +- 74 files changed, 1868 insertions(+), 698 deletions(-) create mode 100644 backend/database/share/extended.go delete mode 100644 frontend/src/components/settings/UserForm.vue diff --git a/CHANGELOG.md b/CHANGELOG.md index 5dd0bf7de7..47ff001add 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ All notable changes to this project will be documented in this file. For commit guidelines, please refer to [Standard Version](https://github.com/conventional-changelog/standard-version). +## v0.8.6-beta + + **Notes**: + - Please remove `indexAbumArt` config option from your config: it has been deprecated... I found a way to detect album art without impacting indexing performance -- so its default behavior. + - Download button should be invisible before password input #1162 + - opus files / opus files detected wrongly #1164 + - changed autoplay behavior on plyr to not start playing if blocked instead of playing muted. + - QR-Code disappearing / sliding out from shared link #1155 + - audio player matches dark/light mode better + + **BugFixes**: + - Copy/Move index update changes to be more thorough and update album artwork #1220 #1219 + - fix preview related issues #1225 #1223 + - Scrollbar missing on user-edit-prompt in v0.8.5-beta #1221 + - copy share download link inconsistency #1207 + - fixed some onlyoffice related issues #1192 #1068 + - Creating a file, then a folder with the same name makes the folder unusable #1167 + - fix plyr issue switching from video to audio via next/previous button. + ## v0.8.5-beta **New Features**: diff --git a/_docker/src/proxy/backend/config.yaml b/_docker/src/proxy/backend/config.yaml index 048e9c931c..1e66781872 100644 --- a/_docker/src/proxy/backend/config.yaml +++ b/_docker/src/proxy/backend/config.yaml @@ -19,6 +19,8 @@ frontend: auth: methods: + password: + enabled: false proxy: enabled: true header: "X-Username" diff --git a/backend/adapters/fs/diskcache/file_cache.go b/backend/adapters/fs/diskcache/file_cache.go index ff934c4767..5651f43f3a 100644 --- a/backend/adapters/fs/diskcache/file_cache.go +++ b/backend/adapters/fs/diskcache/file_cache.go @@ -2,7 +2,7 @@ package diskcache import ( "context" - "crypto/sha1" //nolint:gosec + "crypto/sha1" "encoding/hex" "errors" "fmt" @@ -106,7 +106,7 @@ func (f *FileCache) getScopedLocks(key string) (lock sync.Locker) { } func (f *FileCache) getFileName(key string) string { - hasher := sha1.New() //nolint:gosec + hasher := sha1.New() _, _ = hasher.Write([]byte(key)) hash := hex.EncodeToString(hasher.Sum(nil)) return filepath.Join(f.dir, fmt.Sprintf("%s/%s/%s", hash[:1], hash[1:3], hash)) diff --git a/backend/adapters/fs/files/file_test.go b/backend/adapters/fs/files/file_test.go index ea5e62f7b8..eb8550977d 100644 --- a/backend/adapters/fs/files/file_test.go +++ b/backend/adapters/fs/files/file_test.go @@ -177,3 +177,177 @@ func TestSortItems(t *testing.T) { }) } } + +func TestDeleteFilesCacheClearing(t *testing.T) { + // Create a temporary directory for testing + tempDir, err := os.MkdirTemp("", "filebrowser_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + + // Create a test file + testFile := filepath.Join(tempDir, "Test Object") + err = os.WriteFile(testFile, []byte("test content"), 0644) + if err != nil { + t.Fatalf("Failed to create test file: %v", err) + } + + // Initialize a mock index + idx := indexing.Index{ + Source: settings.Source{ + Path: tempDir, + }, + } + + // Get the real path and cache it + _, isDir, err := idx.GetRealPath("/Test Object") + if err != nil { + t.Fatalf("Failed to get real path: %v", err) + } + + // Verify the file is detected as a file (not directory) + if isDir { + t.Errorf("Expected file to be detected as file, but got directory") + } + + // Initialize the index in the indexing system + indexing.Initialize(settings.Source{ + Name: "test", + Path: tempDir, + }, true) // true for mock mode + + // Delete the file + err = DeleteFiles("test", testFile, tempDir) + if err != nil { + t.Fatalf("Failed to delete file: %v", err) + } + + // Create a directory with the same name + testDir := filepath.Join(tempDir, "Test Object") + err = os.Mkdir(testDir, 0755) + if err != nil { + t.Fatalf("Failed to create test directory: %v", err) + } + + // Get the real path again - it should now detect it as a directory + // The cache should have been cleared, so it should re-detect the type + realPath2, isDir2, err := idx.GetRealPath("/Test Object") + if err != nil { + t.Fatalf("Failed to get real path after recreation: %v", err) + } + + // Verify the directory is detected as a directory + if !isDir2 { + t.Errorf("Expected directory to be detected as directory, but got file. Real path: %s", realPath2) + } + + // Clean up + os.RemoveAll(tempDir) +} + +func TestOverrideDirectoryToFile(t *testing.T) { + // Create a temporary directory for testing + tempDir, err := os.MkdirTemp("", "filebrowser_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + + // Initialize the index in the indexing system + indexing.Initialize(settings.Source{ + Name: "test", + Path: tempDir, + }, true) // true for mock mode + + // Create a directory first + testDir := filepath.Join(tempDir, "Test Object") + err = os.Mkdir(testDir, 0755) + if err != nil { + t.Fatalf("Failed to create test directory: %v", err) + } + + // Now try to create a file with the same name (should work with override) + fileOpts := iteminfo.FileOptions{ + Path: "/Test Object", + Source: "test", + } + + // Create a test reader with some content + testContent := "This is test file content" + reader := strings.NewReader(testContent) + + err = WriteFile(fileOpts, reader) + if err != nil { + t.Fatalf("Failed to create file over directory: %v", err) + } + + // Verify the file was created and the directory was removed + stat, err := os.Stat(testDir) + if err != nil { + t.Fatalf("File should exist but got error: %v", err) + } + + if stat.IsDir() { + t.Errorf("Expected file but got directory") + } + + // Verify the content + content, err := os.ReadFile(testDir) + if err != nil { + t.Fatalf("Failed to read file content: %v", err) + } + + if string(content) != testContent { + t.Errorf("Expected content %q but got %q", testContent, string(content)) + } + + // Clean up + os.RemoveAll(tempDir) +} + +func TestOverrideFileToDirectory(t *testing.T) { + // Create a temporary directory for testing + tempDir, err := os.MkdirTemp("", "filebrowser_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer os.RemoveAll(tempDir) + + // Initialize the index in the indexing system + indexing.Initialize(settings.Source{ + Name: "test", + Path: tempDir, + }, true) // true for mock mode + + // Create a file first + testFile := filepath.Join(tempDir, "Test Object") + err = os.WriteFile(testFile, []byte("test content"), 0644) + if err != nil { + t.Fatalf("Failed to create test file: %v", err) + } + + // Now try to create a directory with the same name (should work with override) + fileOpts := iteminfo.FileOptions{ + Path: "/Test Object/", + Source: "test", + } + + err = WriteDirectory(fileOpts) + if err != nil { + t.Fatalf("Failed to create directory over file: %v", err) + } + + // Verify the directory was created and the file was removed + stat, err := os.Stat(testFile) + if err != nil { + t.Fatalf("Directory should exist but got error: %v", err) + } + + if !stat.IsDir() { + t.Errorf("Expected directory but got file") + } + + // Clean up + os.RemoveAll(tempDir) +} diff --git a/backend/adapters/fs/files/files.go b/backend/adapters/fs/files/files.go index 33311a2996..9b90c7f627 100644 --- a/backend/adapters/fs/files/files.go +++ b/backend/adapters/fs/files/files.go @@ -168,6 +168,18 @@ func extractAudioMetadata(item *iteminfo.ExtendedFileInfo) error { } defer file.Close() + // Check file size first to prevent reading extremely large files + fileInfo, err := file.Stat() + if err != nil { + return err + } + + // Skip files larger than 50MB to prevent memory issues + maxSize := int64(50) + if fileInfo.Size() > maxSize*1024*1024 { + return fmt.Errorf("file exceeds metadata check limit: %d MB", maxSize) + } + m, err := tag.ReadFrom(file) if err != nil { return err @@ -185,10 +197,10 @@ func extractAudioMetadata(item *iteminfo.ExtendedFileInfo) error { track, _ := m.Track() item.AudioMeta.Track = track - // Extract album art and encode as base64 + // Extract album art and encode as base64 with strict size limits if picture := m.Picture(); picture != nil && picture.Data != nil { - // Limit album art size to prevent excessive response sizes (max 1MB) - if len(picture.Data) <= 1024*1024 { + // More aggressive size limit to prevent memory issues (max 2MB) + if len(picture.Data) <= 2*1024*1024 { item.AudioMeta.AlbumArt = base64.StdEncoding.EncodeToString(picture.Data) } else { logger.Debugf("Skipping album art for %s: too large (%d bytes)", item.RealPath, len(picture.Data)) @@ -210,6 +222,17 @@ func DeleteFiles(source, absPath string, absDirPath string) error { if index.Config.DisableIndexing { return nil } + + // Clear RealPathCache entries for the deleted path to prevent cache issues + // when a folder with the same name is created later + indexPath := index.MakeIndexPath(absPath) + realPath, _, err := index.GetRealPath(indexPath) + if err == nil { + // Clear both the path and the isdir cache entries + indexing.RealPathCache.Delete(realPath) + indexing.RealPathCache.Delete(realPath + ":isdir") + } + refreshConfig := iteminfo.FileOptions{Path: index.MakeIndexPath(absDirPath), IsDir: true} err = index.RefreshFileInfo(refreshConfig) if err != nil { @@ -218,7 +241,7 @@ func DeleteFiles(source, absPath string, absDirPath string) error { return nil } -func RefreshIndex(source string, path string, isDir bool) error { +func RefreshIndex(source string, path string, isDir bool, recursive bool) error { idx := indexing.GetIndex(source) if idx == nil { return fmt.Errorf("could not get index: %v ", source) @@ -227,7 +250,7 @@ func RefreshIndex(source string, path string, isDir bool) error { return nil } path = idx.MakeIndexPath(path) - return idx.RefreshFileInfo(iteminfo.FileOptions{Path: path, IsDir: isDir}) + return idx.RefreshFileInfo(iteminfo.FileOptions{Path: path, IsDir: isDir, Recursive: recursive}) } // validateMoveDestination checks if a move/rename operation is valid @@ -269,21 +292,47 @@ func MoveResource(isSrcDir, isDestDir bool, sourceIndex, destIndex, realsrc, rea if err != nil { return err } - go RefreshIndex(sourceIndex, realsrc, isSrcDir) //nolint:errcheck - go RefreshIndex(destIndex, realdst, isDestDir) //nolint:errcheck - // update shares - idx := indexing.GetIndex(sourceIndex) - if idx == nil { - return fmt.Errorf("could not get index: %v ", sourceIndex) + // For move operations: + // 1. Delete the source from the index (recursively if it's a directory) + // 2. Recursively index the destination to capture the entire moved tree + + // Get indexes for deletion and refresh operations + srcIdx := indexing.GetIndex(sourceIndex) + if srcIdx == nil { + return fmt.Errorf("could not get source index: %v", sourceIndex) } - idx2 := indexing.GetIndex(destIndex) - if idx2 == nil { - return fmt.Errorf("could not get index: %v ", destIndex) + dstIdx := indexing.GetIndex(destIndex) + if dstIdx == nil { + return fmt.Errorf("could not get destination index: %v", destIndex) } + // Delete from source index (recursively for directories) + go srcIdx.DeleteMetadata(realsrc, isSrcDir, isSrcDir) //nolint:errcheck + + // Clear RealPathCache entries for the moved path to prevent cache issues + // when a file/folder with the same name is created later + srcIndexPath := srcIdx.MakeIndexPath(realsrc) + srcRealPath, _, err := srcIdx.GetRealPath(srcIndexPath) + if err == nil { + // Clear both the path and the isdir cache entries + indexing.RealPathCache.Delete(srcRealPath) + indexing.RealPathCache.Delete(srcRealPath + ":isdir") + } + + // For move operations, refresh the parent directory to capture the moved file + refreshPath := realdst + refreshIsDir := isDestDir + if !isSrcDir { + // If moving a file (regardless of destination), refresh the parent directory + refreshPath = filepath.Dir(realdst) + refreshIsDir = true + } + + go RefreshIndex(destIndex, refreshPath, refreshIsDir, true) //nolint:errcheck + // Use backend source paths to match how shares are stored - go s.UpdateShares(idx.Path, idx.MakeIndexPath(realsrc), idx2.Path, idx2.MakeIndexPath(realdst)) //nolint:errcheck + go s.UpdateShares(srcIdx.Path, srcIdx.MakeIndexPath(realsrc), dstIdx.Path, dstIdx.MakeIndexPath(realdst)) //nolint:errcheck return nil } @@ -297,9 +346,31 @@ func CopyResource(isSrcDir, isDestDir bool, sourceIndex, destIndex, realsrc, rea if err != nil { return err } - go RefreshIndex(sourceIndex, realsrc, isSrcDir) //nolint:errcheck - go RefreshIndex(destIndex, realdst, isDestDir) //nolint:errcheck - // update shares + + // For copy operations: + // 1. Shallow refresh of source (just to update access times if needed) + // 2. Recursively index the destination to capture the entire copied tree + + // Refresh source (parent directory if it's a file) + srcRefreshPath := realsrc + srcRefreshIsDir := isSrcDir + if !isSrcDir { + srcRefreshPath = filepath.Dir(realsrc) + srcRefreshIsDir = true + } + + go RefreshIndex(sourceIndex, srcRefreshPath, srcRefreshIsDir, false) //nolint:errcheck + + // Refresh destination (parent directory if it's a file) + dstRefreshPath := realdst + dstRefreshIsDir := isDestDir + if !isSrcDir { + // If copying a file (regardless of destination), refresh the parent directory + dstRefreshPath = filepath.Dir(realdst) + dstRefreshIsDir = true + } + + go RefreshIndex(destIndex, dstRefreshPath, dstRefreshIsDir, true) //nolint:errcheck return nil } @@ -309,12 +380,31 @@ func WriteDirectory(opts iteminfo.FileOptions) error { return fmt.Errorf("could not get index: %v ", opts.Source) } realPath, _, _ := idx.GetRealPath(opts.Path) + + var stat os.FileInfo + var err error + // Check if the destination exists and is a file + if stat, err = os.Stat(realPath); err == nil && !stat.IsDir() { + // If it's a file and we're trying to create a directory, remove the file first + err = os.Remove(realPath) + if err != nil { + return fmt.Errorf("could not remove existing file to create directory: %v", err) + } + // Clear the cache for the removed file + indexPath := idx.MakeIndexPath(opts.Path) + realPath, _, err = idx.GetRealPath(indexPath) + if err == nil { + indexing.RealPathCache.Delete(realPath) + indexing.RealPathCache.Delete(realPath + ":isdir") + } + } + // Ensure the parent directories exist - err := os.MkdirAll(realPath, fileutils.PermDir) + err = os.MkdirAll(realPath, fileutils.PermDir) if err != nil { return err } - return RefreshIndex(idx.Name, opts.Path, true) + return RefreshIndex(idx.Name, opts.Path, true, true) } func WriteFile(opts iteminfo.FileOptions, in io.Reader) error { @@ -322,14 +412,31 @@ func WriteFile(opts iteminfo.FileOptions, in io.Reader) error { if idx == nil { return fmt.Errorf("could not get index: %v ", opts.Source) } - dst, _, _ := idx.GetRealPath(opts.Path) + realPath, _, _ := idx.GetRealPath(opts.Path) // Ensure the parent directories exist - err := os.MkdirAll(filepath.Dir(dst), fileutils.PermDir) + err := os.MkdirAll(filepath.Dir(realPath), fileutils.PermDir) if err != nil { return err } + var stat os.FileInfo + // Check if the destination exists and is a directory + if stat, err = os.Stat(realPath); err == nil && stat.IsDir() { + // If it's a directory and we're trying to create a file, remove the directory first + err = os.RemoveAll(realPath) + if err != nil { + return fmt.Errorf("could not remove existing directory to create file: %v", err) + } + // Clear the cache for the removed directory + indexPath := idx.MakeIndexPath(opts.Path) + realPath, _, err = idx.GetRealPath(indexPath) + if err == nil { + indexing.RealPathCache.Delete(realPath) + indexing.RealPathCache.Delete(realPath + ":isdir") + } + } + // Open the file for writing (create if it doesn't exist, truncate if it does) - file, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileutils.PermFile) + file, err := os.OpenFile(realPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileutils.PermFile) if err != nil { return err } @@ -340,7 +447,7 @@ func WriteFile(opts iteminfo.FileOptions, in io.Reader) error { if err != nil { return err } - return RefreshIndex(opts.Source, opts.Path, false) + return RefreshIndex(opts.Source, opts.Path, false, false) } // getContent reads and returns the file content if it's considered an editable text file. diff --git a/backend/adapters/fs/files/mime.go b/backend/adapters/fs/files/mime.go index 1782fb727b..5d7d8b8489 100644 --- a/backend/adapters/fs/files/mime.go +++ b/backend/adapters/fs/files/mime.go @@ -590,10 +590,11 @@ var types = map[string]string{ ".xpi": "application/x-xpinstall", ".wasm": "application/wasm", ".m4a": "audio/mp4", - ".flac": "audio/x-flac", + ".flac": "audio/flac", ".amr": "audio/amr", ".aac": "audio/aac", - ".opus": "video/ogg", + ".opus": "audio/ogg", // https://wiki.xiph.org/MIME_Types_and_File_Extensions + ".ogx": "application/ogg", ".m4v": "video/mp4", ".mkv": "video/x-matroska", ".caf": "audio/x-caf", diff --git a/backend/common/settings/config.go b/backend/common/settings/config.go index 9b96219863..2fb5146392 100644 --- a/backend/common/settings/config.go +++ b/backend/common/settings/config.go @@ -412,10 +412,10 @@ func setDefaults(generate bool) Settings { }, }, } - // set default image preview types + // Initialize ImagePreview map with all supported types set to false by default s.Integrations.Media.Convert.ImagePreview = make(map[ImagePreviewType]bool) for _, t := range AllImagePreviewTypes { - s.Integrations.Media.Convert.ImagePreview[t] = (t == HEICImagePreview) // default is heic + s.Integrations.Media.Convert.ImagePreview[t] = false } return s } @@ -562,10 +562,10 @@ func loadCustomFavicon() { // Validate file format based on extension ext := strings.ToLower(filepath.Ext(faviconPath)) switch ext { - case ".ico", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp": + case ".ico", ".png", ".svg": // Valid favicon formats default: - logger.Warningf("Unsupported favicon format '%v', supported formats: .ico, .png, .jpg, .gif, .svg, .webp", ext) + logger.Warningf("Unsupported favicon format '%v', supported formats: .ico, .png, .svg", ext) Config.Frontend.Favicon = "" // Unset invalid path return } diff --git a/backend/common/settings/generator.go b/backend/common/settings/generator.go index 694fb57c09..1357899564 100644 --- a/backend/common/settings/generator.go +++ b/backend/common/settings/generator.go @@ -542,6 +542,11 @@ func buildNodeWithDefaults(v reflect.Value, comm CommentsMap, defaults reflect.V } mapNode := &yaml.Node{Kind: yaml.MappingNode} + // Special handling for ImagePreview maps - show all supported types + if isImagePreviewMap(v) { + return buildImagePreviewMap(v, comm, secrets, deprecated) + } + for _, key := range v.MapKeys() { // Handle key keyStr := fmt.Sprintf("%v", key.Interface()) @@ -866,3 +871,53 @@ func AlignComments(input string) string { return strings.Join(outputLines, "\n") } + +// isImagePreviewMap checks if the given map is an ImagePreview map +func isImagePreviewMap(v reflect.Value) bool { + if v.Kind() != reflect.Map { + return false + } + + // Check if the map key type is ImagePreviewType + keyType := v.Type().Key() + return keyType.Name() == "ImagePreviewType" +} + +// buildImagePreviewMap builds a YAML node for ImagePreview maps, showing all supported types +func buildImagePreviewMap(v reflect.Value, comm CommentsMap, secrets SecretFieldsMap, deprecated DeprecatedFieldsMap) (*yaml.Node, error) { + mapNode := &yaml.Node{Kind: yaml.MappingNode} + + // Get all supported image preview types from the global slice + for _, imageType := range AllImagePreviewTypes { + typeName := string(imageType) + + // Create key node + keyNode := &yaml.Node{ + Kind: yaml.ScalarNode, + Value: typeName, + } + + // Get the value from the map, defaulting to false if not present + var value bool + if v.Len() > 0 { + // Look for the key in the map + for _, mapKey := range v.MapKeys() { + if mapKey.String() == typeName { + value = v.MapIndex(mapKey).Bool() + break + } + } + } + + // Create value node + valNode := &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!bool", + Value: fmt.Sprintf("%t", value), + } + + mapNode.Content = append(mapNode.Content, keyNode, valNode) + } + + return mapNode, nil +} diff --git a/backend/common/settings/settings.go b/backend/common/settings/settings.go index 19fe5ced1e..b85a701736 100644 --- a/backend/common/settings/settings.go +++ b/backend/common/settings/settings.go @@ -14,7 +14,7 @@ type AuthMethod string // GenerateKey generates a key of 512 bits. func GenerateKey() ([]byte, error) { - b := make([]byte, 64) //nolint:gomnd + b := make([]byte, 64) _, err := rand.Read(b) // Note that err == nil only if we read len(b) bytes. if err != nil { diff --git a/backend/common/settings/structs.go b/backend/common/settings/structs.go index fa27c426fa..54f0095673 100644 --- a/backend/common/settings/structs.go +++ b/backend/common/settings/structs.go @@ -74,6 +74,7 @@ type ImagePreviewType string const ( HEICImagePreview ImagePreviewType = "heic" + //RAWImagePreview ImagePreviewType = "raw" ) func (i ImagePreviewType) String() string { @@ -83,6 +84,7 @@ func (i ImagePreviewType) String() string { // AllImagePreviewTypes contains all supported image preview types. var AllImagePreviewTypes = []ImagePreviewType{ HEICImagePreview, + //RAWImagePreview, } type LogConfig struct { @@ -113,7 +115,7 @@ type SourceConfig struct { DefaultUserScope string `json:"defaultUserScope"` // default "/" should match folders under path DefaultEnabled bool `json:"defaultEnabled"` // should be added as a default source for new users? CreateUserDir bool `json:"createUserDir"` // create a user directory for each user - IndexAlbumArt bool `json:"indexAlbumArt"` // check for album art in audio files and remember it for folder previews. Can slow down indexing. + IndexAlbumArt bool `json:"indexAlbumArt"` // deprecated: always enabled since 0.8.6 } type IncludeIndexFilter struct { diff --git a/backend/database/share/extended.go b/backend/database/share/extended.go new file mode 100644 index 0000000000..576ebf0362 --- /dev/null +++ b/backend/database/share/extended.go @@ -0,0 +1,96 @@ +package share + +import ( + "os" + "path/filepath" +) + +// IsSingleFileShare determines if this share is for a single file (not a directory). +// It checks both the file extension and filesystem to determine if the path points to a file. +func (l *Link) IsSingleFileShare() bool { + if l.Path == "" { + return false + } + + // First, check if the path has a file extension (common indicator of a file) + ext := filepath.Ext(l.Path) + if ext != "" { + // If it has an extension, it's likely a file, but let's verify with filesystem + return l.isFileOnFilesystem() + } + + // If no extension, check if it's a directory by looking at the filesystem + return !l.isDirectoryOnFilesystem() +} + +// isFileOnFilesystem checks if the path exists and is a file on the filesystem +func (l *Link) isFileOnFilesystem() bool { + // Construct the full path using Source and Path + fullPath := l.Path + if l.Source != "" { + // If Source is provided, it might be a relative path from the source + fullPath = filepath.Join(l.Source, l.Path) + } + + info, err := os.Stat(fullPath) + if err != nil { + // If we can't stat the file, fall back to extension check + return filepath.Ext(l.Path) != "" + } + + return !info.IsDir() +} + +// isDirectoryOnFilesystem checks if the path exists and is a directory on the filesystem +func (l *Link) isDirectoryOnFilesystem() bool { + // Construct the full path using Source and Path + fullPath := l.Path + if l.Source != "" { + // If Source is provided, it might be a relative path from the source + fullPath = filepath.Join(l.Source, l.Path) + } + + info, err := os.Stat(fullPath) + if err != nil { + // If we can't stat the file, assume it's a file if it has an extension + return filepath.Ext(l.Path) == "" + } + + return info.IsDir() +} + +// IsExpired checks if the share has expired based on the Expire timestamp +func (l *Link) IsExpired() bool { + if l.Expire == 0 { + return false // No expiration set + } + // This would need time.Now().Unix() but we avoid importing time here + // The actual expiration check is handled in the storage layer + return false // Placeholder - actual implementation would check current time +} + +// HasPassword checks if the share is password protected +func (l *Link) HasPassword() bool { + return l.PasswordHash != "" +} + +// IsPermanent checks if the share is permanent (no expiration) +func (l *Link) IsPermanent() bool { + return l.Expire == 0 +} + +// GetFileExtension returns the file extension of the shared file +func (l *Link) GetFileExtension() string { + if l.Path == "" { + return "" + } + return filepath.Ext(l.Path) +} + +// GetFileName returns just the filename (without path) of the shared item +func (l *Link) GetFileName() string { + if l.Path == "" { + return "" + } + return filepath.Base(l.Path) +} diff --git a/backend/database/storage/storage.go b/backend/database/storage/storage.go index 4011924a45..0e69f6ccf9 100644 --- a/backend/database/storage/storage.go +++ b/backend/database/storage/storage.go @@ -7,6 +7,7 @@ import ( "strings" storm "github.com/asdine/storm/v3" + "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" "github.com/gtsteffaniak/filebrowser/backend/common/settings" "github.com/gtsteffaniak/filebrowser/backend/common/utils" "github.com/gtsteffaniak/filebrowser/backend/database/storage/bolt" @@ -57,7 +58,7 @@ func dbExists(path string) (bool, error) { d := filepath.Dir(path) _, err = os.Stat(d) if os.IsNotExist(err) { - if err := os.MkdirAll(d, 0700); err != nil { //nolint:govet,gomnd + if err = os.MkdirAll(d, fileutils.PermDir); err != nil { return false, err } return false, nil diff --git a/backend/ffmpeg/image.go b/backend/ffmpeg/image.go index eba428e26e..657cff208e 100644 --- a/backend/ffmpeg/image.go +++ b/backend/ffmpeg/image.go @@ -8,6 +8,8 @@ import ( "path/filepath" "strconv" "strings" + + "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" ) // ImageService handles image operations with ffmpeg @@ -154,7 +156,7 @@ func (s *ImageService) ConvertHEICToJPEGDirect(heicPath string, targetWidth, tar // Create temporary output file outputDir := s.cacheDir - err = os.MkdirAll(outputDir, 0755) + err = os.MkdirAll(outputDir, fileutils.PermDir) if err != nil { return nil, fmt.Errorf("failed to create cache directory: %w", err) } @@ -208,7 +210,7 @@ func (s *ImageService) ConvertHEICToJPEG(heicPath string, targetWidth, targetHei // Create temporary directory for tile processing outputDir := s.cacheDir tempDir := filepath.Join(outputDir, fmt.Sprintf("heic_tiles_%d", os.Getpid())) - err := os.MkdirAll(tempDir, 0755) + err := os.MkdirAll(tempDir, fileutils.PermDir) if err != nil { return nil, fmt.Errorf("failed to create temp directory: %w", err) } diff --git a/backend/http/httpRouter.go b/backend/http/httpRouter.go index ded3922984..2ee23ec66d 100644 --- a/backend/http/httpRouter.go +++ b/backend/http/httpRouter.go @@ -137,6 +137,7 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch publicAPI.HandleFunc("GET /resources", withHashFile(publicShareHandler)) publicAPI.HandleFunc("GET /users", withUser(userGetHandler)) publicAPI.HandleFunc("POST /onlyoffice/callback", withHashFile(onlyofficeCallbackHandler)) + publicAPI.HandleFunc("GET /onlyoffice/callback", withHashFile(onlyofficeCallbackHandler)) publicAPI.HandleFunc("GET /onlyoffice/config", withHashFile(onlyofficeClientConfigGetHandler)) // Settings routes @@ -153,6 +154,7 @@ func StartHttp(ctx context.Context, storage *bolt.BoltStore, shutdownComplete ch api.HandleFunc("GET /onlyoffice/config", withUser(onlyofficeClientConfigGetHandler)) api.HandleFunc("POST /onlyoffice/callback", withUser(onlyofficeCallbackHandler)) + api.HandleFunc("GET /onlyoffice/callback", withUser(onlyofficeCallbackHandler)) api.HandleFunc("GET /search", withUser(searchHandler)) // Mount the public API sub-router diff --git a/backend/http/onlyOffice.go b/backend/http/onlyOffice.go index 4d5631a3a5..72d966f792 100644 --- a/backend/http/onlyOffice.go +++ b/backend/http/onlyOffice.go @@ -1,6 +1,7 @@ package http import ( + "encoding/base64" "encoding/json" "errors" "fmt" @@ -35,6 +36,17 @@ type OnlyOfficeCallback struct { UserData string `json:"userdata,omitempty"` } +// OnlyOfficeJWTPayload represents the JWT payload structure for OnlyOffice callbacks +type OnlyOfficeJWTPayload struct { + Key string `json:"key"` + Status int `json:"status"` + Users []string `json:"users"` + Actions []struct { + Type int `json:"type"` + UserID string `json:"userid"` + } `json:"actions"` +} + func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { if settings.Config.Integrations.OnlyOffice.Url == "" { return http.StatusInternalServerError, errors.New("only-office integration must be configured in settings") @@ -179,7 +191,10 @@ func buildOnlyOfficeDownloadURL(source, path, hash, token string) string { // Determine base URL (internal URL takes priority for OnlyOffice server communication) baseURL := settings.Config.Server.BaseURL if settings.Config.Server.InternalUrl != "" { - baseURL = settings.Config.Server.InternalUrl + settings.Config.Server.BaseURL + // Ensure proper URL joining without double slashes + internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/") + baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/") + baseURL = internalURL + "/" + baseURLPath } var downloadURL string @@ -202,7 +217,10 @@ func buildOnlyOfficeDownloadURL(source, path, hash, token string) string { func buildOnlyOfficeCallbackURL(source, path, hash, token string) string { baseURL := settings.Config.Server.BaseURL if settings.Config.Server.InternalUrl != "" { - baseURL = settings.Config.Server.InternalUrl + settings.Config.Server.BaseURL + // Ensure proper URL joining without double slashes + internalURL := strings.TrimSuffix(settings.Config.Server.InternalUrl, "/") + baseURLPath := strings.TrimPrefix(settings.Config.Server.BaseURL, "/") + baseURL = internalURL + "/" + baseURLPath } var callbackURL string @@ -229,21 +247,8 @@ func buildOnlyOfficeCallbackURL(source, path, hash, token string) string { return callbackURL } -func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { - // Parse OnlyOffice callback data - body, err := io.ReadAll(r.Body) - if err != nil { - logger.Errorf("OnlyOffice callback: failed to read request body: %v", err) - return http.StatusInternalServerError, err - } - - var data OnlyOfficeCallback - err = json.Unmarshal(body, &data) - if err != nil { - logger.Errorf("OnlyOffice callback: failed to parse JSON: %v", err) - return http.StatusInternalServerError, err - } - +// processOnlyOfficeCallback handles the common callback processing logic for both GET and POST requests +func processOnlyOfficeCallback(w http.ResponseWriter, r *http.Request, d *requestContext, data *OnlyOfficeCallback) (int, error) { // Extract clean parameters from query string source := r.URL.Query().Get("source") path := r.URL.Query().Get("path") @@ -291,7 +296,6 @@ func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *reques // // When the document is fully closed by all editors, // the document key should no longer be re-used. - logger.Debugf("OnlyOffice: document closed, cleaning up document ID for source=%s, path=%s", source, path) deleteOfficeId(source, path) } @@ -347,6 +351,61 @@ func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *reques return renderJSON(w, r, resp) } +func onlyofficeCallbackHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) { + // Parse callback data based on request method + var callbackData *OnlyOfficeCallback + var err error + + if r.Method == "GET" { + // OnlyOffice sends callback data in Authorization header as JWT + callbackData, err = parseOnlyOfficeCallbackFromJWT(r) + } else if r.Method == "POST" { + // OnlyOffice sends callback data in request body as JSON + callbackData, err = parseOnlyOfficeCallbackFromJSON(r) + } else { + return http.StatusMethodNotAllowed, fmt.Errorf("unsupported method: %s", r.Method) + } + + if err != nil { + logger.Errorf("OnlyOffice callback: failed to parse callback data: %v", err) + return http.StatusBadRequest, err + } + + // Process the callback data using shared logic + return processOnlyOfficeCallback(w, r, d, callbackData) +} + +// parseOnlyOfficeCallbackFromJWT extracts callback data from JWT in Authorization header +func parseOnlyOfficeCallbackFromJWT(r *http.Request) (*OnlyOfficeCallback, error) { + authHeader := r.Header.Get("Authorization") + if authHeader == "" { + return nil, errors.New("missing Authorization header") + } + + if !strings.HasPrefix(authHeader, "Bearer ") { + return nil, errors.New("invalid Authorization header format") + } + + jwtToken := strings.TrimPrefix(authHeader, "Bearer ") + + return parseOnlyOfficeJWT(jwtToken) +} + +// parseOnlyOfficeCallbackFromJSON extracts callback data from JSON request body +func parseOnlyOfficeCallbackFromJSON(r *http.Request) (*OnlyOfficeCallback, error) { + body, err := io.ReadAll(r.Body) + if err != nil { + return nil, fmt.Errorf("failed to read request body: %v", err) + } + var data OnlyOfficeCallback + err = json.Unmarshal(body, &data) + if err != nil { + return nil, fmt.Errorf("failed to parse JSON: %v", err) + } + + return &data, nil +} + func getOnlyOfficeId(realpath string) (string, error) { // error is intentionally ignored in order treat errors // the same as a cache-miss @@ -366,3 +425,71 @@ func deleteOfficeId(source, path string) { realpath, _, _ := idx.GetRealPath(path) utils.OnlyOfficeCache.Delete(realpath) } + +// parseOnlyOfficeJWT parses the JWT token from OnlyOffice callback +func parseOnlyOfficeJWT(tokenString string) (*OnlyOfficeCallback, error) { + // Parse the JWT token without signature verification since OnlyOffice uses different signing + // We'll parse it manually to avoid signature validation issues + parts := strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, fmt.Errorf("invalid JWT format") + } + + // Decode the payload (second part) with fallback to standard base64 + payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + // Fallback to standard base64 decoding + payloadBytes, err = base64.StdEncoding.DecodeString(parts[1]) + if err != nil { + return nil, fmt.Errorf("failed to decode JWT payload: %v", err) + } + } + + var claims jwt.MapClaims + err = json.Unmarshal(payloadBytes, &claims) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal JWT claims: %v", err) + } + + // Extract payload from claims with fallback + payload, ok := claims["payload"].(map[string]interface{}) + if !ok { + // Fallback: try to use claims directly if no payload wrapper + payload = map[string]interface{}(claims) + } + + // Convert to OnlyOfficeCallback struct with safe type assertions + callback := &OnlyOfficeCallback{} + + // Extract key with validation + if key, ok := payload["key"].(string); ok && key != "" { + callback.Key = key + } else { + logger.Warningf("OnlyOffice callback: missing or empty key in JWT payload") + } + + // Extract status with validation + if status, ok := payload["status"].(float64); ok { + callback.Status = int(status) + } else { + logger.Warningf("OnlyOffice callback: missing or invalid status in JWT payload") + callback.Status = 0 // Default to unknown status + } + + // Extract users with safe array handling + if users, ok := payload["users"].([]interface{}); ok { + callback.Users = make([]string, 0, len(users)) + for _, user := range users { + if userStr, ok := user.(string); ok && userStr != "" { + callback.Users = append(callback.Users, userStr) + } + } + } + + // Validate essential fields + if callback.Key == "" { + return nil, fmt.Errorf("missing document key in JWT payload") + } + + return callback, nil +} diff --git a/backend/http/preview.go b/backend/http/preview.go index 8ea073e3a4..6c166af261 100644 --- a/backend/http/preview.go +++ b/backend/http/preview.go @@ -7,6 +7,7 @@ import ( "net/http" "net/url" "os" + "path/filepath" "strconv" "strings" @@ -97,8 +98,8 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext if !(previewSize == "large" || previewSize == "original") { previewSize = "small" } - if d.fileInfo.Type == "directory" && !d.fileInfo.HasPreview { - return http.StatusBadRequest, fmt.Errorf("this folder does not have a preview") + if !d.fileInfo.HasPreview { + return http.StatusBadRequest, fmt.Errorf("this item does not have a preview") } if d.fileInfo.Type == "directory" { // get extended file info of first previewable item in directory @@ -132,16 +133,11 @@ func previewHelperFunc(w http.ResponseWriter, r *http.Request, d *requestContext setContentDisposition(w, r, d.fileInfo.Name) isImage := strings.HasPrefix(d.fileInfo.Type, "image") - if config.Server.DisableResize && isImage { + ext := strings.ToLower(filepath.Ext(d.fileInfo.Name)) + resizable := iteminfo.ResizableImageTypes[ext] + if (!resizable || config.Server.DisableResize) && isImage { return rawFileHandler(w, r, d.fileInfo) } - - if !d.fileInfo.HasPreview { - if isImage { - return rawFileHandler(w, r, d.fileInfo) - } - return http.StatusNotImplemented, fmt.Errorf("can't create preview for %s type", d.fileInfo.Type) - } seekPercentage := 0 percentage := r.URL.Query().Get("atPercentage") if percentage != "" { diff --git a/backend/http/raw.go b/backend/http/raw.go index a9001f7a5e..3b2f34a3ba 100644 --- a/backend/http/raw.go +++ b/backend/http/raw.go @@ -15,6 +15,7 @@ import ( "strings" "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/files" + "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" "github.com/gtsteffaniak/filebrowser/backend/common/settings" "github.com/gtsteffaniak/filebrowser/backend/common/utils" "github.com/gtsteffaniak/filebrowser/backend/indexing" @@ -160,7 +161,7 @@ func addFile(path string, d *requestContext, tarWriter *tar.Writer, zipWriter *z if tarWriter != nil { header := &tar.Header{ Name: relPath + "/", - Mode: 0755, + Mode: fileutils.PermDir, Typeflag: tar.TypeDir, ModTime: fileInfo.ModTime(), } diff --git a/backend/http/resource.go b/backend/http/resource.go index f70c4f8e85..fd3065a592 100644 --- a/backend/http/resource.go +++ b/backend/http/resource.go @@ -284,12 +284,12 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte // Use a temporary file in the cache directory for chunks. // Create a unique name for the temporary file to avoid collisions. - hasher := md5.New() //nolint:gosec + hasher := md5.New() hasher.Write([]byte(realPath)) uploadID := hex.EncodeToString(hasher.Sum(nil)) tempFilePath := filepath.Join(settings.Config.Server.CacheDir, "uploads", uploadID) - if err = os.MkdirAll(filepath.Dir(tempFilePath), 0755); err != nil { + if err = os.MkdirAll(filepath.Dir(tempFilePath), fileutils.PermDir); err != nil { logger.Debugf("could not create temp dir: %v", err) return http.StatusInternalServerError, fmt.Errorf("could not create temp dir: %v", err) } @@ -326,7 +326,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte logger.Debugf("could not move temp file to destination: %v", err) return http.StatusInternalServerError, fmt.Errorf("could not move temp file to destination: %v", err) } - go files.RefreshIndex(source, realPath, false) //nolint:errcheck + go files.RefreshIndex(source, realPath, false, false) //nolint:errcheck } return http.StatusOK, nil diff --git a/backend/http/share.go b/backend/http/share.go index c44fe6c61c..de61a184fb 100644 --- a/backend/http/share.go +++ b/backend/http/share.go @@ -176,8 +176,8 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) var expire int64 = 0 if body.Expires != "" { - //nolint:govet - num, err := strconv.Atoi(body.Expires) + var num int + num, err = strconv.Atoi(body.Expires) if err != nil { return http.StatusInternalServerError, err } @@ -204,7 +204,7 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext) stringHash := "" var token string if len(hash) > 0 { - tokenBuffer := make([]byte, 24) //nolint:gomnd + tokenBuffer := make([]byte, 24) if _, err = rand.Read(tokenBuffer); err != nil { return http.StatusInternalServerError, err } diff --git a/backend/http/static.go b/backend/http/static.go index f61e30830c..ce28479318 100644 --- a/backend/http/static.go +++ b/backend/http/static.go @@ -92,6 +92,7 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont shareProps["hash"] = d.share.Hash if d.shareValid { + shareProps["singleFileShare"] = d.share.IsSingleFileShare() disableNavButtons = disableNavButtons || d.share.HideNavButtons shareProps["viewMode"] = d.share.ViewMode shareProps["banner"] = d.share.Banner @@ -109,6 +110,12 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, d *requestCont shareProps["viewMode"] = d.share.ViewMode shareProps["enableOnlyOffice"] = d.share.EnableOnlyOffice shareProps["enableOnlyOfficeEditing"] = d.share.EnableOnlyOfficeEditing + + // Additional computed properties from extended.go + shareProps["hasPassword"] = d.share.HasPassword() + shareProps["isPermanent"] = d.share.IsPermanent() + shareProps["fileExtension"] = d.share.GetFileExtension() + shareProps["fileName"] = d.share.GetFileName() if d.share.Favicon != "" { if strings.HasPrefix(d.share.Favicon, "http") { data["favicon"] = d.share.Favicon diff --git a/backend/indexing/indexingFiles.go b/backend/indexing/indexingFiles.go index f5d781cbce..06d13b51a1 100644 --- a/backend/indexing/indexingFiles.go +++ b/backend/indexing/indexingFiles.go @@ -20,6 +20,20 @@ import ( var RealPathCache = cache.NewCache(48*time.Hour, 72*time.Hour) +// actionConfig holds all configuration options for indexing operations +type actionConfig struct { + Quick bool // whether to perform a quick scan (skip unchanged directories) + Recursive bool // whether to recursively index subdirectories +} + +// NewactionConfig creates a new actionConfig with common presets +func NewactionConfig() *actionConfig { + return &actionConfig{ + Quick: false, + Recursive: true, + } +} + // reduced index is json exposed to the client type ReducedIndex struct { IdxName string `json:"name"` @@ -100,8 +114,13 @@ func Initialize(source settings.Source, mock bool) { } } +// indexDirectoryWithOptions wraps indexDirectory with actionConfig +func (idx *Index) indexDirectoryWithOptions(adjustedPath string, config *actionConfig) error { + return idx.indexDirectory(adjustedPath, config) +} + // Define a function to recursively index files and directories -func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) error { +func (idx *Index) indexDirectory(adjustedPath string, config *actionConfig) error { realPath := strings.TrimRight(idx.Path, "/") + adjustedPath // Open the directory dir, err := os.Open(realPath) @@ -123,7 +142,7 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err } // if indexing, mark the directory as valid and indexed. - if recursive { + if config.Recursive { // Prevent race conditions if scanning becomes concurrent in the future. idx.mu.Lock() idx.DirectoriesLedger[adjustedPath] = struct{}{} @@ -146,14 +165,18 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err // If the directory has not been modified since the last index, skip expensive readdir // recursively check cached dirs for mod time changes as well - if recursive { + if config.Recursive { if modChange { idx.mu.Lock() idx.FilesChangedDuringIndexing = true idx.mu.Unlock() - } else if quick { + } else if config.Quick { for _, item := range cacheDirItems { - err = idx.indexDirectory(combinedPath+item.Name, quick, true) + subConfig := &actionConfig{ + Quick: config.Quick, + Recursive: true, + } + err = idx.indexDirectory(combinedPath+item.Name, subConfig) if err != nil && err != errors.ErrNotIndexed { logger.Errorf("error indexing directory %v : %v", combinedPath+item.Name, err) } @@ -161,7 +184,7 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err return nil } } - dirFileInfo, err2 := idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, quick, recursive, true) + dirFileInfo, err2 := idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, config) if err2 != nil { return err2 } @@ -205,7 +228,10 @@ func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error) combinedPath = "/" } var response *iteminfo.FileInfo - response, err = idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, false, false, false) + response, err = idx.GetDirInfo(dir, dirInfo, realPath, adjustedPath, combinedPath, &actionConfig{ + Quick: false, + Recursive: false, + }) if err != nil { return nil, err } @@ -232,7 +258,7 @@ func (idx *Index) GetFsDirInfo(adjustedPath string) (*iteminfo.FileInfo, error) } -func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjustedPath, combinedPath string, quick, recursive, checkSkip bool) (*iteminfo.FileInfo, error) { +func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjustedPath, combinedPath string, config *actionConfig) (*iteminfo.FileInfo, error) { // Read directory contents files, err := dirInfo.Readdir(-1) if err != nil { @@ -242,7 +268,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus fileInfos := []iteminfo.ItemInfo{} dirInfos := []iteminfo.ItemInfo{} hasPreview := false - if !recursive { + if !config.Recursive { realDirInfo, exists := idx.GetMetadataInfo(adjustedPath, true) if exists { hasPreview = realDirInfo.HasPreview @@ -260,7 +286,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus continue } } - if checkSkip && idx.shouldSkip(isDir, hidden, fullCombined, baseName) { + if idx.shouldSkip(isDir, hidden, fullCombined, baseName) { continue } itemInfo := &iteminfo.ItemInfo{ @@ -271,7 +297,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus if isDir { dirPath := combinedPath + file.Name() - if idx.hasIndex && recursive && len(idx.Config.NeverWatchPaths) > 0 { + if idx.hasIndex && config.Recursive && len(idx.Config.NeverWatchPaths) > 0 { if slices.Contains(idx.Config.NeverWatchPaths, fullCombined) { realDirInfo, exists := idx.GetMetadataInfo(dirPath, true) if exists { @@ -285,11 +311,11 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus continue } - if recursive { + if config.Recursive { // clear for garbage collection file = nil // Recursively index the subdirectory - err = idx.indexDirectory(dirPath, quick, recursive) + err = idx.indexDirectory(dirPath, config) if err != nil { logger.Errorf("Failed to index directory %s: %v", dirPath, err) continue @@ -303,7 +329,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus totalSize += itemInfo.Size itemInfo.Type = "directory" dirInfos = append(dirInfos, *itemInfo) - if recursive { + if config.Recursive { idx.NumDirs++ } } else { @@ -311,14 +337,22 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus itemInfo.DetectType(realPath+"/"+file.Name(), false) simpleType := strings.Split(itemInfo.Type, "/")[0] if simpleType == "audio" { - if recursive && !quick && idx.Config.IndexAlbumArt { - itemInfo.HasPreview = iteminfo.HasAlbumArt(realPath+"/"+file.Name(), filepath.Ext(file.Name())) + // Check if this file is new or changed by comparing with previous metadata + shouldCheckAlbumArt := false + previousInfo, exists := idx.GetReducedMetadata(fullCombined, false) + if !exists { + // File is new - check album art + shouldCheckAlbumArt = true + } else if previousInfo.ModTime != file.ModTime() { + // File has been modified - check album art + shouldCheckAlbumArt = true + } else { + // File unchanged - use cached album art info + itemInfo.HasPreview = previousInfo.HasPreview } - if !recursive && !itemInfo.HasPreview { - info, exists := idx.GetReducedMetadata(fullCombined, false) - if exists { - itemInfo.HasPreview = info.HasPreview - } + + if shouldCheckAlbumArt { + itemInfo.HasPreview = iteminfo.HasAlbumArt(realPath+"/"+file.Name(), filepath.Ext(file.Name())) } } ext := strings.ToLower(filepath.Ext(file.Name())) @@ -338,16 +372,8 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus } itemInfo.Size = int64(size) - fileInfos = append(fileInfos, *itemInfo) - if shouldCountSize { - totalSize += itemInfo.Size - } - if recursive { - idx.NumFiles++ - } - if itemInfo.HasPreview { - hasPreview = true - } + + // Set HasPreview before appending to fileInfos // these don't create preview for parent folders if settings.Config.Integrations.OnlyOffice.Secret != "" && iteminfo.IsOnlyOffice(file.Name()) { itemInfo.HasPreview = true @@ -355,6 +381,17 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus if iteminfo.HasDocConvertableExtension(itemInfo.Name, itemInfo.Type) { itemInfo.HasPreview = true } + + fileInfos = append(fileInfos, *itemInfo) + if shouldCountSize { + totalSize += itemInfo.Size + } + if config.Recursive { + idx.NumFiles++ + } + if itemInfo.HasPreview { + hasPreview = true + } } } @@ -382,6 +419,7 @@ func (idx *Index) GetDirInfo(dirInfo *os.File, stat os.FileInfo, realPath, adjus HasPreview: hasPreview, } dirFileInfo.SortItems() + return dirFileInfo, nil } @@ -441,29 +479,32 @@ func (idx *Index) GetRealPath(relativePath ...string) (string, bool, error) { } func (idx *Index) RefreshFileInfo(opts iteminfo.FileOptions) error { - refreshOptions := iteminfo.FileOptions{ - Path: opts.Path, - IsDir: opts.IsDir, + config := &actionConfig{ + Quick: false, + Recursive: opts.Recursive, } - if !refreshOptions.IsDir { - refreshOptions.Path = idx.MakeIndexPath(filepath.Dir(refreshOptions.Path)) - refreshOptions.IsDir = true + + targetPath := opts.Path + if !opts.IsDir { + targetPath = idx.MakeIndexPath(filepath.Dir(targetPath)) } - err := idx.indexDirectory(refreshOptions.Path, false, false) + + // Use the recursive flag from options - false for quick scan, true for recursive + err := idx.indexDirectoryWithOptions(targetPath, config) if err != nil { return err } - file, exists := idx.GetMetadataInfo(refreshOptions.Path, true) + file, exists := idx.GetMetadataInfo(targetPath, true) if !exists { - return fmt.Errorf("file/folder does not exist in metadata: %s", refreshOptions.Path) + return fmt.Errorf("file/folder does not exist in metadata: %s", targetPath) } - current, firstExisted := idx.GetMetadataInfo(refreshOptions.Path, true) + current, firstExisted := idx.GetMetadataInfo(targetPath, true) refreshParentInfo := firstExisted && current.Size != file.Size //utils.PrintStructFields(*file) result := idx.UpdateMetadata(file) if !result { - return fmt.Errorf("file/folder does not exist in metadata: %s", refreshOptions.Path) + return fmt.Errorf("file/folder does not exist in metadata: %s", targetPath) } if !exists { return nil diff --git a/backend/indexing/indexingSchedule.go b/backend/indexing/indexingSchedule.go index c3812b23cb..15c9cfbe8e 100644 --- a/backend/indexing/indexingSchedule.go +++ b/backend/indexing/indexingSchedule.go @@ -131,6 +131,7 @@ func (idx *Index) RunIndexing(origin string, quick bool) { return } idx.PreScan() + prevNumDirs := idx.NumDirs prevNumFiles := idx.NumFiles if quick { @@ -147,7 +148,11 @@ func (idx *Index) RunIndexing(origin string, quick bool) { startTime := time.Now() idx.FilesChangedDuringIndexing = false // Perform the indexing operation - err := idx.indexDirectory("/", quick, true) + config := &actionConfig{ + Quick: quick, + Recursive: true, + } + err := idx.indexDirectory("/", config) if err != nil { logger.Errorf("Error during indexing: %v", err) } diff --git a/backend/indexing/iteminfo/conditions.go b/backend/indexing/iteminfo/conditions.go index 7cd150e113..5e6a8b7d9a 100644 --- a/backend/indexing/iteminfo/conditions.go +++ b/backend/indexing/iteminfo/conditions.go @@ -1,6 +1,10 @@ package iteminfo import ( + "bytes" + "encoding/binary" + "fmt" + "io" "mime" "net/http" "os" @@ -9,7 +13,6 @@ import ( "strconv" "strings" - "github.com/dhowden/tag" "github.com/gtsteffaniak/filebrowser/backend/common/settings" ) @@ -50,6 +53,15 @@ var MuPdfConvertable = map[string]bool{ ".md": true, // Markdown } +var ResizableImageTypes = map[string]bool{ + ".jpg": true, + ".jpeg": true, + ".png": true, + ".gif": true, + ".bmp": true, + ".other": false, +} + // Known bundle-style extensions that are technically directories but treated as files var BundleExtensions = []string{ ".app", // macOS application bundle @@ -320,31 +332,139 @@ func (i *ItemInfo) DetectType(realPath string, saveContent bool) { } } -// hasAlbumArt efficiently checks if an audio file contains embedded album art. -// It returns true if album art is found, and false otherwise. +// hasAlbumArtLowLevel efficiently checks for album art in audio files. +// It handles ID3v2 tags (MP3) and Vorbis comments (FLAC, OGG) with low-level parsing. +func hasAlbumArtLowLevel(filePath string, extension string) (bool, error) { + file, err := os.Open(filePath) + if err != nil { + return false, fmt.Errorf("failed to open file: %w", err) + } + defer file.Close() + + // Handle different audio formats + switch extension { + case ".mp3": + return hasAlbumArtMP3(file) + case ".flac", ".ogg": + return hasAlbumArtVorbis(file) + case ".m4a", ".mp4": + return hasAlbumArtM4A(file) + default: + // For other formats, return false (no album art detection) + return false, nil + } +} + +// hasAlbumArtMP3 checks for APIC frames in ID3v2 tags +func hasAlbumArtMP3(file *os.File) (bool, error) { + // 1. Read the 10-byte ID3v2 header. + header := make([]byte, 10) + if _, err := io.ReadFull(file, header); err != nil { + return false, nil // No ID3v2 tag found + } + + // 2. Check for the "ID3" identifier. + if string(header[0:3]) != "ID3" { + return false, nil // No ID3v2 tag found + } + + // 3. Decode the tag size. It's a "synchsafe" integer. + tagSize := (int(header[6]) << 21) | (int(header[7]) << 14) | (int(header[8]) << 7) | int(header[9]) + + // 4. Read the entire tag content into a buffer. + tagData := make([]byte, tagSize) + if _, err := io.ReadFull(file, tagData); err != nil { + return false, fmt.Errorf("failed to read tag data: %w", err) + } + + position := 0 + // 5. Loop through the frames within the tag data. + for position < tagSize { + if position+10 > tagSize { + break + } + + frameHeader := tagData[position : position+10] + frameID := string(frameHeader[0:4]) + + // We found it! The APIC frame contains the album art. + if frameID == "APIC" { + return true, nil + } + + // If it's not APIC, find the frame's size to skip over it. + var frameSize uint32 + if err := binary.Read(bytes.NewReader(frameHeader[4:8]), binary.BigEndian, &frameSize); err != nil { + return false, fmt.Errorf("corrupt frame header: %w", err) + } + + // Move position to the next frame header. + position += 10 + int(frameSize) + + // Break if the next frame would start with padding (null bytes). + if position >= tagSize || tagData[position] == 0 { + break + } + } + + return false, nil +} + +// hasAlbumArtVorbis checks for METADATA_BLOCK_PICTURE in Vorbis comments (FLAC, OGG) +func hasAlbumArtVorbis(file *os.File) (bool, error) { + // For FLAC files, look for METADATA_BLOCK_PICTURE in Vorbis comments + // This is a simplified check - in practice, you'd need to parse the FLAC structure + // For now, we'll do a basic search for common picture-related strings + buffer := make([]byte, 8192) // Read first 8KB + n, err := file.Read(buffer) + if err != nil && err != io.EOF { + return false, err + } + + // Look for METADATA_BLOCK_PICTURE or COVERART in the buffer + content := string(buffer[:n]) + if strings.Contains(content, "METADATA_BLOCK_PICTURE") || + strings.Contains(content, "COVERART") || + strings.Contains(content, "COVER_ART") { + return true, nil + } + + return false, nil +} + +// hasAlbumArtM4A checks for embedded artwork in M4A/MP4 files +func hasAlbumArtM4A(file *os.File) (bool, error) { + // For M4A files, look for 'covr' atom which contains artwork + // This is a simplified check - in practice, you'd need to parse the MP4 structure + buffer := make([]byte, 8192) // Read first 8KB + n, err := file.Read(buffer) + if err != nil && err != io.EOF { + return false, err + } + + // Look for 'covr' atom in the buffer + content := string(buffer[:n]) + if strings.Contains(content, "covr") { + return true, nil + } + + return false, nil +} + func HasAlbumArt(filePath string, extension string) bool { if !CouldHaveAlbumArt(extension) { return false } - file, err := os.Open(filePath) - if err != nil { - return false - } - defer file.Close() - // Read metadata from the file. - m, err := tag.ReadFrom(file) + // Use low-level detection for all audio formats + hasArt, err := hasAlbumArtLowLevel(filePath, extension) if err != nil { - // If the error is simply that no tags were found, it's not a processing error. - // It just means there's no album art. - if err == tag.ErrNoTagsFound { - return false - } - // For any other error (e.g., corrupted file), return the error. + // If there's an error with low-level detection, return false + // This is safer than potentially crashing the indexing process return false } - // m.Picture() returns the first picture found. If it's not nil, album art exists. - return m.Picture() != nil + + return hasArt } // DetectTypeByHeader detects the MIME type of a file based on its header. diff --git a/backend/indexing/iteminfo/fileinfo.go b/backend/indexing/iteminfo/fileinfo.go index a13a38f6f3..fec2605129 100644 --- a/backend/indexing/iteminfo/fileinfo.go +++ b/backend/indexing/iteminfo/fileinfo.go @@ -64,6 +64,7 @@ type FileOptions struct { Expand bool ReadHeader bool Content bool + Recursive bool // whether to recursively index directories } func (f FileOptions) Components() (string, string) { diff --git a/backend/indexing/mutate.go b/backend/indexing/mutate.go index 0dc2bbd109..9d094065c4 100644 --- a/backend/indexing/mutate.go +++ b/backend/indexing/mutate.go @@ -18,6 +18,67 @@ func (idx *Index) UpdateMetadata(info *iteminfo.FileInfo) bool { return true } +// DeleteMetadata removes the specified path from the index. +// If recursive is true and the path is a directory, it will also remove all subdirectories. +func (idx *Index) DeleteMetadata(path string, isDir bool, recursive bool) bool { + idx.mu.Lock() + defer idx.mu.Unlock() + + indexPath := idx.MakeIndexPath(path) + + if !isDir { + // For files, remove from parent directory's Files slice + parentPath := idx.MakeIndexPath(filepath.Dir(path)) + if parentDir, exists := idx.Directories[parentPath]; exists { + fileName := filepath.Base(path) + for i, file := range parentDir.Files { + if file.Name == fileName { + // Remove file from slice + parentDir.Files = append(parentDir.Files[:i], parentDir.Files[i+1:]...) + break + } + } + } + return true + } + + // For directories + if recursive { + // Remove all subdirectories that start with this path + toDelete := []string{} + for dirPath := range idx.Directories { + if dirPath == indexPath || (len(dirPath) > len(indexPath) && + dirPath[:len(indexPath)] == indexPath && + (indexPath == "/" || dirPath[len(indexPath)] == '/')) { + toDelete = append(toDelete, dirPath) + } + } + for _, dirPath := range toDelete { + delete(idx.Directories, dirPath) + } + } else { + // Just remove this specific directory + delete(idx.Directories, indexPath) + } + + // Remove from parent directory's Folders slice + if indexPath != "/" { + parentPath := idx.MakeIndexPath(filepath.Dir(path)) + if parentDir, exists := idx.Directories[parentPath]; exists { + dirName := filepath.Base(path) + for i, folder := range parentDir.Folders { + if folder.Name == dirName { + // Remove folder from slice + parentDir.Folders = append(parentDir.Folders[:i], parentDir.Folders[i+1:]...) + break + } + } + } + } + + return true +} + // GetMetadataInfo retrieves the FileInfo from the specified file or directory in the index. func (idx *Index) GetReducedMetadata(target string, isDir bool) (*iteminfo.FileInfo, bool) { idx.mu.RLock() diff --git a/backend/preview/preview.go b/backend/preview/preview.go index 7f0e8ffbd8..aa59a70a18 100644 --- a/backend/preview/preview.go +++ b/backend/preview/preview.go @@ -16,6 +16,7 @@ import ( "sync" "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/diskcache" + "github.com/gtsteffaniak/filebrowser/backend/adapters/fs/fileutils" "github.com/gtsteffaniak/filebrowser/backend/common/settings" "github.com/gtsteffaniak/filebrowser/backend/common/utils" "github.com/gtsteffaniak/filebrowser/backend/indexing/iteminfo" @@ -53,16 +54,16 @@ func NewPreviewGenerator(concurrencyLimit int, ffmpegPath string, cacheDir strin // No-op cache if no cacheDir is specified fileCache = diskcache.NewNoOp() } - // Create directories recursively with 0755 permissions - err := os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs"), 0755) + // Create directories recursively + err := os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "docs"), fileutils.PermDir) if err != nil { logger.Error(err) } - err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "videos"), 0755) + err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "thumbnails", "videos"), fileutils.PermDir) if err != nil { logger.Error(err) } - err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "heic"), 0755) + err = os.MkdirAll(filepath.Join(settings.Config.Server.CacheDir, "heic"), fileutils.PermDir) if err != nil { logger.Error(err) } @@ -102,7 +103,7 @@ func GetPreviewForFile(file iteminfo.ExtendedFileInfo, previewSize, url string, if file.AudioMeta != nil && file.AudioMeta.AlbumArt != "" { // md5 is based on album art // md5 file.AlbumArt - hasher := md5.New() //nolint:gosec + hasher := md5.New() _, _ = hasher.Write([]byte(file.AudioMeta.AlbumArt)) thisMd5 = hex.EncodeToString(hasher.Sum(nil)) file.Checksums = make(map[string]string) @@ -113,6 +114,11 @@ func GetPreviewForFile(file iteminfo.ExtendedFileInfo, previewSize, url string, if err != nil { return nil, fmt.Errorf("failed to get checksum: %w", err) } + // Ensure the file.Checksums map is initialized and MD5 is set + if file.Checksums == nil { + file.Checksums = make(map[string]string) + } + file.Checksums["md5"] = thisMd5 } cacheKey := CacheKey(thisMd5, previewSize, seekPercentage) if data, found, err := service.fileCache.Load(context.Background(), cacheKey); err != nil { @@ -131,7 +137,7 @@ func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, officeUrl stri ) // Generate thumbnail image from video - hasher := md5.New() //nolint:gosec + hasher := md5.New() _, _ = hasher.Write([]byte(CacheKey(file.Checksums["md5"], previewSize, seekPercentage))) hash := hex.EncodeToString(hasher.Sum(nil)) // Generate an image from office document @@ -205,7 +211,7 @@ func GeneratePreview(file iteminfo.ExtendedFileInfo, previewSize, officeUrl stri } else { cacheKey := CacheKey(file.Checksums["md5"], previewSize, seekPercentage) if err := service.fileCache.Store(context.Background(), cacheKey, imageBytes); err != nil { - logger.Errorf("failed to cache resized image: %v", err) + logger.Errorf("failed to cache original image: %v", err) } return imageBytes, nil } diff --git a/backend/swagger/docs/docs.go b/backend/swagger/docs/docs.go index 29a261d233..bcd4dcda32 100644 --- a/backend/swagger/docs/docs.go +++ b/backend/swagger/docs/docs.go @@ -3195,7 +3195,7 @@ const docTemplate = `{ ] }, "indexAlbumArt": { - "description": "check for album art in audio files and remember it for folder previews. Can slow down indexing.", + "description": "deprecated: always enabled since 0.8.6", "type": "boolean" }, "indexingIntervalMinutes": { diff --git a/backend/swagger/docs/swagger.json b/backend/swagger/docs/swagger.json index 44c262b6db..be935baafe 100644 --- a/backend/swagger/docs/swagger.json +++ b/backend/swagger/docs/swagger.json @@ -3184,7 +3184,7 @@ ] }, "indexAlbumArt": { - "description": "check for album art in audio files and remember it for folder previews. Can slow down indexing.", + "description": "deprecated: always enabled since 0.8.6", "type": "boolean" }, "indexingIntervalMinutes": { diff --git a/backend/swagger/docs/swagger.yaml b/backend/swagger/docs/swagger.yaml index 47c341ddc8..29d5809031 100644 --- a/backend/swagger/docs/swagger.yaml +++ b/backend/swagger/docs/swagger.yaml @@ -584,8 +584,7 @@ definitions: - $ref: '#/definitions/settings.IncludeIndexFilter' description: include files and folders from indexing, if exclude is not set indexAlbumArt: - description: check for album art in audio files and remember it for folder - previews. Can slow down indexing. + description: 'deprecated: always enabled since 0.8.6' type: boolean indexingIntervalMinutes: description: optional manual overide interval in minutes to re-index the source diff --git a/frontend/public/config.generated.yaml b/frontend/public/config.generated.yaml index 042057abe5..0fd5ee4371 100644 --- a/frontend/public/config.generated.yaml +++ b/frontend/public/config.generated.yaml @@ -47,7 +47,6 @@ server: defaultUserScope: "/" # default "/" should match folders under path defaultEnabled: false # should be added as a default source for new users? createUserDir: false # create a user directory for each user - indexAlbumArt: false # check for album art in audio files and remember it for folder previews. Can slow down indexing. 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 @@ -168,4 +167,4 @@ integrations: ffmpegPath: "" # path to ffmpeg directory with ffmpeg and ffprobe (eg. /usr/local/bin) convert: # config for ffmpeg conversion settings imagePreview: # supported image preview formats. default is heic - heic: true + heic: false diff --git a/frontend/src/components/ContextMenu.vue b/frontend/src/components/ContextMenu.vue index e1626d9b83..8634223e1a 100644 --- a/frontend/src/components/ContextMenu.vue +++ b/frontend/src/components/ContextMenu.vue @@ -87,7 +87,7 @@ v-if="!showCreate && selectedCount == 1 && isSearchActive" icon="folder" :label="$t('buttons.openParentFolder')" - @action="openParentFolder" + @action="openParentFolder" /> - + @@ -189,7 +189,7 @@ export default { return false }, hasOverflowItems() { - return this.showEdit || this.showDelete || this.showSave || this.showGoToRaw; + return this.showEdit || this.showDelete || this.showSave || this.showGoToRaw || this.hasDownload; }, showGoToRaw() { const cv = getters.currentView(); @@ -212,6 +212,9 @@ export default { const showDelete = cv != "settings" && !this.showCreate && this.selectedCount > 0 && !this.isSearchActive; return showDelete; }, + hasDownload() { + return this.selectedCount > 0; + }, isPreview() { const cv = getters.currentView(); return ( diff --git a/frontend/src/components/files/ShareInfoCard.vue b/frontend/src/components/files/ShareInfoCard.vue index d5cbe910a4..8808e1f733 100644 --- a/frontend/src/components/files/ShareInfoCard.vue +++ b/frontend/src/components/files/ShareInfoCard.vue @@ -10,21 +10,25 @@ -
- - - - +
+
+ + + + +
@@ -60,6 +64,9 @@ export default { }, }, computed: { + accessible() { + return shareInfo.isPasswordProtected && state.share.passwordValid; + }, getShareBanner() { if (this.shareInfo.banner.startsWith("http")) { return this.shareInfo.banner; @@ -122,6 +129,7 @@ export default { .banner img { width: 100%; } + .share { display: flex; } @@ -146,6 +154,7 @@ export default { .share__box__element canvas { border-style: solid; } + .share__box__center { text-align: center; } diff --git a/frontend/src/components/prompts/Share.vue b/frontend/src/components/prompts/Share.vue index 6350c49ec9..7cac16ef1b 100644 --- a/frontend/src/components/prompts/Share.vue +++ b/frontend/src/components/prompts/Share.vue @@ -562,7 +562,14 @@ export default { * @param {Share} share */ buildDownloadLink(share) { - if (share.downloadURL && globalVars.externalUrl == "") { + if (share.downloadURL) { + // Only fix the URL if it doesn't already have the correct external domain + if (globalVars.externalUrl) { + + // URL already has the correct external domain, use as-is + return share.downloadURL; + } + // URL needs fixing (internal domain or no externalUrl set) return this.fixDownloadURL(share.downloadURL); } return publicApi.getDownloadURL(share, [this.item.name]); diff --git a/frontend/src/components/prompts/UserEdit.vue b/frontend/src/components/prompts/UserEdit.vue index bd0f2c5a92..bfaecd910f 100644 --- a/frontend/src/components/prompts/UserEdit.vue +++ b/frontend/src/components/prompts/UserEdit.vue @@ -1,42 +1,228 @@ diff --git a/frontend/src/components/settings/UserForm.vue b/frontend/src/components/settings/UserForm.vue deleted file mode 100644 index 6db60de040..0000000000 --- a/frontend/src/components/settings/UserForm.vue +++ /dev/null @@ -1,351 +0,0 @@ - - - - - diff --git a/frontend/src/components/sidebar/General.vue b/frontend/src/components/sidebar/General.vue index e81ff9b447..8b044323b2 100644 --- a/frontend/src/components/sidebar/General.vue +++ b/frontend/src/components/sidebar/General.vue @@ -186,7 +186,7 @@ export default { if (!getters.isLoggedIn()) { return; } - if (!this.isStickySidebar) { + if (!this.isStickySidebar && !shareInfo.singleFileShare) { mutations.closeSidebar(); } }, diff --git a/frontend/src/components/sidebar/Sidebar.vue b/frontend/src/components/sidebar/Sidebar.vue index 48c1e95d0e..96202e570e 100644 --- a/frontend/src/components/sidebar/Sidebar.vue +++ b/frontend/src/components/sidebar/Sidebar.vue @@ -101,7 +101,17 @@ export default { transition: 0.5s ease; top: 4em; padding-bottom: 4em; - background-color: #dddddd; + background-color: rgb(37 49 55 / 5%) !important; +} + +/* sidebar with backdrop-filter support */ +@supports (backdrop-filter: none) { + #sidebar { + backdrop-filter: blur(16px) invert(0.1); + } + #sidebar.dark-mode { + background-color: rgb(37 49 55 / 33%) !important; + } } #sidebar.behind-overlay { @@ -112,13 +122,6 @@ export default { z-index: 3; } -@supports (backdrop-filter: none) { - #sidebar { - background-color: rgba(237, 237, 237, 0.33) !important; - backdrop-filter: blur(16px) invert(0.1); - } -} - body.rtl nav { left: unset; right: -17em; diff --git a/frontend/src/css/base.css b/frontend/src/css/base.css index ce8e4fbf0f..5c57d52672 100644 --- a/frontend/src/css/base.css +++ b/frontend/src/css/base.css @@ -199,7 +199,6 @@ input.sizeInput:disabled { backdrop-filter: invert(.1); height: 2em; width: 5em; - } .roundedInputLeft { diff --git a/frontend/src/css/dark.css b/frontend/src/css/dark.css index b6f3e20b5f..6ceaf6b232 100644 --- a/frontend/src/css/dark.css +++ b/frontend/src/css/dark.css @@ -235,18 +235,3 @@ background-color: #283136; } -/* Header with backdrop-filter support */ -@supports (backdrop-filter: none) { - .dark-mode-header { - background-color: rgb(37 49 55 / 33%) !important; - backdrop-filter: blur(16px) invert(0.1); - } - #sidebar.dark-mode { - background-color: rgb(37 49 55 / 33%) !important; - backdrop-filter: blur(16px) invert(0.1); - } -} - -#sidebar.dark-mode { - background-color: var(--alt-background); -} \ No newline at end of file diff --git a/frontend/src/css/header.css b/frontend/src/css/header.css index e7f498e129..33cb630c11 100644 --- a/frontend/src/css/header.css +++ b/frontend/src/css/header.css @@ -12,13 +12,6 @@ header { padding: 0.5em; } -@supports (backdrop-filter: none) { - header { - background-color: rgba(237, 237, 237, 0.33) !important; - backdrop-filter: blur(16px) invert(0.1); - } -} - header>* { flex: 0 0 auto; } @@ -51,10 +44,3 @@ header .action span { display: none; } -/* Header with backdrop-filter support */ -@supports (backdrop-filter: none) { - header { - background-color: rgba(237, 237, 237, 0.33) !important; - backdrop-filter: blur(16px) invert(0.1); - } -} \ No newline at end of file diff --git a/frontend/src/i18n/ar.json b/frontend/src/i18n/ar.json index 7f575a220f..c33187ccef 100644 --- a/frontend/src/i18n/ar.json +++ b/frontend/src/i18n/ar.json @@ -159,7 +159,6 @@ "schedule": "جدولة", "scheduleMessage": "أختر الوقت والتاريخ لجدولة نشر هذا المقال.", "show": "عرض", - "size": "الحجم", "upload": "التحميل", "deleteUserMessage": "هل أنت متأكد من رغبتك في حذف هذا المستخدم؟", "filesSelected": "الملفات المحددة", @@ -187,7 +186,6 @@ "source": "المصدر{suffix}", "deleteMessageMultiple": "هل تريد بالتأكيد حذف الملف (الملفات) {count} ؟", "deleteMessageShare": "هل أنت متأكد أنك تريد حذف هذه المشاركة؟ {path} ?", - "lastModified": "آخر تعديل{suffix}", "numberDirs": "عدد الدلائل{suffix}", "numberFiles": "عدد الملفات{suffix}", "renameMessageConflict": "عنصر باسم \"{filename}\" موجود بالفعل!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "الحد الأقصى للتحميلات المتزامنة: {maxConcurrentUpload} ، تم تعطيل التحميل المقطّع", "quickJump": "الانتقال بسرعة إلى ملفات أخرى", "moveSuccess": "تم نقل الملفات بنجاح!", - "copySuccess": "تم نسخ الملفات بنجاح!" + "copySuccess": "تم نسخ الملفات بنجاح!", + "lastModified": "آخر تعديل{suffix}", + "size": "الحجم{suffix}" }, "search": { "images": "الصور", diff --git a/frontend/src/i18n/cz.json b/frontend/src/i18n/cz.json index 8902e14686..ec12e6531e 100644 --- a/frontend/src/i18n/cz.json +++ b/frontend/src/i18n/cz.json @@ -210,7 +210,6 @@ "schedule": "Naplánovat", "scheduleMessage": "Vyberte datum a čas naplánování publikace tohoto příspěvku.", "show": "Zobrazit", - "size": "Velikost", "upload": "Nahrát", "optionalPassword": "Volitelné heslo", "typeName": "Typ:", @@ -235,7 +234,6 @@ "source": "Zdroj:{suffix}", "deleteMessageMultiple": "Opravdu chcete odstranit soubor(y) {count}?", "deleteMessageShare": "Jste si jisti, že chcete tuto sdílenou složku odstranit: {path} ?", - "lastModified": "Poslední úprava{suffix}", "numberDirs": "Počet adresářů{suffix}", "numberFiles": "Počet souborů{suffix}", "renameMessageConflict": "Položka s názvem \"{filename}\" již existuje!", @@ -243,7 +241,9 @@ "uploadSettingsNoChunk": "Maximální souběžné nahrávání: {maxConcurrentUpload}, vypnuto hromadné nahrávání", "quickJump": "Rychlý přechod na jiné soubory", "moveSuccess": "Soubory byly úspěšně přesunuty!", - "copySuccess": "Soubory byly úspěšně zkopírovány!" + "copySuccess": "Soubory byly úspěšně zkopírovány!", + "lastModified": "Poslední úprava{suffix}", + "size": "Velikost{suffix}" }, "search": { "images": "Obrázky", diff --git a/frontend/src/i18n/de.json b/frontend/src/i18n/de.json index 93157f7579..56bc98e6f0 100644 --- a/frontend/src/i18n/de.json +++ b/frontend/src/i18n/de.json @@ -159,7 +159,6 @@ "schedule": "Zeitplan", "scheduleMessage": "Wählen Sie ein Datum und eine Zeit für die Veröffentlichung dieses Beitrags.", "show": "Anzeigen", - "size": "Größe", "upload": "Hochladen", "optionalPassword": "Optionales Kennwort", "deleteUserMessage": "Sind Sie sicher, dass Sie diesen Benutzer löschen möchten?", @@ -187,7 +186,6 @@ "source": "Quelle{suffix}", "deleteMessageMultiple": "Sind Sie sicher, dass Sie die Datei(en) {count} löschen möchten?", "deleteMessageShare": "Sind Sie sicher, dass Sie diese Freigabe löschen möchten: {path} ?", - "lastModified": "Zuletzt modifiziert{suffix}", "numberDirs": "Anzahl der Verzeichnisse{suffix}", "numberFiles": "Anzahl der Dateien{suffix}", "renameMessageConflict": "Ein Artikel mit dem Namen \"{filename}\" existiert bereits!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Max. gleichzeitige Uploads: {maxConcurrentUpload}, Chunked Upload deaktiviert", "quickJump": "Schnelles Springen zu anderen Dateien", "moveSuccess": "Dateien erfolgreich verschoben!", - "copySuccess": "Dateien erfolgreich kopiert!" + "copySuccess": "Dateien erfolgreich kopiert!", + "lastModified": "Zuletzt modifiziert{suffix}", + "size": "Größe{suffix}" }, "search": { "images": "Bilder", diff --git a/frontend/src/i18n/el.json b/frontend/src/i18n/el.json index e573f63ae2..3cb75ba124 100644 --- a/frontend/src/i18n/el.json +++ b/frontend/src/i18n/el.json @@ -162,7 +162,6 @@ "schedule": "Προγραμματισμός", "scheduleMessage": "Επιλέξτε μια ημερομηνία και ώρα για τον προγραμματισμό της δημοσίευσης αυτής της ανάρτησης.", "show": "Εμφάνιση", - "size": "Μέγεθος", "upload": "Μεταφόρτωση", "optionalPassword": "Προαιρετικός κωδικός πρόσβασης", "deleteUserMessage": "Είστε σίγουροι ότι θέλετε να διαγράψετε αυτόν τον χρήστη;", @@ -190,7 +189,6 @@ "source": "Πηγή{suffix}", "deleteMessageMultiple": "Είστε σίγουροι ότι θέλετε να διαγράψετε το/τα αρχείο/α {count};", "deleteMessageShare": "Είστε σίγουροι ότι θέλετε να διαγράψετε αυτό το μερίδιο: {path} ?", - "lastModified": "Τελευταία τροποποίηση{suffix}", "numberDirs": "Αριθμός καταλόγων{suffix}", "numberFiles": "Αριθμός αρχείων{suffix}", "renameMessageConflict": "Ένα στοιχείο με όνομα \"{filename}\" υπάρχει ήδη!", @@ -198,7 +196,9 @@ "uploadSettingsNoChunk": "Μέγιστες ταυτόχρονες μεταφορτώσεις: {maxConcurrentUpload}, chunked upload disabled", "quickJump": "Γρήγορη μετάβαση σε άλλα αρχεία", "moveSuccess": "Τα αρχεία μετακινήθηκαν με επιτυχία!", - "copySuccess": "Τα αρχεία αντιγράφηκαν με επιτυχία!" + "copySuccess": "Τα αρχεία αντιγράφηκαν με επιτυχία!", + "lastModified": "Τελευταία τροποποίηση{suffix}", + "size": "Μέγεθος{suffix}" }, "search": { "images": "Εικόνες", diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.json index 22519c7a0e..8f8e3fb2bf 100644 --- a/frontend/src/i18n/en.json +++ b/frontend/src/i18n/en.json @@ -76,7 +76,7 @@ "clear": "Clear", "closePreview": "Close preview", "home": "Home", - "lastModified": "Last modified", + "lastModified": "Last modified{suffix}", "loading": "Loading...", "lonely": "It feels lonely here...", "metadata": "Metadata", @@ -235,7 +235,7 @@ "schedule": "Schedule", "scheduleMessage": "Pick a date and time to schedule the publication of this post.", "show": "Show", - "size": "Size", + "size": "Size{suffix}", "upload": "Upload", "uploadSettingsChunked": "Max concurrent uploads: {maxConcurrentUpload}, chunk size: {uploadChunkSizeMb} MB", "uploadSettingsNoChunk": "Max concurrent uploads: {maxConcurrentUpload}, chunked upload disabled", diff --git a/frontend/src/i18n/es.json b/frontend/src/i18n/es.json index 2c1146f375..85f34a38cb 100644 --- a/frontend/src/i18n/es.json +++ b/frontend/src/i18n/es.json @@ -159,7 +159,6 @@ "schedule": "Programar", "scheduleMessage": "Selecciona una fecha y hora para la publicacion:", "show": "Mostrar", - "size": "Tamaño", "upload": "Subir", "optionalPassword": "Contraseña (opcional)", "deleteUserMessage": "¿Estas seguro que quieres eliminar este usuario?", @@ -187,7 +186,6 @@ "source": "Fuente{suffix}", "deleteMessageMultiple": "¿Está seguro de que desea eliminar los archivos de {count}?", "deleteMessageShare": "¿Estás seguro de que quieres borrar esta acción? {path} ?", - "lastModified": "Última modificación{suffix}", "numberDirs": "Número de directorios{suffix}", "numberFiles": "Número de ficheros{suffix}", "renameMessageConflict": "Ya existe un elemento llamado \"{filename}\".", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Carga máxima simultánea: {maxConcurrentUpload} Carga por trozos desactivada", "quickJump": "Saltar rápidamente a otros archivos", "moveSuccess": "¡Archivos movidos con éxito!", - "copySuccess": "¡Archivos copiados correctamente!" + "copySuccess": "¡Archivos copiados correctamente!", + "lastModified": "Última modificación{suffix}", + "size": "Talla{suffix}" }, "search": { "images": "Imágenes", diff --git a/frontend/src/i18n/fr.json b/frontend/src/i18n/fr.json index f3246dc528..152a261991 100644 --- a/frontend/src/i18n/fr.json +++ b/frontend/src/i18n/fr.json @@ -159,7 +159,6 @@ "schedule": "Fixer la date", "scheduleMessage": "Choisissez une date pour planifier la publication de ce post", "show": "Montrer", - "size": "Taille", "upload": "Importer", "optionalPassword": "Mot de passe optionnel", "deleteUserMessage": "Êtes-vous sûr de vouloir supprimer cet utilisateur ?", @@ -187,7 +186,6 @@ "source": "Source{suffix}", "deleteMessageMultiple": "Êtes-vous sûr de vouloir supprimer le(s) fichier(s) {count}?", "deleteMessageShare": "Êtes-vous sûr de vouloir supprimer ce partage : {path} ?", - "lastModified": "Dernière modification{suffix}", "numberDirs": "Nombre de répertoires{suffix}", "numberFiles": "Nombre de fichiers{suffix}", "renameMessageConflict": "Un article nommé \"{filename}\" existe déjà !", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Nombre maximum de téléchargements simultanés : {maxConcurrentUpload}, chunked upload désactivé", "quickJump": "Passer rapidement à d'autres fichiers", "moveSuccess": "Les fichiers ont été déplacés avec succès !", - "copySuccess": "Les fichiers ont été copiés avec succès !" + "copySuccess": "Les fichiers ont été copiés avec succès !", + "lastModified": "Dernière modification{suffix}", + "size": "Taille{suffix}" }, "search": { "images": "Images", diff --git a/frontend/src/i18n/he.json b/frontend/src/i18n/he.json index 087aa465c5..945b5c04d5 100644 --- a/frontend/src/i18n/he.json +++ b/frontend/src/i18n/he.json @@ -159,7 +159,6 @@ "schedule": "תזמון", "scheduleMessage": "בחר תאריך ושעה לתזמון הפרסום של פוסט זה.", "show": "הצג", - "size": "גודל", "upload": "העלאה", "optionalPassword": "סיסמא אופציונלית", "deleteUserMessage": "האם אתה בטוח שברצונך למחוק משתמש זה?", @@ -187,7 +186,6 @@ "source": "מקור{suffix}", "deleteMessageMultiple": "האם אתה בטוח שברצונך למחוק את הקובץ/ים {count}?", "deleteMessageShare": "האם אתה בטוח שברצונך למחוק שיתוף זה: {path}?", - "lastModified": "שינוי אחרון{suffix}", "numberDirs": "מספר הספריות{suffix}", "numberFiles": "מספר הקבצים{suffix}", "renameMessageConflict": "פריט בשם \"{filename}\" כבר קיים!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "מספר העלאות מקסימלי בו-זמנית: {maxConcurrentUpload}, העלאה מקוטעת מושבתת", "quickJump": "קפיצה מהירה לקבצים אחרים", "moveSuccess": "הקבצים הועברו בהצלחה!", - "copySuccess": "הקבצים הועתקו בהצלחה!" + "copySuccess": "הקבצים הועתקו בהצלחה!", + "lastModified": "שינוי אחרון{suffix}", + "size": "גודל{suffix}" }, "search": { "images": "תמונות", diff --git a/frontend/src/i18n/hu.json b/frontend/src/i18n/hu.json index 3b29d1d246..390b0ab7f0 100644 --- a/frontend/src/i18n/hu.json +++ b/frontend/src/i18n/hu.json @@ -159,7 +159,6 @@ "schedule": "Ütemezés", "scheduleMessage": "Válasszon egy dátumot és időpontot a bejegyzés közzétételének ütemezéséhez.", "show": "Megjelenítés", - "size": "Méret", "upload": "Feltöltés", "optionalPassword": "Választható jelszó", "deleteUserMessage": "Biztos, hogy törölni szeretné ezt a felhasználót?", @@ -187,7 +186,6 @@ "source": "Forrás{suffix}", "deleteMessageMultiple": "Biztos, hogy törölni szeretné a {count} fájl(ok)at?", "deleteMessageShare": "Biztos, hogy törölni szeretné ezt a megosztást: {path} ?", - "lastModified": "Utoljára módosítva{suffix}", "numberDirs": "A könyvtárak száma{suffix}", "numberFiles": "Fájlok száma{suffix}", "renameMessageConflict": "A \"{filename}\" nevű elem már létezik!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Maximális egyidejű feltöltés: {maxConcurrentUpload}, chunked upload disabled", "quickJump": "Gyors ugrás más fájlokra", "moveSuccess": "Fájlok sikeresen áthelyezve!", - "copySuccess": "A fájlok másolása sikeres volt!" + "copySuccess": "A fájlok másolása sikeres volt!", + "lastModified": "Utoljára módosítva{suffix}", + "size": "Méret{suffix}" }, "search": { "images": "Képek", diff --git a/frontend/src/i18n/it.json b/frontend/src/i18n/it.json index c57ee06d82..f19690eb8a 100644 --- a/frontend/src/i18n/it.json +++ b/frontend/src/i18n/it.json @@ -159,7 +159,6 @@ "schedule": "Pianifica", "scheduleMessage": "Seleziona data e ora per programmare la pubbilicazione di questo post", "show": "Mostra", - "size": "Dimensione", "upload": "Carica", "deleteUserMessage": "Siete sicuri di voler eliminare questo utente?", "filesSelected": "file selezionati", @@ -187,7 +186,6 @@ "source": "Fonte{suffix}", "deleteMessageMultiple": "Siete sicuri di voler eliminare i file {count}?", "deleteMessageShare": "Sei sicuro di voler eliminare questa condivisione: {path} ?", - "lastModified": "Ultima modifica{suffix}", "numberDirs": "Numero di directory{suffix}", "numberFiles": "Numero di file{suffix}", "renameMessageConflict": "Un elemento chiamato \"{filename}\" esiste già!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Carichi massimi contemporanei: {maxConcurrentUpload}, caricamento chunked disabilitato", "quickJump": "Salto rapido ad altri file", "moveSuccess": "I file sono stati spostati con successo!", - "copySuccess": "I file sono stati copiati con successo!" + "copySuccess": "I file sono stati copiati con successo!", + "lastModified": "Ultima modifica{suffix}", + "size": "Dimensione{suffix}" }, "search": { "images": "Immagini", diff --git a/frontend/src/i18n/ja.json b/frontend/src/i18n/ja.json index 5c9d8f259d..d9ac9e7b9d 100644 --- a/frontend/src/i18n/ja.json +++ b/frontend/src/i18n/ja.json @@ -159,7 +159,6 @@ "schedule": "スケジュール", "scheduleMessage": "この投稿の公開日時をスケジュールしてください。", "show": "表示", - "size": "サイズ", "upload": "アップロード", "deleteUserMessage": "本当にこのユーザーを削除しますか?", "filesSelected": "選択されたファイル", @@ -187,7 +186,6 @@ "source": "送信元{suffix}", "deleteMessageMultiple": "本当に{count}個のファイルを削除しますか?", "deleteMessageShare": "この共有を削除してもよろしいですか? {path}", - "lastModified": "最終更新日時{suffix}", "numberDirs": "ディレクトリ数{suffix}", "numberFiles": "ファイル数{suffix}", "quickJump": "他のファイルに素早くジャンプ", @@ -195,7 +193,9 @@ "copySuccess": "ファイルは正常にコピーされました!", "renameMessageConflict": "\"{filename}\"という名前のアイテムがすでに存在します!", "uploadSettingsChunked": "最大同時アップロード数:{maxConcurrentUpload}、チャンクサイズ:{uploadChunkSizeMb}MB", - "uploadSettingsNoChunk": "最大同時アップロード数:{maxConcurrentUpload}、チャンクアップロード無効" + "uploadSettingsNoChunk": "最大同時アップロード数:{maxConcurrentUpload}、チャンクアップロード無効", + "lastModified": "最終更新日{suffix}", + "size": "サイズ{suffix}" }, "search": { "images": "画像", diff --git a/frontend/src/i18n/ko.json b/frontend/src/i18n/ko.json index 3428f84b3b..1d6fc96163 100644 --- a/frontend/src/i18n/ko.json +++ b/frontend/src/i18n/ko.json @@ -159,7 +159,6 @@ "schedule": "일정", "scheduleMessage": "이 글을 공개할 시간을 알려주세요.", "show": "보기", - "size": "크기", "upload": "업로드", "deleteUserMessage": "이 사용자를 삭제하시겠습니까?", "filesSelected": "선택한 파일", @@ -187,7 +186,6 @@ "source": "출처{suffix}", "deleteMessageMultiple": "{count} 파일을 정말 삭제하시겠습니까?", "deleteMessageShare": "이 공유를 삭제하시겠습니까? {path} ?", - "lastModified": "마지막 수정{suffix}", "numberDirs": "디렉터리 수{suffix}", "numberFiles": "파일 수{suffix}", "renameMessageConflict": "\"{filename}\"라는 이름의 항목이 이미 존재합니다!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "최대 동시 업로드: {maxConcurrentUpload}, 청크 업로드 비활성화", "quickJump": "다른 파일로 빠르게 이동", "moveSuccess": "파일이 성공적으로 이동했습니다!", - "copySuccess": "파일이 성공적으로 복사되었습니다!" + "copySuccess": "파일이 성공적으로 복사되었습니다!", + "lastModified": "마지막 수정{suffix}", + "size": "크기{suffix}" }, "search": { "images": "이미지", diff --git a/frontend/src/i18n/nl-be.json b/frontend/src/i18n/nl-be.json index 4dc9d638a2..4d5a7bdb69 100644 --- a/frontend/src/i18n/nl-be.json +++ b/frontend/src/i18n/nl-be.json @@ -159,7 +159,6 @@ "schedule": "Plannen", "scheduleMessage": "Kies een datum en tijd om de publicatie van dit bericht in te plannen.", "show": "Tonen", - "size": "Grootte", "upload": "Uploaden", "deleteUserMessage": "Weet je zeker dat je deze gebruiker wilt verwijderen?", "selected": "geselecteerd", @@ -187,7 +186,6 @@ "source": "Bron{suffix}", "deleteMessageMultiple": "Weet je zeker dat je {count} bestand(en) wilt verwijderen?", "deleteMessageShare": "Weet je zeker dat je deze share wilt verwijderen: {path} ?", - "lastModified": "Laatst gewijzigd{suffix}", "numberDirs": "Aantal mappen{suffix}", "numberFiles": "Aantal bestanden{suffix}", "renameMessageConflict": "Een item met de naam \"{filename}\" bestaat al!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Max gelijktijdige uploads: {maxConcurrentUpload}, chunked upload uitgeschakeld", "quickJump": "Snel naar andere bestanden springen", "moveSuccess": "Bestanden succesvol verplaatst!", - "copySuccess": "Bestanden succesvol gekopieerd!" + "copySuccess": "Bestanden succesvol gekopieerd!", + "lastModified": "Laatst gewijzigd{suffix}", + "size": "Maat{suffix}" }, "search": { "images": "Afbeeldingen", diff --git a/frontend/src/i18n/pl.json b/frontend/src/i18n/pl.json index 962b7e8739..8f26782753 100644 --- a/frontend/src/i18n/pl.json +++ b/frontend/src/i18n/pl.json @@ -159,7 +159,6 @@ "schedule": "Grafi", "scheduleMessage": "Wybierz datę i czas dla publikacji tego wpisu.", "show": "Pokaż", - "size": "Rozmiar", "upload": "Prześlij", "deleteUserMessage": "Czy na pewno chcesz usunąć tego użytkownika?", "filesSelected": "wybrane pliki", @@ -187,7 +186,6 @@ "source": "Źródło{suffix}", "deleteMessageMultiple": "Czy na pewno chcesz usunąć plik(i) {count}?", "deleteMessageShare": "Czy na pewno chcesz usunąć ten udział: {path} ?", - "lastModified": "Ostatnia modyfikacja{suffix}", "numberDirs": "Liczba katalogów{suffix}", "numberFiles": "Liczba plików{suffix}", "renameMessageConflict": "Element o nazwie \"{filename}\" już istnieje!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Maksymalny jednoczesny upload: {maxConcurrentUpload}, przesyłanie fragmentaryczne wyłączone", "quickJump": "Szybkie przechodzenie do innych plików", "moveSuccess": "Pliki zostały przeniesione pomyślnie!", - "copySuccess": "Pliki zostały skopiowane pomyślnie!" + "copySuccess": "Pliki zostały skopiowane pomyślnie!", + "lastModified": "Ostatnia modyfikacja{suffix}", + "size": "Rozmiar{suffix}" }, "search": { "images": "Zdjęcia", diff --git a/frontend/src/i18n/pt-br.json b/frontend/src/i18n/pt-br.json index 93b4434c1f..4a88b0ee1b 100644 --- a/frontend/src/i18n/pt-br.json +++ b/frontend/src/i18n/pt-br.json @@ -159,7 +159,6 @@ "schedule": "Agendar", "scheduleMessage": "Escolha uma data para agendar a publicação deste post.", "show": "Mostrar", - "size": "Tamanho", "upload": "Enviar", "optionalPassword": "Senha opcional", "deleteUserMessage": "Tem certeza de que deseja excluir esse usuário?", @@ -187,7 +186,6 @@ "source": "Fonte{suffix}", "deleteMessageMultiple": "Tem certeza de que deseja excluir o(s) arquivo(s) {count}?", "deleteMessageShare": "Tem certeza de que deseja excluir esse compartilhamento: {path} ?", - "lastModified": "Última modificação{suffix}", "numberDirs": "Número de diretórios{suffix}", "numberFiles": "Número de arquivos{suffix}", "renameMessageConflict": "Já existe um item chamado \"{filename}\"!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Máximo de uploads simultâneos: {maxConcurrentUpload}, upload em pedaços desativado", "quickJump": "Pular rapidamente para outros arquivos", "moveSuccess": "Os arquivos foram movidos com sucesso!", - "copySuccess": "Os arquivos foram copiados com sucesso!" + "copySuccess": "Os arquivos foram copiados com sucesso!", + "lastModified": "Última modificação{suffix}", + "size": "Tamanho{suffix}" }, "search": { "images": "Imagens", diff --git a/frontend/src/i18n/pt.json b/frontend/src/i18n/pt.json index cc3d22b860..46abac641c 100644 --- a/frontend/src/i18n/pt.json +++ b/frontend/src/i18n/pt.json @@ -159,7 +159,6 @@ "schedule": "Agendar", "scheduleMessage": "Escolha uma data para publicar este post.", "show": "Mostrar", - "size": "Tamanho", "upload": "Carregar", "deleteUserMessage": "Tem a certeza de que pretende apagar este utilizador?", "selected": "selecionado", @@ -187,7 +186,6 @@ "source": "Fonte{suffix}", "deleteMessageMultiple": "Tem a certeza de que pretende apagar o(s) ficheiro(s) {count}?", "deleteMessageShare": "Tem a certeza de que pretende apagar esta partilha: {path} ?", - "lastModified": "Última modificação{suffix}", "numberDirs": "Número de diretórios{suffix}", "numberFiles": "Número de ficheiros{suffix}", "renameMessageConflict": "Já existe um item com o nome \"{filename}\"!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Máximo de carregamentos simultâneos: {maxConcurrentUpload}, carregamento em pedaços desativado", "quickJump": "Saltar rapidamente para outros ficheiros", "moveSuccess": "Ficheiros movidos com sucesso!", - "copySuccess": "Ficheiros copiados com sucesso!" + "copySuccess": "Ficheiros copiados com sucesso!", + "lastModified": "Última modificação{suffix}", + "size": "Tamanho{suffix}" }, "search": { "images": "Imagens", diff --git a/frontend/src/i18n/ro.json b/frontend/src/i18n/ro.json index 60faa1ff55..3ba52e97fc 100644 --- a/frontend/src/i18n/ro.json +++ b/frontend/src/i18n/ro.json @@ -159,7 +159,6 @@ "schedule": "Programare", "scheduleMessage": "Alege data si ora pentru a programa publicarea acestei postări.", "show": "Arată", - "size": "Dimensiune", "upload": "Încărcare", "deleteUserMessage": "Sunteți sigur că doriți să ștergeți acest utilizator?", "filesSelected": "fișiere selectate", @@ -187,7 +186,6 @@ "source": "Sursa{suffix}", "deleteMessageMultiple": "Sunteți sigur că doriți să eliminați fișierul (fișierele) {count}?", "deleteMessageShare": "Sunteți sigur că doriți să ștergeți această partajare: {path} ?", - "lastModified": "Ultima modificare{suffix}", "numberDirs": "Număr de directoare{suffix}", "numberFiles": "Număr de fișiere{suffix}", "renameMessageConflict": "Un element numit \"{filename}\" există deja!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Încărcări simultane maxime: {maxConcurrentUpload}, încărcare fragmentată dezactivată", "quickJump": "Salt rapid la alte fișiere", "moveSuccess": "Fișiere mutate cu succes!", - "copySuccess": "Fișiere copiate cu succes!" + "copySuccess": "Fișiere copiate cu succes!", + "lastModified": "Ultima modificare{suffix}", + "size": "Mărime{suffix}" }, "search": { "images": "Imagini", diff --git a/frontend/src/i18n/ru.json b/frontend/src/i18n/ru.json index 75220b1054..899846b4c7 100644 --- a/frontend/src/i18n/ru.json +++ b/frontend/src/i18n/ru.json @@ -159,7 +159,6 @@ "schedule": "Планировка", "scheduleMessage": "Запланировать дату и время публикации.", "show": "Показать", - "size": "Размер", "upload": "Загрузить", "optionalPassword": "Необязательный пароль", "deleteUserMessage": "Вы уверены, что хотите удалить этого пользователя?", @@ -187,7 +186,6 @@ "source": "Источник{suffix}", "deleteMessageMultiple": "Вы уверены, что хотите удалить файл(ы) {count}?", "deleteMessageShare": "Вы уверены, что хотите удалить этот ресурс: {path} ?", - "lastModified": "Последнее изменение{suffix}", "numberDirs": "Количество каталогов{suffix}", "numberFiles": "Количество файлов{suffix}", "renameMessageConflict": "Элемент с именем \"{filename}\" уже существует!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Максимальное количество одновременных загрузок: {maxConcurrentUpload}, загрузка в куски отключена", "quickJump": "Быстрый переход к другим файлам", "moveSuccess": "Файлы успешно перемещены!", - "copySuccess": "Файлы успешно скопированы!" + "copySuccess": "Файлы успешно скопированы!", + "lastModified": "Последнее изменение{suffix}", + "size": "Размер{suffix}" }, "search": { "images": "Изображения", diff --git a/frontend/src/i18n/sk.json b/frontend/src/i18n/sk.json index 328d67c6a6..6a132d0c39 100644 --- a/frontend/src/i18n/sk.json +++ b/frontend/src/i18n/sk.json @@ -159,7 +159,6 @@ "schedule": "Naplánovať", "scheduleMessage": "Pick a date and time to schedule the publication of this post.", "show": "Zobraziť", - "size": "Veľkosť", "upload": "Nahrať", "optionalPassword": "Voliteľné heslo", "deleteUserMessage": "Ste si istí, že chcete odstrániť tohto používateľa?", @@ -187,7 +186,6 @@ "source": "Zdroj{suffix}", "deleteMessageMultiple": "Ste si istí, že chcete odstrániť súbor(y) {count}?", "deleteMessageShare": "Ste si istí, že chcete odstrániť toto zdieľanie: {path} ?", - "lastModified": "Posledná úprava{suffix}", "numberDirs": "Počet adresárov{suffix}", "numberFiles": "Počet súborov{suffix}", "renameMessageConflict": "Položka s názvom \"{filename}\" už existuje!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Maximálne súbežné nahrávanie: {maxConcurrentUpload}, chunked upload vypnuté", "quickJump": "Rýchly prechod na iné súbory", "moveSuccess": "Súbory boli úspešne presunuté!", - "copySuccess": "Súbory boli úspešne skopírované!" + "copySuccess": "Súbory boli úspešne skopírované!", + "lastModified": "Posledná úprava{suffix}", + "size": "Veľkosť{suffix}" }, "search": { "images": "Obrázky", diff --git a/frontend/src/i18n/sv-se.json b/frontend/src/i18n/sv-se.json index c5398a80e9..72ae625833 100644 --- a/frontend/src/i18n/sv-se.json +++ b/frontend/src/i18n/sv-se.json @@ -159,7 +159,6 @@ "schedule": "Schema", "scheduleMessage": "Pick a date and time to schedule the publication of this post.", "show": "Visa", - "size": "Storlek", "upload": "Ladda upp", "deleteUserMessage": "Är du säker på att du vill ta bort den här användaren?", "selected": "utvalda", @@ -187,7 +186,6 @@ "source": "Källa{suffix}", "deleteMessageMultiple": "Är du säker att du vill ta bort {count} fil(er)?", "deleteMessageShare": "Är du säker på att du vill ta bort den här aktien: {path} ?", - "lastModified": "Senast ändrad{suffix}", "numberDirs": "Antal kataloger{suffix}", "numberFiles": "Antal filer{suffix}", "renameMessageConflict": "Ett objekt med namnet \"{filename}\" finns redan!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Max samtidiga uppladdningar: {maxConcurrentUpload}, chunked uppladdning inaktiverad", "quickJump": "Hoppa snabbt till andra filer", "moveSuccess": "Filerna flyttades framgångsrikt!", - "copySuccess": "Filerna kopierades framgångsrikt!" + "copySuccess": "Filerna kopierades framgångsrikt!", + "lastModified": "Senast ändrad{suffix}", + "size": "Storlek{suffix}" }, "search": { "images": "Bilder", diff --git a/frontend/src/i18n/tr.json b/frontend/src/i18n/tr.json index 373fa06f94..6f1c4f24c2 100644 --- a/frontend/src/i18n/tr.json +++ b/frontend/src/i18n/tr.json @@ -159,7 +159,6 @@ "schedule": "Planla", "scheduleMessage": "Bu paylaşımın yayınlanmasını planlamak için bir tarih ve saat seçin.", "show": "Göster", - "size": "Boyut", "upload": "Gönder", "optionalPassword": "İsteğe bağlı şifre", "deleteUserMessage": "Bu kullanıcıyı silmek istediğinizden emin misiniz?", @@ -187,7 +186,6 @@ "source": "Kaynak{suffix}", "deleteMessageMultiple": "{count} dosya(lar)ını silmek istediğinizden emin misiniz?", "deleteMessageShare": "Bu paylaşımı silmek istediğinizden emin misiniz? {path} ?", - "lastModified": "Son Değişiklik{suffix}", "numberDirs": "Dizin sayısı{suffix}", "numberFiles": "Dosya sayısı{suffix}", "renameMessageConflict": "\"{filename}\" adında bir öğe zaten var!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Maksimum eşzamanlı yükleme: {maxConcurrentUpload}, yığınlanmış yükleme devre dışı", "quickJump": "Diğer dosyalara hızlıca atlayın", "moveSuccess": "Dosyalar başarıyla taşındı!", - "copySuccess": "Dosyalar başarıyla kopyalandı!" + "copySuccess": "Dosyalar başarıyla kopyalandı!", + "lastModified": "Son Değişiklik{suffix}", + "size": "Boyut{suffix}" }, "search": { "images": "Görseller", diff --git a/frontend/src/i18n/ua.json b/frontend/src/i18n/ua.json index 0bb16d5158..0c54c46ffb 100644 --- a/frontend/src/i18n/ua.json +++ b/frontend/src/i18n/ua.json @@ -159,7 +159,6 @@ "schedule": "Планування", "scheduleMessage": "Запланувати дату та час публікації.", "show": "Показати", - "size": "Розмір", "upload": "Завантажити", "optionalPassword": "Необов'язковий пароль", "deleteUserMessage": "Ви впевнені, що хочете видалити цього користувача?", @@ -187,7 +186,6 @@ "source": "Джерело{suffix}", "deleteMessageMultiple": "Ви дійсно хочете видалити файл(и) {count}?", "deleteMessageShare": "Ви впевнені, що хочете видалити цей ресурс? {path} ?", - "lastModified": "Останній раз змінено{suffix}", "numberDirs": "Кількість каталогів{suffix}", "numberFiles": "Кількість файлів{suffix}", "renameMessageConflict": "Елемент з назвою \"{filename}\" вже існує!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "Максимальне одночасне завантаження: {maxConcurrentUpload}, chunked upload вимкнено", "quickJump": "Швидкий перехід до інших файлів", "moveSuccess": "Файли успішно перенесено!", - "copySuccess": "Файли успішно скопійовано!" + "copySuccess": "Файли успішно скопійовано!", + "lastModified": "Останній раз змінено{suffix}", + "size": "Розмір{suffix}" }, "search": { "images": "Зображення", diff --git a/frontend/src/i18n/zh-cn.json b/frontend/src/i18n/zh-cn.json index 4ebcf5815c..5ca1844dc6 100644 --- a/frontend/src/i18n/zh-cn.json +++ b/frontend/src/i18n/zh-cn.json @@ -159,7 +159,6 @@ "schedule": "计划", "scheduleMessage": "请选择发布这篇帖子的日期与时间。", "show": "点击以显示", - "size": "大小", "upload": "上传", "optionalPassword": "密码(选填,不填即无密码)", "deleteUserMessage": "您确定要删除该用户吗?", @@ -187,7 +186,6 @@ "source": "资料来源{suffix}", "deleteMessageMultiple": "您确定要删除{count} 文件吗?", "deleteMessageShare": "您确定要删除此共享? {path} ?", - "lastModified": "最后修改{suffix}", "numberDirs": "目录数量{suffix}", "numberFiles": "文件数量{suffix}", "renameMessageConflict": "名为 \"{filename}\" 的项目已经存在!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "最大并发上传:{maxConcurrentUpload}已禁用分块上传", "quickJump": "快速跳转到其他文件", "moveSuccess": "文件移动成功!", - "copySuccess": "文件复制成功!" + "copySuccess": "文件复制成功!", + "lastModified": "最后修改{suffix}", + "size": "尺寸{suffix}" }, "search": { "images": "图像", diff --git a/frontend/src/i18n/zh-tw.json b/frontend/src/i18n/zh-tw.json index 90e4da6493..35c9ab3525 100644 --- a/frontend/src/i18n/zh-tw.json +++ b/frontend/src/i18n/zh-tw.json @@ -159,7 +159,6 @@ "schedule": "計畫", "scheduleMessage": "請選擇發佈這篇貼文的日期。", "show": "顯示", - "size": "大小", "upload": "上傳", "destinationSource": "目的地來源:", "deleteUserMessage": "您確定要刪除此使用者嗎?", @@ -187,7 +186,6 @@ "source": "來源{suffix}", "deleteMessageMultiple": "您確定要刪除{count} 檔案嗎?", "deleteMessageShare": "您確定要刪除此共用嗎? {path} ?", - "lastModified": "最後修改{suffix}", "numberDirs": "目錄數量{suffix}", "numberFiles": "檔案數量{suffix}", "renameMessageConflict": "名為 \"{filename}\" 的項目已經存在!", @@ -195,7 +193,9 @@ "uploadSettingsNoChunk": "最大同時上傳數量:{maxConcurrentUpload}, 已停用分塊上傳", "quickJump": "快速跳到其他檔案", "moveSuccess": "檔案移動成功!", - "copySuccess": "檔案已成功複製!" + "copySuccess": "檔案已成功複製!", + "lastModified": "最後修改{suffix}", + "size": "尺寸{suffix}" }, "search": { "images": "影像", diff --git a/frontend/src/store/getters.js b/frontend/src/store/getters.js index 2b72c7df03..39f92877bc 100644 --- a/frontend/src/store/getters.js +++ b/frontend/src/store/getters.js @@ -178,6 +178,9 @@ export const getters = { if (previewViews.includes(cv) && !state.user.preview?.disableHideSidebar) { visible = false } + if (shareInfo.singleFileShare) { + visible = state.showSidebar + } return visible }, isStickySidebar: () => { @@ -423,14 +426,18 @@ export const getters = { } return "close"; } - if (cv == "listingView") { + if (cv == "listingView" || shareInfo.singleFileShare) { if (state.user.stickySidebar) { return "menu"; } + return "back"; } return "close"; } + if (shareInfo.singleFileShare) { + return "menu"; + } if (cv == "settings") { if (state.isMobile) { return "menu"; diff --git a/frontend/src/store/mutations.js b/frontend/src/store/mutations.js index b62e3ab532..da0b3d5145 100644 --- a/frontend/src/store/mutations.js +++ b/frontend/src/store/mutations.js @@ -180,6 +180,10 @@ export const mutations = { state.showSidebar = false; emitStateChanged(); }, + setSidebarVisible(value) { + state.showSidebar = value; + emitStateChanged(); + }, setUpload(value) { state.upload = value; emitStateChanged(); @@ -284,6 +288,7 @@ export const mutations = { hash: null, token: "", subPath: "", + passwordValid: false, }; emitStateChanged(); }, diff --git a/frontend/src/store/state.js b/frontend/src/store/state.js index bbb6a9bae5..6270ad34d3 100644 --- a/frontend/src/store/state.js +++ b/frontend/src/store/state.js @@ -35,6 +35,7 @@ export const state = reactive({ hash: null, token: "", subPath: "", + passwordValid: false, }, sources: { current: "", diff --git a/frontend/src/utils/url.js b/frontend/src/utils/url.js index e79b0f4253..9f2747f4ee 100644 --- a/frontend/src/utils/url.js +++ b/frontend/src/utils/url.js @@ -183,8 +183,9 @@ export function doubleEncode(str) { } /** - * Fixes download URLs by replacing everything before /public/api + * Fixes download URLs by replacing everything before /public/api * with the current window.location.origin + globalVars.baseURL + * This is only needed when the backend didn't use externalUrl * @param {string} downloadUrl - The original download URL from backend * @returns {string} - The corrected URL using current client origin */ @@ -198,10 +199,10 @@ export function fixDownloadURL(downloadUrl) { // If /public/api is not found, return the original URL return downloadUrl; } - + // Extract the part from /public/api onwards const publicApiPath = downloadUrl.substring(publicApiIndex); - + // Build the corrected URL using current client origin and globalVars.baseURL const correctedBaseURL = removeTrailingSlash(globalVars.baseURL); return `${window.location.origin}${correctedBaseURL}${publicApiPath}`; diff --git a/frontend/src/views/Files.vue b/frontend/src/views/Files.vue index d2c10bc059..55c5040e23 100644 --- a/frontend/src/views/Files.vue +++ b/frontend/src/views/Files.vue @@ -199,6 +199,8 @@ export default { } else if (e.status === 401 && this.isShare) { // Handle share password requirement this.attemptedPasswordLogin = this.sharePassword !== ""; + // Reset password validation state on wrong password + mutations.setShareData({ passwordValid: false }); this.showPasswordPrompt(); } else { router.push({ name: "error" }); @@ -234,6 +236,13 @@ export default { mutations.setMultiple(false); mutations.closeHovers(); + if (shareInfo.singleFileShare) { + mutations.setSidebarVisible(true); + } + // Initialize password validation state for password-protected shares + if (shareInfo.isPasswordProtected) { + mutations.setShareData({ passwordValid: false }); + } // Fetch share data let file = await publicApi.fetchPub(this.shareSubPath, this.shareHash, this.sharePassword); file.hash = this.shareHash; @@ -243,6 +252,7 @@ export default { hash: this.shareHash, token: this.shareToken, subPath: this.shareSubPath, + passwordValid: true, }); // If not a directory, fetch content for preview components if (file.type != "directory") { diff --git a/frontend/src/views/bars/Default.vue b/frontend/src/views/bars/Default.vue index f6e156c493..5e974bbb16 100644 --- a/frontend/src/views/bars/Default.vue +++ b/frontend/src/views/bars/Default.vue @@ -165,7 +165,7 @@ export default { }, multiAction() { const listingView = getters.currentView(); - if (listingView == "listingView") { + if (listingView == "listingView" || shareInfo.singleFileShare) { mutations.toggleSidebar(); } else if (listingView == "settings" && state.isMobile) { mutations.toggleSidebar(); @@ -193,4 +193,16 @@ header button:hover { box-shadow: unset !important; -webkit-box-shadow: unset !important; } +header { + background-color: rgb(37 49 55 / 5%) !important; +} +/* Header with backdrop-filter support */ +@supports (backdrop-filter: none) { + header { + backdrop-filter: blur(16px) invert(0.1); + } + .dark-mode-header { + background-color: rgb(37 49 55 / 33%) !important; + } +} \ No newline at end of file diff --git a/frontend/src/views/files/OnlyOfficeEditor.vue b/frontend/src/views/files/OnlyOfficeEditor.vue index e0be1bbf84..ef6387c2fe 100644 --- a/frontend/src/views/files/OnlyOfficeEditor.vue +++ b/frontend/src/views/files/OnlyOfficeEditor.vue @@ -59,6 +59,7 @@ export default { if (state.user.debugOffice) { this.debugMode = true; this.showDebugInfo(); + this.monitorCallbackIssues(); } // Perform the setup and update the config with simplified API parameters @@ -370,13 +371,16 @@ export default { } }); - // Monitor for successful completion + // Monitor for successful completion and server-to-server communication setTimeout(() => { console.error = originalConsoleError; // Restore original console.error if (!this.hasErrors && !detectedNetworkError) { this.updateDebugStatus("✅ Document Download - Complete"); this.updateDebugStatus("🎉 Editor Initialization - Success! All steps completed."); + + // Start monitoring for server-to-server communication issues + this.monitorServerToServerCommunication(); } }, 4000); @@ -389,26 +393,84 @@ export default { this.hasErrors = true; let errorMsg = "❌ OnlyOffice Component Load Error
"; + let suggestions = []; - if (errorInfo === -2) { - errorMsg += "Error Code -2: OnlyOffice server connection failed
"; - errorMsg += "• Verify OnlyOffice server is running
"; - errorMsg += `• Test URL manually: ${this.onlyOfficeUrl}
`; - errorMsg += "• Check network connectivity
"; + if (errorInfo === -1) { + errorMsg += "Error Code -1: Unknown error loading OnlyOffice component
"; + suggestions = [ + "Check browser console for detailed error messages", + "Verify OnlyOffice server is accessible", + "Check if OnlyOffice server is properly configured", + "Try refreshing the page" + ]; + } else if (errorInfo === -2) { + errorMsg += "Error Code -2: Failed to load DocsAPI from OnlyOffice server
"; + suggestions = [ + "Verify OnlyOffice server is running and accessible", + `Test OnlyOffice server URL manually: ${this.onlyOfficeUrl}`, + "Check network connectivity between browser and OnlyOffice server", + "Verify OnlyOffice server is not behind authentication", + "Check if OnlyOffice server is fully initialized (wait a few minutes after startup)" + ]; } else if (errorInfo === -3) { - errorMsg += "Error Code -3: Document loading failed
"; - errorMsg += "• File may be corrupted or unsupported
"; - errorMsg += "• Check file permissions
"; + errorMsg += "Error Code -3: DocsAPI is not defined (OnlyOffice server not responding)
"; + suggestions = [ + "OnlyOffice server is not responding or not properly configured", + "Check OnlyOffice server logs for startup errors", + "Verify OnlyOffice server URL is correct and accessible", + "Ensure OnlyOffice server has completed initialization", + "Check if OnlyOffice server is behind a reverse proxy with incorrect configuration" + ]; } else if (errorInfo === -4) { errorMsg += "Error Code -4: Document download failed
"; - errorMsg += "• Authentication may have expired
"; - errorMsg += "• Check download URL accessibility
"; + suggestions = [ + "Authentication may have expired - try refreshing", + "Check download URL accessibility", + "Verify OnlyOffice server can reach FileBrowser", + "Check network connectivity between OnlyOffice and FileBrowser" + ]; + if (!this.getInternalUrlInfo().isSet) { - errorMsg += "• Suggestion: consider adding `server.internalUrl` if your OnlyOffice service is on the same network as FileBrowser
"; + suggestions.push("Consider adding `server.internalUrl` if OnlyOffice is on same network"); } + } else if (errorInfo === -5) { + errorMsg += "Error Code -5: Document security error
"; + suggestions = [ + "Check if document is password protected", + "Verify OnlyOffice server security settings", + "Check OnlyOffice server logs for security errors", + "Verify document format is supported" + ]; + } else if (errorInfo === -6) { + errorMsg += "Error Code -6: Document access denied
"; + suggestions = [ + "Check user permissions in FileBrowser", + "Verify OnlyOffice server has proper authentication", + "Check if file path contains special characters", + "Verify OnlyOffice server configuration" + ]; } else { errorMsg += `Error Code: ${errorInfo || 'Unknown error'}
`; - errorMsg += "• Check browser console for detailed error messages
"; + suggestions = [ + "Check browser console for detailed error messages", + "Try refreshing the page", + "Check OnlyOffice server logs" + ]; + } + + // Add suggestions as bullet points + errorMsg += "
Suggestions:
"; + suggestions.forEach(suggestion => { + errorMsg += `• ${suggestion}
`; + }); + + // Add configuration check + const configIssues = this.checkConfigurationIssues(); + if (configIssues.length > 0) { + errorMsg += "
Configuration Issues Detected:
"; + configIssues.forEach(issue => { + errorMsg += `• ${issue}
`; + }); } errorMsg += `
${wikiLinkText}`; @@ -416,6 +478,243 @@ export default { this.updateDebugStatus(errorMsg); } }, + + checkConfigurationIssues() { + const issues = []; + + // Check OnlyOffice URL + if (!this.onlyOfficeUrl || this.onlyOfficeUrl === '') { + issues.push("OnlyOffice URL is not configured"); + } else if (!this.onlyOfficeUrl.startsWith('http')) { + issues.push("OnlyOffice URL should start with http:// or https://"); + } + + // Check internal URL configuration + const internalUrlInfo = this.getInternalUrlInfo(); + if (internalUrlInfo.isSet && internalUrlInfo.message.includes('Error')) { + issues.push("Internal URL configuration has parsing errors"); + } + + // Check document URL accessibility + if (this.clientConfig && this.clientConfig.document && this.clientConfig.document.url) { + try { + const docUrl = new URL(this.clientConfig.document.url); + if (docUrl.protocol !== window.location.protocol) { + issues.push("Document URL protocol mismatch with current page"); + } + } catch (e) { + issues.push("Document URL is malformed"); + } + } + + // Check callback URL + if (this.clientConfig && this.clientConfig.editorConfig && this.clientConfig.editorConfig.callbackUrl) { + try { + const callbackUrl = new URL(this.clientConfig.editorConfig.callbackUrl); + if (callbackUrl.protocol !== window.location.protocol) { + issues.push("Callback URL protocol mismatch with current page"); + } + } catch (e) { + issues.push("Callback URL is malformed"); + } + } + + return issues; + }, + + // Monitor for callback-related issues and server-to-server communication problems + monitorCallbackIssues() { + if (!this.debugMode) return; + + // Monitor for callback errors in the network tab + const originalFetch = window.fetch; + window.fetch = (...args) => { + return originalFetch.apply(window, args).then(response => { + if (response.url.includes('onlyoffice/callback')) { + if (response.status === 405) { + this.hasErrors = true; + this.updateDebugStatus(` + ❌ Callback Method Not Allowed (405)
+ Issue: OnlyOffice server is sending ${args[1]?.method || 'GET'} requests to callback URL
+ Expected: POST requests
+ Root Cause: OnlyOffice server configuration issue
+ Solution:
+ • Check OnlyOffice server callback configuration
+ • Verify callback URL is correctly set in OnlyOffice server
+ • Ensure OnlyOffice server is using correct HTTP method
+ • Check OnlyOffice server logs for callback configuration errors
+ `); + } else if (response.status === 400) { + this.hasErrors = true; + this.updateDebugStatus(` + ❌ Callback Bad Request (400)
+ Issue: OnlyOffice server sent invalid callback data
+ Root Cause: OnlyOffice server → FileBrowser API communication problem
+ Solution:
+ • Check OnlyOffice server logs for callback generation errors
+ • Verify JWT secret matches between OnlyOffice and FileBrowser
+ • Check OnlyOffice server callback URL configuration
+ • Ensure OnlyOffice server can reach FileBrowser internal URL
+ `); + } else if (response.status === 500) { + this.hasErrors = true; + this.updateDebugStatus(` + ❌ Callback Internal Server Error (500)
+ Issue: FileBrowser API error processing OnlyOffice callback
+ Root Cause: FileBrowser API configuration or processing issue
+ Solution:
+ • Check FileBrowser server logs for callback processing errors
+ • Verify FileBrowser API configuration
+ • Check if OnlyOffice server is sending valid callback data
+ • Ensure FileBrowser has proper permissions to save files
+ `); + } + } + return response; + }); + }; + + // Monitor for JWT parsing errors and other callback issues + const originalConsoleError = console.error; + console.error = (...args) => { + originalConsoleError.apply(console, args); + + const errorStr = args.join(' '); + if (errorStr.includes('JWT') && errorStr.includes('callback')) { + this.hasErrors = true; + this.updateDebugStatus(` + ❌ JWT Parsing Error in Callback
+ Issue: OnlyOffice callback JWT token cannot be parsed
+ Root Cause: OnlyOffice server → FileBrowser API JWT communication problem
+ Solution:
+ • Check OnlyOffice server JWT configuration
+ • Verify JWT secret matches between OnlyOffice and FileBrowser
+ • Check OnlyOffice server logs for JWT generation errors
+ • Ensure OnlyOffice server is using correct JWT signing method
+ `); + } else if (errorStr.includes('callback') && (errorStr.includes('network') || errorStr.includes('fetch'))) { + this.hasErrors = true; + this.updateDebugStatus(` + ❌ Callback Network Error
+ Issue: OnlyOffice server cannot reach FileBrowser callback URL
+ Root Cause: Network connectivity between OnlyOffice server and FileBrowser API
+ Solution:
+ • Check if OnlyOffice server can reach FileBrowser internal URL
+ • Verify callback URL is accessible from OnlyOffice server
+ • Check network configuration between services
+ • Ensure FileBrowser internal URL is correctly configured
+ `); + } + }; + + // Monitor for document save failures (indicates server-to-server communication issues) + this.monitorDocumentSaveFailures(); + + // Restore original functions after 15 seconds + setTimeout(() => { + window.fetch = originalFetch; + console.error = originalConsoleError; + }, 15000); + }, + + // Monitor for document save failures which indicate server-to-server communication issues + monitorDocumentSaveFailures() { + if (!this.debugMode) return; + + // Track if document was opened but never saved + let documentOpened = false; + let saveAttempts = 0; + let lastSaveAttempt = 0; + + // Monitor for document ready event + const checkDocumentReady = () => { + if (this.clientConfig && this.clientConfig.document) { + documentOpened = true; + console.log("OnlyOffice debug: Document opened successfully"); + } + }; + + // Monitor for save attempts + const checkSaveAttempts = () => { + if (documentOpened) { + saveAttempts++; + lastSaveAttempt = Date.now(); + console.log(`OnlyOffice debug: Save attempt #${saveAttempts}`); + } + }; + + // Check for save failures after 30 seconds + setTimeout(() => { + if (documentOpened && saveAttempts === 0) { + this.hasErrors = true; + this.updateDebugStatus(` + ❌ Document Save Issues Detected
+ Issue: Document opened but no save attempts detected
+ Root Cause: OnlyOffice server → FileBrowser API communication problem
+ Possible Causes:
+ • OnlyOffice server cannot reach FileBrowser callback URL
+ • Callback URL is incorrect or inaccessible
+ • JWT secret mismatch between OnlyOffice and FileBrowser
+ • Network connectivity issues between services
+ Solution:
+ • Check OnlyOffice server logs for callback errors
+ • Verify callback URL is accessible from OnlyOffice server
+ • Test callback URL manually from OnlyOffice server
+ • Check FileBrowser internal URL configuration
+ `); + } + }, 30000); + + // Expose monitoring functions globally for debugging + window.onlyOfficeDebug = { + checkDocumentReady, + checkSaveAttempts, + getStats: () => ({ documentOpened, saveAttempts, lastSaveAttempt }) + }; + }, + + // Monitor for server-to-server communication issues (OnlyOffice server → FileBrowser API) + monitorServerToServerCommunication() { + if (!this.debugMode) return; + + // Instead of testing the download URL (which fails due to hostname resolution), + // we'll monitor for actual callback success/failure patterns + this.updateDebugStatus("🔄 Monitoring OnlyOffice server → FileBrowser API communication..."); + + // Set up a timer to check if callbacks are working + let callbackCount = 0; + + // Monitor for successful callbacks in the network tab + const originalFetch = window.fetch; + window.fetch = (...args) => { + return originalFetch.apply(window, args).then(response => { + if (response.url.includes('onlyoffice/callback') && response.status === 200) { + callbackCount++; + this.updateDebugStatus(`✅ OnlyOffice callback #${callbackCount} received successfully`); + } + return response; + }); + }; + + // Check after 10 seconds if we've seen any callbacks + setTimeout(() => { + window.fetch = originalFetch; // Restore original fetch + + if (callbackCount > 0) { + this.updateDebugStatus(`✅ OnlyOffice server → FileBrowser API communication confirmed (${callbackCount} callbacks received)`); + } else { + // Only show warning if we haven't seen any callbacks and document was opened + if (this.clientConfig && this.clientConfig.document) { + this.updateDebugStatus(` + ⚠️ No OnlyOffice callbacks detected yet
+ Note: This is normal if you haven't made changes to the document
+ Expected: Callbacks will appear when you edit and save the document
+ If editing fails: Check OnlyOffice server logs for callback errors
+ `); + } + } + }, 10000); + }, }, }; diff --git a/frontend/src/views/files/plyrViewer.vue b/frontend/src/views/files/plyrViewer.vue index d305c15a3a..7fa0ea0050 100644 --- a/frontend/src/views/files/plyrViewer.vue +++ b/frontend/src/views/files/plyrViewer.vue @@ -1,11 +1,19 @@