Compare commits

...
Author SHA1 Message Date
Graham Steffaniak e56d215ff2 fixed issues for 0.6.x (#463) 2025-03-28 18:35:08 -05:00
Christoph Auer dfe024ab62 i18n: Small improvements to de.json (#453) 2025-03-26 18:47:34 -05:00
Graham SteffaniakandNguyễn Trần Chung ce292c7be1 Beta/v0.6.3 (#450)
Co-authored-by: Nguyễn Trần Chung <nguyentranchung52th@gmail.com>
2025-03-24 18:12:06 -05:00
Nguyễn Trần Chung e39cf2ddf9 Update makefile (#445) 2025-03-22 10:29:38 -07:00
Graham Steffaniak 6909df0071 Beta/v0.6.2 (#443) 2025-03-20 18:29:42 -05:00
74 changed files with 941 additions and 720 deletions

No files matched your search

+34
View File
@@ -2,6 +2,40 @@
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.6.4-beta
**BugFixes**:
- fix preview arow issue. https://github.com/gtsteffaniak/filebrowser/issues/457
- fix password change issue.
- apply user defaults to publi user on startup https://github.com/gtsteffaniak/filebrowser/issues/451
## v0.6.3-beta
**Notes**:
- windows directories get better naming, root directories like "D:\ get named "D", otherwise base filepath is the name when unselected "D:\path\to\folder" gets named "folder" (just like linux)
- `.pdf` files added to default onlyoffice exclusion list.
**BugFixes**:
- windows would not refresh file info automatically when viewing because of path issue.
- windows paths without name for "D:\" would cause issues.
- share path error https://github.com/gtsteffaniak/filebrowser/issues/429
- fix bug where resource content flag would load entire file into memory.
## v0.6.2-beta
**Notes**:
- Added playwright tests for bugfixes for permantent fix for stability.
(except onlyoffice since it requires integrations)
**BugFixes**:
- Context menu should only be available inside the folder/files container https://github.com/gtsteffaniak/filebrowser/issues/430
- drag and drop files from desktop to browser is fixed.
- replace prompt cancel button didn't work.
- key events on listing page not working (like delete key)
- fixed share viewing issue https://github.com/gtsteffaniak/filebrowser/issues/429
- disableUsedPercentage hides entire source https://github.com/gtsteffaniak/filebrowser/issues/438
- createUserDir fix for proxy users and new users https://github.com/gtsteffaniak/filebrowser/issues/440
## v0.6.1-beta
**New Feature**:
+1 -1
View File
@@ -1,6 +1,6 @@
FROM gtstef/playwright-base
WORKDIR /app
COPY [ "./_docker/src/regular/", "./" ]
COPY [ "./_docker/src/general/", "./" ]
WORKDIR /app/frontend
COPY [ "./frontend/", "./" ]
WORKDIR /app/backend/
@@ -10,9 +10,9 @@ import { defineConfig, devices } from "@playwright/test";
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
globalSetup: "./global-setup",
timeout: 6000,
testDir: "./tests",
globalSetup: "./tests-playwright/global-setup",
timeout: 5000,
testDir: "./tests-playwright/general",
/* Run tests in files in parallel */
fullyParallel: false,
/* Fail the build on CI if you accidentally left test.only in the source code. */
@@ -28,7 +28,7 @@ export default defineConfig({
actionTimeout: 5000,
storageState: "loginAuth.json",
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: "http://127.0.0.1",
baseURL: "http://127.0.0.1/",
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
+1 -1
View File
@@ -1,6 +1,6 @@
server:
port: 80
baseURL: "/"
baseURL: "/files/"
logging:
- levels: "info|error|debug"
sources:
@@ -11,8 +11,8 @@ import { defineConfig, devices } from "@playwright/test";
*/
export default defineConfig({
//globalSetup: "./global-setup",
timeout: 6000,
testDir: "./tests-proxy",
timeout: 5000,
testDir: "./tests-playwright/noauth",
/* Run tests in files in parallel */
fullyParallel: false,
/* Fail the build on CI if you accidentally left test.only in the source code. */
+4 -2
View File
@@ -5,6 +5,9 @@ server:
- levels: "info|error|debug"
sources:
- path: "../frontend/tests/playwright-files"
config:
defaultEnabled: true
createUserDir: true
frontend:
name: "Graham's Filebrowser"
disableDefaultLinks: true
@@ -23,10 +26,9 @@ auth:
userDefaults:
darkMode: true
disableSettings: false
scope: "."
singleClick: false
permissions:
admin: false
modify: false
modify: true
share: false
api: false
@@ -11,8 +11,8 @@ import { defineConfig, devices } from "@playwright/test";
*/
export default defineConfig({
//globalSetup: "./global-setup",
timeout: 6000,
testDir: "./tests-proxy",
timeout: 3000,
testDir: "./tests-playwright/proxy",
/* Run tests in files in parallel */
fullyParallel: false,
/* Fail the build on CI if you accidentally left test.only in the source code. */
@@ -25,7 +25,7 @@ export default defineConfig({
reporter: "line",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
actionTimeout: 5000,
actionTimeout: 3000,
//storageState: "loginAuth.json",
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: "http://127.0.0.1",
-3
View File
@@ -9,7 +9,6 @@ import (
"strings"
"github.com/gtsteffaniak/filebrowser/backend/errors"
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/users"
@@ -168,8 +167,6 @@ func (a *HookAuth) SaveUser() (*users.User, error) {
}
u = a.GetUser(d)
files.MakeUserDirs(u)
err = a.Users.Save(u, false)
if err != nil {
return nil, err
+127
View File
@@ -0,0 +1,127 @@
package cmd
import (
"flag"
"fmt"
"os"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/storage"
"github.com/gtsteffaniak/filebrowser/backend/users"
"github.com/gtsteffaniak/filebrowser/backend/version"
)
var (
configPath string
)
// return bool to indicate if the program should continue running
func runCLI() bool {
// Global flags
var help bool
// Override the default usage output to use generalUsage()
flag.Usage = generalUsage
flag.StringVar(&configPath, "c", "", "Path to the config file, default: config.yaml")
flag.BoolVar(&help, "h", false, "Get help about commands")
if configPath == "" {
configPath = os.Getenv("FILEBROWSER_CONFIG")
}
if configPath == "" {
configPath = "config.yaml"
}
// Parse global flags (before subcommands)
flag.Parse() // print generalUsage on error
// Show help if requested
if help {
generalUsage()
return false
}
// Create a new FlagSet for the 'set' subcommand
setCmd := flag.NewFlagSet("set", flag.ExitOnError)
var user, scope, dbConfig string
var asAdmin bool
setCmd.StringVar(&user, "u", "", "Comma-separated username and password: \"set -u <username>,<password>\"")
setCmd.BoolVar(&asAdmin, "a", false, "Create user as admin user, used in combination with -u")
setCmd.StringVar(&scope, "s", "", "Specify a user scope, otherwise default user config scope is used")
setCmd.StringVar(&dbConfig, "c", "config.yaml", "Path to the config file, default: config.yaml")
// Parse subcommand flags only if a subcommand is specified
if len(os.Args) > 1 {
switch os.Args[1] {
case "set":
err := setCmd.Parse(os.Args[2:])
if err != nil {
setCmd.PrintDefaults()
os.Exit(1)
}
userInfo := strings.Split(user, ",")
if len(userInfo) < 2 {
fmt.Printf("not enough info to create user: \"set -u username,password\", only provided %v\n", userInfo)
setCmd.PrintDefaults()
os.Exit(1)
}
username := userInfo[0]
password := userInfo[1]
ok := getStore(dbConfig)
if !ok {
logger.Fatal("could not load db info")
}
user, err := store.Users.Get(username)
if err != nil {
newUser := users.User{
Username: username,
NonAdminEditable: users.NonAdminEditable{
Password: password,
},
}
for _, source := range settings.Config.Server.SourceMap {
if source.Config.DefaultEnabled {
newUser.Scopes = append(newUser.Scopes, users.SourceScope{
Name: source.Name,
Scope: source.Config.DefaultUserScope,
})
}
}
// Create the user logic
if asAdmin {
logger.Info(fmt.Sprintf("Creating user as admin: %s\n", username))
} else {
logger.Info(fmt.Sprintf("Creating non-admin user: %s\n", username))
}
err = storage.CreateUser(newUser, asAdmin)
if err != nil {
logger.Error(fmt.Sprintf("could not create user: %v", err))
}
return false
}
user.Password = password
if asAdmin {
user.Perm.Admin = true
}
err = store.Users.Save(user, true)
if err != nil {
logger.Error(fmt.Sprintf("could not update user: %v", err))
}
fmt.Printf("successfully updated user: %s\n", username)
return false
case "version":
fmt.Printf(`FileBrowser Quantum - A modern web-based file manager
Version : %v
Commit : %v
Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v
`, version.Version, version.CommitSHA, version.Version)
return false
}
}
return true
}
+12 -157
View File
@@ -2,11 +2,9 @@ package cmd
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"github.com/gtsteffaniak/filebrowser/backend/diskcache"
@@ -19,62 +17,20 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/swagger/docs"
"github.com/swaggo/swag"
"github.com/gtsteffaniak/filebrowser/backend/users"
"github.com/gtsteffaniak/filebrowser/backend/version"
)
func getStore(configFile string) (*storage.Storage, bool) {
var store *storage.Storage
func getStore(configFile string) bool {
// Use the config file (global flag)
settings.Initialize(configFile)
store, hasDB, err := storage.InitializeDb(settings.Config.Server.Database)
s, hasDB, err := storage.InitializeDb(settings.Config.Server.Database)
if err != nil {
logger.Fatal(fmt.Sprintf("could not load db info: %v", err))
}
// update source info for users if names/sources/paths might have changed
usersList, err2 := store.Users.Gets()
if err2 != nil {
logger.Fatal(fmt.Sprintf("could not load users: %v", err2))
}
// this function adds scopes as needed on startup
for _, user := range usersList {
updateUser := false
newScopes := []users.SourceScope{}
for _, source := range settings.Config.Server.SourceMap {
scopePath := ""
if !user.Perm.Admin {
scopePath = source.Config.DefaultUserScope
}
scope, err := settings.GetScopeFromSourcePath(user.Scopes, source.Path)
if err != nil {
if user.Perm.Admin || source.Config.DefaultEnabled {
newScopes = append(newScopes, users.SourceScope{Scope: scopePath, Name: source.Path}) // backend name is path
updateUser = true
}
} else {
newScopes = append(newScopes, users.SourceScope{Scope: scope, Name: source.Path}) // backend name is path
}
}
user.Scopes = newScopes
// maintain backwards compatibility, update user scope from scopes
if len(user.Scopes) == 0 {
user.Scopes = []users.SourceScope{
{
Scope: user.Scope,
Name: settings.Config.Server.DefaultSource.Path, // backend name is path
},
}
updateUser = true
}
if !updateUser {
continue
}
err := store.Users.Save(user, false)
if err != nil {
logger.Error(fmt.Sprintf("could not update user: %v", err))
}
}
return store, hasDB
store = s
return hasDB
}
func generalUsage() {
@@ -91,122 +47,20 @@ commands:
}
func StartFilebrowser() {
// Global flags
var configPath string
var help bool
// Override the default usage output to use generalUsage()
flag.Usage = generalUsage
flag.StringVar(&configPath, "c", "", "Path to the config file, default: config.yaml")
flag.BoolVar(&help, "h", false, "Get help about commands")
if configPath == "" {
configPath = os.Getenv("FILEBROWSER_CONFIG")
}
if configPath == "" {
configPath = "config.yaml"
}
// Parse global flags (before subcommands)
flag.Parse() // print generalUsage on error
// Show help if requested
if help {
generalUsage()
keepGoing := runCLI()
if !keepGoing {
return
}
// Create a new FlagSet for the 'set' subcommand
setCmd := flag.NewFlagSet("set", flag.ExitOnError)
var user, scope, dbConfig string
var asAdmin bool
setCmd.StringVar(&user, "u", "", "Comma-separated username and password: \"set -u <username>,<password>\"")
setCmd.BoolVar(&asAdmin, "a", false, "Create user as admin user, used in combination with -u")
setCmd.StringVar(&scope, "s", "", "Specify a user scope, otherwise default user config scope is used")
setCmd.StringVar(&dbConfig, "c", "config.yaml", "Path to the config file, default: config.yaml")
// Create context and channels for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan struct{}) // Signals server has stopped
shutdownComplete := make(chan struct{}) // Signals shutdown process is complete
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
// Parse subcommand flags only if a subcommand is specified
if len(os.Args) > 1 {
switch os.Args[1] {
case "set":
err := setCmd.Parse(os.Args[2:])
if err != nil {
setCmd.PrintDefaults()
os.Exit(1)
}
userInfo := strings.Split(user, ",")
if len(userInfo) < 2 {
fmt.Printf("not enough info to create user: \"set -u username,password\", only provided %v\n", userInfo)
setCmd.PrintDefaults()
os.Exit(1)
}
username := userInfo[0]
password := userInfo[1]
store, ok := getStore(dbConfig)
if !ok {
logger.Fatal("could not load db info")
}
user, err := store.Users.Get(username)
if err != nil {
newUser := users.User{
Username: username,
NonAdminEditable: users.NonAdminEditable{
Password: password,
},
}
for _, source := range settings.Config.Server.SourceMap {
if source.Config.DefaultEnabled {
newUser.Scopes = append(newUser.Scopes, users.SourceScope{
Name: source.Name,
Scope: source.Config.DefaultUserScope,
})
}
}
// Create the user logic
if asAdmin {
logger.Info(fmt.Sprintf("Creating user as admin: %s\n", username))
} else {
logger.Info(fmt.Sprintf("Creating non-admin user: %s\n", username))
}
err = storage.CreateUser(newUser, asAdmin)
if err != nil {
logger.Error(fmt.Sprintf("could not create user: %v", err))
}
return
}
user.Password = password
if asAdmin {
user.Perm.Admin = true
}
err = store.Users.Save(user, true)
if err != nil {
logger.Error(fmt.Sprintf("could not update user: %v", err))
}
fmt.Printf("successfully updated user: %s\n", username)
return
case "version":
fmt.Printf(`FileBrowser Quantum - A modern web-based file manager
Version : %v
Commit : %v
Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v
`, version.Version, version.CommitSHA, version.Version)
return
}
}
store, dbExists := getStore(configPath)
done := make(chan struct{}) // Signals server has stopped
shutdownComplete := make(chan struct{}) // Signals shutdown process is complete
dbExists := getStore(configPath)
database := fmt.Sprintf("Using existing database : %v", settings.Config.Server.Database)
if !dbExists {
database = fmt.Sprintf("Creating new database : %v", settings.Config.Server.Database)
@@ -231,6 +85,7 @@ Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v
for _, source := range settings.Config.Server.SourceMap {
go files.Initialize(source)
}
validateUserInfo()
// Start the rootCMD in a goroutine
go func() {
if err := rootCMD(ctx, store, &serverConfig, shutdownComplete); err != nil {
+72
View File
@@ -0,0 +1,72 @@
package cmd
import (
"fmt"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/users"
)
func validateUserInfo() {
// update source info for users if names/sources/paths might have changed
usersList, err := store.Users.Gets()
if err != nil {
logger.Fatal(fmt.Sprintf("could not load users: %v", err))
}
for _, user := range usersList {
if user.Username == "publicUser" {
settings.ApplyUserDefaults(user)
err := store.Users.Save(user, false)
if err != nil {
logger.Error(fmt.Sprintf("could not update user: %v", err))
}
}
updateUserScopes(user)
}
}
func updateUserScopes(user *users.User) {
updateUser := false
newScopes := []users.SourceScope{}
for _, source := range settings.Config.Server.SourceMap {
scopePath, err := settings.GetScopeFromSourcePath(user.Scopes, source.Path)
if !user.Perm.Admin {
scopePath = source.Config.DefaultUserScope
}
if scopePath == "" {
scopePath = "/"
}
if source.Config.CreateUserDir && !user.Perm.Admin {
scopePath = fmt.Sprintf("%s%s", scopePath, users.CleanUsername(user.Username))
}
// if user doesn't yet have scope for source, add it for admins and default sources
if err != nil {
if user.Perm.Admin || source.Config.DefaultEnabled {
newScopes = append(newScopes, users.SourceScope{Scope: scopePath, Name: source.Path}) // backend name is path
updateUser = true
}
} else {
newScopes = append(newScopes, users.SourceScope{Scope: scopePath, Name: source.Path}) // backend name is path
}
user.Scopes = newScopes
}
// maintain backwards compatibility, update user scope from scopes
if len(user.Scopes) == 0 {
user.Scopes = []users.SourceScope{
{
Scope: settings.Config.Server.DefaultSource.Config.DefaultUserScope,
Name: settings.Config.Server.DefaultSource.Path, // backend name is path
},
}
updateUser = true
}
if !updateUser {
return
}
err := store.Users.Save(user, false)
if err != nil {
logger.Error(fmt.Sprintf("could not update user: %v", err))
}
}
+6 -2
View File
@@ -82,7 +82,6 @@ func FileInfoFaster(opts FileOptions) (ExtendedFileInfo, error) {
if index == nil {
return response, fmt.Errorf("could not get index: %v ", opts.Source)
}
realPath, isDir, err := index.GetRealPath(opts.Path)
if err != nil {
return response, err
@@ -115,7 +114,12 @@ func FileInfoFaster(opts FileOptions) (ExtendedFileInfo, error) {
if !exists {
return response, fmt.Errorf("could not get metadata for path: %v", opts.Path)
}
if opts.Content {
if opts.Content && strings.HasPrefix(info.Type, "text") {
// Check file size
if info.Size > 50*1024*1024 { // 50 megabytes in bytes
logger.Debug(fmt.Sprintf("Reading large text file contents: "+info.Path, info.Name))
}
content, err := getContent(realPath)
if err != nil {
return response, err
-2
View File
@@ -184,10 +184,8 @@ func (idx *Index) indexDirectory(adjustedPath string, quick, recursive bool) err
}
dirFileInfo.SortItems()
// Update the current directory metadata in the index
idx.UpdateMetadata(dirFileInfo)
return nil
}
+22 -40
View File
@@ -3,65 +3,47 @@ package files
import (
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/users"
)
var (
invalidFilenameChars = regexp.MustCompile(`[^0-9A-Za-z@_\-.]`)
dashes = regexp.MustCompile(`[\-]+`)
)
// todo fix this!!
// MakeUserDir makes the user directory according to settings.
func (idx *Index) MakeUserDir(username string, scope string) error {
if idx.Config.CreateUserDir {
username = cleanUsername(username)
if username == "" || username == "-" || username == "." {
logger.Error(fmt.Sprintf("create user: invalid user for home dir creation: [%s]", username))
}
}
userScope := path.Join("/", scope)
fullPath := filepath.Join(idx.Path, userScope)
logger.Debug(fmt.Sprintf("creating user home dir: [%s]", fullPath))
func MakeUserDir(fullPath string) error {
if err := os.MkdirAll(fullPath, os.ModePerm); err != nil {
return err
}
return nil
}
func MakeUserDirs(u *users.User) {
for _, scope := range u.Scopes {
source := settings.Config.Server.NameToSource[scope.Name]
func MakeUserDirs(u *users.User) error {
cleanedUserName := users.CleanUsername(u.Username)
if cleanedUserName == "" || cleanedUserName == "-" || cleanedUserName == "." {
logger.Error(fmt.Sprintf("create user: invalid user for home dir creation: [%s]", u.Username))
}
for i, scope := range u.Scopes {
source := settings.Config.Server.SourceMap[scope.Name]
if source.Config.CreateUserDir {
idx := GetIndex(source.Name)
if idx == nil {
logger.Error(fmt.Sprintf("create user: failed to find source index for user home dir creation: %s", source.Name))
if !source.Config.CreateUserDir {
continue
}
err := idx.MakeUserDir(u.Username, scope.Scope)
if err != nil {
logger.Error(fmt.Sprintf("create user: failed to create user home dir: %s", err))
fullPath := ""
if filepath.Base(scope.Scope) != cleanedUserName && !u.Perm.Admin {
scope.Scope = filepath.Join(scope.Scope, cleanedUserName)
fullPath = filepath.Join(source.Path, scope.Scope)
} else {
fullPath = filepath.Join(source.Path, scope.Scope, cleanedUserName)
}
err := MakeUserDir(fullPath)
if err != nil {
return fmt.Errorf("create user: failed to create user home dir: %s", err)
}
// update scope to reflect new user home dir
u.Scopes[i] = scope
}
}
}
func cleanUsername(s string) string {
// Remove any trailing space to avoid ending on -
s = strings.Trim(s, " ")
s = strings.Replace(s, "..", "", -1)
// Replace all characters which not in the list `0-9A-Za-z@_\-.` with a dash
s = invalidFilenameChars.ReplaceAllString(s, "-")
// Remove any multiple dashes caused by replacements above
s = dashes.ReplaceAllString(s, "-")
return s
return nil
}
+14 -14
View File
@@ -1,24 +1,24 @@
module github.com/gtsteffaniak/filebrowser/backend
go 1.23
go 1.23.0
toolchain go1.23.1
toolchain go1.24.1
require (
github.com/asdine/storm/v3 v3.2.1
github.com/disintegration/imaging v1.6.2
github.com/dsoprea/go-exif/v3 v3.0.1
github.com/goccy/go-yaml v1.15.23
github.com/golang-jwt/jwt/v4 v4.5.1
github.com/google/go-cmp v0.6.0
github.com/goccy/go-yaml v1.16.0
github.com/golang-jwt/jwt/v4 v4.5.2
github.com/google/go-cmp v0.7.0
github.com/shirou/gopsutil/v3 v3.24.5
github.com/spf13/afero v1.11.0
github.com/stretchr/testify v1.10.0
github.com/swaggo/http-swagger v1.3.4
github.com/swaggo/swag v1.16.4
golang.org/x/crypto v0.33.0
golang.org/x/image v0.24.0
golang.org/x/sys v0.30.0
golang.org/x/crypto v0.36.0
golang.org/x/image v0.25.0
golang.org/x/sys v0.31.0
)
require (
@@ -28,11 +28,11 @@ require (
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect
github.com/go-errors/errors v1.5.1 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonpointer v0.21.1 // indirect
github.com/go-openapi/jsonreference v0.21.0 // indirect
github.com/go-openapi/spec v0.21.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/golang/geo v0.0.0-20230421003525-6adc56603217 // indirect
github.com/go-openapi/swag v0.23.1 // indirect
github.com/golang/geo v0.0.0-20250321002858-2bb09a976f49 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
@@ -41,9 +41,9 @@ require (
github.com/swaggo/files v1.0.1 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.etcd.io/bbolt v1.4.0 // indirect
golang.org/x/net v0.35.0 // indirect
golang.org/x/text v0.22.0 // indirect
golang.org/x/tools v0.30.0 // indirect
golang.org/x/net v0.37.0 // indirect
golang.org/x/text v0.23.0 // indirect
golang.org/x/tools v0.31.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+28 -28
View File
@@ -36,23 +36,23 @@ github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3Bop
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/jsonpointer v0.21.1 h1:whnzv/pNXtK2FbX/W9yJfRmE2gsmkfahjMKB0fZvcic=
github.com/go-openapi/jsonpointer v0.21.1/go.mod h1:50I1STOfbY1ycR8jGz8DaMeLCdXiI6aDteEdRNNzpdk=
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=
github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
github.com/goccy/go-yaml v1.15.23 h1:WS0GAX1uNPDLUvLkNU2vXq6oTnsmfVFocjQ/4qA48qo=
github.com/goccy/go-yaml v1.15.23/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/go-openapi/swag v0.23.1 h1:lpsStH0n2ittzTnbaSloVZLuB5+fvSY/+hnagBjSNZU=
github.com/go-openapi/swag v0.23.1/go.mod h1:STZs8TbRvEQQKUA+JZNAm3EWlgaOBGpyFDqQnDHMef0=
github.com/goccy/go-yaml v1.16.0 h1:d7m1G7A0t+logajVtklHfDYJs2Et9g3gHwdBNNFou0w=
github.com/goccy/go-yaml v1.16.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/geo v0.0.0-20230421003525-6adc56603217 h1:HKlyj6in2JV6wVkmQ4XmG/EIm+SCYlPZ+V4GWit7Z+I=
github.com/golang/geo v0.0.0-20230421003525-6adc56603217/go.mod h1:8wI0hitZ3a1IxZfeH3/5I97CI8i5cLGsYe7xNhQGs9U=
github.com/golang/geo v0.0.0-20250321002858-2bb09a976f49 h1:JJ32MDIC/hIQ/Fq8Ej9Hgh1s3D82FYNMt54WYViOI7Y=
github.com/golang/geo v0.0.0-20250321002858-2bb09a976f49/go.mod h1:J+F9/3Ofc8ysEOY2/cNjxTMl2eB1gvPIywEHUplPgDA=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
@@ -60,8 +60,8 @@ github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
@@ -104,14 +104,14 @@ go.etcd.io/bbolt v1.4.0 h1:TU77id3TnN/zKr7CO/uk+fBCwF2jGcMuw2B/FMAzYIk=
go.etcd.io/bbolt v1.4.0/go.mod h1:AsD+OCi/qPN1giOX1aiLAha3o1U8rAz65bvN4j0sRuk=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM=
golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191105084925-a882066a44e0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@@ -123,12 +123,12 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -143,8 +143,8 @@ golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -153,13 +153,13 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.30.0 h1:BgcpHewrV5AUp2G9MebG4XPFI1E2W41zU1SaqVA9vJY=
golang.org/x/tools v0.30.0/go.mod h1:c347cR/OJfw5TI+GfX7RUPNMdDRRbjvYTS0jPyvsVtY=
golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
-3
View File
@@ -15,7 +15,6 @@ import (
"golang.org/x/crypto/bcrypt"
"github.com/gtsteffaniak/filebrowser/backend/errors"
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/share"
"github.com/gtsteffaniak/filebrowser/backend/users"
@@ -151,8 +150,6 @@ func signupHandler(w http.ResponseWriter, r *http.Request) {
user.Username = info.Username
user.Password = info.Password
files.MakeUserDirs(user)
err = store.Users.Save(user, true)
if err == errors.ErrExist {
http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
+12 -8
View File
@@ -11,8 +11,8 @@ import (
jwt "github.com/golang-jwt/jwt/v4"
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/share"
"github.com/gtsteffaniak/filebrowser/backend/storage"
"github.com/gtsteffaniak/filebrowser/backend/users"
)
@@ -56,7 +56,8 @@ func withHashFileHelper(fn handleFunc) handleFunc {
return status, fmt.Errorf("could not authenticate share request")
}
}
data.path = link.Path + "/" + path
data.path = strings.TrimSuffix(link.Path, "/") + "/" + strings.TrimPrefix(path, "/")
// Get file information with options
file, err := FileInfoFasterFunc(files.FileOptions{
Path: data.path,
@@ -66,12 +67,11 @@ func withHashFileHelper(fn handleFunc) handleFunc {
})
file.Token = link.Token
if err != nil {
logger.Error(fmt.Sprintf("error fetching file info for share %v %v %v", hash, path, err))
return errToStatus(err), fmt.Errorf("error fetching share from server")
}
// Set the file info in the `data` object
data.raw = file
// Call the next handler with the data
return fn(w, r, data)
}
@@ -111,13 +111,17 @@ func withUserHelper(fn handleFunc) handleFunc {
return http.StatusInternalServerError, err
}
if config.Auth.Methods.ProxyAuth.CreateUser {
newUser := &users.User{Username: proxyUser}
settings.ApplyUserDefaults(newUser)
err := store.Users.Save(newUser, false)
hashpass, err := users.HashPwd(proxyUser)
if err != nil {
return http.StatusInternalServerError, err
}
data.user, err = store.Users.Get(proxyUser)
newUser := storage.CreateUser(users.User{
Username: proxyUser,
NonAdminEditable: users.NonAdminEditable{
Password: hashpass, // hashed password that can't actually be used
},
}, false)
data.user, err = store.Users.Get(newUser)
if err != nil {
return http.StatusInternalServerError, err
}
+2 -2
View File
@@ -7,7 +7,6 @@ import (
"io"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
@@ -16,6 +15,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/utils"
)
const (
@@ -63,7 +63,7 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
return http.StatusForbidden, err
}
fileInfo, err := files.FileInfoFaster(files.FileOptions{
Path: filepath.Join(userscope, path),
Path: utils.JoinPathAsUnix(userscope, path),
Modify: d.user.Perm.Modify,
Source: source,
Expand: false,
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/img"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/utils"
)
type ImgService interface {
@@ -61,7 +62,7 @@ func previewHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (
return http.StatusForbidden, err
}
fileInfo, err := files.FileInfoFaster(files.FileOptions{
Path: filepath.Join(userscope, path),
Path: utils.JoinPathAsUnix(userscope, path),
Modify: d.user.Perm.Modify,
Source: source,
Expand: true,
+1 -9
View File
@@ -29,21 +29,13 @@ import (
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /public/dl [get]
func publicRawHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
filePrefix := ""
file, ok := d.raw.(files.ExtendedFileInfo)
if ok {
filePrefix = file.Source + "::"
}
encodedFiles := file.Path + r.URL.Query().Get("files")
encodedFiles := r.URL.Query().Get("files")
// Decode the URL-encoded path
files, err := url.QueryUnescape(encodedFiles)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
fileList := strings.Split(files, "||")
for i, f := range fileList {
fileList[i] = filePrefix + f
}
return rawFilesHandler(w, r, d, fileList)
}
+8 -14
View File
@@ -43,11 +43,6 @@ func setContentDisposition(w http.ResponseWriter, r *http.Request, fileName stri
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/raw [get]
func rawHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
filePrefix := ""
file, ok := d.raw.(files.ExtendedFileInfo)
if ok {
filePrefix = file.Path
}
encodedFiles := r.URL.Query().Get("files")
// Decode the URL-encoded path
files, err := url.QueryUnescape(encodedFiles)
@@ -55,9 +50,6 @@ func rawHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int,
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
fileList := strings.Split(files, "||")
for i, f := range fileList {
fileList[i] = filepath.Join(filePrefix, f)
}
return rawFilesHandler(w, r, d, fileList)
}
@@ -192,9 +184,8 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
firstFileSource := splitFile[0]
firstFilePath := splitFile[1]
fileName := filepath.Base(firstFilePath)
userscope, err := settings.GetScopeFromSourceName(d.user.Scopes, firstFileSource)
if err != nil {
if err != nil && d.user.Username != "publicUser" {
return http.StatusForbidden, err
}
idx := files.GetIndex(firstFileSource)
@@ -231,9 +222,10 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
w.Header().Set("Cache-Control", "private")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))
sizeInMB := estimatedSize / 1024 / 1024
// if larger than 100 megabytes, log it
if estimatedSize > 100*1024/1024 {
logger.Debug(fmt.Sprintf("User %v is downloading large (%d MB) file: %v", d.user.Username, estimatedSize/1024/1024, fileName))
if sizeInMB > 100 {
logger.Debug(fmt.Sprintf("User %v is downloading large (%d MB) file: %v", d.user.Username, sizeInMB, fileName))
}
// Stream file to response
_, err2 = io.Copy(w, fd)
@@ -267,9 +259,11 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
// Set headers for archive
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+fileName)
w.Header().Set("Content-Length", fmt.Sprintf("%d", estimatedSize))
sizeInMB := estimatedSize / 1024 / 1024
// if larger than 100 megabytes, log it
if estimatedSize > 100*1024/1024 {
logger.Debug(fmt.Sprintf("User %v is downloading large (%d MB) file: %v", d.user.Username, estimatedSize/1024/1024, fileName))
if sizeInMB > 100 {
logger.Debug(fmt.Sprintf("User %v is downloading large (%d MB) file: %v", d.user.Username, sizeInMB, fileName))
}
// Create archive and stream it
if extension == ".zip" {
+6 -5
View File
@@ -18,6 +18,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/utils"
)
// resourceGetHandler retrieves information about a resource.
@@ -50,8 +51,9 @@ func resourceGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
if err != nil {
return http.StatusForbidden, err
}
fileInfo, err := files.FileInfoFaster(files.FileOptions{
Path: filepath.Join(userscope, path),
Path: utils.JoinPathAsUnix(userscope, path),
Modify: d.user.Perm.Modify,
Source: source,
Expand: true,
@@ -115,7 +117,7 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon
return http.StatusForbidden, err
}
fileInfo, err := files.FileInfoFaster(files.FileOptions{
Path: filepath.Join(userscope, path),
Path: utils.JoinPathAsUnix(userscope, path),
Source: source,
Modify: d.user.Perm.Modify,
Expand: false,
@@ -172,7 +174,7 @@ func resourcePostHandler(w http.ResponseWriter, r *http.Request, d *requestConte
return http.StatusForbidden, err
}
fileOpts := files.FileOptions{
Path: filepath.Join(userscope, path),
Path: utils.JoinPathAsUnix(userscope, path),
Source: source,
Modify: d.user.Perm.Modify,
Expand: false,
@@ -246,7 +248,7 @@ func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContex
return http.StatusForbidden, err
}
fileOpts := files.FileOptions{
Path: filepath.Join(userscope, path),
Path: utils.JoinPathAsUnix(userscope, path),
Source: source,
Modify: d.user.Perm.Modify,
Expand: false,
@@ -387,7 +389,6 @@ func patchAction(ctx context.Context, action, src, dst string, d *requestContext
case "rename", "move":
idx := files.GetIndex(srcIndex)
srcPath := idx.MakeIndexPath(src)
fmt.Println("srcPath", srcPath)
fileInfo, err := files.FileInfoFaster(files.FileOptions{
Path: srcPath,
Source: srcIndex,
+1 -1
View File
@@ -103,7 +103,7 @@ func StartHttp(ctx context.Context, Service ImgService, storage *storage.Storage
// Share routes
api.HandleFunc("GET /shares", withPermShare(shareListHandler))
api.HandleFunc("GET /share", withPermShare(shareGetsHandler))
api.HandleFunc("GET /share", withPermShare(shareGetHandler))
api.HandleFunc("POST /share", withPermShare(sharePostHandler))
api.HandleFunc("DELETE /share", withPermShare(shareDeleteHandler))
+1 -1
View File
@@ -21,7 +21,7 @@ type settingsData struct {
// @Tags Settings
// @Accept json
// @Produce json
// @Param property query string false "Property to retrieve"
// @Param property query string false "Property to retrieve: `userDefaults`, `frontend`, `auth`, `server`, `sources`"
// @Success 200 {object} settingsData "System settings data"
// @Router /api/settings [get]
func settingsGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
+1 -1
View File
@@ -64,7 +64,7 @@ func shareListHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
// @Success 200 {array} share.Link "List of share links for the specified path"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/share [get]
func shareGetsHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
func shareGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
path := r.URL.Query().Get("path")
source := r.URL.Query().Get("source")
if source == "" {
+9 -3
View File
@@ -11,7 +11,6 @@ import (
yaml "github.com/goccy/go-yaml"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/users"
"github.com/gtsteffaniak/filebrowser/backend/utils"
"github.com/gtsteffaniak/filebrowser/backend/version"
)
@@ -61,7 +60,10 @@ func setupSources() {
} else {
for k, source := range Config.Server.Sources {
realPath := getRealPath(source.Path)
name := utils.GetLastComponent(realPath)
name := filepath.Base(realPath)
if name == "\\" {
name = strings.Split(realPath, ":")[0]
}
source.Path = realPath // use absolute path
if source.Name == "" {
_, ok := Config.Server.SourceMap[source.Path]
@@ -223,7 +225,7 @@ func setDefaults() Settings {
Name: "FileBrowser Quantum",
},
UserDefaults: UserDefaults{
DisableOnlyOfficeExt: ".txt .csv .html",
DisableOnlyOfficeExt: ".txt .csv .html .pdf",
StickySidebar: true,
LockPassword: false,
ShowHidden: false,
@@ -248,9 +250,13 @@ func ConvertToBackendScopes(scopes []users.SourceScope) ([]users.SourceScope, er
}
newScopes := []users.SourceScope{}
for _, scope := range scopes {
if scope.Scope == "" {
scope.Scope = "/"
}
// first check if its already a path name and keep it
source, ok := Config.Server.SourceMap[scope.Name]
if ok {
newScopes = append(newScopes, users.SourceScope{
Name: source.Path, // backend name is path
Scope: scope.Scope,
-1
View File
@@ -159,7 +159,6 @@ type UserDefaults struct {
SingleClick bool `json:"singleClick"`
Perm users.Permissions `json:"perm"`
Permissions users.Permissions `json:"permissions"`
Commands []string `json:"commands,omitempty"`
ShowHidden bool `json:"showHidden"`
DateFormat bool `json:"dateFormat"`
ThemeColor string `json:"themeColor"`
+40 -18
View File
@@ -4,10 +4,13 @@ import (
"fmt"
"reflect"
"slices"
"strings"
storm "github.com/asdine/storm/v3"
"github.com/gtsteffaniak/filebrowser/backend/errors"
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/users"
"github.com/gtsteffaniak/filebrowser/backend/utils"
@@ -70,6 +73,10 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
return err
}
if !slices.Contains(fields, "Password") {
user.Password = existingUser.Password
}
if !actorIsAdmin {
err := checkRestrictedFields(existingUser, fields)
if err != nil {
@@ -93,24 +100,22 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
userFields := reflect.ValueOf(user).Elem() // Get struct value
for _, field := range fields {
correctedField := utils.CapitalizeFirst(field)
// Get the corresponding field using reflection
fieldValue := userFields.FieldByName(correctedField)
fieldValue := userFields.FieldByName(field)
if !fieldValue.IsValid() {
return fmt.Errorf("invalid field: %s", correctedField)
return fmt.Errorf("invalid field: %s", field)
}
// Ensure the field is settable
if !fieldValue.CanSet() {
return fmt.Errorf("cannot set value of field: %s", correctedField)
return fmt.Errorf("cannot set value of field: %s", field)
}
// Get the value to be stored
val := fieldValue.Interface()
// Update the database
if err := st.db.UpdateField(user, correctedField, val); err != nil {
return fmt.Errorf("failed to update user field: %s, error: %v", correctedField, err)
if err := st.db.UpdateField(existingUser, field, val); err != nil {
return fmt.Errorf("failed to update user field: %s, error: %v", field, err)
}
}
return nil
@@ -136,6 +141,10 @@ func (st usersBackend) Save(user *users.User, changePass bool) error {
}
user.Scopes = adjustedScopes
err = files.MakeUserDirs(user)
if err != nil {
logger.Error(err.Error())
}
err = st.db.Save(user)
if err == storm.ErrAlreadyExists {
return errors.ErrExist
@@ -163,7 +172,7 @@ func checkRestrictedFields(existingUser *users.User, fields []string) error {
return fmt.Errorf("password is locked")
}
// Use reflection to get the field names of NonAdminEditable
editableFields := reflect.ValueOf(existingUser.NonAdminEditable)
editableFields := reflect.ValueOf(existingUser)
if editableFields.Kind() == reflect.Struct {
for i := 0; i < editableFields.NumField(); i++ {
fieldName := editableFields.Type().Field(i).Name
@@ -189,23 +198,36 @@ func parseFields(user *users.User, fields []string) ([]string, error) {
// Dynamically populate fields to update
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if (field.Name == "password" && user.Password != "") || field.Name != "password" {
// which=all can't update password
if strings.ToLower(field.Name) != "password" && strings.ToLower(field.Name) != "id" && strings.ToLower(field.Name) != "username" {
fields = append(fields, field.Name)
}
}
} else {
if slices.Contains(fields, "password") && user.Password != "" {
if settings.Config.Auth.Methods.PasswordAuth.Enabled {
pass, err := users.HashPwd(user.Password)
if err != nil {
return fields, err
}
user.Password = pass
}
newfields := []string{}
for _, field := range fields {
capitalField := utils.CapitalizeFirst(field)
if capitalField == "Scopes" {
newScopes, err := settings.ConvertToBackendScopes(user.Scopes)
if err == nil {
user.Scopes = newScopes
}
err = files.MakeUserDirs(user)
if err != nil {
logger.Error(err.Error())
}
}
if capitalField == "Password" {
value, err := users.HashPwd(user.Password)
if err != nil {
logger.Error(err.Error())
}
user.Password = value
}
newfields = append(newfields, capitalField)
}
return fields, nil
return newfields, nil
}
func checkPassword(password string) error {
+1 -4
View File
@@ -8,7 +8,6 @@ import (
storm "github.com/asdine/storm/v3"
"github.com/gtsteffaniak/filebrowser/backend/auth"
"github.com/gtsteffaniak/filebrowser/backend/errors"
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/share"
@@ -110,7 +109,7 @@ func CreateUser(userInfo users.User, asAdmin bool) error {
if userInfo.Username == "" || userInfo.Password == "" {
return errors.ErrInvalidRequestParams
}
logger.Debug(fmt.Sprintf("Creating user: %v %v\n", userInfo.Username, userInfo.Scopes))
logger.Debug(fmt.Sprintf("Creating user: %v %v", userInfo.Username, userInfo.Scopes))
settings.ApplyUserDefaults(newUser)
if asAdmin {
userInfo.Perm = settings.AdminPerms()
@@ -119,8 +118,6 @@ func CreateUser(userInfo users.User, asAdmin bool) error {
userInfo.Scopes = settings.Config.UserDefaults.DefaultScopes
}
// create new home directories
files.MakeUserDirs(newUser)
err := store.Users.Save(newUser, true)
if err != nil {
return err
+1 -7
View File
@@ -904,7 +904,7 @@ const docTemplate = `{
"parameters": [
{
"type": "string",
"description": "Property to retrieve",
"description": "Property to retrieve: ` + "`" + `userDefaults` + "`" + `, ` + "`" + `frontend` + "`" + `, ` + "`" + `auth` + "`" + `, ` + "`" + `server` + "`" + `, ` + "`" + `sources` + "`" + `",
"name": "property",
"in": "query"
}
@@ -1810,12 +1810,6 @@ const docTemplate = `{
"settings.UserDefaults": {
"type": "object",
"properties": {
"commands": {
"type": "array",
"items": {
"type": "string"
}
},
"darkMode": {
"type": "boolean"
},
+1 -7
View File
@@ -893,7 +893,7 @@
"parameters": [
{
"type": "string",
"description": "Property to retrieve",
"description": "Property to retrieve: `userDefaults`, `frontend`, `auth`, `server`, `sources`",
"name": "property",
"in": "query"
}
@@ -1799,12 +1799,6 @@
"settings.UserDefaults": {
"type": "object",
"properties": {
"commands": {
"type": "array",
"items": {
"type": "string"
}
},
"darkMode": {
"type": "boolean"
},
+2 -5
View File
@@ -134,10 +134,6 @@ definitions:
type: object
settings.UserDefaults:
properties:
commands:
items:
type: string
type: array
darkMode:
type: boolean
dateFormat:
@@ -891,7 +887,8 @@ paths:
description: Returns the current configuration settings for signup, user directories,
rules, frontend.
parameters:
- description: Property to retrieve
- description: 'Property to retrieve: `userDefaults`, `frontend`, `auth`, `server`,
`sources`'
in: query
name: property
type: string
+21
View File
@@ -1,9 +1,17 @@
package users
import (
"regexp"
"strings"
jwt "github.com/golang-jwt/jwt/v4"
)
var (
invalidFilenameChars = regexp.MustCompile(`[^0-9A-Za-z@_\-.]`)
dashes = regexp.MustCompile(`[\-]+`)
)
type AuthToken struct {
Key string `json:"key"`
Name string `json:"name"`
@@ -75,3 +83,16 @@ var PublicUser = User{
Api: false,
},
}
func CleanUsername(s string) string {
// Remove any trailing space to avoid ending on -
s = strings.Trim(s, " ")
s = strings.Replace(s, "..", "", -1)
// Replace all characters which not in the list `0-9A-Za-z@_\-.` with a dash
s = invalidFilenameChars.ReplaceAllString(s, "-")
// Remove any multiple dashes caused by replacements above
s = dashes.ReplaceAllString(s, "-")
return s
}
+10
View File
@@ -6,7 +6,9 @@ import (
"encoding/hex"
"fmt"
math "math/rand"
"path/filepath"
"reflect"
"runtime"
"strings"
"time"
@@ -104,3 +106,11 @@ func GetLastComponent(path string) string {
}
return path[lastSlash+1:]
}
func JoinPathAsUnix(parts ...string) string {
joinedPath := filepath.Join(parts...)
if runtime.GOOS == "windows" {
joinedPath = strings.ReplaceAll(joinedPath, "\\", "/")
}
return joinedPath
}
-20
View File
@@ -1,20 +0,0 @@
import { Browser, firefox, expect, Page } from "@playwright/test";
async function globalSetup() {
const browser: Browser = await firefox.launch();
const context = await browser.newContext();
const page: Page = await context.newPage();
await page.goto("http://127.0.0.1/login");
await page.getByPlaceholder("Username").fill("admin");
await page.getByPlaceholder("Password").fill("admin");
await page.getByRole("button", { name: "Login" }).click();
await page.waitForURL("**/files/", { timeout: 100 });
let cookies = await context.cookies();
expect(cookies.find((c) => c.name == "auth")?.value).toBeDefined();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.context().storageState({ path: "./loginAuth.json" });
await browser.close();
}
export default globalSetup
+2 -2
View File
@@ -1,5 +1,5 @@
import { adjustedData } from "./utils";
import { getApiPath, removePrefix,extractSourceFromPath } from "@/utils/url.js";
import { getApiPath, removePrefix, extractSourceFromPath } from "@/utils/url.js";
import { notify } from "@/notify";
// Fetch public share data
@@ -18,7 +18,7 @@ export async function fetchPub(path, hash, password = "") {
throw error;
}
let data = await response.json()
const adjusted = adjustedData(data, getApiPath(`share/${hash}${path}`));
const adjusted = adjustedData(data, `/share/${hash}${path}`);
return adjusted
}
+4 -4
View File
@@ -8,12 +8,12 @@ export async function list() {
return fetchJSON(apiPath);
}
export async function get(path, hash) {
export async function get(path, source) {
try {
const params = { path, hash };
const params = { path, source };
const apiPath = getApiPath("api/share",params);
let data = fetchJSON(apiPath);
return adjustedData(data, `api/share${path}`);
return adjustedData(data, path);
} catch (err) {
notify.showError(err.message || "Error fetching data");
throw err;
@@ -29,7 +29,7 @@ export async function remove(hash) {
}
export async function create(path, source, password = "", expires = "", unit = "hours") {
const params = { path: path, source: source };
const params = { path: encodeURIComponent(path), source: source };
const apiPath = getApiPath("api/share",params);
let body = "{}";
if (password != "" || expires !== "" || unit !== "hours") {
+1
View File
@@ -64,6 +64,7 @@ export function adjustedData(data, url) {
data.items = data.items.map((item) => {
item.url = `${data.url}${encodeURIComponent(item.name)}`;
item.source = data.source
if (data.path == "/") {
item.path = `/${item.name}`
} else {
+14 -10
View File
@@ -12,7 +12,13 @@
<span class="chevron"><i class="material-icons">keyboard_arrow_right</i></span>
<router-link :to="link.url">{{ link.name }}</router-link>
</span>
<action style="display: contents" v-if="showShare" icon="share" show="share" />
<action
aria-label="Show-Share"
style="display: contents"
v-if="showShare"
icon="share"
show="share"
/>
<div v-if="isCardView">
Size:
<input
@@ -31,8 +37,7 @@
<script>
import { state, mutations, getters } from "@/store";
import { baseURL } from "@/utils/constants.js";
import { extractSourceFromPath, removePrefix, removeLeadingSlash } from "@/utils/url.js";
import { extractSourceFromPath, removeLeadingSlash } from "@/utils/url.js";
import Action from "@/components/Action.vue";
export default {
@@ -65,11 +70,10 @@ export default {
if (parts[parts.length - 1] === "") {
parts.pop();
}
let breadcrumbs = [];
let buildRef = this.base;
parts.forEach((element) => {
buildRef = buildRef + encodeURIComponent(element) + "/";
buildRef = buildRef + encodeURIComponent(decodeURIComponent(element)) + "/";
breadcrumbs.push({
name: decodeURIComponent(element),
url: buildRef,
@@ -99,13 +103,13 @@ export default {
const result = extractSourceFromPath(getters.routePath());
if (getters.currentView() == "share") {
this.base = getters.sharePathBase();
this.path = removePrefix(getters.routePath(), this.base + "/");
this.path = getters.routePath(this.base);
} else {
this.path = decodeURIComponent(result.path);
}
this.base = baseURL;
if (state.serverHasMultipleSources) {
this.base = `${this.base}${result.source}/`;
this.base = "/";
if (state.serverHasMultipleSources) {
this.base = `${this.base}${result.source}/`;
}
}
},
updateGallerySize(event) {
+79
View File
@@ -251,6 +251,34 @@ export default {
if (state.serverHasMultipleSources) {
this.selectedSource = state.sources.current;
}
// Adjust contextmenu listener based on browser
if (state.isSafari) {
// For Safari, add touchstart or mousedown to open the context menu
this.$el.addEventListener("touchstart", this.openContextForSafari, {
passive: true,
});
this.$el.addEventListener("mousedown", this.openContextForSafari);
this.$el.addEventListener("touchmove", this.handleTouchMove);
// Also clear the timeout if the user clicks or taps quickly
this.$el.addEventListener("touchend", this.cancelContext);
this.$el.addEventListener("mouseup", this.cancelContext);
} else {
// For other browsers, use regular contextmenu
this.$el.addEventListener("contextmenu", this.openContext);
}
},
beforeUnmount() {
// If Safari, remove touchstart listener
if (state.isSafari) {
this.$el.removeEventListener("touchstart", this.openContextForSafari);
this.$el.removeEventListener("mousedown", this.openContextForSafari);
this.$el.removeEventListener("touchend", this.cancelContext);
this.$el.removeEventListener("mouseup", this.cancelContext);
this.$el.removeEventListener("touchmove", this.handleTouchMove);
} else {
this.$el.removeEventListener("contextmenu", this.openContext);
}
},
computed: {
showOptions() {
@@ -319,6 +347,57 @@ export default {
},
},
methods: {
openContext(event) {
event.preventDefault();
event.stopPropagation();
mutations.showHover({
name: "ContextMenu",
props: {
posX: event.clientX,
posY: event.clientY,
},
});
},
cancelContext() {
if (this.contextTimeout) {
clearTimeout(this.contextTimeout);
this.contextTimeout = null;
}
this.isLongPress = false;
},
openContextForSafari(event) {
this.cancelContext(); // Clear any previous timeouts
this.isLongPress = false; // Reset state
this.isSwipe = false; // Reset swipe detection
const touch = event.touches[0];
this.touchStartX = touch.clientX;
this.touchStartY = touch.clientY;
// Start the long press detection
this.contextTimeout = setTimeout(() => {
if (!this.isSwipe) {
this.isLongPress = true;
event.preventDefault(); // Suppress Safari's callout menu
this.openContext(event); // Open the custom context menu
}
}, 500); // Long press delay (adjust as needed)
},
handleTouchMove(event) {
const touch = event.touches[0];
const deltaX = Math.abs(touch.clientX - this.touchStartX);
const deltaY = Math.abs(touch.clientY - this.touchStartY);
// Set a threshold for movement to detect a swipe
const movementThreshold = 10; // Adjust as needed
if (deltaX > movementThreshold || deltaY > movementThreshold) {
this.isSwipe = true;
this.cancelContext(); // Cancel long press if swipe is detected
}
},
handleTouchEnd() {
this.cancelContext(); // Clear timeout
this.isSwipe = false; // Reset swipe state
},
updateSource(event) {
this.selectedSource = event.target.value;
this.submit();
@@ -96,7 +96,6 @@ import { fromNow } from "@/utils/moment";
import { filesApi } from "@/api";
import * as upload from "@/utils/upload";
import { state, getters, mutations } from "@/store"; // Import your custom store
import { baseURL } from "@/utils/constants";
import { router } from "@/router";
import { url } from "@/utils";
import Icon from "@/components/Icon.vue";
@@ -233,7 +232,7 @@ export default {
window.location.href = this.getRelative(path);
},
getUrl() {
return baseURL.slice(0, -1) + this.url;
return this.url;
},
onRightClick(event) {
event.preventDefault(); // Prevent default context menu
@@ -433,8 +432,7 @@ export default {
},
open() {
location.hash = state.req.items[this.index].name;
const newurl = url.removePrefix(this.url);
router.push({ path: newurl });
router.push({ path: this.url });
},
},
};
+1 -1
View File
@@ -8,6 +8,7 @@
<p>{{ $t("prompts.newFileMessage") }}</p>
<input
class="input input--block"
aria-label="FileName Field"
v-focus
type="text"
@keyup.enter="submit"
@@ -82,7 +83,6 @@ export default {
} catch (error) {
notify.showError(error);
}
},
},
};
+7 -2
View File
@@ -11,7 +11,7 @@
<div class="card-action">
<button
class="button button--flat button--grey"
@click="currentPrompt.action"
@click="closeHovers"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
@@ -29,7 +29,7 @@
</div>
</template>
<script>
import { getters } from "@/store"; // Import your custom store
import { getters, mutations } from "@/store"; // Import your custom store
export default {
name: "replace",
@@ -38,5 +38,10 @@ export default {
return getters.currentPrompt(); // Access the getter directly from the store
},
},
methods: {
closeHovers() {
mutations.closeHovers();
},
},
};
</script>
+16 -28
View File
@@ -3,7 +3,7 @@
<div class="card-title">
<h2>{{ $t("buttons.share") }}</h2>
</div>
<div aria-label="share-paths" class="searchContext">Path: {{ subpath }}</div>
<div aria-label="share-path" class="searchContext">Path: {{ subpath }}</div>
<p>
Note: anyone who has access to the link (and optional password) can access the
shared files. There is no requirement to be logged in.
@@ -115,7 +115,7 @@
<button
class="button button--flat button--blue"
@click="submit"
:aria-label="$t('buttons.share')"
aria-label="Share-Confirm"
:title="$t('buttons.share')"
>
{{ $t("buttons.share") }}
@@ -129,7 +129,6 @@ import { notify } from "@/notify";
import { state, getters, mutations } from "@/store";
import { shareApi, publicApi } from "@/api";
import { fromNow } from "@/utils/moment";
import { removePrefix } from "@/utils/url";
import Clipboard from "clipboard";
export default {
@@ -177,30 +176,21 @@ export default {
},
},
async beforeMount() {
let path = state.req.path;
this.source = state.req.source;
if (state.isSearchActive) {
path = state.selected[0].path;
this.source = state.selected[0].source;
} else if (getters.selectedCount() === 1) {
const selected = getters.getFirstSelected();
path = selected.path;
this.source = selected.source;
this.source = state.req.items[state.selected[0]].source;
}
this.subpath = decodeURIComponent(path);
try {
let path = getters.routePath("files");
if (state.isSearchActive) {
path = state.selected[0].path;
this.source = state.selected[0].source;
} else {
this.source = state.req.source;
if (getters.selectedCount() === 1) {
if (state.sources.count > 1) {
path = removePrefix(
state.req.items[this.selected[0]].url,
"files/" + state.req.source
);
} else {
path = removePrefix(state.req.items[this.selected[0]].url, "files");
}
}
if (state.sources.count > 1) {
path = removePrefix(path, state.req.source);
}
}
this.subpath = decodeURIComponent(path);
// get last element of the path
const links = await shareApi.get(this.subpath);
const links = await shareApi.get(this.subpath, this.source);
this.links = links;
} catch (err) {
notify.showError(err);
@@ -224,9 +214,7 @@ export default {
methods: {
async submit() {
let isPermanent = !this.time || this.time === 0;
let res = null;
if (isPermanent) {
res = await shareApi.create(this.subpath, this.source, this.password);
} else {
@@ -270,7 +258,7 @@ export default {
},
buildDownloadLink(share) {
share.source = this.source;
share.path = this.subpath;
share.path = "/";
return publicApi.getDownloadURL(share);
},
sort() {
@@ -94,11 +94,6 @@ export default {
if (conflict) {
mutations.showHover({
name: "replace",
action: async (event) => {
event.preventDefault();
mutations.closeHovers();
await upload.handleFiles(uploadFiles, path, false);
},
confirm: async (event) => {
event.preventDefault();
mutations.closeHovers();
+2 -30
View File
@@ -47,7 +47,7 @@
</div>
<!-- Section for logged-in users -->
<div v-if="loginCheck && !disableUsedPercentage" class="sidebar-scroll-list">
<div v-if="loginCheck" class="sidebar-scroll-list">
<div class="sources card">
<span>Sources</span>
<div class="inner-card">
@@ -83,16 +83,8 @@
<script>
import * as auth from "@/utils/auth";
import {
signup,
disableExternal,
disableUsedPercentage,
noAuth,
loginPage,
} from "@/utils/constants";
import { filesApi } from "@/api";
import { signup, disableExternal, noAuth, loginPage } from "@/utils/constants";
import ProgressBar from "@/components/ProgressBar.vue";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { state, getters, mutations } from "@/store"; // Import your custom store
export default {
@@ -135,27 +127,7 @@ export default {
}
},
},
mounted() {
if (this.loginCheck) {
this.updateUsage();
}
},
methods: {
async updateUsage() {
if (!disableUsedPercentage) {
if (state.sources.info === undefined) {
return;
}
for (const source of Object.keys(state.sources.info)) {
let usage = await filesApi.usage(source);
let sourceInfo = state.sources.info[source];
sourceInfo.used = getHumanReadableFilesize(usage.used);
sourceInfo.total = getHumanReadableFilesize(usage.total);
sourceInfo.usedPercentage = Math.round((usage.used / usage.total) * 100);
mutations.updateSource(source, sourceInfo);
}
}
},
checkLogin() {
return getters.isLoggedIn() && !getters.routePath().startsWith("/share");
},
+5 -8
View File
@@ -187,10 +187,11 @@ main .spinner .bounce2 {
}
#previewer .preview .info {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 1.5em;
color: #fff;
}
@@ -247,10 +248,6 @@ main .spinner .bounce2 {
padding: 0.4em;
}
#previewer>button:first-of-type {
left: 0.5em;
}
#previewer>button:last-of-type {
right: 0.5em;
}
+35 -35
View File
@@ -3,7 +3,7 @@
"cancel": "Abbrechen",
"close": "Schließen",
"copy": "Kopieren",
"copyFile": "Kopiere Datei",
"copyFile": "Datei kopieren",
"copyToClipboard": "In Zwischenablage kopieren",
"create": "Neu",
"delete": "Löschen",
@@ -11,16 +11,16 @@
"file": "Datei",
"folder": "Ordner",
"info": "Info",
"more": "mehr",
"more": "Mehr",
"move": "Verschieben",
"moveFile": "Verschiebe Datei",
"moveFile": "Datei verschieben",
"new": "Neu",
"next": "nächste",
"next": "Weiter",
"ok": "OK",
"permalink": "permanenten Verweis anzeigen",
"previous": "vorherige",
"permalink": "Permalink anzeigen",
"previous": "Zurück",
"publish": "Veröffentlichen",
"rename": "umbenennen",
"rename": "Umbenennen",
"replace": "Ersetzen",
"reportIssue": "Fehler melden",
"save": "Speichern",
@@ -29,11 +29,11 @@
"select": "Auswählen",
"selectMultiple": "Mehrfachauswahl",
"share": "Teilen",
"shell": "Kommandozeile ein/ausschalten",
"shell": "Kommandozeile ein-/ausschalten",
"submit": "Absenden",
"switchView": "Ansicht wechseln",
"toggleSidebar": "Seitenleiste anzeigen",
"update": "Update",
"update": "Aktualisieren",
"upload": "Upload",
"openFile": "Datei öffnen",
"continue": "Fortfahren"
@@ -56,8 +56,8 @@
"files": "Dateien",
"folders": "Ordner",
"home": "Home",
"lastModified": "zuletzt verändert",
"loading": "Lade...",
"lastModified": "Zuletzt geändert",
"loading": "Laden...",
"lonely": "Hier scheint nichts zu sein...",
"metadata": "Metadaten",
"multipleSelectionEnabled": "Mehrfachauswahl aktiviert",
@@ -108,13 +108,13 @@
"zhTW": "中文 (繁體)"
},
"login": {
"createAnAccount": "Account erstellen",
"loginInstead": "Account besteht bereits",
"password": "Passwort",
"passwordConfirm": "Passwort Bestätigung",
"passwordsDontMatch": "Passwörter stimmen nicht überein",
"createAnAccount": "Konto erstellen",
"loginInstead": "Bei bestehendem Konto anmelden",
"password": "Kennwort",
"passwordConfirm": "Kennwort bestätigen",
"passwordsDontMatch": "Kennwörter stimmen nicht überein",
"signup": "Registrieren",
"submit": "Login",
"submit": "Anmelden",
"username": "Benutzername",
"usernameTaken": "Benutzername ist bereits vergeben",
"wrongCredentials": "Falsche Zugangsdaten"
@@ -127,16 +127,16 @@
"deleteMessageMultiple": "Sind Sie sicher, dass Sie {count} Datei(en) löschen möchten?",
"deleteMessageSingle": "Sind Sie sicher, dass Sie diesen Ordner/diese Datei löschen möchten?",
"deleteMessageShare": "Sind Sie sicher, dass Sie diese Freigabe löschen möchten ({path})?",
"deleteTitle": "Lösche Dateien",
"deleteTitle": "Dateien löschen",
"displayName": "Anzeigename:",
"download": "Lade Dateien",
"download": "Dateien herunterladen",
"downloadMessage": "Wählen Sie ein Format zum Herunterladen aus.",
"error": "Etwas ist schief gelaufen",
"fileInfo": "Dateiinformation",
"filesSelected": "{count} Dateien ausgewählt.",
"lastModified": "Zuletzt geändert",
"move": "Verschieben",
"moveMessage": "Wählen Sie einen neuen Platz für ihre Datei(en)/Ordner:",
"moveMessage": "Wählen Sie einen neuen Ort für ihre Datei(en)/Ordner:",
"newArchetype": "Erstelle neuen Beitrag auf dem Archetyp. Ihre Datei wird im Inhalteordner erstellt.",
"newDir": "Neuer Ordner",
"newDirMessage": "Geben Sie den Namen des neuen Ordners an.",
@@ -145,7 +145,7 @@
"numberDirs": "Anzahl der Ordner",
"numberFiles": "Anzahl der Dateien",
"rename": "Umbenennen",
"renameMessage": "Fügen Sie einen Namen ein für",
"renameMessage": "Geben Sie einen Namen ein für",
"replace": "Ersetzen",
"replaceMessage": "Eine der Datei mit dem gleichen Namen, wie die Sie hochladen wollen, existiert bereits. Soll die vorhandene Datei übersprungen oder ersetzt werden?\n",
"schedule": "Plan",
@@ -155,15 +155,15 @@
"upload": "Upload",
"uploadFiles": "Upload von {files} Dateien...",
"uploadMessage": "Wählen Sie eine Upload-Methode",
"optionalPassword": "Optionales Passwort"
"optionalPassword": "Optionales Kennwort"
},
"search": {
"images": "Bilder",
"music": "Musik",
"pdf": "PDF",
"pressToSearch": "Drücken Sie Enter um zu suchen...",
"pressToSearch": "Drücken Sie Enter, um zu suchen...",
"search": "Suche...",
"typeToSearch": "Tippen um zu suchen...",
"typeToSearch": "Tippen, um zu suchen...",
"types": "Typen",
"video": "Video"
},
@@ -174,18 +174,18 @@
"allowEdit": "Bearbeiten, Umbenennen und Löschen von Dateien oder Ordnern",
"allowNew": "Erstellen neuer Dateien und Ordner",
"allowPublish": "Veröffentlichen von neuen Beiträgen und Seiten",
"allowSignup": "Erlaube Benutzern sich zu registrieren",
"avoidChanges": "(leer lassen um Änderungen zu vermeiden)",
"allowSignup": "Benutzern erlauben, sich zu registrieren",
"avoidChanges": "(leer lassen, um Änderungen zu vermeiden)",
"branding": "Design",
"brandingDirectoryPath": "Designverzeichnispfad",
"brandingHelp": "Sie können das Erscheinungsbild Ihres File Browser anpassen, in dem Sie den Namen ändern, das Logo austauchsen oder eigene Stile definieren und sogar externe Links zu GitHub deaktivieren.\nUm mehr Informationen zum Anpassen des Designs zu bekommen, gehen Sie bitte zu {0}.",
"changePassword": "Passwort ändern",
"changePassword": "Kennwort ändern",
"commandRunner": "Befehlseingabe",
"commandRunnerHelp": "Hier könne Sie Befehle eintragen, welche bei den benannten Aktionen ausgeführt werden. Sie müssen pro Zeile jeweils einen Befehl eingeben. Die Umgebungsvariable {0} und {1} sind verfügbar, wobei {0} relative zu {1} ist. Für mehr Informationen über diese Funktion und die verfügbaren Umgebungsvariablen, lesen Sie bitte die {2}.",
"commandsUpdated": "Befehle aktualisiert!",
"createUserDir": "Automatisches Erstellen des Home-Verzeichnisses beim Anlegen neuer Benutzer",
"tusUploads": "Gestückelter Upload",
"tusUploadsHelp": "File Browser unterstützt das Hochladen von gestückelten Dateien und ermöglicht so einen effizienten, zuverlässigen, fortsetzbaren und gestückelten Datei-Upload auch in unzuverlässigen Netzwerken.",
"tusUploadsHelp": "File Browser unterstützt das Hochladen von gestückelten Dateien und ermöglicht so einen effizienten, zuverlässigen und fortsetzbaren Datei-Upload auch in unzuverlässigen Netzwerken.",
"tusUploadsChunkSize": "Gibt die maximale Größe pro Anfrage an (direkte Uploads werden für kleinere Uploads verwendet). Bitte geben Sie eine Byte-Angabe oder eine Zeichenfolge wie 10 MB, 1 GB usw. an",
"tusUploadsRetryCount": "Anzahl der Wiederholungsversuche, wenn das Hochladen eines Stückes fehlschlägt.",
"customStylesheet": "Individuelles Stylesheet",
@@ -194,7 +194,7 @@
"disableUsedDiskPercentage": "Diagramm zur Festplattennutzung deaktivieren",
"documentation": "Dokumentation",
"examples": "Beispiele",
"executeOnShell": "In Shell ausführen",
"executeOnShell": "In Kommandozeile ausführen",
"executeOnShellDescription": "Es ist voreingestellt das der File Brower Befehle ausführt in dem er die Befehlsdateien direkt aufruft. Wenn Sie wollen, dass sie über einer Kommandozeile (wie Bash oder PowerShell) laufen, könne Sie diese hier definieren mit allen bennötigten Argumenten und Optionen. Wenn gesetzt, wird das Kommando das ausgeführt werden soll als Parameter angehängt. Das gilt für Benuzerkommandos sowie auch für Ereignisse.",
"globalRules": "Das ist ein globales Set von Regeln die erlauben oder nicht erlauben. Die sind für alle Benutzer zutreffend. Es können spezielle Regeln in den Einstellungen der Benutzer definiert werden, die diese überschreiben.",
"globalSettings": "Globale Einstellungen",
@@ -206,15 +206,15 @@
"newPassword": "Ihr neues Passwort.",
"newPasswordConfirm": "Bestätigen Sie Ihr neues Passwort",
"newUser": "Neuer Benutzer",
"password": "Passwort",
"passwordUpdated": "Passwort aktualisiert!",
"password": "Kennwort",
"passwordUpdated": "Kennwort aktualisiert!",
"path": "Pfad",
"perm": {
"create": "Dateien und Ordner erstellen",
"delete": "Dateien und Ordner löschen",
"download": "Download",
"execute": "Befehle ausführen",
"modify": "Dateien editieren",
"modify": "Dateien bearbeiten",
"rename": "Umbenennen oder Verschieben von Dateien oder Ordnern",
"share": "Datei teilen"
},
@@ -222,7 +222,7 @@
"permissionsHelp": "Sie können einem Benutzer Administratorrechte einräumen oder die Berechtigunen individuell festlegen. Wenn Sie \"Administrator\" auswählen, werden alle anderen Rechte automatisch vergeben. Die Nutzerverwaltung kann nur durch einen Administrator erfolgen.\n",
"profileSettings": "Profileinstellungen",
"ruleExample1": "Verhindert den Zugang zu versteckten Dateien (dot-Files, wie .git, .gitignore) in allen Ordnern\n",
"ruleExample2": "blockiert den Zugang auf Dateien mit dem Namen Caddyfile in der Wurzel/Basis des Scopes.",
"ruleExample2": "Blockiert den Zugang auf Dateien mit dem Namen Caddyfile in der Wurzel/Basis des Scopes.",
"rules": "Regeln",
"rulesHelp": "Hier können Sie erlaubte und verbotene Aktionen für einen einzelnen Benutzer festlegen. Blockierte Dateien werden nicht im Listing angezeigt und sind nicht erreichbar für den Nutzer. Wir unterstützen reguläre Ausdrücke (Regex) und Pfade die relativ zum Benutzerordner sind. \n",
"scope": "Scope",
@@ -245,8 +245,8 @@
"userDeleted": "Benutzer gelöscht!",
"userManagement": "Benutzerverwaltung",
"userUpdated": "Benutzer aktualisiert!",
"username": "Nutzername",
"users": "Nutzer"
"username": "Benutzername",
"users": "Benutzer"
},
"sidebar": {
"help": "Hilfe",
+1 -1
View File
@@ -139,7 +139,7 @@ router.beforeResolve(async (to, from, next) => {
// Handle auth requirements
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (state != null && state.user != null && !('username' in state.user)) {
if (state != null && state.user != null && !state.user.username){
await validateLogin();
}
+26 -26
View File
@@ -1,10 +1,11 @@
import { removePrefix } from "@/utils/url.js";
import { getFileExtension } from "@/utils/files.js";
import { state } from "./state.js";
import { mutations } from "./mutations.js";
import { noAuth,baseURL } from "@/utils/constants.js";
import { noAuth } from "@/utils/constants.js";
import { getTypeInfo } from "@/utils/mimetype";
export const getters = {
previewType: () => getTypeInfo(state.req.type).simpleType,
isCardView: () => (state.user.viewMode == "gallery" || state.user.viewMode == "normal" ) && getters.currentView() == "listingView" ,
currentHash: () => state.route.hash.replace("#", ""),
isMobile: () => state.isMobile,
@@ -21,22 +22,9 @@ export const getters = {
if (noAuth) {
return true
}
if (state.user !== null && state.user?.username != undefined && state.user?.username != "publicUser") {
if (state.user !== null && state.user?.username != "" && state.user?.username != "publicUser") {
return true;
}
const userData = localStorage.getItem("userData");
if (userData == undefined) {
return false;
}
try {
const userInfo = JSON.parse(userData);
if (userInfo.username != "publicUser") {
mutations.setCurrentUser(userInfo);
return true;
}
} catch (error) {
return false;
}
return false
},
isAdmin: () => state.user.perm?.admin == true,
@@ -94,34 +82,46 @@ export const getters = {
return { dirs, files };
},
isSidebarVisible: () => {
const currentView = getters.currentView();
let visible = (state.showSidebar || getters.isStickySidebar()) && state.user.username != "publicUser"
if (getters.currentView() == "settings") {
if (currentView == "settings") {
visible = !getters.isMobile();
}
if (getters.currentView() == "share") {
if (currentView == "share") {
visible = false
}
if (typeof getters.currentPromptName() === "string" && !getters.isStickySidebar()) {
visible = false;
}
if (currentView == "preview") {
const contentType = getters.previewType()
if (
contentType == "audio" ||
contentType == "video" ||
contentType == "image" ||
contentType == "pdf"
) {
visible = false
}
}
if (
getters.currentView() == "editor" ||
getters.currentView() == "preview" ||
getters.currentView() == "onlyOfficeEditor"
currentView == "editor" ||
currentView == "onlyOfficeEditor"
) {
visible = false;
}
return visible
},
isStickySidebar: () => {
let sticky = state.user?.stickySidebar
if (getters.currentView() == "settings") {
let sticky = state.user?.stickySidebar;
const currentView = getters.currentView();
if (currentView == "settings") {
sticky = true
}
if (getters.currentView() == null && !getters.isLoading() && getters.isShare() ) {
if (currentView == null && !getters.isLoading() && getters.isShare() ) {
sticky = true
}
if (getters.isMobile() || getters.currentView() == "preview") {
if (getters.isMobile()) {
sticky = false
}
return sticky
@@ -142,7 +142,7 @@ export const getters = {
// Step 1: Split the path by '/'
let parts = urlPath.split("/");
// Step 2: Assign hash to the second part (index 2) and join the rest for subPath
return baseURL + "share/"+ parts[1];
return "/share/"+ parts[1] + "/";
},
currentView: () => {
const pathname = getters.routePath()
+1 -7
View File
@@ -130,16 +130,14 @@ export const mutations = {
},
setCurrentUser: (value) => {
try {
localStorage.setItem("userData", undefined);
// If value is null or undefined, emit state change and exit early
if (!value) {
state.user = value;
emitStateChanged();
return;
}
mutations.setSources(value);
if (value.username != "publicUser") {
localStorage.setItem("userData", JSON.stringify(value));
mutations.setSources(value);
}
// Ensure locale exists and is valid
if (!value.locale) {
@@ -189,7 +187,6 @@ export const mutations = {
emitStateChanged();
},
updateCurrentUser: (value) => {
localStorage.setItem("userData", undefined);
// Ensure the input is a valid object
if (typeof value !== "object" || value === null) return;
@@ -220,9 +217,6 @@ export const mutations = {
usersApi.update(state.user, Object.keys(value));
}
if (state.user.username != "publicUser") {
localStorage.setItem("userData", JSON.stringify(state.user));
}
// Emit state change event
emitStateChanged();
},
+1
View File
@@ -17,6 +17,7 @@ export const state = reactive({
info: {},
},
user: {
username: "",
quickDownloadEnabled: false,
gallarySize: 0,
singleClick: false,
+15 -4
View File
@@ -1,9 +1,9 @@
import { mutations, getters } from "@/store";
import { mutations, getters, state } from "@/store";
import router from "@/router";
import { usersApi } from "@/api";
import { usersApi,filesApi } from "@/api";
import { getApiPath } from "@/utils/url.js";
import { recaptcha, loginPage } from "@/utils/constants";
import { recaptcha, loginPage, disableUsedPercentage } from "@/utils/constants";
import { getHumanReadableFilesize } from "@/utils/filesizes";
export async function setNewToken(token) {
document.cookie = `auth=${token}; path=/`;
@@ -18,6 +18,17 @@ export async function validateLogin() {
} catch (error) {
console.log("Error validating login");
}
if (!disableUsedPercentage) {
for (const source of Object.keys(state.sources.info)) {
let usage = await filesApi.usage(source);
let sourceInfo = state.sources.info[source];
sourceInfo.used = getHumanReadableFilesize(usage.used);
sourceInfo.total = getHumanReadableFilesize(usage.total);
sourceInfo.usedPercentage = Math.round((usage.used / usage.total) * 100);
mutations.updateSource(source, sourceInfo);
}
}
return getters.isLoggedIn()
}
+5 -9
View File
@@ -103,32 +103,28 @@ export function scanFiles(dt) {
}
export async function handleFiles(files, base, overwrite = false) {
console.log("Uploading files", files);
let blockUpdates = false;
let c = 0
let count = files.length
for (const file of files) {
c += 1
const id = state.upload.id;
let path = base;
if (file.fullPath !== undefined) {
path += url.encodePath(file.fullPath);
} else {
path += url.encodeRFC5987ValueChars(file.name);
}
let path = url.removeTrailingSlash(base) + "/" +file.name;
if (file.type == "directory") {
path += "/";
}
const item = {
id,
path,
id: id,
path: path,
file: file.file, // Ensure `file.file` is the Blob or File
overwrite,
};
let last = 0;
notify.showPopup("success", `(${c} of ${count}) Uploading ${file.name}`, false);
console.log(`Uploading ${file.name}`, item);
await filesApi.post(
item.path,
item.file,
+6 -3
View File
@@ -115,14 +115,17 @@ export function base64Encode(str) {
return btoa(unescape(encodeURIComponent(str)));
}
// expect url to include /files/ prefix
export function extractSourceFromPath(url) {
let source;
let path = removePrefix(url, 'files');
let path = url;
if (state.serverHasMultipleSources) {
source = path.split('/')[1];
path = removePrefix(path, source);
source = path.split('/')[2];
path = removePrefix(path, `/files/${source}`);
} else {
source = state.sources.current;
path = removePrefix(path, '/files');
}
return { source, path };
}
+14 -1
View File
@@ -1,10 +1,12 @@
import { describe, it, expect, vi } from 'vitest';
import { removePrefix, extractSourceFromPath } from './url.js';
import { removePrefix, extractSourceFromPath, getApiPath } from './url.js';
describe('testurl', () => {
it('url prefix', () => {
let tests = [
{input: "/files/files", trimArg: "/files/",expected: "/files",},
{input: "/files/share/something/", trimArg: "files", expected:"/share/something/"},
{input: "test/iscool/", trimArg: "test",expected:"/iscool/"},
{input: "test",trimArg: "",expected:"/test"},
{input: "/test", trimArg: "test",expected:"/"},
@@ -19,6 +21,17 @@ describe('testurl', () => {
});
describe('getapipath', () => {
it('url prefix', () => {
let tests = [
{input: "/share/to/thing", expected: "/files/share/to/thing",},
]
for (let test of tests) {
expect(getApiPath(test.input)).toEqual(test.expected);
}
});
});
describe('extractSourceFromPath', () => {
it('single source extract', async () => {
vi.doMock("@/store", () => {
+13 -8
View File
@@ -29,6 +29,7 @@ import { state, mutations, getters } from "@/store";
import { url } from "@/utils";
import { notify } from "@/notify";
import router from "@/router";
import { baseURL } from "@/utils/constants";
export default {
name: "files",
@@ -70,7 +71,6 @@ export default {
$route: "fetchData",
reload(value) {
if (value) {
console.log("Reloading");
this.fetchData();
}
},
@@ -101,15 +101,20 @@ export default {
}
},
async fetchData() {
// lets redirect if multiple sources and user went to /files/
if (
state.serverHasMultipleSources &&
(getters.routePath() === "/files/" || getters.routePath() === "/files")
) {
router.push(`/files/${state.sources.current}`);
if (!getters.isLoggedIn()) {
return;
}
const routePath = url.removeTrailingSlash(getters.routePath(`${baseURL}files`));
const rootRoute =
routePath == "/files" ||
routePath == "/files/" ||
routePath == "" ||
routePath == "/";
// lets redirect if multiple sources and user went to /files/
if (state.serverHasMultipleSources && rootRoute) {
router.push(`${routePath}/${state.sources.current}`);
return;
}
this.lastHash = "";
// Set loading to true and reset the error.
mutations.setLoading("files", true);
+21 -21
View File
@@ -298,7 +298,6 @@ export default {
this.colunmsResize();
// Add the needed event listeners to the window and document.
window.addEventListener("keydown", this.keyEvent);
window.addEventListener("scroll", this.scrollEvent);
window.addEventListener("resize", this.windowsResize);
window.addEventListener("click", this.clickClear);
window.addEventListener("keyup", this.clearCtrKey);
@@ -307,7 +306,9 @@ export default {
// Adjust contextmenu listener based on browser
if (state.isSafari) {
// For Safari, add touchstart or mousedown to open the context menu
this.$el.addEventListener("touchstart", this.openContextForSafari);
this.$el.addEventListener("touchstart", this.openContextForSafari, {
passive: true,
});
this.$el.addEventListener("mousedown", this.openContextForSafari);
this.$el.addEventListener("touchmove", this.handleTouchMove);
@@ -316,10 +317,10 @@ export default {
this.$el.addEventListener("mouseup", this.cancelContext);
} else {
// For other browsers, use regular contextmenu
window.addEventListener("contextmenu", this.openContext);
this.$el.addEventListener("contextmenu", this.openContext);
}
// if safari , make sure click and hold opens context menu, but not for any other browser
if (!state.user.perm?.create) return;
if (!state.user.perm?.modify) return;
this.$el.addEventListener("dragenter", this.dragEnter);
this.$el.addEventListener("dragleave", this.dragLeave);
this.$el.addEventListener("drop", this.drop);
@@ -327,7 +328,6 @@ export default {
beforeUnmount() {
// Remove event listeners before destroying this page.
window.removeEventListener("keydown", this.keyEvent);
window.removeEventListener("scroll", this.scrollEvent);
window.removeEventListener("resize", this.windowsResize);
// If Safari, remove touchstart listener
if (state.isSafari) {
@@ -337,7 +337,7 @@ export default {
this.$el.removeEventListener("mouseup", this.cancelContext);
this.$el.removeEventListener("touchmove", this.handleTouchMove);
} else {
window.removeEventListener("contextmenu", this.openContext);
this.$el.removeEventListener("contextmenu", this.openContext);
}
},
methods: {
@@ -517,7 +517,7 @@ export default {
}
},
keyEvent(event) {
if (state.isSearchActive || getters.currentView() !== "files") {
if (state.isSearchActive || getters.currentView() !== "listingView") {
return;
}
const { key, ctrlKey, metaKey, which } = event;
@@ -553,6 +553,7 @@ export default {
}
return;
}
// Handle key events using a switch statement
switch (key) {
case "Enter":
@@ -791,26 +792,25 @@ export default {
}
let files = await upload.scanFiles(dt);
const folderUpload = Boolean(files[0].webkitRelativePath);
const uploadFiles = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
const fullPath = folderUpload ? file.webkitRelativePath : undefined;
uploadFiles.push({
file, // File object directly
name: file.name,
size: file.size,
isDir: false,
fullPath,
});
}
let items = state.req.items;
let path = getters.routePath();
if (el !== null && el.classList.contains("item") && el.dataset.dir === "true") {
let response = await filesApi.fetchFiles(decodeURIComponent(el.__vue__.url));
path = el.__vue__.url;
items = state.req.items;
items = response.items;
}
const uploadFiles = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
uploadFiles.push({
file,
name: file.name,
source: state.req.source,
size: file.size,
});
}
const conflict = upload.checkConflict(uploadFiles, items);
try {
+17 -15
View File
@@ -1,10 +1,9 @@
<template>
<div id="previewer" @mousemove="toggleNavigation" @touchstart="toggleNavigation">
<div class="preview">
<ExtendedImage v-if="getSimpleType(req.type) == 'image'" :src="raw">
</ExtendedImage>
<ExtendedImage v-if="previewType == 'image'" :src="raw"> </ExtendedImage>
<audio
v-else-if="getSimpleType(req.type) == 'audio'"
v-else-if="previewType == 'audio'"
ref="player"
:src="raw"
controls
@@ -12,7 +11,7 @@
@play="autoPlay = true"
></audio>
<video
v-else-if="getSimpleType(req.type) == 'video'"
v-else-if="previewType == 'video'"
ref="player"
:src="raw"
controls
@@ -29,11 +28,7 @@
/>
</video>
<object
v-else-if="getSimpleType(req.type) == 'pdf'"
class="pdf"
:data="raw"
></object>
<object v-else-if="previewType == 'pdf'" class="pdf" :data="raw"></object>
<div v-else class="info">
<div class="title">
<i class="material-icons">feedback</i>
@@ -90,9 +85,9 @@ import url from "@/utils/url.js";
import throttle from "@/utils/throttle";
import ExtendedImage from "@/components/files/ExtendedImage.vue";
import { state, getters, mutations } from "@/store";
import { getTypeInfo } from "@/utils/mimetype";
import { getFileExtension } from "@/utils/files";
import { convertToVTT } from "@/utils/subtitles";
import { getTypeInfo } from "@/utils/mimetype";
export default {
name: "preview",
@@ -117,6 +112,12 @@ export default {
};
},
computed: {
sidebarShowing() {
return getters.isSidebarVisible();
},
previewType() {
return getters.previewType();
},
raw() {
return filesApi.getDownloadURL(state.req.source, state.req.path, true);
},
@@ -184,9 +185,6 @@ export default {
}
return subs;
},
getSimpleType(mimetype) {
return getTypeInfo(mimetype).simpleType;
},
deleteFile() {
this.currentPrompt = {
name: "delete",
@@ -259,14 +257,18 @@ export default {
let composedListing = this.listing[j];
composedListing.path = directoryPath + "/" + composedListing.name;
this.previousLink = composedListing.url;
this.previousRaw = this.prefetchUrl(composedListing);
if (getTypeInfo(composedListing.type).simpleType == "image") {
this.previousRaw = this.prefetchUrl(composedListing);
}
break;
}
for (let j = i + 1; j < this.listing.length; j++) {
let composedListing = this.listing[j];
composedListing.path = directoryPath + "/" + composedListing.name;
this.nextLink = composedListing.url;
this.nextRaw = this.prefetchUrl(composedListing);
if (getTypeInfo(composedListing.type).simpleType == "image") {
this.nextRaw = this.prefetchUrl(composedListing);
}
break;
}
return;
File renamed without changes.
@@ -1,6 +1,7 @@
import { test, expect } from "@playwright/test";
import { test, expect } from "../test-setup";
test("info from listing", async ({ page, context }) => {
test("info from listing", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="file.tar.gz"]').waitFor({ state: 'visible' });
@@ -9,9 +10,10 @@ test("info from listing", async ({ page, context }) => {
await expect(page.locator('.selected-count-header')).toHaveText('1 selected');
await page.locator('button[aria-label="Info"]').click();
await expect(page.locator('.break-word')).toHaveText('Display Name: file.tar.gz');
checkForErrors();
});
test("info from search", async ({ page, context }) => {
test("info from search", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('#search').click()
@@ -22,9 +24,22 @@ test("info from search", async ({ page, context }) => {
await expect(page.locator('.selected-count-header')).toHaveText('1 selected');
await page.locator('button[aria-label="Info"]').click();
await expect(page.locator('.break-word')).toHaveText('Display Name: file.tar.gz');
checkForErrors();
})
test("2x copy from listing to new folder", async ({ page, context }) => {
test("open from search", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('#search').click()
await page.locator('#main-input').fill('file.tar.gz');
await expect(page.locator('#result-list')).toHaveCount(1);
await page.locator('li[aria-label="file.tar.gz"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - file.tar.gz");
await expect(page.locator('#previewer')).toContainText('Preview is not available for this file.');
checkForErrors();
})
test("2x copy from listing to new folder", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="copyme.txt"]').waitFor({ state: 'visible' });
@@ -70,9 +85,10 @@ test("2x copy from listing to new folder", async ({ page, context }) => {
await expect(popup2).toHaveText("Successfully copied file/folder, redirecting...");
await page.waitForURL('**/newfolder/');
await expect(page).toHaveTitle("Graham's Filebrowser - Files - newfolder");
checkForErrors();
})
test("delete file", async ({ page, context }) => {
test("delete file", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="deleteme.txt"]').waitFor({ state: 'visible' });
@@ -86,9 +102,11 @@ test("delete file", async ({ page, context }) => {
const popup = page.locator('#popup-notification-content');
await popup.waitFor({ state: 'visible' });
await expect(popup).toHaveText("Deleted item successfully! reloading...");
checkForErrors();
})
test("delete nested file prompt", async ({ page, context }) => {
test("delete nested file prompt", async({ page, checkForErrors, context }) => {
await page.goto("/files/playwright-files/folder%23hash/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - folder#hash");
await page.locator('a[aria-label="file#.sh"]').waitFor({ state: 'visible' });
@@ -98,5 +116,5 @@ test("delete nested file prompt", async ({ page, context }) => {
await page.locator('button[aria-label="Delete"]').click();
await expect(page.locator('.card-content')).toHaveText('Are you sure you want to delete this file/folder?/folder#hash/file#.sh');
await expect(page.locator('div[aria-label="delete-path"]')).toHaveText('/folder#hash/file#.sh');
checkForErrors();
})
@@ -1,19 +1,20 @@
import { test, expect } from "@playwright/test";
import { test, expect } from "../test-setup";
test("navigate with hash in file name", async ({ page, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="folder#hash"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="folder#hash"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - folder#hash");
await page.locator('a[aria-label="file#.sh"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="file#.sh"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - file#.sh");
await expect(page.locator('.topTitle')).toHaveText('file#.sh');
test("navigate with hash in file name", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="folder#hash"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="folder#hash"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - folder#hash");
await page.locator('a[aria-label="file#.sh"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="file#.sh"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - file#.sh");
await expect(page.locator('.topTitle')).toHaveText('file#.sh');
checkForErrors()
})
test("breadcrumbs navigation checks", async ({ page }) => {
test("breadcrumbs navigation checks", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page.locator('a[aria-label="Home"]')).toHaveAttribute("href", "/playwright-files/");
@@ -42,11 +43,10 @@ test("breadcrumbs navigation checks", async ({ page }) => {
expect(spanChildrenCount).toBe(1);
breadCrumbLink = page.locator('span[aria-label="breadcrumb-link-files"] a')
await expect(breadCrumbLink).toHaveText("files");
checkForErrors();
});
test("navigate from search item", async ({ page }) => {
test("navigate from search item", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('#search').click()
@@ -55,4 +55,5 @@ test("navigate from search item", async ({ page }) => {
await page.locator('li[aria-label="for testing.md"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - for testing.md");
await expect(page.locator('.topTitle')).toHaveText('for testing.md');
checkForErrors()
});
@@ -0,0 +1,34 @@
import { test, expect } from "../test-setup";
test("breadcrumbs navigation checks", async ({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
const shareHash = await page.evaluate(() => localStorage.getItem('shareHash'));
if (shareHash == "") {
throw new Error("Share hash not found in localStorage");
}
await page.goto("/share/" + shareHash);
await expect(page).toHaveTitle("Graham's Filebrowser - Share - myfolder");
await expect(page.locator('a[aria-label="Home"]')).toHaveAttribute("href", `/share/${shareHash}/`);
await page.dblclick('a[aria-label="testdata"]');
await expect(page).toHaveTitle("Graham's Filebrowser - Share - testdata");
// Ensure no <span> children exist directly under .breadcrumbs (ie no breadcrumbs paths)
let spanChildrenCount = await page.locator('.breadcrumbs > span').count();
await page.waitForSelector('.breadcrumbs');
expect(spanChildrenCount).toBe(1);
checkForErrors();
});
test("root share path is valid", async ({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('button[aria-label="Show-Share"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Show-Share"]').click();
await expect(page.locator('div[aria-label="share-path"]')).toHaveText('Path: /');
checkForErrors();
});
@@ -1,6 +1,6 @@
import { test, expect } from "@playwright/test";
import { test, expect } from "../test-setup";
test("sidebar links", async ({ page }) => {
test("sidebar links", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
// Verify the page title
@@ -17,9 +17,11 @@ test("sidebar links", async ({ page }) => {
// Assert that the <a> does not contain the text 'Help'
await expect(credits.locator("span").locator("a")).not.toHaveText('Help');
// Check for console errors
checkForErrors();
});
test("adjusting theme colors", async ({ page }) => {
test("adjusting theme colors", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
const originalPrimaryColor = await page.evaluate(() => {
return getComputedStyle(document.documentElement).getPropertyValue('--primaryColor').trim();
@@ -38,4 +40,6 @@ test("adjusting theme colors", async ({ page }) => {
return getComputedStyle(document.documentElement).getPropertyValue('--primaryColor').trim();
});
await expect(newPrimaryColor).toBe('#9b59b6');
// Check for console errors
checkForErrors();
});
+43
View File
@@ -0,0 +1,43 @@
import { Browser, firefox, expect, Page } from "@playwright/test";
// Perform authentication and store auth state
async function globalSetup() {
const browser: Browser = await firefox.launch();
const context = await browser.newContext();
const page: Page = await context.newPage();
await page.goto("http://127.0.0.1/login");
await page.getByPlaceholder("Username").fill("admin");
await page.getByPlaceholder("Password").fill("admin");
await page.getByRole("button", { name: "Login" }).click();
await page.waitForURL("**/files/", { timeout: 250 });
const cookies = await context.cookies();
expect(cookies.find((c) => c.name === "auth")?.value).toBeDefined();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.waitForURL("**/files/playwright-files", { timeout: 250 });
// Create a share
await page.locator('a[aria-label="myfolder"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="myfolder"]').click({ button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('1 selected');
await page.locator('button[aria-label="Share"]').click();
await expect(page.locator('div[aria-label="share-path"]')).toHaveText('Path: /myfolder');
await page.locator('button[aria-label="Share-Confirm"]').click();
await expect(page.locator("#share .card-content table tbody tr:not(:has(th))")).toHaveCount(1);
const shareHash = await page.locator("#share .card-content table tbody tr:not(:has(th)) td").first().textContent();
if (!shareHash) {
throw new Error("Failed to retrieve shareHash");
}
// Store shareHash in localStorage
await page.evaluate((hash) => {
localStorage.setItem('shareHash', hash);
}, shareHash);
await context.storageState({ path: "./loginAuth.json" });
await browser.close();
}
export default globalSetup;
@@ -1,16 +1,18 @@
import { test, expect } from "@playwright/test";
import { test, expect } from "../test-setup";
test("blob file preview", async ({ page, context }) => {
test("blob file preview", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="file.tar.gz"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="file.tar.gz"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - file.tar.gz");
await page.locator('button[title="Close"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
// Check for console errors
checkForErrors();
});
test("text file editor", async ({ page, context }) => {
test("text file editor", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="copyme.txt"]').waitFor({ state: 'visible' });
@@ -20,9 +22,11 @@ test("text file editor", async ({ page, context }) => {
expect(firstLineText).toBe('test file for playwright');
await page.locator('button[title="Close"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
// Check for console errors
checkForErrors();
});
test("navigate folders", async ({ page, context }) => {
test("navigate folders", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="myfolder"]').waitFor({ state: 'visible' });
@@ -34,21 +38,6 @@ test("navigate folders", async ({ page, context }) => {
await page.locator('a[aria-label="gray-sample.jpg"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="gray-sample.jpg"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - gray-sample.jpg");
});
test("navigating images", async ({ page, context }) => {
await page.goto("/files/playwright-files/myfolder/testdata/20130612_142406.jpg");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - 20130612_142406.jpg");
await page.locator('button[aria-label="Previous"]').waitFor({ state: 'hidden' });
await page.mouse.move(100, 100);
await page.locator('button[aria-label="Next"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Next"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - gray-sample.jpg");
await page.locator('button[aria-label="Previous"]').waitFor({ state: 'hidden' });
await page.locator('button[aria-label="Next"]').waitFor({ state: 'hidden' });
await page.mouse.move(100, 100);
await page.locator('button[aria-label="Next"]').waitFor({ state: 'visible' });
//await page.locator('button[aria-label="Next"]').click();
// went to next image
//await expect(page).toHaveTitle("Graham's Filebrowser - Files - IMG_2578.JPG");
// Check for console errors
checkForErrors();
});
@@ -0,0 +1,14 @@
import { test, expect } from "../test-setup";
test("Create first new file", async ({ page, checkForErrors, context }) => {
await page.goto("/");
await expect(page.locator('#listingView .message > span')).toHaveText('It feels lonely here...');
await page.locator('#listingView').click({ button: "right" });
await page.locator('button[aria-label="New file"]').click();
await page.locator('input[aria-label="FileName Field"]').fill('test.txt');
await page.locator('button[aria-label="Create"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - test.txt");
await page.locator('button[aria-label="Close"]').click();
await expect(page.locator('#listingView .file-items')).toHaveCount(1);
checkForErrors();
});
+29
View File
@@ -0,0 +1,29 @@
import { test as base, expect, Page } from "@playwright/test";
export const test = base.extend<{ checkForErrors: () => void }>({
checkForErrors: async ({ page }, use) => {
const { checkForErrors } = setupErrorTracking(page);
await use(checkForErrors);
},
});
// Error tracking function
export function setupErrorTracking(page: Page) {
const errors: string[] = [];
page.on("console", (message) => {
if (message.type() === "error") {
errors.push(message.text());
}
});
return {
checkForErrors: () => {
if (errors.length > 0) {
console.error("Console Errors Detected:", errors);
}
expect(errors).toHaveLength(0);
},
};
}
export { expect };
-55
View File
@@ -1,55 +0,0 @@
import { test, expect } from "@playwright/test";
test("blob file preview", async ({ page, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="file.tar.gz"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="file.tar.gz"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - file.tar.gz");
await page.locator('button[title="Close"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
});
test("text file editor", async ({ page, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="copyme.txt"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="copyme.txt"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - copyme.txt");
const firstLineText = await page.locator('.ace_text-layer .ace_line').first().textContent();
expect(firstLineText).toBe('test file for playwright');
await page.locator('button[title="Close"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
});
test("navigate folders", async ({ page, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="myfolder"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="myfolder"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - myfolder");
await page.locator('a[aria-label="testdata"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="testdata"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - testdata");
await page.locator('a[aria-label="gray-sample.jpg"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="gray-sample.jpg"]').dblclick();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - gray-sample.jpg");
});
test("navigating images", async ({ page, context }) => {
await page.goto("/files/myfolder/testdata/20130612_142406.jpg");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - 20130612_142406.jpg");
await page.locator('button[aria-label="Previous"]').waitFor({ state: 'hidden' });
await page.mouse.move(100, 100);
await page.locator('button[aria-label="Next"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Next"]').click();
// went to next image
await expect(page).toHaveTitle("Graham's Filebrowser - Files - gray-sample.jpg");
await page.locator('button[aria-label="Previous"]').waitFor({ state: 'hidden' });
await page.locator('button[aria-label="Next"]').waitFor({ state: 'hidden' });
await page.mouse.move(100, 100);
await page.locator('button[aria-label="Next"]').waitFor({ state: 'visible' });
//await page.locator('button[aria-label="Next"]').click();
// went to next image
//await expect(page).toHaveTitle("Graham's Filebrowser - Files - IMG_2578.JPG");
});
+1 -1
View File
@@ -85,6 +85,6 @@ vi.mock('@/store', () => {
vi.mock('@/utils/constants', () => {
return {
baseURL: "http://example.com",
baseURL: "/files/",
};
});
+23 -23
View File
@@ -1,25 +1,25 @@
{
"compilerOptions": {
"baseUrl": ".",
"allowJs": true,
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node10",
"strict": true,
"sourceMap": true,
"noImplicitReturns": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"resolveJsonModule": true,
"types": ["vite/client", "@intlify/unplugin-vue-i18n/messages"],
"paths": {
"@/*": ["./src/*"]
},
"checkJs": false, // check later
"compilerOptions": {
"baseUrl": ".",
"allowJs": true,
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node10",
"strict": true,
"sourceMap": true,
"noImplicitReturns": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"resolveJsonModule": true,
"types": ["vite/client", "@intlify/unplugin-vue-i18n/messages"],
"paths": {
"@/*": ["./src/*"]
},
"include": ["src/**/*.ts", "src/**/*.js", "src/**/*.vue", "tests/auth.spec.ts"],
"exclude": ["node_modules", "dist"]
}
"checkJs": false, // check later
},
"include": ["src/**/*.ts", "src/**/*.js", "src/**/*.vue", "tests-playwright/general/auth.spec.ts"],
"exclude": ["node_modules", "dist"]
}
+1 -1
View File
@@ -1,7 +1,7 @@
.SILENT:
setup:
echo "creating ./backend/test_config.yaml for local testing..." && \
if [ ! -f backend/test__config.yaml ]; then \
if [ ! -f backend/test_config.yaml ]; then \
cp backend/config.yaml backend/test_config.yaml; \
fi
echo "installing swagger needed to generate backend api docs..." && \