Compare commits

...
10 Commits
60 changed files with 928 additions and 494 deletions

No files matched your search

+1
View File
@@ -1,4 +1,5 @@
backend/**.db
backend/tmp
backend/vendor/**
frontend/dist/**
frontend/node_modules/**
+10 -10
View File
@@ -87,16 +87,16 @@ jobs:
echo "✅ Successfully merged '$BETA_BRANCH' into '$STABLE_BRANCH'."
- name: Delete beta branch after successful merge
run: |
VERSION="${{ github.event.inputs.version }}"
BETA_BRANCH="beta/v$VERSION"
# Delete beta branch locally and remotely
git branch -d "$BETA_BRANCH"
git push origin --delete "$BETA_BRANCH"
echo "✅ Successfully deleted '$BETA_BRANCH'."
# - name: Delete beta branch after successful merge
# run: |
# VERSION="${{ github.event.inputs.version }}"
# BETA_BRANCH="beta/v$VERSION"
#
# # Delete beta branch locally and remotely
# git branch -d "$BETA_BRANCH"
# git push origin --delete "$BETA_BRANCH"
#
# echo "✅ Successfully deleted '$BETA_BRANCH'."
- name: Create Pull Request to Main
uses: peter-evans/create-pull-request@v6
+10 -10
View File
@@ -87,13 +87,13 @@ jobs:
echo "✅ Successfully merged '$DEV_BRANCH' into '$BETA_BRANCH'."
- name: Delete dev branch after successful merge
run: |
VERSION="${{ github.event.inputs.version }}"
DEV_BRANCH="dev/v$VERSION"
# Delete dev branch locally and remotely
git branch -d "$DEV_BRANCH"
git push origin --delete "$DEV_BRANCH"
echo "✅ Successfully deleted '$DEV_BRANCH'."
# - name: Delete dev branch after successful merge
# run: |
# VERSION="${{ github.event.inputs.version }}"
# DEV_BRANCH="dev/v$VERSION"
#
# # Delete dev branch locally and remotely
# git branch -d "$DEV_BRANCH"
# git push origin --delete "$DEV_BRANCH"
#
# echo "✅ Successfully deleted '$DEV_BRANCH'."
+1
View File
@@ -9,6 +9,7 @@ rice-box.go
/backend/filebrowser
/backend/filebrowser.exe
/backend/backend.exe
/backend/tmp
/frontend/dist
/frontend/pkg
/frontend/test-results
+48
View File
@@ -2,6 +2,54 @@
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.7-beta
**Notes**:
- added full tests for single source example.
- adds descriptive error if temp dir can't be created on fatal startup
- clears temp directory on shutdown.
- removed put settings api (unused)
- removed more unused config properties.
**BugFixes**:
- fix url encoding issue for search links when theres only one source https://github.com/gtsteffaniak/filebrowser/issues/501
- files with # could have problems, double encoded.
## v0.6.6-beta
**New Feature**:
- limit tar size creation to limit server burden. For example, don't let customers try to download the entire filesystem as a zip. see `server.maxArchiveSize` on config wiki.
**Notes**:
- disableUsedPercentage also hides text and source bar.
- share errors show up in logs in more verbose way.
- archive creation occurs on disk rather than in memory, use `server.cacheDir` to determine where temp files are stored.
- automatically ensures leading slash for scope
- https://github.com/gtsteffaniak/filebrowser/issues/472
- https://github.com/gtsteffaniak/filebrowser/issues/476
**BugFixes**:
- fix proxy user creation issue https://github.com/gtsteffaniak/filebrowser/issues/478
- externalUrl prefix issue fixed for shares. https://github.com/gtsteffaniak/filebrowser/issues/465
- fix File Opens Instead of Just Downloading https://github.com/gtsteffaniak/filebrowser/issues/480
- fix Download file name https://github.com/gtsteffaniak/filebrowser/issues/481
## v0.6.5-beta
**Notes**:
- added more share and download tests
**BugFixes**:
- fix share download issue https://github.com/gtsteffaniak/filebrowser/issues/465
- fix content length size calculation issue when downloading multiple files.
## 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**:
+3
View File
@@ -19,6 +19,9 @@
> [!WARNING]
> There is no stable version -- planned 2025.
> [!NOTE]
> [Read about upcoming 0.7.0 release](https://github.com/gtsteffaniak/filebrowser/discussions/459)
FileBrowser Quantum is a fork of the file browser open-source project with the following changes:
1. ✅ Indexes files (See [indexing Wiki](https://github.com/gtsteffaniak/filebrowser/wiki/Indexing) for more info.)
+1 -1
View File
@@ -20,9 +20,9 @@ RUN npm run build-docker
FROM alpine:latest
ENV FILEBROWSER_NO_EMBEDED="true"
RUN apk --no-cache add ca-certificates mailcap
WORKDIR /home/filebrowser
RUN adduser -D -s /bin/true -u 1000 filebrowser
USER filebrowser
WORKDIR /home/filebrowser
COPY --from=base --chown=filebrowser:1000 /app/filebrowser* ./
COPY --from=base --chown=filebrowser:1000 /app/config.yaml ./
COPY --from=nbuild --chown=filebrowser:1000 /app/dist/ ./http/dist/
@@ -10,7 +10,7 @@ import { defineConfig, devices } from "@playwright/test";
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
//globalSetup: "./global-setup",
globalSetup: "./tests-playwright/noauth-setup",
timeout: 5000,
testDir: "./tests-playwright/noauth",
/* Run tests in files in parallel */
@@ -25,6 +25,7 @@ export default defineConfig({
reporter: "line",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
storageState: "noauth.json",
actionTimeout: 5000,
//storageState: "loginAuth.json",
/* Base URL to use in actions like `await page.goto('/')`. */
+2
View File
@@ -8,6 +8,7 @@ server:
config:
defaultEnabled: true
createUserDir: true
frontend:
name: "Graham's Filebrowser"
disableDefaultLinks: true
@@ -15,6 +16,7 @@ frontend:
- text: "A playwright test"
url: "https://playwright.dev/"
title: "Playwright"
auth:
signup: false
methods:
+1 -1
View File
@@ -163,7 +163,7 @@ func (a *HookAuth) SaveUser() (*users.User, error) {
ShowHidden: a.Settings.UserDefaults.ShowHidden,
},
Username: a.Cred.Username,
Perm: a.Settings.UserDefaults.Perm,
Perm: a.Settings.UserDefaults.Permissions,
}
u = a.GetUser(d)
+6 -1
View File
@@ -9,6 +9,7 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/diskcache"
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/fileutils"
fbhttp "github.com/gtsteffaniak/filebrowser/backend/http"
"github.com/gtsteffaniak/filebrowser/backend/img"
"github.com/gtsteffaniak/filebrowser/backend/logger"
@@ -101,6 +102,7 @@ func StartFilebrowser() {
case <-done:
logger.Info("Server stopped unexpectedly. Shutting down...")
}
fileutils.ClearCacheDir()
<-shutdownComplete // Ensure we don't exit prematurely
// Wait for the server to stop
@@ -121,7 +123,10 @@ func rootCMD(ctx context.Context, store *storage.Storage, serverConfig *settings
var err error
fileCache, err = diskcache.NewFileCache(cacheDir)
if err != nil {
logger.Fatal(fmt.Sprintf("failed to create file cache: %v", err))
if cacheDir == "tmp" {
logger.Error("The cache dir could not be created. Make sure the user that you executed the program with has access to create directories in the local path. filebrowser is trying to use the default `server.cacheDir: tmp` , but you can change this location if you need to. Please see configuration wiki for more information about this error. https://github.com/gtsteffaniak/filebrowser/wiki/Configuration")
}
logger.Fatal(fmt.Sprintf("failed to create file cache path, which is now require to run the server: %v", err))
}
} else {
// No-op cache if no cacheDir is specified
+7
View File
@@ -15,6 +15,13 @@ func validateUserInfo() {
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)
}
}
+3
View File
@@ -71,6 +71,9 @@ func (idx *Index) Search(search string, scope string, sourceSession string) []Se
// search files first
for _, item := range dir.Files {
fullPath := dirName + "/" + item.Name
if dirName == "/" {
fullPath = dirName + item.Name
}
value, found := sessionInProgress.Load(sourceSession)
if !found || value != runningHash {
idx.mu.Unlock()
+23 -1
View File
@@ -90,7 +90,8 @@ func TestSearchWhileIndexing(t *testing.T) {
func TestSearchIndexes(t *testing.T) {
index := Index{
Directories: map[string]*FileInfo{
"/test": {Files: []ItemInfo{{Name: "audio1.wav", Type: "audio"}}},
"/": {Files: []ItemInfo{{Name: "audio-one.wav", Type: "audio"}}},
"/test": {Files: []ItemInfo{{Name: "audio-one.wav", Type: "audio"}}},
"/test/path": {Files: []ItemInfo{{Name: "file.txt", Type: "text"}}},
"/new/test": {Files: []ItemInfo{
{Name: "audio.wav", Type: "audio"},
@@ -230,6 +231,27 @@ func TestSearchIndexes(t *testing.T) {
},
},
},
{
search: "audio",
scope: "/",
expectedResult: []SearchResult{
{
Path: "/audio-one.wav",
Type: "audio",
Size: 0,
},
{
Path: "/test/audio-one.wav",
Type: "audio",
Size: 0,
},
{
Path: "/new/test/audio.wav",
Type: "audio",
Size: 0,
},
},
},
}
for _, tt := range tests {
+12 -1
View File
@@ -5,6 +5,7 @@ import (
"path/filepath"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
)
// UpdateFileMetadata updates the FileInfo for the specified directory in the index.
@@ -78,7 +79,17 @@ func GetIndex(name string) *Index {
defer indexesMutex.Unlock()
index, ok := indexes[name]
if !ok {
logger.Error(fmt.Sprintf("index %s not found", name))
// try path if name fails
// todo: update everywhere else so this isn't needed.
source, ok := settings.Config.Server.SourceMap[name]
if !ok {
logger.Error(fmt.Sprintf("index %s not found", name))
}
index, ok = indexes[source.Name]
if !ok {
logger.Error(fmt.Sprintf("index %s not found", name))
}
}
return index
}
-1
View File
@@ -13,7 +13,6 @@ import (
// todo fix this!!
// MakeUserDir makes the user directory according to settings.
func MakeUserDir(fullPath string) error {
logger.Debug(fmt.Sprintf("creating user home dir: [%s]", fullPath))
if err := os.MkdirAll(fullPath, os.ModePerm); err != nil {
return err
}
+18
View File
@@ -8,6 +8,7 @@ import (
"path/filepath"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
)
// MoveFile moves a file from src to dst.
@@ -175,3 +176,20 @@ func CommonPrefix(sep byte, paths ...string) string {
return string(c)
}
func ClearCacheDir() {
cacheDir := settings.Config.Server.CacheDir
entries, err := os.ReadDir(cacheDir)
if err != nil {
logger.Error(fmt.Sprintf("failed clear cache dir: %v", err))
}
for _, entry := range entries {
path := filepath.Join(cacheDir, entry.Name())
err = os.RemoveAll(path)
if err != nil {
logger.Error(fmt.Sprintf("failed clear cache dir: %v", err))
}
}
}
+9 -5
View File
@@ -57,7 +57,9 @@ func withHashFileHelper(fn handleFunc) handleFunc {
}
}
data.path = strings.TrimSuffix(link.Path, "/") + "/" + strings.TrimPrefix(path, "/")
if path == "" || path == "/" {
data.path = link.Path
}
// Get file information with options
file, err := FileInfoFasterFunc(files.FileOptions{
Path: data.path,
@@ -67,7 +69,7 @@ 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))
logger.Error(fmt.Sprintf("error fetching file info for share. hash=%v path=%v error=%v", hash, data.path, err))
return errToStatus(err), fmt.Errorf("error fetching share from server")
}
// Set the file info in the `data` object
@@ -115,13 +117,16 @@ func withUserHelper(fn handleFunc) handleFunc {
if err != nil {
return http.StatusInternalServerError, err
}
newUser := storage.CreateUser(users.User{
err = 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
}
data.user, err = store.Users.Get(proxyUser)
if err != nil {
return http.StatusInternalServerError, err
}
@@ -140,7 +145,6 @@ func withUserHelper(fn handleFunc) handleFunc {
return http.StatusUnauthorized, err
}
data.token = tokenString
var tk users.AuthToken
token, err := jwt.ParseWithClaims(tokenString, &tk, keyFunc)
if err != nil {
+20 -4
View File
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/gtsteffaniak/filebrowser/backend/files"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/users"
_ "github.com/gtsteffaniak/filebrowser/backend/swagger/docs"
@@ -19,7 +20,7 @@ import (
// @Tags Resources
// @Accept json
// @Produce json
// @Param files query string true "a list of files in the following format 'source::filename' and separated by '||' with additional items in the list. (required)"
// @Param files query string true "a list of files in the following format 'filename' and separated by '||' with additional items in the list. (required)"
// @Param inline query bool false "If true, sets 'Content-Disposition' to 'inline'. Otherwise, defaults to 'attachment'."
// @Param algo query string false "Compression algorithm for archiving multiple files or directories. Options: 'zip' and 'tar.gz'. Default is 'zip'."
// @Success 200 {file} file "Raw file or directory content, or archive for multiple files"
@@ -31,12 +32,27 @@ import (
func publicRawHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
encodedFiles := r.URL.Query().Get("files")
// Decode the URL-encoded path
files, err := url.QueryUnescape(encodedFiles)
f, err := url.QueryUnescape(encodedFiles)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
fileList := strings.Split(files, "||")
return rawFilesHandler(w, r, d, fileList)
fileInfo, ok := d.raw.(files.ExtendedFileInfo)
if !ok {
logger.Error("public share handler: failed to assert type files.FileInfo")
return http.StatusInternalServerError, fmt.Errorf("failed to assert type files.FileInfo")
}
fileList := []string{}
for _, file := range strings.Split(f, "||") {
fileList = append(fileList, fileInfo.Source+"::"+fileInfo.Path+file)
}
var status int
status, err = rawFilesHandler(w, r, d, fileList)
if err != nil {
logger.Error(fmt.Sprintf("public share handler: error processing filelist: %v", err))
return status, fmt.Errorf("error processing filelist: %v", f)
}
return status, nil
}
func publicShareHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
+83 -48
View File
@@ -16,11 +16,12 @@ 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"
)
func setContentDisposition(w http.ResponseWriter, r *http.Request, fileName string) {
if r.URL.Query().Get("inline") == "true" {
w.Header().Set("Content-Disposition", "inline")
w.Header().Set("Content-Disposition", "inline; filename*=utf-8''"+url.PathEscape(fileName))
} else {
// As per RFC6266 section 4.3
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(fileName))
@@ -60,9 +61,13 @@ func addFile(path string, d *requestContext, tarWriter *tar.Writer, zipWriter *z
}
source := splitFile[0]
path = splitFile[1]
userScope, err := settings.GetScopeFromSourceName(d.user.Scopes, source)
if d.share == nil && err != nil {
return fmt.Errorf("source %s is not available for user %s", source, d.user.Username)
var err error
userScope := "/"
if d.user.Username != "publicUser" {
userScope, err = settings.GetScopeFromSourceName(d.user.Scopes, source)
if d.share == nil && err != nil {
return fmt.Errorf("source %s is not available for user %s", source, d.user.Username)
}
}
idx := files.GetIndex(source)
@@ -184,9 +189,13 @@ 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 && d.user.Username != "publicUser" {
return http.StatusForbidden, err
var err error
userscope := "/"
if d.user.Username != "publicUser" {
userscope, err = settings.GetScopeFromSourceName(d.user.Scopes, firstFileSource)
if err != nil {
return http.StatusForbidden, err
}
}
idx := files.GetIndex(firstFileSource)
if idx == nil {
@@ -196,13 +205,11 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
if err != nil {
return http.StatusInternalServerError, err
}
// Compute estimated download size
estimatedSize, err := computeArchiveSize(fileList, d)
if err != nil {
return http.StatusInternalServerError, err
}
// ** Single file download with Content-Length **
if len(fileList) == 1 && !isDir {
fd, err2 := os.Open(realPath)
@@ -235,6 +242,12 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
return 200, nil
}
if config.Server.MaxArchiveSizeGB > 0 {
maxSize := config.Server.MaxArchiveSizeGB * 1024 * 1024 * 1024
if estimatedSize > maxSize {
return http.StatusRequestEntityTooLarge, fmt.Errorf("pre-archive combined size of files exceeds maximum limit of %d GB", config.Server.MaxArchiveSizeGB)
}
}
// ** Archive (ZIP/TAR.GZ) handling **
algo := r.URL.Query().Get("algo")
var extension string
@@ -247,7 +260,7 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
return http.StatusInternalServerError, errors.New("format not implemented")
}
baseDirName := filepath.Base(filepath.Dir(realPath))
baseDirName := filepath.Base(filepath.Dir(firstFilePath))
if baseDirName == "" || baseDirName == "/" {
baseDirName = "download"
}
@@ -256,22 +269,47 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
}
fileName = url.PathEscape(baseDirName + extension)
// Set headers for archive
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+fileName)
w.Header().Set("Content-Length", fmt.Sprintf("%d", estimatedSize))
archiveData := filepath.Join(config.Server.CacheDir, utils.InsecureRandomIdentifier(10))
if extension == ".zip" {
archiveData = archiveData + ".zip"
err = createZip(d, archiveData, fileList...)
} else {
archiveData = archiveData + ".tar.gz"
err = createTarGz(d, archiveData, fileList...)
}
if err != nil {
return http.StatusInternalServerError, err
}
sizeInMB := estimatedSize / 1024 / 1024
// if larger than 100 megabytes, log it
// stream archive to response
fd, err := os.Open(archiveData)
if err != nil {
return http.StatusInternalServerError, err
}
defer fd.Close()
// Get file size
fileInfo, err := fd.Stat()
if err != nil {
os.Remove(archiveData) // Remove the file if stat fails
return http.StatusInternalServerError, err
}
sizeInMB := fileInfo.Size() / 1024 / 1024
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" {
err = createZip(w, d, fileList...)
} else {
err = createTarGz(w, d, fileList...)
}
// Set headers AFTER computing actual archive size
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+fileName)
w.Header().Set("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))
w.Header().Set("Content-Type", "application/octet-stream")
// Stream the file
_, err = io.Copy(w, fd)
os.Remove(archiveData) // Remove the file after streaming
if err != nil {
logger.Error(fmt.Sprintf("Failed to copy archive data to response: %v", err))
return http.StatusInternalServerError, err
}
@@ -291,9 +329,13 @@ func computeArchiveSize(fileList []string, d *requestContext) (int64, error) {
if idx == nil {
return 0, fmt.Errorf("source %s is not available", source)
}
userScope, err := settings.GetScopeFromSourceName(d.user.Scopes, source)
if d.share == nil && err != nil {
return 0, fmt.Errorf("source %s is not available for user %s", source, d.user.Username)
var err error
userScope := "/"
if d.user.Username != "publicUser" {
userScope, err = settings.GetScopeFromSourceName(d.user.Scopes, source)
if d.share == nil && err != nil {
return 0, fmt.Errorf("source %s is not available for user %s", source, d.user.Username)
}
}
_, isDir, err := idx.GetRealPath(userScope, path)
if err != nil {
@@ -308,52 +350,45 @@ func computeArchiveSize(fileList []string, d *requestContext) (int64, error) {
return estimatedSize, nil
}
func createZip(w io.Writer, d *requestContext, filenames ...string) error {
zipWriter := zip.NewWriter(w)
defer zipWriter.Close()
// Stream the response to avoid high memory usage
if f, ok := w.(http.Flusher); ok {
f.Flush()
func createZip(d *requestContext, tmpDirPath string, filenames ...string) error {
file, err := os.Create(tmpDirPath)
if err != nil {
return err
}
defer file.Close()
zipWriter := zip.NewWriter(file)
defer zipWriter.Close()
// Check if we have exactly one directory
//flatten := len(filenames) == 1
for _, fname := range filenames {
err := addFile(fname, d, nil, zipWriter, false)
if err != nil {
logger.Error(fmt.Sprintf("Failed to add %s to ZIP: %v", fname, err))
return err
}
// Flush after adding each file
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
return nil
}
func createTarGz(w io.Writer, d *requestContext, filenames ...string) error {
gzWriter := gzip.NewWriter(w)
defer gzWriter.Close()
func createTarGz(d *requestContext, tmpDirPath string, filenames ...string) error {
file, err := os.Create(tmpDirPath)
if err != nil {
return err
}
defer file.Close()
gzWriter := gzip.NewWriter(file)
defer gzWriter.Close()
tarWriter := tar.NewWriter(gzWriter)
defer tarWriter.Close()
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
// Check if we have exactly one directory
//flatten := len(filenames) == 1
for _, fname := range filenames {
err := addFile(fname, d, tarWriter, nil, false)
if err != nil {
logger.Error(fmt.Sprintf("Failed to add %s to TAR.GZ: %v", fname, err))
return err
}
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
return nil
-1
View File
@@ -114,7 +114,6 @@ func StartHttp(ctx context.Context, Service ImgService, storage *storage.Storage
// Settings routes
api.HandleFunc("GET /settings", withAdmin(settingsGetHandler))
api.HandleFunc("PUT /settings", withAdmin(settingsPutHandler))
api.HandleFunc("GET /onlyoffice/config", withUser(onlyofficeClientConfigGetHandler))
api.HandleFunc("POST /onlyoffice/callback", withUser(onlyofficeCallbackHandler))
-37
View File
@@ -1,20 +1,9 @@
package http
import (
"encoding/json"
"net/http"
"github.com/gtsteffaniak/filebrowser/backend/settings"
)
type settingsData struct {
Signup bool `json:"signup"`
CreateUserDir bool `json:"createUserDir"`
UserHomeBasePath string `json:"userHomeBasePath"`
Defaults settings.UserDefaults `json:"defaults"`
Frontend settings.Frontend `json:"frontend"`
}
// settingsGetHandler retrieves the current system settings.
// @Summary Get system settings
// @Description Returns the current configuration settings for signup, user directories, rules, frontend.
@@ -45,29 +34,3 @@ func settingsGetHandler(w http.ResponseWriter, r *http.Request, d *requestContex
}
return renderJSON(w, r, config)
}
// settingsPutHandler updates the system settings.
// @Summary Update system settings
// @Description Updates the system configuration settings for signup, user directories, rules, frontend.
// @Tags Settings
// @Accept json
// @Produce json
// @Param body body settingsData true "Settings data to update"
// @Success 200 "Settings updated successfully"
// @Failure 400 {object} map[string]string "Bad request - failed to decode body"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/settings [put]
func settingsPutHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
req := &settingsData{}
err := json.NewDecoder(r.Body).Decode(req)
if err != nil {
return http.StatusBadRequest, err
}
config.Server.UserHomeBasePath = req.UserHomeBasePath
config.UserDefaults = req.Defaults
config.Frontend = req.Frontend
config.Auth.Signup = req.Signup
err = store.Settings.Save(config)
return errToStatus(err), err
}
+6 -5
View File
@@ -39,7 +39,6 @@ func shareListHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
if err == errors.ErrNotExist {
return renderJSON(w, r, []*share.Link{})
}
if err != nil {
return http.StatusInternalServerError, err
}
@@ -174,14 +173,16 @@ func sharePostHandler(w http.ResponseWriter, r *http.Request, d *requestContext)
stringHash = string(hash)
}
path := r.URL.Query().Get("path")
source := r.URL.Query().Get("source")
if source == "" {
source = config.Server.DefaultSource.Name
sourceName := r.URL.Query().Get("source")
if sourceName == "" {
sourceName = config.Server.DefaultSource.Name
}
source := config.Server.NameToSource[sourceName]
s = &share.Link{
Path: path,
Hash: secure_hash,
Source: source,
Source: source.Path,
Expire: expire,
UserID: d.user.ID,
PasswordHash: stringHash,
-17
View File
@@ -5,13 +5,10 @@ import (
"fmt"
"io/fs"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/gtsteffaniak/filebrowser/backend/auth"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/version"
)
@@ -47,7 +44,6 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, file, contentT
"DisableExternal": config.Frontend.DisableDefaultLinks,
"DisableUsedPercentage": config.Frontend.DisableUsedPercentage,
"darkMode": settings.Config.UserDefaults.DarkMode,
"Color": config.Frontend.Color,
"BaseURL": config.Server.BaseURL,
"Version": version.Version,
"CommitSHA": version.CommitSHA,
@@ -68,19 +64,6 @@ func handleWithStaticData(w http.ResponseWriter, r *http.Request, file, contentT
"SourceCount": len(config.Server.Sources),
}
if config.Frontend.Files != "" {
fPath := filepath.Join(config.Frontend.Files, "custom.css")
_, err := os.Stat(fPath) //nolint:govet
if err != nil && !os.IsNotExist(err) {
logger.Error(fmt.Sprintf("couldn't load custom styles: %v", err))
}
if err == nil {
data["CSS"] = true
}
}
if config.Auth.Methods.PasswordAuth.Enabled {
raw, err := store.Auth.Get("password") //nolint:govet
if err != nil {
+6 -1
View File
@@ -126,7 +126,6 @@ func setupAuth() {
if Config.Auth.Method != "" {
logger.Warning("The `auth.method` setting is deprecated and will be removed in a future version. Please use `auth.methods` instead.")
}
Config.UserDefaults.Perm = Config.UserDefaults.Permissions
if Config.Auth.Methods.PasswordAuth.Enabled {
Config.Auth.AuthMethods = append(Config.Auth.AuthMethods, "Password")
}
@@ -206,6 +205,8 @@ func setDefaults() Settings {
Database: "database.db",
SourceMap: map[string]Source{},
NameToSource: map[string]Source{},
MaxArchiveSizeGB: 50,
CacheDir: "tmp",
},
Auth: Auth{
AdminUsername: "admin",
@@ -234,6 +235,7 @@ func setDefaults() Settings {
ViewMode: "normal",
Locale: "en",
GallerySize: 3,
ThemeColor: "var(--blue)",
Permissions: users.Permissions{
Modify: false,
Share: false,
@@ -253,6 +255,9 @@ func ConvertToBackendScopes(scopes []users.SourceScope) ([]users.SourceScope, er
if scope.Scope == "" {
scope.Scope = "/"
}
if !strings.HasPrefix(scope.Scope, "/") {
scope.Scope = "/" + scope.Scope
}
// first check if its already a path name and keep it
source, ok := Config.Server.SourceMap[scope.Name]
if ok {
+6 -2
View File
@@ -44,9 +44,14 @@ func ApplyUserDefaults(u *users.User) {
u.Locale = Config.UserDefaults.Locale
u.ViewMode = Config.UserDefaults.ViewMode
u.SingleClick = Config.UserDefaults.SingleClick
u.Perm = Config.UserDefaults.Perm
u.Perm = Config.UserDefaults.Permissions
u.ShowHidden = Config.UserDefaults.ShowHidden
u.DateFormat = Config.UserDefaults.DateFormat
u.DisableOnlyOfficeExt = Config.UserDefaults.DisableOnlyOfficeExt
u.ThemeColor = Config.UserDefaults.ThemeColor
u.GallerySize = Config.UserDefaults.GallerySize
u.QuickDownload = Config.UserDefaults.QuickDownload
u.LockPassword = Config.UserDefaults.LockPassword
if len(u.Scopes) == 0 {
u.Scopes = []users.SourceScope{
{
@@ -55,5 +60,4 @@ func ApplyUserDefaults(u *users.User) {
},
}
}
}
-3
View File
@@ -28,9 +28,6 @@ func (s *Storage) Get() (*Settings, error) {
if err != nil {
return nil, err
}
if set.Server.UserHomeBasePath == "" {
set.Server.UserHomeBasePath = DefaultUsersHomeBasePath
}
return set, nil
}
+10 -18
View File
@@ -13,24 +13,20 @@ const (
)
type Settings struct {
Commands map[string][]string `json:"commands"`
Shell []string `json:"shell"`
Server Server `json:"server"`
Auth Auth `json:"auth"`
Frontend Frontend `json:"frontend"`
Users []UserDefaults `json:"users,omitempty"`
UserDefaults UserDefaults `json:"userDefaults"`
Integrations Integrations `json:"integrations"`
Server Server `json:"server"`
Auth Auth `json:"auth"`
Frontend Frontend `json:"frontend"`
Users []UserDefaults `json:"users,omitempty"`
UserDefaults UserDefaults `json:"userDefaults"`
Integrations Integrations `json:"integrations"`
}
type Auth struct {
TokenExpirationHours int `json:"tokenExpirationHours"`
Recaptcha Recaptcha `json:"recaptcha"`
Methods LoginMethods `json:"methods"`
Command string `json:"command"`
Signup bool `json:"signup"`
Method string `json:"method"`
Shell string `json:"shell"`
Key []byte `json:"key"`
AdminUsername string `json:"adminUsername"`
AdminPassword string `json:"adminPassword"`
@@ -73,16 +69,15 @@ type Server struct {
BaseURL string `json:"baseURL"`
Logging []LogConfig `json:"logging"`
Database string `json:"database"`
Root string `json:"root"` // deprecated, use sources
UserHomeBasePath string `json:"userHomeBasePath"`
Sources []Source `json:"sources"`
ExternalUrl string `json:"externalUrl"`
InternalUrl string `json:"internalUrl"` // used by integrations
CacheDir string `json:"cacheDir"`
MaxArchiveSizeGB int64 `json:"maxArchiveSize"`
// not exposed to config
SourceMap map[string]Source // uses realpath as key
NameToSource map[string]Source // uses name as key
DefaultSource Source
SourceMap map[string]Source `json:"-"` // uses realpath as key
NameToSource map[string]Source `json:"-"` // uses name as key
DefaultSource Source `json:"-"`
}
type Integrations struct {
@@ -134,8 +129,6 @@ type Frontend struct {
Name string `json:"name"`
DisableDefaultLinks bool `json:"disableDefaultLinks"`
DisableUsedPercentage bool `json:"disableUsedPercentage"`
Files string `json:"files"`
Color string `json:"color"`
ExternalLinks []ExternalLink `json:"externalLinks"`
}
@@ -157,7 +150,6 @@ type UserDefaults struct {
ViewMode string `json:"viewMode"`
GallerySize int `json:"gallerySize"`
SingleClick bool `json:"singleClick"`
Perm users.Permissions `json:"perm"`
Permissions users.Permissions `json:"permissions"`
ShowHidden bool `json:"showHidden"`
DateFormat bool `json:"dateFormat"`
+26 -20
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"reflect"
"slices"
"strings"
storm "github.com/asdine/storm/v3"
@@ -72,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 {
@@ -109,7 +114,7 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
// Get the value to be stored
val := fieldValue.Interface()
// Update the database
if err := st.db.UpdateField(user, field, val); err != nil {
if err := st.db.UpdateField(existingUser, field, val); err != nil {
return fmt.Errorf("failed to update user field: %s, error: %v", field, err)
}
}
@@ -193,34 +198,35 @@ 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)
}
}
}
newfields := []string{}
for _, field := range fields {
newfields = append(newfields, utils.CapitalizeFirst(field))
}
if slices.Contains(newfields, "Password") && user.Password != "" {
if settings.Config.Auth.Methods.PasswordAuth.Enabled {
pass, err := users.HashPwd(user.Password)
if err != nil {
return newfields, err
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())
}
user.Password = pass
}
}
if slices.Contains(newfields, "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 newfields, nil
}
+1 -57
View File
@@ -917,53 +917,6 @@ const docTemplate = `{
}
}
}
},
"put": {
"description": "Updates the system configuration settings for signup, user directories, rules, frontend.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Settings"
],
"summary": "Update system settings",
"parameters": [
{
"description": "Settings data to update",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/http.settingsData"
}
}
],
"responses": {
"200": {
"description": "Settings updated successfully"
},
"400": {
"description": "Bad request - failed to decode body",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/api/share": {
@@ -1543,7 +1496,7 @@ const docTemplate = `{
"parameters": [
{
"type": "string",
"description": "a list of files in the following format 'source::filename' and separated by '||' with additional items in the list. (required)",
"description": "a list of files in the following format 'filename' and separated by '||' with additional items in the list. (required)",
"name": "files",
"in": "query",
"required": true
@@ -1784,9 +1737,6 @@ const docTemplate = `{
"settings.Frontend": {
"type": "object",
"properties": {
"color": {
"type": "string"
},
"disableDefaultLinks": {
"type": "boolean"
},
@@ -1799,9 +1749,6 @@ const docTemplate = `{
"$ref": "#/definitions/settings.ExternalLink"
}
},
"files": {
"type": "string"
},
"name": {
"type": "string"
}
@@ -1831,9 +1778,6 @@ const docTemplate = `{
"lockPassword": {
"type": "boolean"
},
"perm": {
"$ref": "#/definitions/users.Permissions"
},
"permissions": {
"$ref": "#/definitions/users.Permissions"
},
+1 -57
View File
@@ -906,53 +906,6 @@
}
}
}
},
"put": {
"description": "Updates the system configuration settings for signup, user directories, rules, frontend.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"Settings"
],
"summary": "Update system settings",
"parameters": [
{
"description": "Settings data to update",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/http.settingsData"
}
}
],
"responses": {
"200": {
"description": "Settings updated successfully"
},
"400": {
"description": "Bad request - failed to decode body",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"500": {
"description": "Internal server error",
"schema": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
}
}
}
},
"/api/share": {
@@ -1532,7 +1485,7 @@
"parameters": [
{
"type": "string",
"description": "a list of files in the following format 'source::filename' and separated by '||' with additional items in the list. (required)",
"description": "a list of files in the following format 'filename' and separated by '||' with additional items in the list. (required)",
"name": "files",
"in": "query",
"required": true
@@ -1773,9 +1726,6 @@
"settings.Frontend": {
"type": "object",
"properties": {
"color": {
"type": "string"
},
"disableDefaultLinks": {
"type": "boolean"
},
@@ -1788,9 +1738,6 @@
"$ref": "#/definitions/settings.ExternalLink"
}
},
"files": {
"type": "string"
},
"name": {
"type": "string"
}
@@ -1820,9 +1767,6 @@
"lockPassword": {
"type": "boolean"
},
"perm": {
"$ref": "#/definitions/users.Permissions"
},
"permissions": {
"$ref": "#/definitions/users.Permissions"
},
+2 -40
View File
@@ -117,8 +117,6 @@ definitions:
type: object
settings.Frontend:
properties:
color:
type: string
disableDefaultLinks:
type: boolean
disableUsedPercentage:
@@ -127,8 +125,6 @@ definitions:
items:
$ref: '#/definitions/settings.ExternalLink'
type: array
files:
type: string
name:
type: string
type: object
@@ -148,8 +144,6 @@ definitions:
type: string
lockPassword:
type: boolean
perm:
$ref: '#/definitions/users.Permissions'
permissions:
$ref: '#/definitions/users.Permissions'
quickDownload:
@@ -902,38 +896,6 @@ paths:
summary: Get system settings
tags:
- Settings
put:
consumes:
- application/json
description: Updates the system configuration settings for signup, user directories,
rules, frontend.
parameters:
- description: Settings data to update
in: body
name: body
required: true
schema:
$ref: '#/definitions/http.settingsData'
produces:
- application/json
responses:
"200":
description: Settings updated successfully
"400":
description: Bad request - failed to decode body
schema:
additionalProperties:
type: string
type: object
"500":
description: Internal server error
schema:
additionalProperties:
type: string
type: object
summary: Update system settings
tags:
- Settings
/api/share:
get:
consumes:
@@ -1315,8 +1277,8 @@ paths:
description: Returns the raw content of a file, multiple files, or a directory.
Supports downloading files as archives in various formats.
parameters:
- description: a list of files in the following format 'source::filename' and
separated by '||' with additional items in the list. (required)
- description: a list of files in the following format 'filename' and separated
by '||' with additional items in the list. (required)
in: query
name: files
required: true
+28 -29
View File
@@ -1,8 +1,8 @@
import { fetchURL, adjustedData } from './utils'
import { getApiPath, extractSourceFromPath } from '@/utils/url.js'
import { getApiPath, extractSourceFromPath,removePrefix } from '@/utils/url.js'
import { state } from '@/store'
import { notify } from '@/notify'
import { externalUrl } from '@/utils/constants'
import { externalUrl,baseURL } from '@/utils/constants'
// Notify if errors occur
export async function fetchFiles(url, content = false) {
@@ -64,34 +64,32 @@ export function download(format, files) {
if (format !== 'zip') {
format = 'tar.gz'
}
try {
let fileargs = ''
if (files.length === 1) {
const result = extractSourceFromPath(decodeURI(files[0]))
fileargs = result.source + '::' + result.path + '||'
} else {
for (let file of files) {
const result = extractSourceFromPath(decodeURI(file))
fileargs += result.source + '::' + result.path + '||'
}
}
fileargs = fileargs.slice(0, -2) // remove trailing "||"
const apiPath = getApiPath('api/raw', {
files: encodeURIComponent(fileargs),
algo: format
})
const url = window.origin + apiPath
// Create a temporary <a> element to trigger the download
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '') // Ensures it triggers a download
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // Clean up
} catch (err) {
notify.showError(err.message || 'Error downloading files')
let fileargs = ''
if (files.length === 1) {
const result = extractSourceFromPath(decodeURI(files[0]))
fileargs = result.source + '::' + result.path + '||'
} else {
for (let file of files) {
const result = extractSourceFromPath(decodeURI(file))
fileargs += result.source + '::' + result.path + '||'
}
}
fileargs = fileargs.slice(0, -2) // remove trailing "||"
const apiPath = getApiPath('api/raw', {
files: encodeURIComponent(fileargs),
algo: format
})
const url = window.origin + apiPath
// Create a temporary <a> element to trigger the download
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '') // Ensures it triggers a download
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // Clean up
}
export async function post(url, content = '', overwrite = false, onupload) {
@@ -212,7 +210,8 @@ export function getDownloadURL(source, path, inline, useExternal) {
}
const apiPath = getApiPath('api/raw', params)
if (externalUrl && useExternal) {
return externalUrl + apiPath
return externalUrl + removePrefix(apiPath, baseURL)
}
return window.origin + apiPath
} catch (err) {
+23 -25
View File
@@ -1,5 +1,5 @@
import { adjustedData } from "./utils";
import { getApiPath, removePrefix, extractSourceFromPath } from "@/utils/url.js";
import { getApiPath } from "@/utils/url.js";
import { notify } from "@/notify";
// Fetch public share data
@@ -23,32 +23,30 @@ export async function fetchPub(path, hash, password = "") {
}
// Download files with given parameters
export function download(share, ...files) {
try {
let fileargs = ''
if (files.length === 1) {
const result = extractSourceFromPath(decodeURI(files[0]))
fileargs = result.path + '||'
} else {
for (let file of files) {
const result = extractSourceFromPath(decodeURI(file))
fileargs += result.path + '||'
}
export function download(format, files) {
console.log("Downloading files:",format, files)
let fileargs = ''
if (files.length === 1) {
fileargs = decodeURI(files[0]) + '||'
} else {
for (let file of files) {
fileargs += decodeURI(file) + '||'
}
fileargs = fileargs.slice(0, -2); // remove trailing "||"
const params = {
"path": removePrefix(share.path, "share"),
"files": fileargs,
"hash": share.hash,
"token": share.token,
"inline": share.inline,
};
const apiPath = getApiPath("api/public/dl", params);
window.open(window.origin+apiPath)
} catch (err) {
notify.showError(err.message || "Error downloading files");
throw err;
}
fileargs = fileargs.slice(0, -2) // remove trailing "||"
const apiPath = getApiPath('api/public/dl', {
files: encodeURIComponent(fileargs),
hash: format.hash,
})
const url = window.origin + apiPath
// Create a temporary <a> element to trigger the download
const link = document.createElement('a')
link.href = url
link.setAttribute('download', '') // Ensures it triggers a download
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // Clean up
}
// Get the public user data
+4 -3
View File
@@ -1,7 +1,7 @@
import { fetchURL, fetchJSON, adjustedData } from "./utils";
import { notify } from "@/notify";
import { getApiPath } from "@/utils/url.js";
import { externalUrl } from "@/utils/constants";
import { getApiPath,removePrefix } from "@/utils/url.js";
import { externalUrl,baseURL } from "@/utils/constants";
export async function list() {
const apiPath = getApiPath("api/shares");
@@ -43,7 +43,8 @@ export async function create(path, source, password = "", expires = "", unit = "
export function getShareURL(share) {
if (externalUrl) {
return externalUrl+getApiPath(`share/${share.hash}`);
const apiPath = getApiPath(`share/${share.hash}`)
return externalUrl + removePrefix(apiPath, baseURL);
}
return window.origin+getApiPath(`share/${share.hash}`);
}
+12 -3
View File
@@ -403,8 +403,17 @@ export default {
this.submit();
},
getRelative(path) {
// double encode # to fix issue with # in path
// replace all # with %23
path = path.replace(/#/g, "%23");
path = path.slice(1); // remove leading slash
const fullpath = "/files/" + this.selectedSource + "/" + encodeURIComponent(path);
let fullpath = path;
if (state.sources.count === 1) {
fullpath = "/files/" + encodeURIComponent(path);
} else {
fullpath = "/files/" + this.selectedSource + "/" + encodeURIComponent(path);
}
return fullpath;
},
getIcon(mimetype) {
@@ -430,9 +439,9 @@ export default {
return "";
}
parts.pop();
parts = parts.join("/") + "/";
parts = parts.join("/");
if (isDir) {
parts = "/" + parts; // fix weird rtl thing
parts = "/" + parts + "/"; // fix weird rtl thing
}
return parts;
@@ -196,6 +196,7 @@ export default {
methods: {
downloadFile(event) {
event.preventDefault();
event.stopPropagation();
mutations.resetSelected();
mutations.addSelected(this.index);
downloadFiles();
@@ -129,9 +129,7 @@ import { notify } from "@/notify";
import { state, getters, mutations } from "@/store";
import { shareApi, publicApi } from "@/api";
import { fromNow } from "@/utils/moment";
import { extractSourceFromPath } from "@/utils/url";
import Clipboard from "clipboard";
import { baseURL } from "@/utils/constants";
export default {
name: "share",
@@ -1,30 +0,0 @@
<template>
<div>
<h3>{{ $t("settings.userCommands") }}</h3>
<p class="small">
{{ $t("settings.userCommandsHelp") }} <i>git svn hg</i>.
</p>
<input class="input input--block" type="text" v-model.trim="raw" />
</div>
</template>
<script>
export default {
name: "permissions",
props: ["commands"],
computed: {
raw: {
get() {
return this.commands.join(" ");
},
set(value) {
if (value !== "") {
this.$emit("update:commands", value.split(" "));
} else {
this.$emit("update:commands", []);
}
},
},
},
};
</script>
@@ -22,7 +22,6 @@
</template>
<script>
import { enableExec } from "@/utils/constants";
export default {
name: "permissions",
props: ["perm"],
@@ -41,7 +40,6 @@ export default {
this.perm.admin = value;
},
},
isExecEnabled: () => enableExec,
},
};
</script>
@@ -101,15 +101,12 @@
</p>
<permissions :perm="localUser.perm" />
<commands v-if="isExecEnabled" v-model:commands="user.commands" />
</div>
</template>
<script>
import Languages from "./Languages.vue";
import Permissions from "./Permissions.vue";
import Commands from "./Commands.vue";
import { enableExec } from "@/utils/constants";
import { state } from "@/store";
import { settingsApi } from "@/api";
@@ -118,7 +115,6 @@ export default {
components: {
Permissions,
Languages,
Commands,
},
data() {
return {
@@ -193,9 +189,6 @@ export default {
displayHomeDirectoryCheckbox() {
return this.isNew && this.createUserDir;
},
isExecEnabled() {
return enableExec; // Removed arrow function
},
},
methods: {
setUpdatePassword() {
+8 -2
View File
@@ -63,7 +63,7 @@
>
<i class="material-icons source-icon">folder</i>
<span>{{ name }}</span>
<div>
<div v-if="!disableUsedPercentage">
<progress-bar
:val="info.usedPercentage"
text-position="inside"
@@ -83,7 +83,13 @@
<script>
import * as auth from "@/utils/auth";
import { signup, disableExternal, noAuth, loginPage } from "@/utils/constants";
import {
signup,
disableExternal,
noAuth,
loginPage,
disableUsedPercentage,
} from "@/utils/constants";
import ProgressBar from "@/components/ProgressBar.vue";
import { state, getters, mutations } from "@/store"; // Import your custom store
+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 && !state.user.username){
if (state != null && state.user != null && !state.user.username) {
await validateLogin();
}
-2
View File
@@ -15,7 +15,6 @@ const noAuth = window.FileBrowser.NoAuth;
const loginPage = window.FileBrowser.LoginPage;
const enableThumbs = window.FileBrowser.EnableThumbs;
const resizePreview = window.FileBrowser.ResizePreview;
const enableExec = window.FileBrowser.EnableExec;
const externalUrl = window.FileBrowser.ExternalUrl
const onlyOfficeUrl = window.FileBrowser.OnlyOfficeUrl
const serverHasMultipleSources = window.FileBrowser.SourceCount > 1;
@@ -47,7 +46,6 @@ export {
loginPage,
enableThumbs,
resizePreview,
enableExec,
origin,
darkMode,
settings,
+16 -10
View File
@@ -22,13 +22,12 @@ export default function download() {
format: files.length ? "zip" : null,
};
// Perform download without opening a new window
publicApi.download(share, ...files);
startDownload(share, files, true);
return;
}
if (getters.isSingleFileSelected()) {
// Single file download without new window
filesApi.download(null, [getters.selectedDownloadUrl()]);
startDownload(null, [getters.selectedDownloadUrl()]);
return;
}
@@ -45,13 +44,20 @@ export default function download() {
} else {
files.push(state.route.path);
}
try {
// Initiate download without new window
filesApi.download(format, files);
notify.showSuccess("Download started");
} catch (e) {
notify.showError("Error downloading", e);
}
startDownload(format, files);
},
});
}
async function startDownload(config, files, isPublic) {
try {
if (isPublic) {
publicApi.download(config, files);
} else {
filesApi.download(config, files);
}
notify.showSuccess("Downloading...");
} catch (e) {
notify.showError(`Error downloading: ${e}`);
}
}
-1
View File
@@ -66,7 +66,6 @@ export function removePrefix(path, prefix = "") {
if (!path.startsWith('/')) {
path = '/' + path;
}
return path;
}
+2
View File
@@ -5,6 +5,7 @@ describe('testurl', () => {
it('url prefix', () => {
let tests = [
{input: "/files/share/hash", trimArg:"/files/",expected: "/share/hash",},
{input: "/files/files", trimArg: "/files/",expected: "/files",},
{input: "/files/share/something/", trimArg: "files", expected:"/share/something/"},
{input: "test/iscool/", trimArg: "test",expected:"/iscool/"},
@@ -25,6 +26,7 @@ describe('getapipath', () => {
it('url prefix', () => {
let tests = [
{input: "/share/to/thing", expected: "/files/share/to/thing",},
{input: "share/hash", expected: "/files/share/hash",},
]
for (let test of tests) {
expect(getApiPath(test.input)).toEqual(test.expected);
-4
View File
@@ -42,7 +42,6 @@ import Sidebar from "@/components/sidebar/Sidebar.vue";
import ContextMenu from "@/components/ContextMenu.vue";
import Notifications from "@/components/Notifications.vue";
import { enableExec } from "@/utils/constants";
import { state, getters, mutations } from "@/store";
export default {
@@ -107,9 +106,6 @@ export default {
isDarkMode() {
return getters.isDarkMode();
},
isExecEnabled() {
return enableExec;
},
currentView() {
return getters.currentView();
},
+1 -1
View File
@@ -326,7 +326,7 @@ export default {
token: this.token,
format: format,
};
publicApi.download(share, ...files);
publicApi.download(share, files);
},
});
},
+1
View File
@@ -87,6 +87,7 @@ import ExtendedImage from "@/components/files/ExtendedImage.vue";
import { state, getters, mutations } from "@/store";
import { getFileExtension } from "@/utils/files";
import { convertToVTT } from "@/utils/subtitles";
import { getTypeInfo } from "@/utils/mimetype";
export default {
name: "preview",
+2 -3
View File
@@ -6,7 +6,8 @@
</div>
<div class="card-content">
Currently there are no global config options, You can edit the configuration yaml to adjust system settings.
Currently there are no global config options, You can edit the configuration yaml to
adjust system settings.
</div>
<div class="card-action">
@@ -19,7 +20,6 @@
import { notify } from "@/notify";
import { state, mutations, getters } from "@/store";
import { settingsApi } from "@/api";
import { enableExec } from "@/utils/constants";
import Errors from "@/views/Errors.vue";
export default {
@@ -41,7 +41,6 @@ export default {
user() {
return state.user;
},
isExecEnabled: () => enableExec,
},
async created() {
mutations.setLoading("settings", true);
@@ -32,3 +32,72 @@ test("root share path is valid", async ({ page, checkForErrors, context }) => {
await expect(page.locator('div[aria-label="share-path"]')).toHaveText('Path: /');
checkForErrors();
});
test("share file works", async ({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
const shareHashFile = await page.evaluate(() => localStorage.getItem('shareHashFile'));
if (shareHashFile == "") {
throw new Error("Share hash not found in localStorage");
}
await page.goto("/share/" + shareHashFile);
await expect(page).toHaveTitle("Graham's Filebrowser - Share - 1file1.txt");
await expect(page.locator('a[aria-label="Home"]')).toHaveAttribute("href", `/share/${shareHashFile}/`);
checkForErrors();
});
test("share download single file", 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 + "/testdata/");
await expect(page).toHaveTitle("Graham's Filebrowser - Share - testdata");
await page.locator('a[aria-label="gray-sample.jpg"]').click({ button: "right" });
await page.locator('button[aria-label="Download"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Download"]').click();
const popup = page.locator('#popup-notification-content');
await popup.waitFor({ state: 'visible' });
await expect(popup).toHaveText("Downloading...");
checkForErrors();
});
test("share download multiple files", 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 + "/testdata/");
await expect(page).toHaveTitle("Graham's Filebrowser - Share - testdata");
await page.locator('a[aria-label="gray-sample.jpg"]').click({ button: "right" });
await page.locator('button[aria-label="Select multiple"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Select multiple"]').click();
const popup = page.locator('#popup-notification-content');
await popup.waitFor({ state: 'visible' });
await expect(popup).toHaveText("Multiple Selection Enabled");
await page.locator('a[aria-label="20130612_142406.jpg"]').click();
await page.locator('a[aria-label="IMG_2578.JPG"]').click();
await page.locator('a[aria-label="gray-sample.jpg"]').click({ button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('3 selected');
await page.locator('button[aria-label="Download"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Download"]').click();
const popup2 = page.locator('#popup-notification-content');
await popup2.waitFor({ state: 'visible' });
await expect(popup2).toHaveText("Downloading...");
checkForErrors();
});
+23 -3
View File
@@ -10,15 +10,15 @@ async function globalSetup() {
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 });
await page.waitForURL("**/files/", { timeout: 500 });
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 });
await page.waitForURL("**/files/playwright-files", { timeout: 500 });
// Create a share
// Create a share of folder
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' });
@@ -36,6 +36,26 @@ async function globalSetup() {
localStorage.setItem('shareHash', hash);
}, shareHash);
await page.goto("http://127.0.0.1/files/playwright-files", { timeout: 500 });
// Create a share of file
await page.locator('a[aria-label="1file1.txt"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="1file1.txt"]').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: /1file1.txt');
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 shareHashFile = await page.locator("#share .card-content table tbody tr:not(:has(th)) td").first().textContent();
if (!shareHashFile) {
throw new Error("Failed to retrieve shareHash");
}
// Store shareHash in localStorage
await page.evaluate((hash) => {
localStorage.setItem('shareHashFile', hash);
}, shareHashFile);
await context.storageState({ path: "./loginAuth.json" });
await browser.close();
}
+53
View File
@@ -0,0 +1,53 @@
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/files", { timeout: 500 });
// Create a share of folder
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 page.goto("http://127.0.0.1/files", { timeout: 500 });
// Create a share of file
await page.locator('a[aria-label="1file1.txt"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="1file1.txt"]').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: /1file1.txt');
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 shareHashFile = await page.locator("#share .card-content table tbody tr:not(:has(th)) td").first().textContent();
if (!shareHashFile) {
throw new Error("Failed to retrieve shareHash");
}
// Store shareHash in localStorage
await page.evaluate((hash) => {
localStorage.setItem('shareHashFile', hash);
}, shareHashFile);
await context.storageState({ path: "./noauth.json" });
await browser.close();
}
export default globalSetup;
@@ -0,0 +1,120 @@
import { test, expect } from "../test-setup";
test("info from listing", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('a[aria-label="file.tar.gz"]').waitFor({ state: 'visible' });
await page.locator('a[aria-label="file.tar.gz"]').click( { button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('1 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, 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({ 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="Info"]').click();
await expect(page.locator('.break-word')).toHaveText('Display Name: file.tar.gz');
checkForErrors();
})
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' });
await page.locator('a[aria-label="copyme.txt"]').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="Copy file"]').click();
await expect(page.locator('div[aria-label="filelist-path"]')).toHaveText('Path: /');
await expect(page.locator('li[aria-selected="true"]')).toHaveCount(0);
await page.locator('li[aria-label="myfolder"]').click();
await expect(page.locator('li[aria-selected="true"]')).toHaveCount(1);
await page.locator('button[aria-label="Copy"]').click();
const popup = page.locator('#popup-notification-content');
await popup.waitFor({ state: 'visible' });
await expect(popup).toHaveText("Successfully copied file/folder, redirecting...");
await page.waitForURL('**/myfolder/');
await expect(page).toHaveTitle("Graham's Filebrowser - Files - myfolder");
// verify exists and copy again
await page.locator('a[aria-label="copyme.txt"]').waitFor({ state: 'visible' });
// create new directory
// Ensure #listingView is visible
await page.locator('#listingView').click({ button: "right" });
await page.locator('button[aria-label="New folder"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="New folder"]').click();
await page.locator('input[aria-label="New Folder Name"]').waitFor({ state: 'visible' });
await page.locator('input[aria-label="New Folder Name"]').fill('newfolder');
await page.locator('button[aria-label="Create"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - newfolder");
await page.goBack();
await expect(page).toHaveTitle("Graham's Filebrowser - Files - myfolder");
await page.locator('a[aria-label="copyme.txt"]').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="Copy file"]').click();
await expect(page.locator('div[aria-label="filelist-path"]')).toHaveText('Path: /myfolder/');
await page.locator('li[aria-label="newfolder"]').click();
await page.locator('button[aria-label="Copy"]').click();
const popup2 = page.locator('#popup-notification-content');
await popup2.waitFor({ state: 'visible' });
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, 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' });
await page.locator('a[aria-label="deleteme.txt"]').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="Delete"]').click();
await expect( page.locator('.card-content')).toHaveText('Are you sure you want to delete this file/folder?/deleteme.txt');
await expect(page.locator('div[aria-label="delete-path"]')).toHaveText('/deleteme.txt');
await page.locator('button[aria-label="Confirm-Delete"]').click();
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, checkForErrors, context }) => {
await page.goto("/files/files/folder%23hash/");
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"]').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="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();
})
@@ -0,0 +1,60 @@
import { test, expect } from "../test-setup";
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, checkForErrors, context }) => {
await page.goto("/files/");
await expect(page.locator('a[aria-label="Home"]')).toHaveAttribute("href", "/files/");
// 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(0);
await page.goto("/files/myfolder");
await page.waitForSelector('.breadcrumbs');
spanChildrenCount = await page.locator('.breadcrumbs > span').count();
expect(spanChildrenCount).toBe(1);
let breadCrumbLink = page.locator('span[aria-label="breadcrumb-link-myfolder"] a')
await expect(breadCrumbLink).toHaveText("myfolder");
await page.goto("/files/myfolder/testdata");
await page.waitForSelector('.breadcrumbs');
spanChildrenCount = await page.locator('.breadcrumbs > span').count();
expect(spanChildrenCount).toBe(2);
breadCrumbLink = page.locator('span[aria-label="breadcrumb-link-testdata"] a')
await expect(breadCrumbLink).toHaveText("testdata");
// TODO: fix this test.. router issue for /files path
//await page.goto("/files/files");
//await page.waitForSelector('.breadcrumbs');
//spanChildrenCount = await page.locator('.breadcrumbs > span').count();
//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, 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('for testing');
await expect(page.locator('#result-list')).toHaveCount(1);
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,102 @@
import { test, expect } from "../test-setup";
test("breadcrumbs navigation checks", async ({ page, checkForErrors, context }) => {
await page.goto("/files/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("/files/share/" + shareHash);
await expect(page).toHaveTitle("Graham's Filebrowser - Share - myfolder");
await expect(page.locator('a[aria-label="Home"]')).toHaveAttribute("href", `/files/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/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();
});
test("share file works", async ({ page, checkForErrors, context }) => {
await page.goto("/files/files/");
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
const shareHashFile = await page.evaluate(() => localStorage.getItem('shareHashFile'));
if (shareHashFile == "") {
throw new Error("Share hash not found in localStorage");
}
await page.goto("/files/share/" + shareHashFile);
await expect(page).toHaveTitle("Graham's Filebrowser - Share - 1file1.txt");
await expect(page.locator('a[aria-label="Home"]')).toHaveAttribute("href", `/files/share/${shareHashFile}/`);
checkForErrors();
});
test("share download single file", async ({ page, checkForErrors, context }) => {
await page.goto("/files/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("/files/share/" + shareHash + "/testdata/");
await expect(page).toHaveTitle("Graham's Filebrowser - Share - testdata");
await page.locator('a[aria-label="gray-sample.jpg"]').click({ button: "right" });
await page.locator('button[aria-label="Download"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Download"]').click();
const popup = page.locator('#popup-notification-content');
await popup.waitFor({ state: 'visible' });
await expect(popup).toHaveText("Downloading...");
checkForErrors();
});
test("share download multiple files", async ({ page, checkForErrors, context }) => {
await page.goto("/files/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("/files/share/" + shareHash + "/testdata/");
await expect(page).toHaveTitle("Graham's Filebrowser - Share - testdata");
await page.locator('a[aria-label="gray-sample.jpg"]').click({ button: "right" });
await page.locator('button[aria-label="Select multiple"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Select multiple"]').click();
const popup = page.locator('#popup-notification-content');
await popup.waitFor({ state: 'visible' });
await expect(popup).toHaveText("Multiple Selection Enabled");
await page.locator('a[aria-label="20130612_142406.jpg"]').click();
await page.locator('a[aria-label="IMG_2578.JPG"]').click();
await page.locator('a[aria-label="gray-sample.jpg"]').click({ button: "right" });
await page.locator('.selected-count-header').waitFor({ state: 'visible' });
await expect(page.locator('.selected-count-header')).toHaveText('3 selected');
await page.locator('button[aria-label="Download"]').waitFor({ state: 'visible' });
await page.locator('button[aria-label="Download"]').click();
const popup2 = page.locator('#popup-notification-content');
await popup2.waitFor({ state: 'visible' });
await expect(popup2).toHaveText("Downloading...");
checkForErrors();
});
@@ -0,0 +1,45 @@
import { test, expect } from "../test-setup";
test("sidebar links", async({ page, checkForErrors, context }) => {
await page.goto("/files/");
// Verify the page title
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
// Locate the credits container
const credits = page.locator('.credits'); // Fix the selector to match the HTML structure
// Assert that the <h3> contains the text 'FileBrowser Quantum'
await expect(credits.locator("h4")).toHaveText("Graham's Filebrowser");
// Assert that the <a> contains the text 'A playwright test'
await expect(credits.locator("span").locator("a")).toHaveText('A playwright test');
// 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, checkForErrors, context }) => {
await page.goto("/files/");
const originalPrimaryColor = await page.evaluate(() => {
return getComputedStyle(document.documentElement).getPropertyValue('--primaryColor').trim();
});
await expect(originalPrimaryColor).toBe('#2196f3');
// Verify the page title
await expect(page).toHaveTitle("Graham's Filebrowser - Files - playwright-files");
await page.locator('i[aria-label="settings"]').click();
await expect(page).toHaveTitle("Graham's Filebrowser - Settings");
await page.locator('button', { hasText: 'violet' }).click();
const popup = page.locator('#popup-notification-content');
await popup.waitFor({ state: 'visible' });
await expect(popup).toHaveText('Settings updated!');
const newPrimaryColor = await page.evaluate(() => {
return getComputedStyle(document.documentElement).getPropertyValue('--primaryColor').trim();
});
await expect(newPrimaryColor).toBe('#9b59b6');
// Check for console errors
checkForErrors();
});
+26 -7
View File
@@ -1,6 +1,6 @@
import { test as base, expect, Page } from "@playwright/test";
export const test = base.extend<{ checkForErrors: () => void }>({
export const test = base.extend<{ checkForErrors: (expectedConsoleErrors?: number, expectedApiErrors?: number) => void }>({
checkForErrors: async ({ page }, use) => {
const { checkForErrors } = setupErrorTracking(page);
await use(checkForErrors);
@@ -9,19 +9,38 @@ export const test = base.extend<{ checkForErrors: () => void }>({
// Error tracking function
export function setupErrorTracking(page: Page) {
const errors: string[] = [];
const consoleErrors: string[] = [];
const failedResponses: { url: string; status: number }[] = [];
// Track console errors
page.on("console", (message) => {
if (message.type() === "error") {
errors.push(message.text());
consoleErrors.push(message.text());
}
});
// Track failed API calls
page.on("response", (response) => {
if (!response.ok()) {
failedResponses.push({
url: response.url(),
status: response.status(),
});
}
});
return {
checkForErrors: () => {
if (errors.length > 0) {
console.error("Console Errors Detected:", errors);
checkForErrors: (expectedConsoleErrors = 0, expectedApiErrors = 0) => {
if (consoleErrors.length !== expectedConsoleErrors) {
console.error("Unexpected Console Errors:", consoleErrors);
}
expect(errors).toHaveLength(0);
if (failedResponses.length !== expectedApiErrors) {
console.error("Unexpected Failed API Calls:", failedResponses);
}
expect(consoleErrors).toHaveLength(expectedConsoleErrors);
expect(failedResponses).toHaveLength(expectedApiErrors);
},
};
}
+13 -17
View File
@@ -1,12 +1,13 @@
SHELL := /bin/bash
.SILENT:
setup:
echo "creating ./backend/test_config.yaml for local testing..." && \
echo "creating ./backend/test_config.yaml for local testing..."
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..." && \
go install github.com/swaggo/swag/cmd/swag@latest && \
echo "installing npm requirements for frontend..." && \
echo "installing swagger needed to generate backend api docs..."
go install github.com/swaggo/swag/cmd/swag@latest
echo "installing npm requirements for frontend..."
cd frontend && npm i
update:
@@ -29,8 +30,8 @@ run: build-frontend
--ldflags="-w -s -X 'github.com/gtsteffaniak/filebrowser/backend/version.CommitSHA=testingCommit' -X 'github.com/gtsteffaniak/filebrowser/backend/version.Version=testing'" . -c test_config.yaml
build-frontend:
cd backend/http && rm -rf dist && rm -rf embed/* && ln -s ../../frontend/dist && \
cd ../../frontend && npm run build
cd backend/http && rm -rf dist && rm -rf embed/* && ln -s ../../frontend/dist
cd frontend && npm run build
lint-frontend:
cd frontend && npm run lint
@@ -51,15 +52,10 @@ test-frontend:
cd frontend && npm run test
test-playwright: build-frontend
cd backend && GOOS=linux go build -o filebrowser . && cd .. && \
docker build -t filebrowser-playwright-tests -f _docker/Dockerfile.playwright-general . && \
docker run --rm --name filebrowser-playwright-tests filebrowser-playwright-tests && \
docker build -t filebrowser-playwright-tests -f _docker/Dockerfile.playwright-noauth . && \
docker run --rm --name filebrowser-playwright-tests filebrowser-playwright-tests && \
docker build -t filebrowser-playwright-tests -f _docker/Dockerfile.playwright-proxy . && \
cd backend && GOOS=linux go build -o filebrowser .
docker build -t filebrowser-playwright-tests -f _docker/Dockerfile.playwright-general .
docker run --rm --name filebrowser-playwright-tests filebrowser-playwright-tests
# Run on a windows machine!
release-windows:
cd frontend && npm run build-windows && \
cd ../backend && go build --ldflags="-w -s -X github.com/gtsteffaniak/filebrowser/backend/version.CommitSHA=' -X 'github.com/gtsteffaniak/filebrowser/backend/version.Version='" .
docker build -t filebrowser-playwright-tests -f _docker/Dockerfile.playwright-noauth .
docker run --rm --name filebrowser-playwright-tests filebrowser-playwright-tests
docker build -t filebrowser-playwright-tests -f _docker/Dockerfile.playwright-proxy .
docker run --rm --name filebrowser-playwright-tests filebrowser-playwright-tests