Compare commits

...
24 Commits
Author SHA1 Message Date
Graham Steffaniak 0ffc1c1ae6 Disable bool validation (#528) 2025-04-12 12:03:53 -05:00
Graham Steffaniak d3e49b2803 Update validations v0.6.8 (#525) 2025-04-12 10:18:50 -05:00
Graham Steffaniak 5be5646c7c updated fields 2025-04-11 19:06:50 -05:00
Graham Steffaniak 19e6a836a5 updated workflow 2025-04-11 19:01:14 -05:00
Graham Steffaniak a435fa20bf updated workflow 2025-04-11 18:58:09 -05:00
Graham Steffaniak 3ddedea6ef updated workflow 2025-04-11 18:53:14 -05:00
Graham Steffaniak 3d612c61a4 fix typo for deselect (#524) 2025-04-11 18:32:48 -05:00
Graham Steffaniak 938527301b fixes scope reset issue on restart (#522) 2025-04-10 15:51:49 -05:00
Graham Steffaniak 79a0b3def9 add validation to 0.6.8 release (#521) 2025-04-10 10:53:17 -05:00
Graham Steffaniak 9757cd58b6 updated workflow 2025-04-09 14:05:43 -05:00
Graham Steffaniak 31304ef9a6 updated with ghcr pushing (#513) 2025-04-09 10:54:16 -05:00
Aaron Ky-Riesenbach cf4abf63c6 Allow secrets to be read from environment variables (#511) 2025-04-08 18:16:52 -05:00
Graham Steffaniak a83f39d41f Beta/v0.6.7 (#507) 2025-04-08 10:05:52 -05:00
Graham Steffaniak 2de5dbaf68 updated docker directory perms (#500) 2025-04-06 16:57:14 -05:00
Graham Steffaniak db77552bd8 bump v0.6.6 release with share fix for file (#489) 2025-04-04 09:37:31 -05:00
Graham Steffaniak 2c26b6fc45 Beta/v0.6.6 (#485) 2025-04-03 18:29:31 -05:00
Graham Steffaniak 948add54fc Beta/v0.6.5 (#469) 2025-04-01 12:00:07 -05:00
Graham Steffaniak f56fa85fa4 fixed issues for 0.6.4 (#463) (#464) 2025-03-28 18:48:45 -05:00
Graham Steffaniak 23db04bacb Update README.md (#462) 2025-03-28 09:44:30 -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
Graham Steffaniak 8460ddbc13 Beta/v0.6.1 (#428) 2025-03-11 17:48:30 -05:00
123 changed files with 3302 additions and 1640 deletions

No files matched your search

+1
View File
@@ -1,4 +1,5 @@
backend/**.db
backend/tmp
backend/vendor/**
frontend/dist/**
frontend/node_modules/**
-39
View File
@@ -30,42 +30,3 @@ jobs:
context: .
file: ./_docker/Dockerfile.playwright-general
push: false
push_latest_to_registry:
needs: [ test_playwright ]
name: Push latest
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Find latest beta tag
run: |
echo "LATEST_TAG=$(git describe --tags $(git rev-list --tags="*-beta*" --max-count=1))" >> $GITHUB_ENV
echo "latest tag is $LATEST_TAG"
- name: Set up QEMU
uses: docker/setup-qemu-action@v3.0.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.0.0
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: gtstef/filebrowser
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
build-args: |
VERSION=${{ env.LATEST_TAG }}
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
platforms: linux/amd64,linux/arm64,linux/arm/v7
file: ./_docker/Dockerfile
push: true
tags: 'gtstef/filebrowser:latest'
labels: ${{ steps.meta.outputs.labels }}
+1 -1
View File
@@ -9,7 +9,7 @@ on:
jobs:
test_playwright:
name: Test Playwright - regular
name: Test Playwright - general
runs-on: ubuntu-latest
steps:
- name: Checkout
+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'."
+20 -10
View File
@@ -24,20 +24,30 @@ jobs:
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{github.actor}}
password: ${{ secrets.PAT }}
- name: Extract metadata (tags, labels) for Docker and GHCR
id: meta
uses: docker/metadata-action@v5
with:
images: gtstef/filebrowser
- name: modify version names
images: |
gtstef/filebrowser
ghcr.io/gtsteffaniak/filebrowser
- name: Modify version names
id: modify-json
run: |
JSON="${{ steps.meta.outputs.tags }}"
# Use jq to remove 'v' from the version field
JSON=$(echo "$JSON" | sed 's/filebrowser:dev-v/filebrowser:/')
JSON=$(echo "$JSON" | sed -E 's/(filebrowser:[0-9]+\.[0-9]+\.[0-9]+)/\1-dev/g')
JSON="$JSON,gtstef/filebrowser:dev"
echo "cleaned_tag=$JSON" >> $GITHUB_OUTPUT
TAGS="${{ steps.meta.outputs.tags }}"
# Apply modifications to both docker.io and ghcr.io tags
CLEANED_TAGS=$(echo "$TAGS" | sed 's/filebrowser:dev-v/filebrowser:/g' | sed -E 's/(filebrowser:[0-9]+\.[0-9]+\.[0-9]+)/\1-dev/g')
# Add dev tag to both registries
CLEANED_TAGS="$CLEANED_TAGS,gtstef/filebrowser:dev,ghcr.io/gtsteffaniak/filebrowser:dev"
echo "cleaned_tag<<EOF" >> $GITHUB_OUTPUT
echo "$CLEANED_TAGS" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Build and push
uses: docker/build-push-action@v6
with:
@@ -49,4 +59,4 @@ jobs:
file: ./_docker/Dockerfile
push: true
tags: ${{ steps.modify-json.outputs.cleaned_tag }}
labels: ${{ steps.meta.outputs.labels }}
labels: ${{ steps.meta.outputs.labels }}
+30 -11
View File
@@ -45,26 +45,45 @@ jobs:
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{github.actor}}
password: ${{ secrets.PAT }}
- name: Extract metadata (tags, labels) for Docker and GHCR
id: meta
uses: docker/metadata-action@v5
with:
images: gtstef/filebrowser
images: |
gtstef/filebrowser
ghcr.io/gtsteffaniak/filebrowser
- name: Modify tags (strip 'v' and add 'beta'/'stable' if needed)
id: modify-json
run: |
JSON='${{ steps.meta.outputs.json }}' # Assuming the JSON output is stored in steps.meta.outputs.json
# Process the JSON array using jq
JSON='${{ steps.meta.outputs.json }}'
MODIFIED_JSON=$(echo "$JSON" | jq '
.tags |= map(sub(":v"; ":")) |
if any(.tags[]; test("beta")) then .tags += ["gtstef/filebrowser:beta"] else . end |
if any(.tags[]; test("stable")) then .tags += ["gtstef/filebrowser:stable"] else . end
.tags |= map(sub(":v"; ":")) |
if any(.tags[]; test("beta")) then
.tags += [
"gtstef/filebrowser:beta",
"ghcr.io/gtsteffaniak/filebrowser:beta",
"gtstef/filebrowser:latest",
"ghcr.io/gtsteffaniak/filebrowser:latest"
]
else . end |
if any(.tags[]; test("stable")) then
.tags += [
"gtstef/filebrowser:stable",
"ghcr.io/gtsteffaniak/filebrowser:stable",
"gtstef/filebrowser:latest",
"ghcr.io/gtsteffaniak/filebrowser:latest"
]
else . end
')
# Convert JSON to a comma-separated string for Docker tags
TAGS_CSV=$(echo "$MODIFIED_JSON" | jq -r '.tags | join(",")')
echo "$TAGS_CSV" > modified_tags.txt # Save for debugging
echo "$TAGS_CSV" > modified_tags.txt # Optional debug output
echo "cleaned_tag=$TAGS_CSV" >> $GITHUB_OUTPUT
- name: Build and push
uses: docker/build-push-action@v6
with:
@@ -76,4 +95,4 @@ jobs:
file: ./_docker/Dockerfile
push: true
tags: ${{ steps.modify-json.outputs.cleaned_tag }}
labels: ${{ steps.meta.outputs.labels }}
labels: ${{ steps.meta.outputs.labels }}
+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
+105
View File
@@ -2,6 +2,111 @@
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.8-beta
**New Features**
- environment variables are available for certain secrets.
- see wiki https://github.com/gtsteffaniak/filebrowser/wiki/Environment-Variables
- thanks @aaronkyriesenbach https://github.com/gtsteffaniak/filebrowser/pull/511
**Notes**:
- config validation (see https://github.com/gtsteffaniak/filebrowser/wiki/Full-Config-Example)
- fails when config file contains unknown fields (helps spot typos)
- some light value validation on certain fields
- removed recaptcha -- was disabled and not used before.
- moved `recaptcha` and `signup` configs to `auth.methods.password`
- also pushes to ghcr `ghcr.io/gtsteffaniak/filebrowser` https://github.com/gtsteffaniak/filebrowser/issues/470
**BugFixes**:
- fix scope reset on restart https://github.com/gtsteffaniak/filebrowser/issues/515
- Clicking empty space to deselect https://github.com/gtsteffaniak/filebrowser/issues/492
## 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**:
- 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**:
- download size information is added, including when downloding multiple files in zip/tar.gz. The browser will see the XMB of X GB and will show browser native progress.
**BugFixes**:
- fixed onlyoffice bug https://github.com/gtsteffaniak/filebrowser/issues/418
- fixed breadcrumbs bug https://github.com/gtsteffaniak/filebrowser/issues/419
- fixed search context bug https://github.com/gtsteffaniak/filebrowser/issues/417
- fixed sessionID for search
## v0.6.0-beta
> [!WARNING]
+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.)
+2 -1
View File
@@ -20,10 +20,11 @@ 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/
USER root
# exposing default port for auto discovery.
+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 -2
View File
@@ -1,12 +1,11 @@
server:
port: 80
baseURL: "/"
baseURL: "/files/"
logging:
- levels: "info|error|debug"
sources:
- path: "../frontend/tests/playwright-files"
auth:
signup: false
methods:
noauth: true
frontend:
@@ -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-proxy",
globalSetup: "./tests-playwright/noauth-setup",
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. */
@@ -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('/')`. */
+6 -3
View File
@@ -5,6 +5,10 @@ server:
- levels: "info|error|debug"
sources:
- path: "../frontend/tests/playwright-files"
config:
defaultEnabled: true
createUserDir: true
frontend:
name: "Graham's Filebrowser"
disableDefaultLinks: true
@@ -12,8 +16,8 @@ frontend:
- text: "A playwright test"
url: "https://playwright.dev/"
title: "Playwright"
auth:
signup: false
methods:
proxy:
enabled: true
@@ -23,10 +27,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",
+1 -4
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"
@@ -164,12 +163,10 @@ 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)
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
}
+18 -158
View File
@@ -2,15 +2,14 @@ package cmd
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"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"
@@ -19,62 +18,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 +48,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 +86,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 {
@@ -246,6 +102,7 @@ Release Info : https://github.com/gtsteffaniak/filebrowser/releases/tag/%v
case <-done:
logger.Info("Server stopped unexpectedly. Shutting down...")
}
fileutils.ClearCacheDir()
<-shutdownComplete // Ensure we don't exit prematurely
// Wait for the server to stop
@@ -266,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
+83
View File
@@ -0,0 +1,83 @@
package cmd
import (
"fmt"
"github.com/gtsteffaniak/filebrowser/backend/fileutils"
"github.com/gtsteffaniak/filebrowser/backend/logger"
"github.com/gtsteffaniak/filebrowser/backend/settings"
"github.com/gtsteffaniak/filebrowser/backend/users"
)
var createBackup = []bool{}
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 {
updateUser := false
if user.Username == "publicUser" {
settings.ApplyUserDefaults(user)
updateUser = true
}
if updateUserScopes(user) {
updateUser = true
}
if updateUser {
if len(createBackup) == 1 {
logger.Warning("Incompatible user settings detected, creating backup of database before converting.")
err = fileutils.CopyFile(settings.Config.Server.Database, fmt.Sprintf("%s.bak", settings.Config.Server.Database))
if err != nil {
logger.Fatal(fmt.Sprintf("Unable to create automatic backup of database due to error: %v", err))
}
}
err := store.Users.Save(user, false)
if err != nil {
logger.Error(fmt.Sprintf("could not update user: %v", err))
}
}
}
}
func updateUserScopes(user *users.User) bool {
updateUser := false
newScopes := []users.SourceScope{}
for _, source := range settings.Config.Server.SourceMap {
scopePath, err := settings.GetScopeFromSourcePath(user.Scopes, source.Path)
// apply default scope if it doesn't exist
if !user.Perm.Admin && scopePath == "" {
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
}
}
// maintain backwards compatibility, update user scope from scopes
if len(newScopes) == 0 {
newScopes = []users.SourceScope{
{
Scope: settings.Config.Server.DefaultSource.Config.DefaultUserScope,
Name: settings.Config.Server.DefaultSource.Path, // backend name is path
},
}
updateUser = true
}
user.Scopes = newScopes
return updateUser
}
+2 -3
View File
@@ -1,14 +1,13 @@
server:
port: 80
baseURL: "/"
logging:
- levels: "info|debug|warning|error"
sources:
- path: "/srv"
auth:
signup: false
userDefaults:
darkMode: true
disableSettings: false
scope: "."
singleClick: false
permissions:
admin: false
+51 -76
View File
@@ -17,7 +17,6 @@ import (
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
@@ -29,11 +28,6 @@ import (
"github.com/gtsteffaniak/filebrowser/backend/utils"
)
var (
pathMutexes = make(map[string]*sync.Mutex)
pathMutexesMu sync.Mutex // Mutex to protect the pathMutexes map
)
type ItemInfo struct {
Name string `json:"name"` // name of the file
Size int64 `json:"size"` // length in bytes for regular files
@@ -88,12 +82,6 @@ func FileInfoFaster(opts FileOptions) (ExtendedFileInfo, error) {
if index == nil {
return response, fmt.Errorf("could not get index: %v ", opts.Source)
}
opts.Path = index.makeIndexPath(opts.Path)
// Lock access for the specific path
pathMutex := getMutex(opts.Path)
pathMutex.Lock()
defer pathMutex.Unlock()
realPath, isDir, err := index.GetRealPath(opts.Path)
if err != nil {
return response, err
@@ -118,7 +106,6 @@ func FileInfoFaster(opts FileOptions) (ExtendedFileInfo, error) {
// }
// return info, nil
//}
err = index.RefreshFileInfo(opts)
if err != nil {
return response, err
@@ -127,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
@@ -187,7 +179,7 @@ func GetChecksum(fullPath, algo string) (map[string]string, error) {
return subs, nil
}
func DeleteFiles(source, absPath string, dirPath string) error {
func DeleteFiles(source, absPath string, absDirPath string) error {
err := os.RemoveAll(absPath)
if err != nil {
return err
@@ -196,7 +188,7 @@ func DeleteFiles(source, absPath string, dirPath string) error {
if index == nil {
return fmt.Errorf("could not get index: %v ", source)
}
refreshConfig := FileOptions{Path: dirPath, IsDir: true}
refreshConfig := FileOptions{Path: index.MakeIndexPath(absDirPath), IsDir: true}
err = index.RefreshFileInfo(refreshConfig)
if err != nil {
return err
@@ -204,68 +196,66 @@ func DeleteFiles(source, absPath string, dirPath string) error {
return nil
}
func MoveResource(sourceIndex, dstIndex, realsrc, realdst string, isSrcDir bool) error {
func MoveResource(sourceIndex, destIndex, realsrc, realdst string) error {
err := fileutils.MoveFile(realsrc, realdst)
if err != nil {
return err
}
index := GetIndex(sourceIndex)
if index == nil {
idxSrc := GetIndex(sourceIndex)
if idxSrc == nil {
return fmt.Errorf("could not get index: %v ", sourceIndex)
}
idxDst := GetIndex(destIndex)
if idxDst == nil {
return fmt.Errorf("could not get index: %v ", sourceIndex)
}
refreshSourceDir := idxSrc.MakeIndexPath(filepath.Dir(realsrc))
refreshDestDir := idxDst.MakeIndexPath(filepath.Dir(realdst))
// refresh info for source and dest
err = index.RefreshFileInfo(FileOptions{
Path: realsrc,
IsDir: isSrcDir,
err = idxSrc.RefreshFileInfo(FileOptions{
Path: refreshSourceDir,
IsDir: true,
})
if err != nil {
return fmt.Errorf("could not refresh index for source: %v", err)
}
refreshConfig := FileOptions{Path: realdst, IsDir: true}
if !isSrcDir {
refreshConfig.Path = filepath.Dir(realdst)
if refreshSourceDir == refreshDestDir {
return nil
}
index = GetIndex(dstIndex)
if index == nil {
return fmt.Errorf("could not get index: %v ", dstIndex)
}
err = index.RefreshFileInfo(refreshConfig)
refreshConfig := FileOptions{Path: refreshDestDir, IsDir: true}
err = idxDst.RefreshFileInfo(refreshConfig)
if err != nil {
return fmt.Errorf("could not refresh index for dest: %v", err)
}
return nil
}
func CopyResource(sourceIndex, dstIndex, realsrc, realdst string, isSrcDir bool) error {
func CopyResource(sourceIndex, destIndex, realsrc, realdst string) error {
err := fileutils.CopyFile(realsrc, realdst)
if err != nil {
return err
}
idxSrc := GetIndex(sourceIndex)
if idxSrc == nil {
return fmt.Errorf("could not get index: %v ", sourceIndex)
}
idxDst := GetIndex(destIndex)
if idxDst == nil {
return fmt.Errorf("could not get index: %v ", sourceIndex)
}
refreshSourceDir := idxSrc.MakeIndexPath(filepath.Dir(realsrc))
refreshDestDir := idxDst.MakeIndexPath(filepath.Dir(realdst))
index := GetIndex(sourceIndex)
if index == nil {
return fmt.Errorf("could not get index: %v ", sourceIndex)
}
refreshConfig := FileOptions{Path: refreshSourceDir, IsDir: true}
// refresh info for source and dest
err = index.RefreshFileInfo(FileOptions{
Path: realsrc,
IsDir: isSrcDir,
})
err = index.RefreshFileInfo(refreshConfig)
if err != nil {
return fmt.Errorf("could not refresh index for source: %v", err)
}
refreshConfig := FileOptions{Path: realdst, IsDir: true}
if !isSrcDir {
refreshConfig.Path = filepath.Dir(realdst)
}
index = GetIndex(dstIndex)
if index == nil {
return fmt.Errorf("could not get index: %v ", dstIndex)
}
refreshConfig = FileOptions{Path: realdst, IsDir: true}
if !isSrcDir {
refreshConfig.Path = filepath.Dir(realdst)
}
refreshConfig.Path = refreshDestDir
err = index.RefreshFileInfo(refreshConfig)
if err != nil {
return errors.ErrEmptyKey
@@ -317,37 +307,35 @@ func WriteFile(opts FileOptions, in io.Reader) error {
if err != nil {
return err
}
opts.Path = parentDir
opts.Path = idx.MakeIndexPath(parentDir)
opts.IsDir = true
return idx.RefreshFileInfo(opts)
}
// resolveSymlinks resolves symlinks in the given path
func resolveSymlinks(path string) (string, bool, error) {
for {
// Get the file info using os.Lstat to handle symlinks
const maxSymlinks = 25
for i := 0; i < maxSymlinks; i++ {
info, err := os.Lstat(path)
if err != nil {
return path, false, fmt.Errorf("could not stat path: %s, %v", path, err)
}
// Check if the path is a symlink
if info.Mode()&os.ModeSymlink != 0 {
// Read the symlink target
target, err := os.Readlink(path)
if err != nil {
return path, false, fmt.Errorf("could not read symlink: %s, %v", path, err)
}
// Resolve the symlink's target relative to its directory
// This ensures the resolved path is absolute and correctly calculated
path = filepath.Join(filepath.Dir(path), target)
} else {
// Not a symlink, so return the resolved path and whether it's a directory
isDir := info.IsDir()
return path, isDir, nil
path = filepath.Clean(filepath.Join(filepath.Dir(path), target))
if !filepath.IsAbs(path) {
path, err = filepath.Abs(path)
if err != nil {
return path, false, fmt.Errorf("could not resolve absolute path: %s, %v", path, err)
}
}
continue
}
return path, info.IsDir(), nil
}
return path, false, fmt.Errorf("too many symlink resolutions for path: %s", path)
}
// addContent reads and sets content based on the file type.
@@ -435,19 +423,6 @@ func IsSymlink(mode os.FileMode) bool {
return mode&os.ModeSymlink != 0
}
func getMutex(path string) *sync.Mutex {
// Lock access to pathMutexes map
pathMutexesMu.Lock()
defer pathMutexesMu.Unlock()
// Create a mutex for the path if it doesn't exist
if pathMutexes[path] == nil {
pathMutexes[path] = &sync.Mutex{}
}
return pathMutexes[path]
}
func Exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
+4 -7
View File
@@ -184,14 +184,13 @@ 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
}
func (idx *Index) makeIndexPath(subPath string) string {
// input should be non-index path.
func (idx *Index) MakeIndexPath(subPath string) string {
if strings.HasPrefix(subPath, "./") {
subPath = strings.TrimPrefix(subPath, ".")
}
@@ -200,8 +199,8 @@ func (idx *Index) makeIndexPath(subPath string) string {
}
// clean path
subPath = strings.TrimSuffix(subPath, "/")
// remove index prefix
adjustedPath := strings.TrimPrefix(subPath, idx.Source.Path)
// remove index prefix
adjustedPath = strings.ReplaceAll(adjustedPath, "\\", "/")
// remove trailing slash
adjustedPath = strings.TrimSuffix(adjustedPath, "/")
@@ -251,10 +250,8 @@ func (idx *Index) RefreshFileInfo(opts FileOptions) error {
IsDir: opts.IsDir,
}
if !refreshOptions.IsDir {
refreshOptions.Path = idx.makeIndexPath(filepath.Dir(refreshOptions.Path))
refreshOptions.Path = idx.MakeIndexPath(filepath.Dir(refreshOptions.Path))
refreshOptions.IsDir = true
} else {
refreshOptions.Path = idx.makeIndexPath(refreshOptions.Path)
}
err := idx.indexDirectory(refreshOptions.Path, false, false)
if err != nil {
+8 -7
View File
@@ -94,14 +94,15 @@ func TestMakeIndexPath(t *testing.T) {
{"Trailing slash removed", "/test/", "/test"},
{"Subpath without root prefix", "/other/test", "/other/test"},
{"Complex nested paths", "/nested/path", "/nested/path"},
// TODO fix {"has source name as start", "/srv.tar.gz", "/srv.tar.gz"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
idx := &Index{Source: settings.Source{Path: "/"}}
result := idx.makeIndexPath(tt.subPath)
idx := &Index{Source: settings.Source{Path: "/srv"}}
result := idx.MakeIndexPath(tt.subPath)
if result != tt.expected {
t.Errorf("makeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected)
t.Errorf("MakeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected)
}
})
}
@@ -120,9 +121,9 @@ func TestMakeIndexPath(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
idx := &Index{Source: settings.Source{Path: "C:\\Users"}}
result := idx.makeIndexPath(tt.subPath)
result := idx.MakeIndexPath(tt.subPath)
if result != tt.expected {
t.Errorf("makeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected)
t.Errorf("MakeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected)
}
})
}
@@ -141,9 +142,9 @@ func TestMakeIndexPathRoot(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
idx := &Index{Source: settings.Source{Path: "/rootpath", Name: "default"}}
result := idx.makeIndexPath(tt.subPath)
result := idx.MakeIndexPath(tt.subPath)
if result != tt.expected {
t.Errorf("makeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected)
t.Errorf("MakeIndexPath(%q)\ngot %q\nwant %q", tt.name, result, tt.expected)
}
})
}
+8 -7
View File
@@ -22,8 +22,11 @@ type SearchResult struct {
}
func (idx *Index) Search(search string, scope string, sourceSession string) []SearchResult {
scope = strings.TrimSuffix(scope, "/")
if search == "" {
scope = ""
}
// Remove slashes
scope = idx.makeIndexPath(scope)
runningHash := utils.InsecureRandomIdentifier(4)
sessionInProgress.Store(sourceSession, runningHash) // Store the value in the sync.Map
searchOptions := ParseSearch(search)
@@ -46,7 +49,6 @@ func (idx *Index) Search(search string, scope string, sourceSession string) []Se
}
idx.mu.Lock()
for _, dirName := range directories {
scopedPath := strings.TrimPrefix(strings.TrimPrefix(dirName, scope), "/") + "/"
idx.mu.Unlock()
dir, found := idx.GetReducedMetadata(dirName, true)
idx.mu.Lock()
@@ -63,15 +65,14 @@ func (idx *Index) Search(search string, scope string, sourceSession string) []Se
}
matches := reducedDir.containsSearchTerm(searchTerm, searchOptions)
if matches {
results[scopedPath] = SearchResult{Path: scopedPath, Type: "directory", Size: dir.Size}
results[dirName+"/"] = SearchResult{Path: dirName + "/", Type: "directory", Size: dir.Size}
count++
}
// search files first
for _, item := range dir.Files {
fullPath := dirName + "/" + item.Name
scopedPath := strings.TrimPrefix(strings.TrimPrefix(fullPath, scope), "/")
if item.Type == "directory" {
scopedPath += "/"
if dirName == "/" {
fullPath = dirName + item.Name
}
value, found := sessionInProgress.Load(sourceSession)
if !found || value != runningHash {
@@ -83,7 +84,7 @@ func (idx *Index) Search(search string, scope string, sourceSession string) []Se
}
matches := item.containsSearchTerm(searchTerm, searchOptions)
if matches {
results[scopedPath] = SearchResult{Path: scopedPath, Type: item.Type, Size: item.Size}
results[fullPath] = SearchResult{Path: fullPath, Type: item.Type, Size: item.Size}
count++
}
}
+49 -11
View File
@@ -90,13 +90,19 @@ 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"},
{Name: "video.mp4", Type: "video"},
{Name: "video.MP4", Type: "video"},
}},
"/first Dir": {
Files: []ItemInfo{
{Name: "space jam.zip", Size: 100, Type: "archive"},
},
},
"/new/test/path": {Files: []ItemInfo{{Name: "archive.zip", Type: "archive"}}},
"/firstDir": {
Files: []ItemInfo{
@@ -127,7 +133,7 @@ func TestSearchIndexes(t *testing.T) {
scope: "/new/",
expectedResult: []SearchResult{
{
Path: "test/audio.wav",
Path: "/new/test/audio.wav",
Type: "audio",
Size: 0,
},
@@ -138,12 +144,12 @@ func TestSearchIndexes(t *testing.T) {
scope: "/",
expectedResult: []SearchResult{
{
Path: "test/",
Path: "/test/",
Type: "directory",
Size: 0,
},
{
Path: "new/test/",
Path: "/new/test/",
Type: "directory",
Size: 0,
},
@@ -154,12 +160,12 @@ func TestSearchIndexes(t *testing.T) {
scope: "/",
expectedResult: []SearchResult{
{
Path: "firstDir/archive.zip",
Path: "/firstDir/archive.zip",
Type: "archive",
Size: 100,
},
{
Path: "new/test/path/archive.zip",
Path: "/new/test/path/archive.zip",
Type: "archive",
Size: 0,
},
@@ -170,7 +176,18 @@ func TestSearchIndexes(t *testing.T) {
scope: "/firstDir",
expectedResult: []SearchResult{
{
Path: "archive.zip",
Path: "/firstDir/archive.zip",
Type: "archive",
Size: 100,
},
},
},
{
search: "space jam",
scope: "/first Dir/",
expectedResult: []SearchResult{
{
Path: "/first Dir/space jam.zip",
Type: "archive",
Size: 100,
},
@@ -181,7 +198,7 @@ func TestSearchIndexes(t *testing.T) {
scope: "/",
expectedResult: []SearchResult{
{
Path: "firstDir/thisIsDir/",
Path: "/firstDir/thisIsDir/",
Type: "directory",
Size: 2097152,
},
@@ -192,7 +209,7 @@ func TestSearchIndexes(t *testing.T) {
scope: "/",
expectedResult: []SearchResult{
{
Path: "firstDir/thisIsDir/",
Path: "/firstDir/thisIsDir/",
Type: "directory",
Size: 2097152,
},
@@ -203,17 +220,38 @@ func TestSearchIndexes(t *testing.T) {
scope: "/",
expectedResult: []SearchResult{
{
Path: "new/test/video.MP4",
Path: "/new/test/video.MP4",
Type: "video",
Size: 0,
},
{
Path: "new/test/video.mp4",
Path: "/new/test/video.mp4",
Type: "video",
Size: 0,
},
},
},
{
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 {
+24 -7
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.
@@ -15,13 +16,16 @@ func (idx *Index) UpdateMetadata(info *FileInfo) bool {
return true
}
// GetMetadataInfo retrieves the FileInfo from the specified directory in the index.
// GetMetadataInfo retrieves the FileInfo from the specified file or directory in the index.
func (idx *Index) GetReducedMetadata(target string, isDir bool) (*FileInfo, bool) {
idx.mu.Lock()
defer idx.mu.Unlock()
checkDir := idx.makeIndexPath(target)
checkDir := idx.MakeIndexPath(target)
if !isDir {
checkDir = idx.makeIndexPath(filepath.Dir(target))
checkDir = idx.MakeIndexPath(filepath.Dir(target))
}
if checkDir == "" {
checkDir = "/"
}
dir, exists := idx.Directories[checkDir]
if !exists {
@@ -48,13 +52,16 @@ func (idx *Index) GetReducedMetadata(target string, isDir bool) (*FileInfo, bool
}
// GetMetadataInfo retrieves the FileInfo from the specified directory in the index.
// raw directory info retrieval -- does not work on files, only returns a directory
func (idx *Index) GetMetadataInfo(target string, isDir bool) (*FileInfo, bool) {
idx.mu.RLock()
defer idx.mu.RUnlock()
checkDir := idx.makeIndexPath(target)
checkDir := idx.MakeIndexPath(target)
if !isDir {
checkDir = idx.makeIndexPath(filepath.Dir(target))
checkDir = idx.MakeIndexPath(filepath.Dir(target))
}
if checkDir == "" {
checkDir = "/"
}
dir, exists := idx.Directories[checkDir]
return dir, exists
@@ -72,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 -1
View File
@@ -140,7 +140,7 @@ func TestUpdateFileMetadata(t *testing.T) {
fileInfo, exists := index.GetReducedMetadata("/testpath/testfile.txt", false)
if !exists || fileInfo.Name != "testfile.txt" {
t.Fatalf("expected testfile.txt to be updated in the directory metadata:%v %v", exists, info.Name)
t.Fatalf("expected '%v' to exist in the directory metadata. %v ", info.Name, exists)
}
}
+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
}
+20 -7
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.
@@ -22,17 +23,12 @@ func MoveFile(src, dst string) error {
// fallback
err = CopyFile(src, dst)
if err != nil {
go func() {
err = os.Remove(src)
if err != nil {
logger.Error(fmt.Sprintf("os.Remove failed %v %v ", src, err))
}
}()
logger.Error(fmt.Sprintf("CopyFile failed %v %v %v ", src, dst, err))
return err
}
go func() {
err = os.Remove(src)
err = os.RemoveAll(src)
if err != nil {
logger.Error(fmt.Sprintf("os.Remove failed %v %v ", src, err))
}
@@ -180,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))
}
}
}
+19 -14
View File
@@ -1,24 +1,25 @@
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/go-playground/validator/v10 v10.26.0
github.com/goccy/go-yaml v1.17.1
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.37.0
golang.org/x/image v0.26.0
golang.org/x/sys v0.32.0
)
require (
@@ -26,24 +27,28 @@ require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // 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/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/golang/geo v0.0.0-20250410091149-9ff723126794 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
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.39.0 // indirect
golang.org/x/text v0.24.0 // indirect
golang.org/x/tools v0.32.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+40 -28
View File
@@ -27,6 +27,8 @@ github.com/dsoprea/go-utility/v2 v2.0.0-20221003142440-7a1927d49d9d/go.mod h1:LV
github.com/dsoprea/go-utility/v2 v2.0.0-20221003160719-7bc88537c05e/go.mod h1:VZ7cB0pTjm1ADBWhJUOHESu4ZYy9JN+ZPqjfiW09EPU=
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 h1:DilThiXje0z+3UQ5YjYiSRRzVdtamFpvBQXKwMglWqw=
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349/go.mod h1:4GC5sXji84i/p+irqghpPFZBF8tRN/Q7+700G0/DLe8=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
github.com/go-errors/errors v1.0.2/go.mod h1:psDX2osz5VnTOnFWbDeWwS7yejl+uV3FEWEp4lssFEs=
github.com/go-errors/errors v1.1.1/go.mod h1:psDX2osz5VnTOnFWbDeWwS7yejl+uV3FEWEp4lssFEs=
@@ -36,23 +38,31 @@ 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/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/goccy/go-yaml v1.17.1 h1:LI34wktB2xEE3ONG/2Ar54+/HJVBriAGJ55PHls4YuY=
github.com/goccy/go-yaml v1.17.1/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-20250410091149-9ff723126794 h1:sYWK0P7YCim7xkB7IqMX6k4YtrcqLVSdCZqmMnqhBAI=
github.com/golang/geo v0.0.0-20250410091149-9ff723126794/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 +70,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=
@@ -73,6 +83,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@@ -104,14 +116,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.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
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.26.0 h1:4XjIFEZWQmCZi6Wv8BoxsDhRU3RVnLX04dToTDAEPlY=
golang.org/x/image v0.26.0/go.mod h1:lcxbMFAovzpnJxzXS3nyL83K27tmqtKzIJpctK8YO5c=
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 +135,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.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
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.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
golang.org/x/sync v0.13.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 +155,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.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.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 +165,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.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
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.32.0 h1:Q7N1vhpkQv7ybVzLFtTjvQya2ewbwNDZzUgfXGqtMWU=
golang.org/x/tools v0.32.0/go.mod h1:ZxrU41P/wAbZD8EDa6dDCa6XfpkhJ7HFMjHJXfBDu8s=
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=
+2 -5
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"
@@ -125,7 +124,7 @@ type signupBody struct {
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /api/signup [post]
func signupHandler(w http.ResponseWriter, r *http.Request) {
if !settings.Config.Auth.Signup {
if !settings.Config.Auth.Methods.PasswordAuth.Signup {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
@@ -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)
@@ -225,7 +222,7 @@ func makeSignedTokenAPI(user *users.User, name string, duration time.Duration, p
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
tokenString, err := token.SignedString(config.Auth.Key)
tokenString, err := token.SignedString([]byte(config.Auth.Key))
if err != nil {
return claim, err
}
+18 -10
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,10 @@ 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, "/")
if path == "" || path == "/" {
data.path = link.Path
}
// Get file information with options
file, err := FileInfoFasterFunc(files.FileOptions{
Path: data.path,
@@ -66,12 +69,11 @@ func withHashFileHelper(fn handleFunc) handleFunc {
})
file.Token = link.Token
if err != nil {
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
data.raw = file
// Call the next handler with the data
return fn(w, r, data)
}
@@ -111,9 +113,16 @@ 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
}
err = storage.CreateUser(users.User{
Username: proxyUser,
NonAdminEditable: users.NonAdminEditable{
Password: hashpass, // hashed password that can't actually be used
},
}, false)
if err != nil {
return http.StatusInternalServerError, err
}
@@ -129,14 +138,13 @@ func withUserHelper(fn handleFunc) handleFunc {
return fn(w, r, data)
}
keyFunc := func(token *jwt.Token) (interface{}, error) {
return config.Auth.Key, nil
return []byte(config.Auth.Key), nil
}
tokenString, err := extractToken(r)
if err != nil {
return http.StatusUnauthorized, err
}
data.token = tokenString
var tk users.AuthToken
token, err := jwt.ParseWithClaims(tokenString, &tk, keyFunc)
if err != nil {
@@ -206,7 +214,7 @@ func wrapHandler(fn handleFunc) http.HandlerFunc {
// Write the JSON error response
if _, writeErr := w.Write(errorBytes); writeErr != nil {
logger.Error(fmt.Sprintf("Error writing error response: %v", writeErr))
logger.Debug(fmt.Sprintf("Error writing error response: %v", writeErr))
}
return
}
+1 -1
View File
@@ -209,7 +209,7 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
handler := withHashFileHelper(publicShareHandler)
if err := store.Settings.Save(&settings.Settings{
Auth: settings.Auth{
Key: []byte("key"),
Key: "key",
},
}); err != nil {
t.Fatalf("failed to save settings: %v", err)
+13 -15
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 (
@@ -37,24 +37,21 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
if settings.Config.Integrations.OnlyOffice.Url == "" {
return http.StatusInternalServerError, errors.New("only-office integration must be configured in settings")
}
if !d.user.Perm.Modify {
return http.StatusForbidden, nil
}
encodedUrl := r.URL.Query().Get("url")
source := r.URL.Query().Get("source")
if source == "" {
source = settings.Config.Server.DefaultSource.Name
}
// Decode the URL-encoded path
url, err := url.QueryUnescape(encodedUrl)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
// get path from url
pathParts := strings.Split(url, "/api/raw?files=/")
path := pathParts[len(pathParts)-1]
pathParts := strings.Split(url, "/api/raw?files=")
sourceFile := pathParts[len(pathParts)-1]
sourceSplit := strings.Split(sourceFile, "::")
if len(sourceSplit) != 2 {
return http.StatusBadRequest, fmt.Errorf("invalid url path %v", url)
}
source := sourceSplit[0]
path := sourceSplit[1]
urlFirst := pathParts[0]
if settings.Config.Server.InternalUrl != "" {
urlFirst = strings.TrimSuffix(settings.Config.Server.InternalUrl, "/")
@@ -66,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,
@@ -87,7 +84,7 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
if d.user.DarkMode {
theme = "dark"
}
callbackURL := fmt.Sprintf("%v/api/onlyoffice/callback?path=%v&auth=%v", urlFirst, path, d.token)
clientConfig := map[string]interface{}{
"document": map[string]interface{}{
"fileType": fileType,
@@ -101,7 +98,7 @@ func onlyofficeClientConfigGetHandler(w http.ResponseWriter, r *http.Request, d
},
},
"editorConfig": map[string]interface{}{
"callbackUrl": fmt.Sprintf("%v/api/onlyoffice/callback?path=%v&auth=%v", urlFirst, path, d.token),
"callbackUrl": callbackURL,
"user": map[string]interface{}{
"id": strconv.FormatUint(uint64(d.user.ID), 10),
"name": d.user.Username,
@@ -201,6 +198,7 @@ func getOnlyOfficeId(source, path string) (string, error) {
}
return "", fmt.Errorf("document key not found")
}
func deleteOfficeId(source, path string) {
idx := files.GetIndex(source)
if idx == nil {
+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,
+20 -12
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"
@@ -29,22 +30,29 @@ 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)
f, 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
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")
}
return rawFilesHandler(w, r, d, fileList)
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) {
+139 -43
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))
@@ -43,11 +44,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 +51,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)
}
@@ -68,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)
@@ -148,7 +145,7 @@ func addSingleFile(realPath, archivePath string, zipWriter *zip.Writer, tarWrite
}
defer file.Close()
info, err := os.Stat(realPath)
info, err := file.Stat()
if err != nil {
return err
}
@@ -158,7 +155,6 @@ func addSingleFile(realPath, archivePath string, zipWriter *zip.Writer, tarWrite
if err != nil {
return err
}
// Ensure correct relative path
header.Name = filepath.ToSlash(archivePath)
if err = tarWriter.WriteHeader(header); err != nil {
return err
@@ -193,10 +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 {
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 {
@@ -206,29 +205,50 @@ 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)
if err2 != nil {
return http.StatusInternalServerError, err
return http.StatusInternalServerError, err2
}
defer fd.Close()
// Get file information
fileInfo, err3 := fd.Stat()
if err3 != nil {
return http.StatusInternalServerError, err
// Get file size
fileInfo, err2 := fd.Stat()
if err2 != nil {
return http.StatusInternalServerError, err2
}
// Set headers and serve the file
// Set headers
setContentDisposition(w, r, fileName)
w.Header().Set("Cache-Control", "private")
w.Header().Set("X-Content-Type-Options", "nosniff")
// Serve the content
http.ServeContent(w, r, fileName, fileInfo.ModTime(), fd)
return 0, nil
w.Header().Set("Content-Length", fmt.Sprintf("%d", fileInfo.Size()))
sizeInMB := estimatedSize / 1024 / 1024
// if larger than 500 megabytes, log it
if sizeInMB > 500 {
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)
if err2 != nil {
return http.StatusInternalServerError, err2
}
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
switch algo {
@@ -239,35 +259,107 @@ func rawFilesHandler(w http.ResponseWriter, r *http.Request, d *requestContext,
default:
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"
}
if len(fileList) == 1 && isDir {
baseDirName = filepath.Base(realPath)
}
downloadFileName := url.PathEscape(baseDirName + extension)
w.Header().Set("Content-Disposition", "attachment; filename*=utf-8''"+downloadFileName)
// Create the archive and stream it directly to the response
fileName = url.PathEscape(baseDirName + extension)
archiveData := filepath.Join(config.Server.CacheDir, utils.InsecureRandomIdentifier(10))
if extension == ".zip" {
err = createZip(w, d, fileList...)
archiveData = archiveData + ".zip"
err = createZip(d, archiveData, fileList...)
} else {
err = createTarGz(w, d, fileList...)
archiveData = archiveData + ".tar.gz"
err = createTarGz(d, archiveData, fileList...)
}
if err != nil {
return http.StatusInternalServerError, err
}
// 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))
}
// 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
}
return 0, nil
}
func createZip(w io.Writer, d *requestContext, filenames ...string) error {
zipWriter := zip.NewWriter(w)
func computeArchiveSize(fileList []string, d *requestContext) (int64, error) {
var estimatedSize int64
for _, fname := range fileList {
splitFile := strings.Split(fname, "::")
if len(splitFile) != 2 {
return http.StatusBadRequest, fmt.Errorf("invalid file in files request: %v", fileList[0])
}
source := splitFile[0]
path := splitFile[1]
idx := files.GetIndex(source)
if idx == nil {
return 0, fmt.Errorf("source %s is not available", source)
}
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 {
return http.StatusInternalServerError, err
}
info, ok := idx.GetReducedMetadata(path, isDir)
if !ok {
return 0, fmt.Errorf("failed to get metadata info for %s", path)
}
estimatedSize += info.Size
}
return estimatedSize, nil
}
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 {
@@ -275,18 +367,22 @@ func createZip(w io.Writer, d *requestContext, filenames ...string) error {
return err
}
}
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()
// 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 {
+13 -17
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,
@@ -114,13 +116,12 @@ func resourceDeleteHandler(w http.ResponseWriter, r *http.Request, d *requestCon
if err != nil {
return http.StatusForbidden, err
}
fileOpts := files.FileOptions{
Path: filepath.Join(userscope, path),
fileInfo, err := files.FileInfoFaster(files.FileOptions{
Path: utils.JoinPathAsUnix(userscope, path),
Source: source,
Modify: d.user.Perm.Modify,
Expand: false,
}
fileInfo, err := files.FileInfoFaster(fileOpts)
})
if err != nil {
return errToStatus(err), err
}
@@ -173,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,
@@ -247,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,
@@ -277,7 +278,6 @@ func resourcePutHandler(w http.ResponseWriter, r *http.Request, d *requestContex
func resourcePatchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
// TODO source := r.URL.Query().Get("source")
action := r.URL.Query().Get("action")
if !d.user.Perm.Modify {
return http.StatusForbidden, fmt.Errorf("user is not allowed to create or modify")
}
@@ -384,17 +384,13 @@ func delThumbs(ctx context.Context, fileCache FileCache, file files.ExtendedFile
func patchAction(ctx context.Context, action, src, dst string, d *requestContext, fileCache FileCache, isSrcDir bool, srcIndex, destIndex string) error {
switch action {
case "copy":
if !d.user.Perm.Modify {
return errors.ErrPermissionDenied
}
err := files.CopyResource(srcIndex, destIndex, src, dst, isSrcDir)
err := files.CopyResource(srcIndex, destIndex, src, dst)
return err
case "rename", "move":
if !d.user.Perm.Modify {
return errors.ErrPermissionDenied
}
idx := files.GetIndex(srcIndex)
srcPath := idx.MakeIndexPath(src)
fileInfo, err := files.FileInfoFaster(files.FileOptions{
Path: src,
Path: srcPath,
Source: srcIndex,
IsDir: isSrcDir,
Modify: d.user.Perm.Modify,
@@ -408,7 +404,7 @@ func patchAction(ctx context.Context, action, src, dst string, d *requestContext
// delete thumbnails
delThumbs(ctx, fileCache, fileInfo)
return files.MoveResource(srcIndex, destIndex, src, dst, isSrcDir)
return files.MoveResource(srcIndex, destIndex, src, dst)
default:
return fmt.Errorf("unsupported action %s: %w", action, errors.ErrInvalidRequestParams)
}
+1 -2
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))
@@ -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))
+10 -6
View File
@@ -3,6 +3,8 @@ package http
import (
"fmt"
"net/http"
"net/url"
"path/filepath"
"strings"
"github.com/gtsteffaniak/filebrowser/backend/files"
@@ -59,8 +61,12 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
if source == "" {
source = config.Server.DefaultSource.Name
}
searchScope := strings.TrimPrefix(r.URL.Query().Get("scope"), ".")
searchScope = strings.TrimPrefix(searchScope, "/")
scope := r.URL.Query().Get("scope")
unencodedScope, err := url.QueryUnescape(scope)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("invalid path encoding: %v", err)
}
searchScope := strings.TrimPrefix(unencodedScope, ".")
// Retrieve the User-Agent and X-Auth headers from the request
sessionId := r.Header.Get("SessionId")
index := files.GetIndex(source)
@@ -71,11 +77,9 @@ func searchHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (i
if err != nil {
return http.StatusForbidden, err
}
userScope := strings.TrimPrefix(userscope, ".")
combinedScope := strings.TrimPrefix(userScope+"/"+searchScope, "/")
combinedPath := index.MakeIndexPath(filepath.Join(userscope, searchScope))
// Perform the search using the provided query and user scope
response := index.Search(query, combinedScope, sessionId)
response := index.Search(query, combinedPath, sessionId)
// Set the Content-Type header to application/json
w.Header().Set("Content-Type", "application/json")
return renderJSON(w, r, response)
+2 -39
View File
@@ -1,28 +1,17 @@
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.
// @Tags Settings
// @Accept json
// @Produce json
// @Param property query string false "Property to retrieve"
// @Success 200 {object} settingsData "System settings data"
// @Param property query string false "Property to retrieve: `userDefaults`, `frontend`, `auth`, `server`, `sources`"
// @Success 200 {object} settings.Settings "System settings data"
// @Router /api/settings [get]
func settingsGetHandler(w http.ResponseWriter, r *http.Request, d *requestContext) (int, error) {
property := r.URL.Query().Get("property")
@@ -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
}
+7 -6
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
}
@@ -64,7 +63,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 == "" {
@@ -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,
+2 -42
View File
@@ -5,13 +5,9 @@ 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,57 +43,21 @@ 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,
"StaticURL": config.Server.BaseURL + "static",
"Signup": settings.Config.Auth.Signup,
"Signup": settings.Config.Auth.Methods.PasswordAuth.Signup,
"NoAuth": config.Auth.Methods.NoAuth,
"PasswordAuth": config.Auth.Methods.PasswordAuth,
"LoginPage": auther.LoginPage(),
"CSS": false,
"ReCaptcha": false,
"EnableThumbs": config.Server.EnableThumbnails,
"ResizePreview": config.Server.ResizePreview,
"EnableExec": config.Server.EnableExec,
"ReCaptchaHost": config.Auth.Recaptcha.Host,
"ExternalLinks": config.Frontend.ExternalLinks,
"ExternalUrl": strings.TrimSuffix(config.Server.ExternalUrl, "/"),
"OnlyOfficeUrl": settings.Config.Integrations.OnlyOffice.Url,
}
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 {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
auther, ok := raw.(*auth.JSONAuth)
if !ok {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if auther.ReCaptcha != nil {
data["ReCaptcha"] = auther.ReCaptcha.Key != "" && auther.ReCaptcha.Secret != ""
data["ReCaptchaHost"] = auther.ReCaptcha.Host
data["ReCaptchaKey"] = auther.ReCaptcha.Key
}
"SourceCount": len(config.Server.Sources),
}
b, err := json.Marshal(data)
+1 -1
View File
@@ -134,7 +134,7 @@ func Error(msg string) {
if len(loggers) > 0 {
Log(levels.ERROR, msg, true, false, RED)
} else {
log.Println("[ERROR] ", msg)
log.Println("[ERROR]", msg)
}
}
+57 -16
View File
@@ -8,10 +8,10 @@ import (
"slices"
"strings"
"github.com/go-playground/validator/v10"
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"
)
@@ -22,6 +22,7 @@ func Initialize(configFile string) {
if err != nil {
logger.Fatal(err.Error())
}
loadEnvConfig()
setupLogging()
setupAuth()
setupSources()
@@ -61,7 +62,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]
@@ -121,10 +125,6 @@ func setupBaseURL() {
}
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")
}
@@ -175,47 +175,78 @@ func loadConfigWithDefaults(configFile string) error {
if err != nil {
return err
}
yamlData := make([]byte, stat.Size())
_, err = yamlFile.Read(yamlData)
if err != nil && configFile != "config.yaml" {
return fmt.Errorf("could not load specified config file: " + err.Error())
return fmt.Errorf("could not load specified config file: %v", err.Error())
}
if err != nil {
logger.Warning(fmt.Sprintf("Could not load config file '%v', using default settings: %v", configFile, err))
}
err = ValidateConfig(yamlData)
if err != nil {
errmsg := "the provided config file failed validation. "
errmsg += "If you are seeing this on a config that worked previeously, "
errmsg += "this is because v0.6.8 requires a fully validated config to run. "
errmsg += "Please review your config for typos and invalid keys which are no longer supported. "
errmsg += "visit https://github.com/gtsteffaniak/filebrowser/wiki/Full-Config-Example for more information."
logger.Error(errmsg)
}
return err
}
func ValidateConfig(yamlData []byte) error {
var err error
Config = setDefaults()
err = yaml.Unmarshal(yamlData, &Config)
err = yaml.NewDecoder(strings.NewReader(string(yamlData)), yaml.DisallowUnknownField()).Decode(&Config)
if err != nil {
return fmt.Errorf("error unmarshaling YAML data: %v", err)
}
validate := validator.New()
err = validate.Struct(Config)
if err != nil {
return fmt.Errorf("could not validate %v", err)
}
return nil
}
func loadEnvConfig() {
adminPassword, ok := os.LookupEnv("FILEBROWSER_ADMIN_PASSWORD")
if ok {
logger.Info("Using admin password from FILEBROWSER_ADMIN_PASSWORD environment variable")
Config.Auth.AdminPassword = adminPassword
}
officeSecret, ok := os.LookupEnv("FILEBROWSER_ONLYOFFICE_SECRET")
if ok {
logger.Info("Using OnlyOffice secret from FILEBROWSER_ONLYOFFICE_SECRET environment variable")
Config.Integrations.OnlyOffice.Secret = officeSecret
}
}
func setDefaults() Settings {
return Settings{
Server: Server{
EnableThumbnails: true,
ResizePreview: false,
EnableExec: false,
Port: 80,
NumImageProcessors: 4,
BaseURL: "",
Database: "database.db",
SourceMap: map[string]Source{},
NameToSource: map[string]Source{},
MaxArchiveSizeGB: 50,
CacheDir: "tmp",
},
Auth: Auth{
AdminUsername: "admin",
AdminPassword: "admin",
TokenExpirationHours: 2,
Signup: false,
Recaptcha: Recaptcha{
Host: "",
},
Methods: LoginMethods{
PasswordAuth: PasswordAuthConfig{
Enabled: true,
MinLength: 5,
Signup: false,
},
},
},
@@ -223,7 +254,7 @@ func setDefaults() Settings {
Name: "FileBrowser Quantum",
},
UserDefaults: UserDefaults{
DisableOnlyOfficeExt: ".txt .csv .html",
DisableOnlyOfficeExt: ".txt .csv .html .pdf",
StickySidebar: true,
LockPassword: false,
ShowHidden: false,
@@ -232,6 +263,7 @@ func setDefaults() Settings {
ViewMode: "normal",
Locale: "en",
GallerySize: 3,
ThemeColor: "var(--blue)",
Permissions: users.Permissions{
Modify: false,
Share: false,
@@ -248,6 +280,15 @@ func ConvertToBackendScopes(scopes []users.SourceScope) ([]users.SourceScope, er
}
newScopes := []users.SourceScope{}
for _, scope := range scopes {
if scope.Scope == "" {
scope.Scope = "/"
}
if !strings.HasPrefix(scope.Scope, "/") {
scope.Scope = "/" + scope.Scope
}
if !strings.HasSuffix(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 {
@@ -272,7 +313,7 @@ func ConvertToBackendScopes(scopes []users.SourceScope) ([]users.SourceScope, er
}
func ConvertToFrontendScopes(scopes []users.SourceScope) []users.SourceScope {
newScopes := make([]users.SourceScope, 0, len(scopes)) // Preserve original order
newScopes := []users.SourceScope{}
for _, scope := range scopes {
if source, ok := Config.Server.SourceMap[scope.Name]; ok {
// Replace scope.Name with source.Path while keeping the same Scope value
+169
View File
@@ -2,7 +2,10 @@ package settings
import (
"reflect"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestInitialize(t *testing.T) {
@@ -37,3 +40,169 @@ func Test_setDefaults(t *testing.T) {
})
}
}
func TestConfigLoadChanged(t *testing.T) {
defaultConfig := setDefaults()
err := loadConfigWithDefaults("./validConfig.yaml")
if err != nil {
t.Fatalf("error loading config file: %v", err)
}
// Use go-cmp to compare the two structs
if diff := cmp.Diff(defaultConfig, Config); diff == "" {
t.Errorf("No change when there should have been (-want +got):\n%s", diff)
}
}
func TestConfigLoadSpecificValues(t *testing.T) {
defaultConfig := setDefaults()
err := loadConfigWithDefaults("./validConfig.yaml")
if err != nil {
t.Fatalf("error loading config file: %v", err)
}
testCases := []struct {
fieldName string
globalVal interface{}
newVal interface{}
}{
{"Server.Database", Config.Server.Database, defaultConfig.Server.Database},
}
for _, tc := range testCases {
if tc.globalVal == tc.newVal {
t.Errorf("Differences should have been found:\nConfig.%s: %v \nSetConfig: %v \n", tc.fieldName, tc.globalVal, tc.newVal)
}
}
}
func TestInvalidConfig(t *testing.T) {
configFile := "./invalidConfig.yaml"
err := loadConfigWithDefaults(configFile)
if err == nil {
t.Fatalf("expected error loading config file %s, got nil", configFile)
}
}
func TestValidationVarious(t *testing.T) {
testCases := []struct {
name string
configFile []byte
searchErr string
}{
{
name: "valid minimal config",
configFile: []byte(`
server:
port: 8080
sources:
- path: "/data"
auth:
tokenExpirationHours: 24
methods:
password:
enabled: true
signup: false
key: ""
adminUsername: "admin"
adminPassword: "password"
frontend:
name: "MyApp"
userDefaults:
stickySidebar: false
darkMode: false
lockPassword: false
locale: "en"
viewMode: "grid"
gallerySize: 5
singleClick: false
showHidden: false
dateFormat: false
themeColor: "#ffffff"
quickDownload: false
integrations:
office:
url: "https://office.example.com"
secret: "secret-key"
`),
searchErr: "",
},
{
name: "missing required server.sources",
configFile: []byte(`
server:
port: 8080
`),
searchErr: "Field validation for 'Sources' failed on the 'required'",
},
{
name: "missing onlyoffice.secret",
configFile: []byte(`
server:
port: 8080
sources:
- path: "/data"
integrations:
office:
url: "https://office.example.com"
`),
searchErr: "Field validation for 'Secret' failed on the 'required'",
},
{
name: "typo: Server with lowercase s",
configFile: []byte(`
serverx:
port: 8080
sources:
- path: "/data"
`),
searchErr: "unknown field \"serverx\"",
},
{
name: "typo in auth.methods.password",
configFile: []byte(`
server:
port: 8080
sources:
- path: "/data"
auth:
tokenExpirationHours: 24
methods:
passwrd:
enabled: true
signup: false
key: ""
adminUsername: "admin"
adminPassword: "password"
`),
searchErr: "unknown field \"passwrd\"",
},
{
name: "invalid userDefaults",
configFile: []byte(`
server:
sources:
- path: "/data"
userDefaults:
permissions:
download: false
`),
searchErr: "unknown field \"download\"",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err := ValidateConfig(tc.configFile)
if !(err == nil && tc.searchErr == "") {
if err == nil || !strings.Contains(err.Error(), tc.searchErr) {
t.Fatalf("testcase %v could not find error: '%v', got: %v", tc.name, tc.searchErr, err)
}
}
if err != nil && tc.searchErr == "" {
t.Fatalf("testcase %v should not have failed but got: %v", tc.name, err)
}
if err == nil && tc.searchErr != "" {
t.Fatalf("testcase %v should have failed but got: %v", tc.name, err)
}
})
}
}
File renamed without changes.
+13 -6
View File
@@ -44,13 +44,20 @@ 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.Scopes = []users.SourceScope{
{
Scope: Config.Server.DefaultSource.Config.DefaultUserScope,
Name: Config.Server.DefaultSource.Path,
},
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{
{
Scope: Config.Server.DefaultSource.Config.DefaultUserScope,
Name: Config.Server.DefaultSource.Path,
},
}
}
}
-40
View File
@@ -1,40 +0,0 @@
package settings
import (
"testing"
"github.com/google/go-cmp/cmp"
)
func TestConfigLoadChanged(t *testing.T) {
defaultConfig := setDefaults()
err := loadConfigWithDefaults("./testingConfig.yaml")
if err != nil {
t.Fatalf("error loading config file: %v", err)
}
// Use go-cmp to compare the two structs
if diff := cmp.Diff(defaultConfig, Config); diff == "" {
t.Errorf("No change when there should have been (-want +got):\n%s", diff)
}
}
func TestConfigLoadSpecificValues(t *testing.T) {
defaultConfig := setDefaults()
err := loadConfigWithDefaults("./testingConfig.yaml")
if err != nil {
t.Fatalf("error loading config file: %v", err)
}
testCases := []struct {
fieldName string
globalVal interface{}
newVal interface{}
}{
{"Server.Database", Config.Server.Database, defaultConfig.Server.Database},
}
for _, tc := range testCases {
if tc.globalVal == tc.newVal {
t.Errorf("Differences should have been found:\nConfig.%s: %v \nSetConfig: %v \n", tc.fieldName, tc.globalVal, tc.newVal)
}
}
}
-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
}
+33 -46
View File
@@ -13,39 +13,40 @@ 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"`
Key string `json:"key"`
AdminUsername string `json:"adminUsername"`
AdminPassword string `json:"adminPassword"`
AuthMethods []string
AuthMethods []string `json:"-"`
}
type LoginMethods struct {
ProxyAuth ProxyAuthConfig `json:"proxy"`
NoAuth bool `json:"noauth"`
PasswordAuth PasswordAuthConfig `json:"password"`
ProxyAuth ProxyAuthConfig `json:"proxy" validate:"omitempty"`
NoAuth bool `json:"noauth" validate:"omitempty"`
PasswordAuth PasswordAuthConfig `json:"password" validate:"omitempty"`
}
type PasswordAuthConfig struct {
Enabled bool `json:"enabled"`
MinLength int `json:"minLength"`
Enabled bool `json:"enabled"`
MinLength int `json:"minLength" validate:"omitempty,min=5"`
Signup bool `json:"signup" validate:"omitempty"`
Recaptcha Recaptcha `json:"recaptcha" validate:"omitempty"`
}
type Recaptcha struct {
Host string `json:"host" validate:"required"`
Key string `json:"key" validate:"required"`
Secret string `json:"secret" validate:"required"`
}
type ProxyAuthConfig struct {
@@ -54,12 +55,6 @@ type ProxyAuthConfig struct {
Header string `json:"header"`
}
type Recaptcha struct {
Host string `json:"host"`
Key string `json:"key"`
Secret string `json:"secret"`
}
type Server struct {
NumImageProcessors int `json:"numImageProcessors"`
Socket string `json:"socket"`
@@ -67,33 +62,30 @@ type Server struct {
TLSCert string `json:"tlsCert"`
EnableThumbnails bool `json:"enableThumbnails"`
ResizePreview bool `json:"resizePreview"`
EnableExec bool `json:"enableExec"`
AuthHook string `json:"authHook"`
Port int `json:"port"`
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"`
Sources []Source `json:"sources" validate:"required,dive"`
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:"-" validate:"omitempty"` // uses realpath as key
NameToSource map[string]Source `json:"-" validate:"omitempty"` // uses name as key
DefaultSource Source `json:"-" validate:"omitempty"`
}
type Integrations struct {
OnlyOffice OnlyOffice `json:"office"`
OnlyOffice OnlyOffice `json:"office" validate:"omitempty"`
}
// onlyoffice secret is stored in the local.json file
// docker exec <containerID> /var/www/onlyoffice/documentserver/npm/json -f /etc/onlyoffice/documentserver/local.json 'services.CoAuthoring.secret.session.string'
type OnlyOffice struct {
Url string `json:"url"`
Secret string `json:"secret"`
Url string `json:"url" validate:"required"`
Secret string `json:"secret" validate:"required"`
}
type LogConfig struct {
@@ -105,8 +97,8 @@ type LogConfig struct {
}
type Source struct {
Path string `json:"path"` // can be relative, filesystem path
Name string `json:"name"` // display name
Path string `json:"path" validate:"required"` // file system path. (Can be relative)
Name string `json:"name"` // display name
Config SourceConfig `json:"config"`
}
@@ -134,15 +126,13 @@ 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"`
}
type ExternalLink struct {
Text string `json:"text"`
Text string `json:"text" validate:"required"`
Title string `json:"title"`
Url string `json:"url"`
Url string `json:"url" validate:"required"`
}
// UserDefaults is a type that holds the default values
@@ -152,14 +142,11 @@ type UserDefaults struct {
DarkMode bool `json:"darkMode"`
LockPassword bool `json:"lockPassword"`
DisableSettings bool `json:"disableSettings,omitempty"`
Scope string `json:"scope"` // deprecated
Locale string `json:"locale"`
ViewMode string `json:"viewMode"`
GallerySize int `json:"gallerySize"`
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"`
+35
View File
@@ -0,0 +1,35 @@
server:
numImageProcessors: 4
socket: ""
tlsKey: ""
tlsCert: ""
enableThumbnails: false
resizePreview: true
port: 80
baseURL: "/"
database: "mydb.db"
sources:
- path: "."
integrations:
office:
url: "http://localhost:9052"
secret: 6H1H7GzUk2alRkNxAPav0W02g8JS5oUd
auth:
methods:
password:
enabled: true
frontend:
name: ""
disableUsedPercentage: true
userDefaults:
locale: ""
viewMode: ""
darkMode: true
disableSettings: false
singleClick: true
permissions:
admin: true
modify: true
share: true
api: true
dateFormat: false
+40 -26
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 {
@@ -81,36 +88,26 @@ func (st usersBackend) Update(user *users.User, actorIsAdmin bool, fields ...str
return fmt.Errorf("no fields to update")
}
// converting scopes to map of paths intead of names (names can change)
if slices.Contains(fields, "scopes") || slices.Contains(fields, "Scopes") {
adjustedScopes, err := settings.ConvertToBackendScopes(user.Scopes)
if err != nil {
return err
}
user.Scopes = adjustedScopes
}
// Use reflection to access struct fields
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 +133,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 +164,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 +190,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 {
+2 -6
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"
@@ -96,11 +95,9 @@ func quickSetup(store *Storage) {
Scope: "",
})
}
user.DarkMode = true
user.ViewMode = "normal"
user.LockPassword = false
user.Perm = settings.AdminPerms()
logger.Debug(fmt.Sprintf("Creating user as admin: %v %v\n", user.Username, user.Password))
logger.Debug(fmt.Sprintf("Creating user as admin: %v %v", user.Username, user.Password))
err = store.Users.Save(user, true)
utils.CheckErr("store.Users.Save", err)
}
@@ -112,6 +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", userInfo.Username, userInfo.Scopes))
settings.ApplyUserDefaults(newUser)
if asAdmin {
userInfo.Perm = settings.AdminPerms()
@@ -120,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
+291 -89
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"
}
@@ -913,54 +913,7 @@ const docTemplate = `{
"200": {
"description": "System settings data",
"schema": {
"$ref": "#/definitions/http.settingsData"
}
}
}
},
"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"
}
"$ref": "#/definitions/settings.Settings"
}
}
}
@@ -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
@@ -1736,26 +1689,6 @@ const docTemplate = `{
}
}
},
"http.settingsData": {
"type": "object",
"properties": {
"createUserDir": {
"type": "boolean"
},
"defaults": {
"$ref": "#/definitions/settings.UserDefaults"
},
"frontend": {
"$ref": "#/definitions/settings.Frontend"
},
"signup": {
"type": "boolean"
},
"userHomeBasePath": {
"type": "string"
}
}
},
"http.signupBody": {
"type": "object",
"properties": {
@@ -1767,8 +1700,38 @@ const docTemplate = `{
}
}
},
"settings.Auth": {
"type": "object",
"properties": {
"adminPassword": {
"type": "string"
},
"adminUsername": {
"type": "string"
},
"key": {
"type": "array",
"items": {
"type": "integer"
}
},
"methods": {
"$ref": "#/definitions/settings.LoginMethods"
},
"signup": {
"type": "boolean"
},
"tokenExpirationHours": {
"type": "integer"
}
}
},
"settings.ExternalLink": {
"type": "object",
"required": [
"text",
"url"
],
"properties": {
"text": {
"type": "string"
@@ -1784,9 +1747,6 @@ const docTemplate = `{
"settings.Frontend": {
"type": "object",
"properties": {
"color": {
"type": "string"
},
"disableDefaultLinks": {
"type": "boolean"
},
@@ -1799,23 +1759,272 @@ const docTemplate = `{
"$ref": "#/definitions/settings.ExternalLink"
}
},
"files": {
"type": "string"
},
"name": {
"type": "string"
}
}
},
"settings.IndexFilter": {
"type": "object",
"properties": {
"fileEndsWith": {
"type": "array",
"items": {
"type": "string"
}
},
"files": {
"type": "array",
"items": {
"type": "string"
}
},
"folders": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"settings.Integrations": {
"type": "object",
"properties": {
"office": {
"$ref": "#/definitions/settings.OnlyOffice"
}
}
},
"settings.LogConfig": {
"type": "object",
"properties": {
"apiLevels": {
"type": "string"
},
"json": {
"type": "boolean"
},
"levels": {
"type": "string"
},
"noColors": {
"type": "boolean"
},
"output": {
"type": "string"
}
}
},
"settings.LoginMethods": {
"type": "object",
"properties": {
"noauth": {
"type": "boolean"
},
"password": {
"$ref": "#/definitions/settings.PasswordAuthConfig"
},
"proxy": {
"$ref": "#/definitions/settings.ProxyAuthConfig"
}
}
},
"settings.OnlyOffice": {
"type": "object",
"required": [
"secret",
"url"
],
"properties": {
"secret": {
"type": "string"
},
"url": {
"type": "string"
}
}
},
"settings.PasswordAuthConfig": {
"type": "object",
"required": [
"enabled"
],
"properties": {
"enabled": {
"type": "boolean"
},
"minLength": {
"type": "integer"
}
}
},
"settings.ProxyAuthConfig": {
"type": "object",
"required": [
"enabled"
],
"properties": {
"createUser": {
"type": "boolean"
},
"enabled": {
"type": "boolean"
},
"header": {
"type": "string"
}
}
},
"settings.Server": {
"type": "object",
"required": [
"sources"
],
"properties": {
"baseURL": {
"type": "string"
},
"cacheDir": {
"type": "string"
},
"database": {
"type": "string"
},
"enableThumbnails": {
"type": "boolean"
},
"externalUrl": {
"type": "string"
},
"internalUrl": {
"description": "used by integrations",
"type": "string"
},
"logging": {
"type": "array",
"items": {
"$ref": "#/definitions/settings.LogConfig"
}
},
"maxArchiveSize": {
"type": "integer"
},
"numImageProcessors": {
"type": "integer"
},
"port": {
"type": "integer"
},
"resizePreview": {
"type": "boolean"
},
"socket": {
"type": "string"
},
"sources": {
"type": "array",
"items": {
"$ref": "#/definitions/settings.Source"
}
},
"tlsCert": {
"type": "string"
},
"tlsKey": {
"type": "string"
}
}
},
"settings.Settings": {
"type": "object",
"properties": {
"auth": {
"$ref": "#/definitions/settings.Auth"
},
"frontend": {
"$ref": "#/definitions/settings.Frontend"
},
"integrations": {
"$ref": "#/definitions/settings.Integrations"
},
"server": {
"$ref": "#/definitions/settings.Server"
},
"userDefaults": {
"$ref": "#/definitions/settings.UserDefaults"
},
"users": {
"type": "array",
"items": {
"$ref": "#/definitions/settings.UserDefaults"
}
}
}
},
"settings.Source": {
"type": "object",
"required": [
"path"
],
"properties": {
"config": {
"$ref": "#/definitions/settings.SourceConfig"
},
"name": {
"description": "display name",
"type": "string"
},
"path": {
"description": "file system path. (Can be relative)",
"type": "string"
}
}
},
"settings.SourceConfig": {
"type": "object",
"properties": {
"createUserDir": {
"type": "boolean"
},
"defaultEnabled": {
"type": "boolean"
},
"defaultUserScope": {
"description": "default \"\" should match folders under path",
"type": "string"
},
"disabled": {
"type": "boolean"
},
"exclude": {
"$ref": "#/definitions/settings.IndexFilter"
},
"ignoreHidden": {
"type": "boolean"
},
"ignoreZeroSizeFolders": {
"type": "boolean"
},
"include": {
"$ref": "#/definitions/settings.IndexFilter"
},
"indexingInterval": {
"type": "integer"
},
"maxWatchers": {
"type": "integer"
},
"neverWatchPaths": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"settings.UserDefaults": {
"type": "object",
"properties": {
"commands": {
"type": "array",
"items": {
"type": "string"
}
},
"darkMode": {
"type": "boolean"
},
@@ -1837,19 +2046,12 @@ const docTemplate = `{
"lockPassword": {
"type": "boolean"
},
"perm": {
"$ref": "#/definitions/users.Permissions"
},
"permissions": {
"$ref": "#/definitions/users.Permissions"
},
"quickDownload": {
"type": "boolean"
},
"scope": {
"description": "deprecated",
"type": "string"
},
"showHidden": {
"type": "boolean"
},
+291 -89
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"
}
@@ -902,54 +902,7 @@
"200": {
"description": "System settings data",
"schema": {
"$ref": "#/definitions/http.settingsData"
}
}
}
},
"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"
}
"$ref": "#/definitions/settings.Settings"
}
}
}
@@ -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
@@ -1725,26 +1678,6 @@
}
}
},
"http.settingsData": {
"type": "object",
"properties": {
"createUserDir": {
"type": "boolean"
},
"defaults": {
"$ref": "#/definitions/settings.UserDefaults"
},
"frontend": {
"$ref": "#/definitions/settings.Frontend"
},
"signup": {
"type": "boolean"
},
"userHomeBasePath": {
"type": "string"
}
}
},
"http.signupBody": {
"type": "object",
"properties": {
@@ -1756,8 +1689,38 @@
}
}
},
"settings.Auth": {
"type": "object",
"properties": {
"adminPassword": {
"type": "string"
},
"adminUsername": {
"type": "string"
},
"key": {
"type": "array",
"items": {
"type": "integer"
}
},
"methods": {
"$ref": "#/definitions/settings.LoginMethods"
},
"signup": {
"type": "boolean"
},
"tokenExpirationHours": {
"type": "integer"
}
}
},
"settings.ExternalLink": {
"type": "object",
"required": [
"text",
"url"
],
"properties": {
"text": {
"type": "string"
@@ -1773,9 +1736,6 @@
"settings.Frontend": {
"type": "object",
"properties": {
"color": {
"type": "string"
},
"disableDefaultLinks": {
"type": "boolean"
},
@@ -1788,23 +1748,272 @@
"$ref": "#/definitions/settings.ExternalLink"
}
},
"files": {
"type": "string"
},
"name": {
"type": "string"
}
}
},
"settings.IndexFilter": {
"type": "object",
"properties": {
"fileEndsWith": {
"type": "array",
"items": {
"type": "string"
}
},
"files": {
"type": "array",
"items": {
"type": "string"
}
},
"folders": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"settings.Integrations": {
"type": "object",
"properties": {
"office": {
"$ref": "#/definitions/settings.OnlyOffice"
}
}
},
"settings.LogConfig": {
"type": "object",
"properties": {
"apiLevels": {
"type": "string"
},
"json": {
"type": "boolean"
},
"levels": {
"type": "string"
},
"noColors": {
"type": "boolean"
},
"output": {
"type": "string"
}
}
},
"settings.LoginMethods": {
"type": "object",
"properties": {
"noauth": {
"type": "boolean"
},
"password": {
"$ref": "#/definitions/settings.PasswordAuthConfig"
},
"proxy": {
"$ref": "#/definitions/settings.ProxyAuthConfig"
}
}
},
"settings.OnlyOffice": {
"type": "object",
"required": [
"secret",
"url"
],
"properties": {
"secret": {
"type": "string"
},
"url": {
"type": "string"
}
}
},
"settings.PasswordAuthConfig": {
"type": "object",
"required": [
"enabled"
],
"properties": {
"enabled": {
"type": "boolean"
},
"minLength": {
"type": "integer"
}
}
},
"settings.ProxyAuthConfig": {
"type": "object",
"required": [
"enabled"
],
"properties": {
"createUser": {
"type": "boolean"
},
"enabled": {
"type": "boolean"
},
"header": {
"type": "string"
}
}
},
"settings.Server": {
"type": "object",
"required": [
"sources"
],
"properties": {
"baseURL": {
"type": "string"
},
"cacheDir": {
"type": "string"
},
"database": {
"type": "string"
},
"enableThumbnails": {
"type": "boolean"
},
"externalUrl": {
"type": "string"
},
"internalUrl": {
"description": "used by integrations",
"type": "string"
},
"logging": {
"type": "array",
"items": {
"$ref": "#/definitions/settings.LogConfig"
}
},
"maxArchiveSize": {
"type": "integer"
},
"numImageProcessors": {
"type": "integer"
},
"port": {
"type": "integer"
},
"resizePreview": {
"type": "boolean"
},
"socket": {
"type": "string"
},
"sources": {
"type": "array",
"items": {
"$ref": "#/definitions/settings.Source"
}
},
"tlsCert": {
"type": "string"
},
"tlsKey": {
"type": "string"
}
}
},
"settings.Settings": {
"type": "object",
"properties": {
"auth": {
"$ref": "#/definitions/settings.Auth"
},
"frontend": {
"$ref": "#/definitions/settings.Frontend"
},
"integrations": {
"$ref": "#/definitions/settings.Integrations"
},
"server": {
"$ref": "#/definitions/settings.Server"
},
"userDefaults": {
"$ref": "#/definitions/settings.UserDefaults"
},
"users": {
"type": "array",
"items": {
"$ref": "#/definitions/settings.UserDefaults"
}
}
}
},
"settings.Source": {
"type": "object",
"required": [
"path"
],
"properties": {
"config": {
"$ref": "#/definitions/settings.SourceConfig"
},
"name": {
"description": "display name",
"type": "string"
},
"path": {
"description": "file system path. (Can be relative)",
"type": "string"
}
}
},
"settings.SourceConfig": {
"type": "object",
"properties": {
"createUserDir": {
"type": "boolean"
},
"defaultEnabled": {
"type": "boolean"
},
"defaultUserScope": {
"description": "default \"\" should match folders under path",
"type": "string"
},
"disabled": {
"type": "boolean"
},
"exclude": {
"$ref": "#/definitions/settings.IndexFilter"
},
"ignoreHidden": {
"type": "boolean"
},
"ignoreZeroSizeFolders": {
"type": "boolean"
},
"include": {
"$ref": "#/definitions/settings.IndexFilter"
},
"indexingInterval": {
"type": "integer"
},
"maxWatchers": {
"type": "integer"
},
"neverWatchPaths": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"settings.UserDefaults": {
"type": "object",
"properties": {
"commands": {
"type": "array",
"items": {
"type": "string"
}
},
"darkMode": {
"type": "boolean"
},
@@ -1826,19 +2035,12 @@
"lockPassword": {
"type": "boolean"
},
"perm": {
"$ref": "#/definitions/users.Permissions"
},
"permissions": {
"$ref": "#/definitions/users.Permissions"
},
"quickDownload": {
"type": "boolean"
},
"scope": {
"description": "deprecated",
"type": "string"
},
"showHidden": {
"type": "boolean"
},
+193 -60
View File
@@ -86,19 +86,6 @@ definitions:
token:
type: string
type: object
http.settingsData:
properties:
createUserDir:
type: boolean
defaults:
$ref: '#/definitions/settings.UserDefaults'
frontend:
$ref: '#/definitions/settings.Frontend'
signup:
type: boolean
userHomeBasePath:
type: string
type: object
http.signupBody:
properties:
password:
@@ -106,6 +93,23 @@ definitions:
username:
type: string
type: object
settings.Auth:
properties:
adminPassword:
type: string
adminUsername:
type: string
key:
items:
type: integer
type: array
methods:
$ref: '#/definitions/settings.LoginMethods'
signup:
type: boolean
tokenExpirationHours:
type: integer
type: object
settings.ExternalLink:
properties:
text:
@@ -114,11 +118,12 @@ definitions:
type: string
url:
type: string
required:
- text
- url
type: object
settings.Frontend:
properties:
color:
type: string
disableDefaultLinks:
type: boolean
disableUsedPercentage:
@@ -127,17 +132,181 @@ definitions:
items:
$ref: '#/definitions/settings.ExternalLink'
type: array
files:
type: string
name:
type: string
type: object
settings.UserDefaults:
settings.IndexFilter:
properties:
commands:
fileEndsWith:
items:
type: string
type: array
files:
items:
type: string
type: array
folders:
items:
type: string
type: array
type: object
settings.Integrations:
properties:
office:
$ref: '#/definitions/settings.OnlyOffice'
type: object
settings.LogConfig:
properties:
apiLevels:
type: string
json:
type: boolean
levels:
type: string
noColors:
type: boolean
output:
type: string
type: object
settings.LoginMethods:
properties:
noauth:
type: boolean
password:
$ref: '#/definitions/settings.PasswordAuthConfig'
proxy:
$ref: '#/definitions/settings.ProxyAuthConfig'
type: object
settings.OnlyOffice:
properties:
secret:
type: string
url:
type: string
required:
- secret
- url
type: object
settings.PasswordAuthConfig:
properties:
enabled:
type: boolean
minLength:
type: integer
required:
- enabled
type: object
settings.ProxyAuthConfig:
properties:
createUser:
type: boolean
enabled:
type: boolean
header:
type: string
required:
- enabled
type: object
settings.Server:
properties:
baseURL:
type: string
cacheDir:
type: string
database:
type: string
enableThumbnails:
type: boolean
externalUrl:
type: string
internalUrl:
description: used by integrations
type: string
logging:
items:
$ref: '#/definitions/settings.LogConfig'
type: array
maxArchiveSize:
type: integer
numImageProcessors:
type: integer
port:
type: integer
resizePreview:
type: boolean
socket:
type: string
sources:
items:
$ref: '#/definitions/settings.Source'
type: array
tlsCert:
type: string
tlsKey:
type: string
required:
- sources
type: object
settings.Settings:
properties:
auth:
$ref: '#/definitions/settings.Auth'
frontend:
$ref: '#/definitions/settings.Frontend'
integrations:
$ref: '#/definitions/settings.Integrations'
server:
$ref: '#/definitions/settings.Server'
userDefaults:
$ref: '#/definitions/settings.UserDefaults'
users:
items:
$ref: '#/definitions/settings.UserDefaults'
type: array
type: object
settings.Source:
properties:
config:
$ref: '#/definitions/settings.SourceConfig'
name:
description: display name
type: string
path:
description: file system path. (Can be relative)
type: string
required:
- path
type: object
settings.SourceConfig:
properties:
createUserDir:
type: boolean
defaultEnabled:
type: boolean
defaultUserScope:
description: default "" should match folders under path
type: string
disabled:
type: boolean
exclude:
$ref: '#/definitions/settings.IndexFilter'
ignoreHidden:
type: boolean
ignoreZeroSizeFolders:
type: boolean
include:
$ref: '#/definitions/settings.IndexFilter'
indexingInterval:
type: integer
maxWatchers:
type: integer
neverWatchPaths:
items:
type: string
type: array
type: object
settings.UserDefaults:
properties:
darkMode:
type: boolean
dateFormat:
@@ -152,15 +321,10 @@ definitions:
type: string
lockPassword:
type: boolean
perm:
$ref: '#/definitions/users.Permissions'
permissions:
$ref: '#/definitions/users.Permissions'
quickDownload:
type: boolean
scope:
description: deprecated
type: string
showHidden:
type: boolean
singleClick:
@@ -891,7 +1055,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
@@ -901,42 +1066,10 @@ paths:
"200":
description: System settings data
schema:
$ref: '#/definitions/http.settingsData'
$ref: '#/definitions/settings.Settings'
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:
@@ -1318,8 +1451,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
+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
}
+13 -3
View File
@@ -6,7 +6,9 @@ import (
"encoding/hex"
"fmt"
math "math/rand"
"path/filepath"
"reflect"
"runtime"
"strings"
"time"
@@ -19,13 +21,13 @@ func CheckErr(source string, err error) {
}
}
func GenerateKey() []byte {
func GenerateKey() string {
b := make([]byte, 64)
_, err := rand.Read(b)
if err != nil {
return nil
return ""
}
return b
return string(b)
}
// CapitalizeFirst returns the input string with the first letter capitalized.
@@ -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
-4
View File
@@ -5,10 +5,6 @@
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
{{ if .ReCaptcha }}
<script src="{{ .ReCaptchaHost }}/recaptcha/api.js?render=explicit" data-vite-ignore></script>
{{ end }}
<title>{{ if .Name }}{{ .Name }}{{ else }}FileBrowser Quantum{{ end }}</title>
<link rel="icon" type="image/png" sizes="256x256" href="{{ .StaticURL }}/img/icons/favicon-256x256.png">
-1
View File
@@ -11,7 +11,6 @@ export default {
computed: {},
setup() {
onMounted(() => {
console.log("static vars", window.FileBrowser);
mutations.setLoading("main-app", false);
// Query the loading element and remove it from the DOM
const loadingDiv = document.getElementById("loading");
+39 -40
View File
@@ -1,11 +1,11 @@
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) {
export async function fetchFiles(url, content = false) {
try {
const result = extractSourceFromPath(url)
const apiPath = getApiPath('api/resources', {
@@ -23,7 +23,7 @@ export async function fetchFiles (url, content = false) {
}
}
async function resourceAction (url, method, content) {
async function resourceAction(url, method, content) {
try {
const result = extractSourceFromPath(url)
let source = result.source
@@ -42,7 +42,7 @@ async function resourceAction (url, method, content) {
}
}
export async function remove (url) {
export async function remove(url) {
try {
return await resourceAction(url, 'DELETE')
} catch (err) {
@@ -51,7 +51,7 @@ export async function remove (url) {
}
}
export async function put (url, content = '') {
export async function put(url, content = '') {
try {
return await resourceAction(url, 'PUT', content)
} catch (err) {
@@ -60,41 +60,39 @@ export async function put (url, content = '') {
}
}
export function download (format, files) {
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) {
export async function post(url, content = '', overwrite = false, onupload) {
try {
const result = extractSourceFromPath(url)
let bufferContent
@@ -143,7 +141,7 @@ export async function post (url, content = '', overwrite = false, onupload) {
}
}
export async function moveCopy (
export async function moveCopy(
items,
action = 'copy',
overwrite = false,
@@ -186,7 +184,7 @@ export async function moveCopy (
}
}
export async function checksum (url, algo) {
export async function checksum(url, algo) {
try {
const result = extractSourceFromPath(url)
const params = {
@@ -204,7 +202,7 @@ export async function checksum (url, algo) {
}
}
export function getDownloadURL (source, path, inline, useExternal) {
export function getDownloadURL(source, path, inline, useExternal) {
try {
const params = {
files: source + '::' + encodeURIComponent(path),
@@ -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) {
@@ -221,7 +220,7 @@ export function getDownloadURL (source, path, inline, useExternal) {
}
}
export function getPreviewURL (source, path, size, modified) {
export function getPreviewURL(source, path, size, modified) {
try {
const params = {
path: encodeURIComponent(path),
@@ -238,7 +237,7 @@ export function getPreviewURL (source, path, size, modified) {
}
}
export async function usage (source) {
export async function usage(source) {
try {
const apiPath = getApiPath('api/usage', { source: source })
const res = await fetchURL(apiPath)
+24 -26
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
@@ -18,37 +18,35 @@ 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
}
// 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
+1 -3
View File
@@ -1,16 +1,14 @@
import { fetchURL } from "./utils";
import { notify } from "@/notify"; // Import notify for error handling
import { removePrefix, getApiPath } from "@/utils/url.js";
import { getApiPath } from "@/utils/url.js";
export default async function search(base, source, query) {
try {
base = removePrefix(base,"files");
query = encodeURIComponent(query);
if (!base.endsWith("/")) {
base += "/";
}
const apiPath = getApiPath("api/search", { scope: base, query: query, source: source });
const res = await fetchURL(apiPath);
let data = await res.json();
+8 -7
View File
@@ -1,19 +1,19 @@
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");
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") {
@@ -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}`);
}
+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 {
+34 -42
View File
@@ -1,19 +1,24 @@
<template>
<div class="breadcrumbs">
<component
:is="element"
:to="homePath"
:aria-label="$t('files.home')"
:title="$t('files.home')"
>
<router-link :to="base" :aria-label="$t('files.home')" :title="$t('files.home')">
<i class="material-icons">home</i>
</component>
</router-link>
<span v-for="(link, index) in items" :key="index">
<span
:aria-label="'breadcrumb-link-' + link.name"
v-for="(link, index) in items"
:key="index"
>
<span class="chevron"><i class="material-icons">keyboard_arrow_right</i></span>
<component :is="element" :to="link.url">{{ link.name }}</component>
<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
@@ -32,7 +37,7 @@
<script>
import { state, mutations, getters } from "@/store";
import { extractSourceFromPath, removePrefix, removeLeadingSlash } from "@/utils/url.js";
import { extractSourceFromPath, removeLeadingSlash } from "@/utils/url.js";
import Action from "@/components/Action.vue";
export default {
@@ -43,11 +48,11 @@ export default {
data() {
return {
gallerySize: state.user.gallerySize,
homePath: "/files/",
base: "/files/",
path: "",
};
},
props: ["base", "noLink"],
props: ["noLink"],
mounted() {
this.updatePaths();
},
@@ -65,40 +70,25 @@ export default {
if (parts[parts.length - 1] === "") {
parts.pop();
}
let breadcrumbs = [];
for (let i = 0; i < parts.length; i++) {
if (i === 0) {
breadcrumbs.push({
name: decodeURIComponent(parts[i]),
url: this.base + "/" + parts[i] + "/",
});
} else {
breadcrumbs.push({
name: decodeURIComponent(parts[i]),
url: breadcrumbs[i - 1].url + parts[i] + "/",
});
}
}
let buildRef = this.base;
parts.forEach((element) => {
buildRef = buildRef + encodeURIComponent(decodeURIComponent(element)) + "/";
breadcrumbs.push({
name: decodeURIComponent(element),
url: buildRef,
});
});
if (breadcrumbs.length > 3) {
while (breadcrumbs.length !== 4) {
breadcrumbs.shift();
}
breadcrumbs[0].name = "...";
}
return breadcrumbs;
},
element() {
if (this.noLink !== undefined) {
return "span";
}
return "router-link";
},
showShare() {
return (
state.user?.perm &&
@@ -111,13 +101,15 @@ export default {
methods: {
updatePaths() {
const result = extractSourceFromPath(getters.routePath());
this.path = removePrefix(result.path, "files");
if (getters.currentView() == "share") {
this.homePath = getters.sharePathBase();
this.path = removePrefix(getters.routePath(), this.homePath + "/");
}
if (state.sources.count > 1) {
this.homePath = "/files/" + result.source;
this.base = getters.sharePathBase();
this.path = getters.routePath(this.base);
} else {
this.path = decodeURIComponent(result.path);
this.base = "/";
if (state.serverHasMultipleSources) {
this.base = `${this.base}${result.source}/`;
}
}
},
updateGallerySize(event) {
+101 -7
View File
@@ -232,7 +232,7 @@ export default {
mutations.closeHovers();
return;
}
if (state.sources.count > 1) {
if (state.serverHasMultipleSources) {
this.selectedSource = state.sources.current;
}
setTimeout(() => {
@@ -248,9 +248,37 @@ export default {
},
},
mounted() {
if (state.sources.count > 1) {
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,12 +347,74 @@ 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; // Correct way to get the new value
this.selectedSource = event.target.value;
this.submit();
},
getRelative(path) {
return "/files/" + this.selectedSource + "/" + 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
let fullpath = path;
if (state.sources.count === 1) {
fullpath = "/files/" + encodeURIComponent(path);
} else {
fullpath = "/files/" + this.selectedSource + "/" + encodeURIComponent(path);
}
return fullpath;
},
getIcon(mimetype) {
return getMaterialIconForType(mimetype);
@@ -349,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;
@@ -433,7 +523,11 @@ export default {
if (source == "") {
source = state.sources.current;
}
this.results = await search(this.getContext, source, searchTypesFull + this.value);
this.results = await search(
encodeURIComponent(this.getContext),
source,
searchTypesFull + this.value
);
this.ongoing = false;
if (this.results.length == 0) {
@@ -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";
@@ -158,7 +157,7 @@ export default {
return this.selected.indexOf(this.index) !== -1;
},
isDraggable() {
return this.readOnly == undefined && state.user.perm?.rename;
return this.readOnly == undefined && state.user.perm?.modify;
},
canDrop() {
if (!this.isDir || this.readOnly !== undefined) return false;
@@ -197,6 +196,7 @@ export default {
methods: {
downloadFile(event) {
event.preventDefault();
event.stopPropagation();
mutations.resetSelected();
mutations.addSelected(this.index);
downloadFiles();
@@ -233,7 +233,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
@@ -326,7 +326,7 @@ export default {
name: state.req.items[i].name,
});
}
let response = await filesApi.fetchFiles(el.__vue__.url);
let response = await filesApi.fetchFiles(decodeURIComponent(el.__vue__.url));
let action = async (overwrite, rename) => {
await filesApi.moveCopy(items, "move", overwrite, rename);
@@ -334,7 +334,6 @@ export default {
mutations.setReload(true);
}, 50);
};
let conflict = upload.checkConflict(items, response.items);
let overwrite = false;
@@ -434,8 +433,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();
@@ -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() {
@@ -227,7 +220,9 @@ export default {
if (this.availableSources.length > 0) {
const newSource = this.availableSources.pop();
if (newSource) {
this.selectedSources.push({ name: newSource.name, scope: "" });
const scope = { name: newSource.name, scope: "" };
this.selectedSources.push(scope);
this.updateParent({ source: scope, input: { target: { value: "" } } });
}
}
},
+3 -25
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">
@@ -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"
@@ -86,13 +86,11 @@ import * as auth from "@/utils/auth";
import {
signup,
disableExternal,
disableUsedPercentage,
noAuth,
loginPage,
disableUsedPercentage,
} from "@/utils/constants";
import { filesApi } from "@/api";
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 +133,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()
+4 -7
View File
@@ -4,6 +4,7 @@ import { emitStateChanged } from './eventBus'; // Import the function from event
import { usersApi } from "@/api";
import { notify } from "@/notify";
import { sortedItems } from "@/utils/sort.js";
import { serverHasMultipleSources } from "@/utils/constants.js";
export const mutations = {
setCurrentSource: (value) => {
@@ -17,6 +18,7 @@ export const mutations = {
emitStateChanged();
},
setSources: (user) => {
state.serverHasMultipleSources = serverHasMultipleSources;
const currentSource = user.scopes.length > 0 ? user.scopes[0].name : "";
let sources = {info: {}, current: currentSource, count: user.scopes.length};
for (const source of user.scopes) {
@@ -128,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) {
@@ -155,6 +155,7 @@ export const mutations = {
},
setSession: (value) => {
state.sessionId = value;
localStorage.setItem("sessionId", value);
emitStateChanged();
},
setMultiple: (value) => {
@@ -186,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;
@@ -217,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();
},
+2
View File
@@ -10,12 +10,14 @@ export const state = reactive({
showSidebar: false,
usages: {},
editor: null,
serverHasMultipleSources: false,
sources: {
current: "",
count: 1,
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()
}
+4 -4
View File
@@ -5,8 +5,8 @@ const disableUsedPercentage = window.FileBrowser.DisableUsedPercentage;
const baseURL = window.FileBrowser.BaseURL;
const staticURL = window.FileBrowser.StaticURL;
const darkMode = window.FileBrowser.darkMode;
const recaptcha = window.FileBrowser.ReCaptcha;
const recaptchaKey = window.FileBrowser.ReCaptchaKey;
const recaptcha = false;
const recaptchaKey = "";
const signup = window.FileBrowser.Signup;
const version = window.FileBrowser.Version;
const commitSHA = window.FileBrowser.CommitSHA;
@@ -15,9 +15,9 @@ 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;
const origin = window.location.origin;
const settings = [
@@ -29,6 +29,7 @@ const settings = [
]
export {
serverHasMultipleSources,
name,
externalUrl,
disableExternal,
@@ -45,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
@@ -63,6 +63,7 @@ export function getTypeInfo(mimeType) {
mimeType === "application/gzip" ||
mimeType === "application/x-xz" ||
mimeType === "application/x-zip-compressed" ||
mimeType === "application/x-compressed" ||
mimeType === "application/x-gzip"
) {
return {
+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,
+8 -6
View File
@@ -66,7 +66,6 @@ export function removePrefix(path, prefix = "") {
if (!path.startsWith('/')) {
path = '/' + path;
}
return path;
}
@@ -115,14 +114,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');
if (state.sources.count <= 1) {
source = state.sources.current;
let path = url;
if (state.serverHasMultipleSources) {
source = path.split('/')[2];
path = removePrefix(path, `/files/${source}`);
} else {
source = path.split('/')[1];
path = removePrefix(path, source);
source = state.sources.current;
path = removePrefix(path, '/files');
}
return { source, path };
}
+25 -12
View File
@@ -1,11 +1,13 @@
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/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/"},
{input: "test",trimArg: "",expected:"/test"},
{input: "/test", trimArg: "test",expected:"/"},
@@ -20,16 +22,27 @@ describe('testurl', () => {
});
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);
}
});
});
describe('extractSourceFromPath', () => {
it('single source extract', async () => {
vi.doMock("@/store", () => {
return {
state: {
count: 1,
current: "default",
serverHasMultipleSources: false,
sources: {
first: { pathPrefix: "", used: "0 B", total: "0 B", usedPercentage: 0 },
},
current: "default",
}
},
};
});
@@ -54,11 +67,13 @@ describe('extractSourceFromPath2', () => {
vi.doMock("@/store", () => {
return {
state: {
count: 2,
current: "first",
serverHasMultipleSources: true,
sources: {
first: { pathPrefix: "first", used: "0 B", total: "0 B", usedPercentage: 0 },
second: { pathPrefix: "second", used: "0 B", total: "0 B", usedPercentage: 0 },
current: "first",
list: [
{ pathPrefix: "first", used: "0 B", total: "0 B", usedPercentage: 0 },
{ pathPrefix: "second", used: "0 B", total: "0 B", usedPercentage: 0 }
],
},
},
};
@@ -68,13 +83,11 @@ describe('extractSourceFromPath2', () => {
{ url: "/files/first/root/file1.txt", expected: { source: "first", path: "/root/file1.txt" } },
{ url: "/files/second/root/folder1/file1.txt", expected: { source: "second", path: "/root/folder1/file1.txt" } },
];
for (const test of tests) {
const result = extractSourceFromPath(test.url);
expect(result.source).toEqual(test.expected.source);
expect(result.path).toEqual(test.expected.path);
}
vi.resetModules(); // Reset modules between tests
});
});
+14 -9
View File
@@ -1,6 +1,6 @@
<template>
<div>
<breadcrumbs v-if="showBreadCrumbs" base="/files" />
<breadcrumbs v-if="showBreadCrumbs" />
<errors v-if="error" :errorCode="error.status" />
<component v-else-if="currentViewLoaded" :is="currentView"></component>
<div v-else>
@@ -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.sources.count > 1 &&
(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);
+3 -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 {
@@ -69,6 +68,9 @@ export default {
if (state.user.themeColor) {
document.documentElement.style.setProperty("--primaryColor", state.user.themeColor);
}
if (!state.sessionId) {
mutations.setSession(localStorage.getItem("sessionId"));
}
},
computed: {
showPadding() {
@@ -104,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);
},
});
},
+23 -24
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) {
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":
@@ -571,12 +572,12 @@ export default {
break;
case "Delete":
if (!state.user.perm.delete || state.selected.length === 0) return;
if (!state.user.perm.modify || state.selected.length === 0) return;
mutations.showHover("delete");
break;
case "F2":
if (!state.user.perm.rename || state.selected.length !== 1) return;
if (!state.user.perm.modify || state.selected.length !== 1) return;
mutations.showHover("rename");
break;
@@ -791,28 +792,26 @@ 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 {
if (conflict) {
@@ -920,7 +919,7 @@ export default {
// if control or shift is pressed, do not clear the selection
if (this.ctrKeyPressed || event.shiftKey) return;
const sameAsBefore = state.selected == this.lastSelected;
if (sameAsBefore && !state.multiple && getters.currentPromptName == null) {
if (sameAsBefore && !state.multiple && getters.currentPromptName() == null) {
mutations.resetSelected();
}
this.lastSelected = state.selected;
@@ -51,6 +51,7 @@ export default {
let configData = await fetchJSON(baseURL + `api/onlyoffice/config?url=${refUrl}`);
configData.type = state.isMobile ? "mobile" : "desktop";
this.clientConfig = configData;
console.log("Client config:", this.clientConfig);
this.ready = true;
} catch (error) {
console.error("Error during setup:", error);
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more