Compare commits

...
35 Commits
Author SHA1 Message Date
Graham Steffaniak 415158d730 Adjusted path tweak (#212) 2024-09-17 12:14:48 -05:00
Graham Steffaniak cd192744c2 Merge branch 'main' into v0.2.9 2024-09-16 20:27:36 -05:00
Graham Steffaniak 906ac19be1 Hotfix v0.2.9 (#210) 2024-09-16 20:25:44 -05:00
Graham Steffaniak c272eb1e61 hotfix: search path adjustment 2024-09-16 20:19:25 -05:00
Graham Steffaniak bae39c8586 Update main.yaml workflow
add fetch depth
2024-09-16 17:26:57 -05:00
Graham Steffaniak 62d1cd88a1 V0.2.9 release (#205) 2024-09-16 16:01:16 -05:00
Graham Steffaniak 8767a43ee8 mention a new fix 2024-09-16 14:59:49 -05:00
Graham Steffaniak c1e846067e updated more quantum 2024-09-16 14:55:44 -05:00
Graham Steffaniak 9bdc332ffd adjust settings menu (#204) 2024-09-16 14:52:51 -05:00
Graham Steffaniak bfa3b6a7d8 Add context menu (#203) 2024-09-07 13:03:51 -05:00
Graham Steffaniak 66d09a4b75 echo workflow 2024-09-06 21:12:20 -05:00
Graham Steffaniak 3cb9308254 updated 2024-09-06 21:08:29 -05:00
Graham Steffaniak b01d663bbe updated 2024-09-06 21:01:04 -05:00
Graham Steffaniak 5998f82e54 workflow 2024-09-06 20:56:41 -05:00
Graham Steffaniak df7624fcfc updated again 2024-09-06 20:54:02 -05:00
Graham Steffaniak 8a72da8b30 updated approach 2024-09-06 20:48:56 -05:00
Graham Steffaniak 125c0d6108 Merge branch 'dev_v0.2.9' of github.com:gtsteffaniak/filebrowser into dev_v0.2.9 2024-09-06 20:45:09 -05:00
Graham Steffaniak f7f08bba2a updated release 2024-09-06 20:44:47 -05:00
Graham Steffaniak b49e5dbc81 updated workflow (#202) 2024-09-06 20:42:59 -05:00
Graham Steffaniak abd5464b80 Metadata changes (#200) 2024-09-02 19:17:15 -05:00
Graham Steffaniak 97dc393c9b Update share views (#199) 2024-09-02 18:42:17 -05:00
Graham Steffaniak a3f684ff82 Update CHANGELOG.md 2024-08-31 19:48:20 -05:00
Graham Steffaniak 876aabfcec Update CHANGELOG.md 2024-08-31 19:47:50 -05:00
Graham Steffaniak e22abd3a4b Update CHANGELOG.md 2024-08-31 19:47:12 -05:00
Graham Steffaniak 01e82e282c go mod tidy 2024-08-27 16:19:52 -05:00
Graham Steffaniak 58a4e07bf4 updated dependencies 2024-08-27 16:18:47 -05:00
Graham Steffaniak 7c2ebb7801 Fix drag to upload (#198) 2024-08-27 14:48:03 -05:00
Graham Steffaniak ab0fdc0e17 updated logic (#197) 2024-08-27 09:22:39 -05:00
Graham Steffaniak c2a627d5c1 updated with arrow keys logic 2024-08-25 13:19:24 -05:00
Graham Steffaniak 0bad14b51e workflow 2024-08-24 19:20:54 -05:00
Graham Steffaniak 74ccfab070 Update search behavior (#195) 2024-08-24 19:12:47 -05:00
Graham Steffaniak 5f185597c9 fix main workflow 2024-08-24 17:06:55 -05:00
Graham Steffaniak 9e9109984d v0.2.8 release (#193) 2024-08-24 17:02:33 -05:00
Graham Steffaniak 5ebaf2a45b State fix (#183) 2024-08-04 14:02:09 -05:00
Graham Steffaniak c7cce0694b workflow update and go releaser (#177) 2024-08-04 12:50:35 -05:00
132 changed files with 4036 additions and 2725 deletions

No files matched your search

+10 -7
View File
@@ -1,4 +1,4 @@
name: main job
name: main release
on:
push:
@@ -12,16 +12,16 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Find latest tag
run: |
echo "LATEST_TAG=$(git describe --tags `git rev-list --tags --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
# Workaround to fix error:
# failed to push: failed to copy: io: read/write on closed pipe
# See https://github.com/docker/build-push-action/issues/761
with:
driver-opts: |
image=moby/buildkit:v0.10.6
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
@@ -36,6 +36,9 @@ jobs:
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: ./Dockerfile
push: true
+22 -10
View File
@@ -1,13 +1,28 @@
name: pr-merge
name: pr-request
on:
pull_request:
branches:
- "main"
- "v[0-9]+.[0-9]+.[0-9]+"
- "dev_*"
jobs:
test_frontend:
name: Push release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- 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: Build
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile.playwright
push: false
push_pr_to_registry:
name: Push PR
runs-on: ubuntu-latest
@@ -18,12 +33,6 @@ jobs:
uses: docker/setup-qemu-action@v3.0.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.0.0
# Workaround to fix error:
# failed to push: failed to copy: io: read/write on closed pipe
# See https://github.com/docker/build-push-action/issues/761
with:
driver-opts: |
image=moby/buildkit:v0.10.6
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
@@ -35,10 +44,13 @@ jobs:
with:
images: gtstef/filebrowser
- name: Build and push
uses: docker/build-push-action@v5
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ steps.meta.outputs.version }}
REVISION=${{ steps.meta.outputs.revision }}
+4 -4
View File
@@ -1,4 +1,4 @@
name: dev
name: dev tests
on:
push:
@@ -21,10 +21,10 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 'stable'
- uses: golangci/golangci-lint-action@v6
go-version: '1.22.5'
- uses: golangci/golangci-lint-action@v5
with:
version: v1.59
version: v1.60
working-directory: backend
format-backend:
runs-on: ubuntu-latest
+7 -10
View File
@@ -1,4 +1,4 @@
name: release
name: version release
on:
push:
@@ -34,6 +34,7 @@ jobs:
draft: false
generate_release_notes: true
name: ${{ steps.extract_branch.outputs.branch }}
push_release_to_registry:
name: Push release
runs-on: ubuntu-latest
@@ -44,14 +45,7 @@ jobs:
uses: docker/setup-qemu-action@v3.0.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.0.0
# Workaround to fix error:
# failed to push: failed to copy: io: read/write on closed pipe
# See https://github.com/docker/build-push-action/issues/761
with:
driver-opts: |
image=moby/buildkit:v0.10.6
- name: Login to Docker Hub
# Only push to Docker Hub when making a release
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
@@ -69,11 +63,14 @@ jobs:
JSON=$(echo "$JSON" | sed 's/filebrowser:v/filebrowser:/')
echo "cleaned_tag=$JSON" >> $GITHUB_OUTPUT
- name: Build and push
uses: docker/build-push-action@v5
uses: docker/build-push-action@v6
with:
context: .
build-args: |
VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
platforms: linux/amd64,linux/arm64,linux/arm/v7
file: ./Dockerfile
push: true
tags: ${{ steps.modify-json.outputs.cleaned_tag }}
labels: ${{ steps.meta.outputs.labels }}
labels: ${{ steps.meta.outputs.labels }}
+50
View File
@@ -0,0 +1,50 @@
name: dev release
on:
push:
branches:
- "dev_v[0-9]+.[0-9]+.[0-9]+"
permissions:
contents: write
jobs:
push_release_to_registry:
name: Push dev release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- 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: Strip v from version number
id: modify-json
run: |
JSON="${{ steps.meta.outputs.tags }}"
# Use jq to remove 'v' from the version field
JSON=$(echo "$JSON" | sed 's/filebrowser:v/filebrowser:/')
echo "CLEANED_TAG=$JSON" >> $GITHUB_ENV
- name: Build and push
uses: docker/build-push-action@v6
with:
build-args: |
VERSION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
REVISION=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
context: .
platforms: linux/amd64
file: ./Dockerfile
push: true
tags: ${{ env.CLEANED_TAG }}
labels: ${{ steps.meta.outputs.labels }}
-24
View File
@@ -1,24 +0,0 @@
name: 'Close stale issues and PRs'
permissions:
issues: write
pull-requests: write
on:
schedule:
- cron: '30 1 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v5
with:
stale-pr-message: 'This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.'
close-pr-message: 'This PR was closed because it has been stalled for 5 days with no activity.'
stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.'
close-issue-message: 'This issue was closed because it has been stalled for 30 days with no activity.'
days-before-stale: 30
days-before-close: 30
exempt-issue-labels: 'feature ☘,enhancement ⚙,bug 🐞'
exempt-pr-labels: 'need-help,wip'
operations-per-run: 100
+7
View File
@@ -15,6 +15,13 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
- name: Install dependencies and build frontend
run: npm i && npm run build
working-directory: frontend
- name: Install UPX
run: sudo apt-get install -y upx
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
+2
View File
@@ -7,10 +7,12 @@ rice-box.go
/filebrowser.exe
/frontend/dist
/frontend/pkg
/frontend/test-results
/frontend/package-lock.json
/backend/vendor
/backend/*.cov
/backend/test_config.yaml
/backend/srv
.DS_Store
node_modules
+29
View File
@@ -2,6 +2,35 @@
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.2.9
This release focused on UI navigation experience. Improving keyboard navigation and adds right click context menu.
**New Features**:
- listing view items are middle-clickable on selected listing or when in single-click mode.
- listing view items can be navigated via arrow keys.
- listing view can jump to items using letters and number keys to cycle through files that start with that character.
- You can use the enter key and backspace key to navigate backwards and forwards on selected items.
- ctr-space will open/close the search (leaving ctr-f to browser default find prompt)
- Added right-click context menu to replace the file selection prompt.
**Bugfixes**:
- Fixed drag to upload not working.
- Fixed shared video link issues.
- Fixed user edit bug related to other user.
- Fixed password reset bug.
- Fixed loading state getting stuck.
## v0.2.8
- **Feature**: New gallary view scaling options (closes [#141](https://github.com/gtsteffaniak/filebrowser/issues/141))
- **Change**: Refactored backend files functions
- **Change**: Improved UI response to filesystem changes
- **Change**: Added frontend tests for deployment integrity
- **Fix**: move/replace file prompt issue
- **Fix**: opening files from search
- **Fix**: Display count issue when hideDotFile is enabled.
## v0.2.7
- **Change**: New sidebar style and behavior
+15 -10
View File
@@ -1,17 +1,22 @@
FROM node:slim as nbuild
WORKDIR /app
COPY ./frontend/package*.json ./
RUN npm i --maxsockets 1
COPY ./frontend/ ./
RUN npm run build
FROM golang:1.22-alpine as base
FROM golang:1.22-alpine AS base
ARG VERSION
ARG REVISION
WORKDIR /app
COPY ./backend ./
RUN go build -ldflags="-w -s" -o filebrowser .
RUN go build -ldflags="-w -s \
-X 'github.com/gtsteffaniak/filebrowser/version.Version=${VERSION}' \
-X 'github.com/gtsteffaniak/filebrowser/version.CommitSHA=${REVISION}'" \
-o filebrowser .
FROM node:slim AS nbuild
WORKDIR /app
COPY ./frontend/package.json ./
RUN npm i --maxsockets 1
COPY ./frontend/ ./
RUN npm run build-docker
FROM alpine:latest
ARG app="/app/filebrowser"
ENV FILEBROWSER_NO_EMBEDED="true"
RUN apk --no-cache add ca-certificates mailcap
COPY --from=base /app/filebrowser* ./
COPY --from=nbuild /app/dist/ ./frontend/dist/
+19
View File
@@ -0,0 +1,19 @@
FROM golang:1.22-alpine AS base
WORKDIR /app
COPY ./backend ./
RUN go build -ldflags="-w -s" -o filebrowser .
FROM node:slim
WORKDIR /app
COPY ./frontend/package.json ./
RUN npm i --maxsockets 1
RUN npx playwright install --with-deps firefox
COPY [ "backend/filebrowser.yaml", "./" ]
COPY ./frontend/ ./frontend
WORKDIR /app/frontend
RUN npm run build-docker
WORKDIR /app
COPY --from=base /app/filebrowser* ./
RUN cp -R frontend/tests/ srv
ENV FILEBROWSER_NO_EMBEDED="true"
RUN ./filebrowser & sleep 2 && cd frontend && npx playwright test
+74 -22
View File
@@ -4,7 +4,7 @@
<p align="center">
<img src="frontend/public/img/icons/favicon-256x256.png" width="100" title="Login With Custom URL">
</p>
<h3 align="center">Filebrowser - A modern web-based file manager</h3>
<h3 align="center">FileBrowser Quantum - A modern web-based file manager</h3>
<p align="center">
<img width="800" src="https://github.com/user-attachments/assets/8ba93582-aba2-4996-8ac3-25f763a2e596" title="Main Screenshot">
</p>
@@ -15,38 +15,41 @@
> Starting with v0.2.4 *ALL* share links need to be re-created (due to
> security fix).
This fork makes the following significant changes to filebrowser for
origin:
FileBrowser Quantum is a fork of the filebrowser opensource project with the
following changes:
1. [x] Better search
- Lightning fast
- real-time results as you type
1. [x] Enhanced lightning fast indexed search
- Real-time results as you type
- Works with more type filters
- interactive results page.
- Enhanced interactive results page.
2. [x] Revamped and simplified GUI navbar and sidebar menu.
- Additional compact view mode as well as refreshed view mode
styles.
3. [x] Revamped configuration via `filebrowser.yml` config file.
- More configurations possible at a per-user level
3. [x] Revamped and simplified configuration via `filebrowser.yml` config file.
4. [x] Faster listing browsing
- Switching view modes is instant
- Changing Sort order is instant
- The entire directory is loaded in 1/3 the time
## About
Filebrowser provides a file managing interface within a specified directory
FileBrowser Quantum provides a file managing interface within a specified directory
and can be used to upload, delete, preview, rename, and edit your files.
It allows the creation of multiple users and each user can have its
directory.
This repository is a fork, a collection of changes that make this program
work better in terms of aesthetics and performance. Improved search,
simplified ui (without removing features) and more secure and up-to-date
This repository is a fork of the original [filebrowser](https://github.com/filebrowser/filebrowser)
with a collection of changes that make this program work better in terms of
aesthetics and performance. Improved search, simplified ui
(without removing features) and more secure and up-to-date
build are just a few examples.
This Implementation of filebrowser differs significantly to the original.
FileBrowser Quantum differs significantly to the original.
There are hundreds of thousands of lines changed and they are generally
no longer compatible with each other. This has been intentional -- the
focus of this fork is on a few key principles:
- Simplicity and improved user experience
- Efficiency of operations and performance
- Improving performance and faster feedback when making changes.
- Minimize external dependencies and standard library usage.
- Of course -- adding much-needed features.
@@ -81,7 +84,7 @@ Using docker:
docker run -it -v /path/to/folder:/srv -p 80:80 gtstef/filebrowser
```
1. docker-compose:
1. docker compose:
- with local storage
@@ -122,9 +125,7 @@ volumes:
```
Not using docker (not recommended)
Note: Must download asset with frontend directory next to filebrowser binary
Not using docker (not recommended), download your binary from releases and run with your custom config file:
```
./filebrowser -c <filebrowser.yml or other /path/to/config.yaml>
@@ -142,8 +143,8 @@ configuration options and other help.
## Migration from filebrowser/filebrowser
If you currently use filebrowser from the filebrowser/filebrowser
repo but want to try using this. I recommend you start fresh without
If you currently use the original opensource filebrowser
but want to try using this. I recommend you start fresh without
reusing the database, but there are a few things you'll need to do if you
must migrate:
@@ -159,10 +160,61 @@ must migrate:
filebrowser.yml and have a valid filebrowser config.
The filebrowser application should run with the same user and rules that
The filebrowser Quantum application should run with the same user and rules that
you have from the original. But keep in mind the differences that are
mentioned at the top of this readme.
## Comparison Chart
Application Name | <img width="48" src="frontend/public/img/icons/favicon-256x256.png" > Quantum | <img width="48" src="https://github.com/filebrowser/filebrowser/blob/master/frontend/public/img/logo.svg" > Filebrowser | <img width="48" src="https://github.com/mickael-kerjean/filestash/blob/master/public/assets/logo/app_icon.png?raw=true" > Filestash | <img width="48" src="https://avatars.githubusercontent.com/u/19211038?s=200&v=4" > Nextcloud | <img width="48" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Google_Drive_logo.png/480px-Google_Drive_logo.png" > Google_Drive | <img width="48" src="https://avatars.githubusercontent.com/u/6422152?v=4" > FileRun
--- | --- | --- | --- | --- | --- | --- |
Filesystem support | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
Linux | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
Windows | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
Mac | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
Self hostable | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
Has Stable Release? | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
S3 support | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
webdav support | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
ftp support | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
Dedicated docs site? | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ |
Multiple sources at once | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
Docker image size | 22 MB | 31 MB | 240 MB (main image) | 250 MB | ❌ | > 2 GB |
Min. Memory Requirements | 128 MB | 128 MB | 128 MB (main image) | 128 MB | ❌ | 4 GB |
has standalone binary | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
price | free | free | free | free tier | free tier | $99+ |
rich media preview | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
upload files from the web? | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
Advanced Search? | ✅ | ❌ | ❌ | configurable | ✅ | ✅ |
Indexed Search? | ✅ | ❌ | ❌ | configurable | ✅ | ✅ |
Content-aware search? | ❌ | ❌ | ❌ | configurable | ✅ | ✅ |
Custom job support | ❌ | ✅ | ❌ | ✅ | ❌ | ✅ |
Multiple users | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Single sign-on support | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
LDAP sign-on support | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
2FA sign-on support | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
Long-live API key support | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
Mobile App | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ |
open source? | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ |
tags support | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ |
sharable web links? | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Event-based notifications | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
Metrics | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
file space quotas | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
text-based files editor | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
office file support | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
Themes | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
Branding support | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ |
activity log | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
Comments support | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
collaboration on same file | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
trash support | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
Starred/pinned files | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
Content preview icons | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ |
Plugins support | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ |
Chromecast support | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
## Roadmap
see [Roadmap Page](./roadmap.md)
+232
View File
@@ -0,0 +1,232 @@
# This code is licensed under the terms of the MIT license https://opensource.org/license/mit
# Copyright (c) 2021 Marat Reymers
## Golden config for golangci-lint v1.59.1
#
# This is the best config for golangci-lint based on my experience and opinion.
# It is very strict, but not extremely strict.
# Feel free to adapt and change it for your needs.
run:
# Timeout for analysis, e.g. 30s, 5m.
# Default: 1m
timeout: 3m
# This file contains only configs which differ from defaults.
# All possible options can be found here https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml
linters-settings:
cyclop:
# The maximal code complexity to report.
# Default: 10
max-complexity: 30
# The maximal average package complexity.
# If it's higher than 0.0 (float) the check is enabled
# Default: 0.0
package-average: 10.0
errcheck:
# Report about not checking of errors in type assertions: `a := b.(MyStruct)`.
# Such cases aren't reported by default.
# Default: false
check-type-assertions: true
exhaustive:
# Program elements to check for exhaustiveness.
# Default: [ switch ]
check:
- switch
- map
exhaustruct:
# List of regular expressions to exclude struct packages and their names from checks.
# Regular expressions must match complete canonical struct package/name/structname.
# Default: []
exclude:
# std libs
- "^net/http.Client$"
- "^net/http.Cookie$"
- "^net/http.Request$"
- "^net/http.Response$"
- "^net/http.Server$"
- "^net/http.Transport$"
- "^net/url.URL$"
- "^os/exec.Cmd$"
- "^reflect.StructField$"
# public libs
- "^github.com/Shopify/sarama.Config$"
- "^github.com/Shopify/sarama.ProducerMessage$"
- "^github.com/mitchellh/mapstructure.DecoderConfig$"
- "^github.com/prometheus/client_golang/.+Opts$"
- "^github.com/spf13/cobra.Command$"
- "^github.com/spf13/cobra.CompletionOptions$"
- "^github.com/stretchr/testify/mock.Mock$"
- "^github.com/testcontainers/testcontainers-go.+Request$"
- "^github.com/testcontainers/testcontainers-go.FromDockerfile$"
- "^golang.org/x/tools/go/analysis.Analyzer$"
- "^google.golang.org/protobuf/.+Options$"
- "^gopkg.in/yaml.v3.Node$"
funlen:
# Checks the number of lines in a function.
# If lower than 0, disable the check.
# Default: 60
lines: 100
# Checks the number of statements in a function.
# If lower than 0, disable the check.
# Default: 40
statements: 50
# Ignore comments when counting lines.
# Default false
ignore-comments: true
gocognit:
# Minimal code complexity to report.
# Default: 30 (but we recommend 10-20)
min-complexity: 20
gocritic:
# Settings passed to gocritic.
# The settings key is the name of a supported gocritic checker.
# The list of supported checkers can be find in https://go-critic.github.io/overview.
settings:
captLocal:
# Whether to restrict checker to params only.
# Default: true
paramsOnly: false
underef:
# Whether to skip (*x).method() calls where x is a pointer receiver.
# Default: true
skipRecvDeref: false
gomodguard:
blocked:
# List of blocked modules.
# Default: []
modules:
- github.com/golang/protobuf:
recommendations:
- google.golang.org/protobuf
reason: "see https://developers.google.com/protocol-buffers/docs/reference/go/faq#modules"
- github.com/satori/go.uuid:
recommendations:
- github.com/google/uuid
reason: "satori's package is not maintained"
- github.com/gofrs/uuid:
recommendations:
- github.com/gofrs/uuid/v5
reason: "gofrs' package was not go module before v5"
govet:
# Enable all analyzers.
# Default: false
enable-all: true
# Disable analyzers by name.
# Run `go tool vet help` to see all analyzers.
# Default: []
disable:
- fieldalignment # too strict
# Settings per analyzer.
settings:
shadow:
# Whether to be strict about shadowing; can be noisy.
# Default: false
strict: false
inamedparam:
# Skips check for interface methods with only a single parameter.
# Default: false
skip-single-param: true
mnd:
# List of function patterns to exclude from analysis.
# Values always ignored: `time.Date`,
# `strconv.FormatInt`, `strconv.FormatUint`, `strconv.FormatFloat`,
# `strconv.ParseInt`, `strconv.ParseUint`, `strconv.ParseFloat`.
# Default: []
ignored-functions:
- args.Error
- flag.Arg
- flag.Duration.*
- flag.Float.*
- flag.Int.*
- flag.Uint.*
- os.Chmod
- os.Mkdir.*
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets.*
- prometheus.LinearBuckets
nakedret:
# Make an issue if func has more lines of code than this setting, and it has naked returns.
# Default: 30
max-func-lines: 0
nolintlint:
# Exclude following linters from requiring an explanation.
# Default: []
allow-no-explanation: [ funlen, gocognit, lll ]
# Enable to require an explanation of nonzero length after each nolint directive.
# Default: false
require-explanation: true
# Enable to require nolint directives to mention the specific linter being suppressed.
# Default: false
require-specific: true
perfsprint:
# Optimizes into strings concatenation.
# Default: true
strconcat: false
rowserrcheck:
# database/sql is always checked
# Default: []
packages:
- github.com/jmoiron/sqlx
sloglint:
# Enforce not using global loggers.
# Values:
# - "": disabled
# - "all": report all global loggers
# - "default": report only the default slog logger
# https://github.com/go-simpler/sloglint?tab=readme-ov-file#no-global
# Default: ""
no-global: "all"
# Enforce using methods that accept a context.
# Values:
# - "": disabled
# - "all": report all contextless calls
# - "scope": report only if a context exists in the scope of the outermost function
# https://github.com/go-simpler/sloglint?tab=readme-ov-file#context-only
# Default: ""
context: "scope"
tenv:
# The option `all` will run against whole test files (`_test.go`) regardless of method/function signatures.
# Otherwise, only methods that take `*testing.T`, `*testing.B`, and `testing.TB` as arguments are checked.
# Default: false
all: true
issues:
# Maximum count of issues with the same text.
# Set to 0 to disable.
# Default: 3
max-same-issues: 50
exclude-rules:
- source: "(noinspection|TODO)"
linters: [ godot ]
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx
- wrapcheck
+24 -3
View File
@@ -1,14 +1,17 @@
# .goreleaser.yaml
project_name: filebrowser
version: 2
builds:
- ldflags:
- -s -w
# Build configuration for darwin and linux
- id: default
ldflags: &ldflags
- -s -w -X github.com/gtsteffaniak/filebrowser/version.Version={{ .Version }} -X github.com/gtsteffaniak/filebrowser/version.CommitSHA={{ .ShortCommit }}
main: main.go
binary: filebrowser
goos:
- darwin
- linux
- windows
goarch:
- amd64
- arm
@@ -16,7 +19,25 @@ builds:
goarm:
- 6
- 7
hooks:
post:
- upx {{ .Path }} # Compress the binary with UPX
# Build configuration for windows without arm
- id: windows
ldflags: *ldflags
main: main.go
binary: filebrowser
goos:
- windows
goarch:
- amd64
- arm64
archives:
- name_template: "{{.Os}}-{{.Arch}}{{if .Arm}}v{{.Arm}}{{end}}-{{ .ProjectName }}"
format: binary
checksum:
disable: true
+1 -1
View File
@@ -187,7 +187,7 @@ func (a *HookAuth) SaveUser() (*users.User, error) {
func (a *HookAuth) GetUser(d *users.User) *users.User {
// adds all permissions when user is admin
isAdmin := d.Perm.Admin
perms := users.Permissions{
perms := settings.Permissions{
Admin: isAdmin,
Execute: isAdmin || d.Perm.Execute,
Create: isAdmin || d.Perm.Create,
+15 -27
View File
@@ -5,49 +5,37 @@
? github.com/gtsteffaniak/filebrowser/auth [no test files]
? github.com/gtsteffaniak/filebrowser/cmd [no test files]
PASS
ok github.com/gtsteffaniak/filebrowser/diskcache 0.003s
ok github.com/gtsteffaniak/filebrowser/diskcache 0.004s
? github.com/gtsteffaniak/filebrowser/errors [no test files]
goos: linux
goarch: amd64
pkg: github.com/gtsteffaniak/filebrowser/files
cpu: 11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz
BenchmarkFillIndex-8 10 3587120 ns/op 273640 B/op 2013 allocs/op
BenchmarkSearchAllIndexes-8 10 31291180 ns/op 19500700 B/op 298636 allocs/op
BenchmarkFillIndex-8 10 3559830 ns/op 274639 B/op 2026 allocs/op
BenchmarkSearchAllIndexes-8 10 31912612 ns/op 20545741 B/op 312477 allocs/op
PASS
ok github.com/gtsteffaniak/filebrowser/files 0.408s
ok github.com/gtsteffaniak/filebrowser/files 0.417s
PASS
ok github.com/gtsteffaniak/filebrowser/fileutils 0.003s
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 h: 401 <nil>
2024/02/07 07:16:43 h: 401 <nil>
2024/02/07 07:16:43 h: 401 <nil>
2024/02/07 07:16:43 h: 401 <nil>
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 Saving new user: publicUser
2024/02/07 07:16:43 h: 401 <nil>
2024/02/07 07:16:43 h: 401 <nil>
ok github.com/gtsteffaniak/filebrowser/fileutils 0.002s
2024/08/27 16:16:13 h: 401 <nil>
2024/08/27 16:16:13 h: 401 <nil>
2024/08/27 16:16:13 h: 401 <nil>
2024/08/27 16:16:13 h: 401 <nil>
2024/08/27 16:16:13 h: 401 <nil>
2024/08/27 16:16:13 h: 401 <nil>
PASS
ok github.com/gtsteffaniak/filebrowser/http 0.202s
ok github.com/gtsteffaniak/filebrowser/http 0.100s
PASS
ok github.com/gtsteffaniak/filebrowser/img 0.125s
ok github.com/gtsteffaniak/filebrowser/img 0.124s
PASS
ok github.com/gtsteffaniak/filebrowser/rules 0.002s
PASS
ok github.com/gtsteffaniak/filebrowser/runner 0.003s
PASS
ok github.com/gtsteffaniak/filebrowser/settings 0.005s
ok github.com/gtsteffaniak/filebrowser/settings 0.004s
? github.com/gtsteffaniak/filebrowser/share [no test files]
? github.com/gtsteffaniak/filebrowser/storage [no test files]
? github.com/gtsteffaniak/filebrowser/storage/bolt [no test files]
PASS
ok github.com/gtsteffaniak/filebrowser/users 0.003s
ok github.com/gtsteffaniak/filebrowser/users 0.002s
? github.com/gtsteffaniak/filebrowser/version [no test files]
+4
View File
@@ -0,0 +1,4 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore
+48 -18
View File
@@ -13,9 +13,10 @@ import (
"strconv"
"syscall"
"embed"
"github.com/spf13/pflag"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/gtsteffaniak/filebrowser/auth"
@@ -25,8 +26,14 @@ import (
"github.com/gtsteffaniak/filebrowser/img"
"github.com/gtsteffaniak/filebrowser/settings"
"github.com/gtsteffaniak/filebrowser/users"
"github.com/gtsteffaniak/filebrowser/version"
)
//go:embed dist/*
var assets embed.FS
var nonEmbededFS = os.Getenv("FILEBROWSER_NO_EMBEDED") == "true"
type dirFS struct {
http.Dir
}
@@ -41,7 +48,8 @@ func init() {
// Bind the flags to the pflag command line parser
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
log.Println("Initializing with config file:", *configFlag)
log.Printf("Initializing FileBrowser Quantum (%v) with config file: %v \n", version.Version, *configFlag)
log.Println("Embeded Frontend:", !nonEmbededFS)
settings.Initialize(*configFlag)
}
@@ -56,13 +64,20 @@ var rootCmd = &cobra.Command{
log.Fatal("Image resize workers count could not be < 1")
}
imgSvc := img.New(serverConfig.NumImageProcessors)
var fileCache diskcache.Interface = diskcache.NewNoOp()
cacheDir := "/tmp"
var fileCache diskcache.Interface
// Use file cache if cacheDir is specified
if cacheDir != "" {
if err := os.MkdirAll(cacheDir, 0700); err != nil { //nolint:govet,gomnd
log.Fatalf("can't make directory %s: %s", cacheDir, err)
var err error
fileCache, err = diskcache.NewFileCache(cacheDir)
if err != nil {
log.Fatalf("failed to create file cache: %v", err)
}
fileCache = diskcache.New(afero.NewOsFs(), cacheDir)
} else {
// No-op cache if no cacheDir is specified
fileCache = diskcache.NewNoOp()
}
// initialize indexing and schedule indexing ever n minutes (default 5)
go files.InitializeIndex(serverConfig.IndexingInterval, serverConfig.Indexing)
@@ -93,15 +108,31 @@ var rootCmd = &cobra.Command{
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, syscall.SIGTERM)
go cleanupHandler(listener, sigc)
assetsFs := dirFS{Dir: http.Dir("frontend/dist")}
handler, err := fbhttp.NewHandler(imgSvc, fileCache, d.store, &serverConfig, assetsFs)
checkErr("fbhttp.NewHandler", err)
defer listener.Close()
log.Println("Listening on", listener.Addr().String())
//nolint: gosec
if err := http.Serve(listener, handler); err != nil {
log.Fatalf("Could not start server on port %d: %v", serverConfig.Port, err)
if !nonEmbededFS {
assetsFs, err := fs.Sub(assets, "dist")
if err != nil {
log.Fatal("Could not embed frontend. Does backend/cmd/dist exist? Must be built and exist first")
}
handler, err := fbhttp.NewHandler(imgSvc, fileCache, d.store, &serverConfig, assetsFs)
checkErr("fbhttp.NewHandler", err)
defer listener.Close()
log.Println("Listening on", listener.Addr().String())
//nolint: gosec
if err := http.Serve(listener, handler); err != nil {
log.Fatalf("Could not start server on port %d: %v", serverConfig.Port, err)
}
} else {
assetsFs := dirFS{Dir: http.Dir("frontend/dist")}
handler, err := fbhttp.NewHandler(imgSvc, fileCache, d.store, &serverConfig, assetsFs)
checkErr("fbhttp.NewHandler", err)
defer listener.Close()
log.Println("Listening on", listener.Addr().String())
//nolint: gosec
if err := http.Serve(listener, handler); err != nil {
log.Fatalf("Could not start server on port %d: %v", serverConfig.Port, err)
}
}
}, pythonConfig{allowNoDB: true}),
}
@@ -132,8 +163,7 @@ func quickSetup(d pythonData) {
checkErr("d.store.Settings.Save", err)
err = d.store.Settings.SaveServer(&settings.Config.Server)
checkErr("d.store.Settings.SaveServer", err)
user := &users.User{}
settings.Config.UserDefaults.Apply(user)
user := users.ApplyDefaults(users.User{})
user.Username = settings.Config.Auth.AdminUsername
user.Password = settings.Config.Auth.AdminPassword
user.Perm.Admin = true
@@ -141,7 +171,7 @@ func quickSetup(d pythonData) {
user.DarkMode = true
user.ViewMode = "normal"
user.LockPassword = false
user.Perm = users.Permissions{
user.Perm = settings.Permissions{
Create: true,
Rename: true,
Modify: true,
@@ -150,6 +180,6 @@ func quickSetup(d pythonData) {
Download: true,
Admin: true,
}
err = d.store.Users.Save(user)
err = d.store.Users.Save(&user)
checkErr("d.store.Users.Save", err)
}
-5
View File
@@ -67,11 +67,6 @@ func getUserIdentifier(flags *pflag.FlagSet) interface{} {
}
func printRules(rulez []rules.Rule, id interface{}) {
if id == nil {
fmt.Printf("Global Rules:\n\n")
} else {
fmt.Printf("Rules for user %v:\n\n", id)
}
for id, rule := range rulez {
fmt.Printf("(%d) ", id)
-5
View File
@@ -34,11 +34,6 @@ list or set it to 0.`,
err = unmarshal(args[0], &list)
checkErr("unmarshal", err)
for _, user := range list {
err = user.Clean("")
checkErr("Clean", err)
}
if mustGetBool(cmd.Flags(), "replace") {
oldUsers, err := d.store.Users.Gets("")
checkErr("d.store.Users.Gets", err)
+2 -2
View File
@@ -1,7 +1,7 @@
package cmd
import (
"fmt"
"log"
"github.com/spf13/cobra"
)
@@ -26,6 +26,6 @@ var usersRmCmd = &cobra.Command{
}
checkErr("usersRmCmd", err)
fmt.Println("user deleted successfully")
log.Println("user deleted successfully")
}, pythonConfig{}),
}
+1 -1
View File
@@ -16,6 +16,6 @@ var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("File Browser v" + version.Version + "/" + version.CommitSHA)
fmt.Println("File Browser " + version.Version + "/" + version.CommitSHA)
},
}
+19 -13
View File
@@ -10,13 +10,17 @@ import (
"os"
"path/filepath"
"sync"
"github.com/spf13/afero"
)
type FileCache struct {
fs afero.Fs
// Cache interface for caching operations
type Cache interface {
Get(key string) ([]byte, error)
Set(key string, value []byte) error
}
// FileCache struct for file-based caching
type FileCache struct {
dir string
// granular locks
scopedLocks struct {
sync.Mutex
@@ -25,10 +29,12 @@ type FileCache struct {
}
}
func New(fs afero.Fs, root string) *FileCache {
return &FileCache{
fs: afero.NewBasePathFs(fs, root),
// NewFileCache creates a new FileCache
func NewFileCache(dir string) (*FileCache, error) {
if err := os.MkdirAll(dir, 0700); err != nil {
return nil, fmt.Errorf("can't make directory %s: %v", dir, err)
}
return &FileCache{dir: dir}, nil
}
func (f *FileCache) Store(ctx context.Context, key string, value []byte) error {
@@ -37,11 +43,11 @@ func (f *FileCache) Store(ctx context.Context, key string, value []byte) error {
defer mu.Unlock()
fileName := f.getFileName(key)
if err := f.fs.MkdirAll(filepath.Dir(fileName), 0700); err != nil { //nolint:gomnd
if err := os.MkdirAll(filepath.Dir(fileName), 0700); err != nil {
return err
}
if err := afero.WriteFile(f.fs, fileName, value, 0700); err != nil { //nolint:gomnd
if err := os.WriteFile(fileName, value, 0600); err != nil {
return err
}
@@ -68,15 +74,15 @@ func (f *FileCache) Delete(ctx context.Context, key string) error {
defer mu.Unlock()
fileName := f.getFileName(key)
if err := f.fs.Remove(fileName); err != nil && !errors.Is(err, os.ErrNotExist) {
if err := os.Remove(fileName); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
func (f *FileCache) open(key string) (afero.File, bool, error) {
func (f *FileCache) open(key string) (*os.File, bool, error) {
fileName := f.getFileName(key)
file, err := f.fs.Open(fileName)
file, err := os.Open(fileName)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, false, nil
@@ -106,5 +112,5 @@ func (f *FileCache) getFileName(key string) string {
hasher := sha1.New() //nolint:gosec
_, _ = hasher.Write([]byte(key))
hash := hex.EncodeToString(hasher.Sum(nil))
return fmt.Sprintf("%s/%s/%s", hash[:1], hash[1:3], hash)
return filepath.Join(f.dir, fmt.Sprintf("%s/%s/%s", hash[:1], hash[1:3], hash))
}
+23 -11
View File
@@ -2,10 +2,10 @@ package diskcache
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
)
@@ -15,35 +15,39 @@ func TestFileCache(t *testing.T) {
key = "key"
value = "some text"
newValue = "new text"
cacheRoot = "/cache"
cacheRoot = "cache"
cachedFilePath = "a/62/a62f2225bf70bfaccbc7f1ef2a397836717377de"
)
fs := afero.NewMemMapFs()
cache := New(fs, "/cache")
// Create temporary directory for the cache
cacheDir, err := os.MkdirTemp("", cacheRoot)
require.NoError(t, err)
defer os.RemoveAll(cacheDir) // Clean up
cache, err := NewFileCache(cacheDir)
require.NoError(t, err)
// store new key
err := cache.Store(ctx, key, []byte(value))
err = cache.Store(ctx, key, []byte(value))
require.NoError(t, err)
checkValue(t, ctx, fs, filepath.Join(cacheRoot, cachedFilePath), cache, key, value)
checkValue(t, ctx, cache, filepath.Join(cacheDir, cachedFilePath), key, value)
// update existing key
err = cache.Store(ctx, key, []byte(newValue))
require.NoError(t, err)
checkValue(t, ctx, fs, filepath.Join(cacheRoot, cachedFilePath), cache, key, newValue)
checkValue(t, ctx, cache, filepath.Join(cacheDir, cachedFilePath), key, newValue)
// delete key
err = cache.Delete(ctx, key)
require.NoError(t, err)
exists, err := afero.Exists(fs, filepath.Join(cacheRoot, cachedFilePath))
require.NoError(t, err)
exists := fileExists(filepath.Join(cacheDir, cachedFilePath))
require.False(t, exists)
}
func checkValue(t *testing.T, ctx context.Context, fs afero.Fs, fileFullPath string, cache *FileCache, key, wantValue string) { //nolint:golint
func checkValue(t *testing.T, ctx context.Context, cache *FileCache, fileFullPath string, key, wantValue string) {
t.Helper()
// check actual file content
b, err := afero.ReadFile(fs, fileFullPath)
b, err := os.ReadFile(fileFullPath)
require.NoError(t, err)
require.Equal(t, wantValue, string(b))
@@ -53,3 +57,11 @@ func checkValue(t *testing.T, ctx context.Context, fs afero.Fs, fileFullPath str
require.True(t, ok)
require.Equal(t, wantValue, string(b))
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
+1 -1
View File
@@ -1,7 +1,7 @@
server:
port: 80
baseURL: "/"
root: "/srv"
root: "./srv"
auth:
method: password
signup: false
+205 -120
View File
@@ -1,26 +1,26 @@
package files
import (
"crypto/md5" //nolint:gosec
"crypto/sha1" //nolint:gosec
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"io"
"mime"
"net/http"
"os"
filepath "path/filepath"
"path/filepath"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/spf13/afero"
"github.com/gtsteffaniak/filebrowser/errors"
"github.com/gtsteffaniak/filebrowser/rules"
"github.com/gtsteffaniak/filebrowser/settings"
"github.com/gtsteffaniak/filebrowser/users"
)
@@ -33,7 +33,6 @@ var (
// FileInfo describes a file.
type FileInfo struct {
*Listing
Fs afero.Fs `json:"-"`
Path string `json:"path,omitempty"`
Name string `json:"name"`
Size int64 `json:"size"`
@@ -52,8 +51,8 @@ type FileInfo struct {
// FileOptions are the options when getting a file info.
type FileOptions struct {
Fs afero.Fs
Path string
Path string // realpath
IsDir bool
Modify bool
Expand bool
ReadHeader bool
@@ -85,13 +84,13 @@ func NewFileInfo(opts FileOptions) (*FileInfo, error) {
if !opts.Checker.Check(opts.Path) {
return nil, os.ErrPermission
}
file, err := stat(opts.Path, opts) // Pass opts.Path here
file, err := stat(opts)
if err != nil {
return nil, err
}
if opts.Expand {
if file.IsDir {
if err := file.readListing(opts.Path, opts.Checker, opts.ReadHeader); err != nil { //nolint:govet
if err = file.readListing(opts.Path, opts.Checker, opts.ReadHeader); err != nil {
return nil, err
}
return file, nil
@@ -103,7 +102,6 @@ func NewFileInfo(opts FileOptions) (*FileInfo, error) {
}
return file, err
}
func FileInfoFaster(opts FileOptions) (*FileInfo, error) {
// Lock access for the specific path
pathMutex := getMutex(opts.Path)
@@ -113,113 +111,83 @@ func FileInfoFaster(opts FileOptions) (*FileInfo, error) {
return nil, os.ErrPermission
}
index := GetIndex(rootPath)
trimmed := strings.TrimPrefix(opts.Path, "/")
if trimmed == "" {
trimmed = "/"
adjustedPath := index.makeIndexPath(opts.Path, opts.IsDir)
if opts.IsDir {
info, exists := index.GetMetadataInfo(adjustedPath)
if exists && !opts.Content {
// Let's not refresh if less than a second has passed
if time.Since(info.CacheTime) > time.Second {
go RefreshFileInfo(opts) //nolint:errcheck
}
// refresh cache after
return &info, nil
}
}
// don't bother caching content
if opts.Content {
file, err := NewFileInfo(opts)
return file, err
}
err := RefreshFileInfo(opts)
if err != nil {
file, err := NewFileInfo(opts)
return file, err
}
adjustedPath := makeIndexPath(trimmed, index.Root)
var info FileInfo
info, exists := index.GetMetadataInfo(adjustedPath)
if exists && !opts.Content {
// Check if the cache time is less than 1 second
if time.Since(info.CacheTime) > time.Second {
go RefreshFileInfo(opts)
}
// refresh cache after
return &info, nil
} else {
// don't bother caching content
if opts.Content {
file, err := NewFileInfo(opts)
return file, err
}
updated := RefreshFileInfo(opts)
if !updated {
file, err := NewFileInfo(opts)
return file, err
}
info, exists = index.GetMetadataInfo(adjustedPath)
if !exists || info.Name == "" {
return &FileInfo{}, errors.ErrEmptyKey
}
return &info, nil
if !exists || info.Name == "" {
return &FileInfo{}, errors.ErrEmptyKey
}
return &info, nil
}
func RefreshFileInfo(opts FileOptions) bool {
func RefreshFileInfo(opts FileOptions) error {
if !opts.Checker.Check(opts.Path) {
return false
return fmt.Errorf("permission denied: %s", opts.Path)
}
index := GetIndex(rootPath)
trimmed := strings.TrimPrefix(opts.Path, "/")
if trimmed == "" {
trimmed = "/"
}
adjustedPath := makeIndexPath(trimmed, index.Root)
file, err := stat(opts.Path, opts) // Pass opts.Path here
adjustedPath := index.makeIndexPath(opts.Path, opts.IsDir)
file, err := stat(opts)
if err != nil {
return false
return fmt.Errorf("File/folder does not exist to refresh data: %s", opts.Path)
}
_ = file.detectType(adjustedPath, true, opts.Content, opts.ReadHeader)
_ = file.detectType(opts.Path, true, opts.Content, opts.ReadHeader)
if file.IsDir {
err := file.readListing(opts.Path, opts.Checker, opts.ReadHeader)
if err != nil {
return false
return fmt.Errorf("Dir info could not be read: %s", opts.Path)
}
//_, exists := index.GetFileMetadata(adjustedPath)
return index.UpdateFileMetadata(adjustedPath, *file)
} else {
//_, exists := index.GetFileMetadata(adjustedPath)
return index.UpdateFileMetadata(adjustedPath, *file)
}
result := index.UpdateFileMetadata(adjustedPath, *file)
if !result {
return fmt.Errorf("File/folder does not exist in metadata: %s", adjustedPath)
}
return nil
}
func stat(path string, opts FileOptions) (*FileInfo, error) {
var file *FileInfo
if lstaterFs, ok := opts.Fs.(afero.Lstater); ok {
info, _, err := lstaterFs.LstatIfPossible(path)
if err == nil {
file = &FileInfo{
Fs: opts.Fs,
Path: opts.Path,
Name: info.Name(),
ModTime: info.ModTime(),
Mode: info.Mode(),
Size: info.Size(),
Extension: filepath.Ext(info.Name()),
Token: opts.Token,
}
if info.IsDir() {
file.IsDir = true
}
if info.Mode()&os.ModeSymlink != 0 {
file.IsSymlink = true
}
}
func stat(opts FileOptions) (*FileInfo, error) {
info, err := os.Lstat(opts.Path)
if err != nil {
return nil, err
}
if file == nil || file.IsSymlink {
info, err := opts.Fs.Stat(opts.Path)
if err != nil {
return nil, err
}
if file != nil && file.IsSymlink {
file.Size = info.Size()
file.IsDir = info.IsDir()
return file, nil
}
file = &FileInfo{
Fs: opts.Fs,
Path: opts.Path,
Name: info.Name(),
ModTime: info.ModTime(),
Mode: info.Mode(),
IsDir: info.IsDir(),
Size: info.Size(),
Extension: filepath.Ext(info.Name()),
Token: opts.Token,
file := &FileInfo{
Path: opts.Path,
Name: info.Name(),
ModTime: info.ModTime(),
Mode: info.Mode(),
Size: info.Size(),
Extension: filepath.Ext(info.Name()),
Token: opts.Token,
}
if info.IsDir() {
file.IsDir = true
}
if info.Mode()&os.ModeSymlink != 0 {
file.IsSymlink = true
targetInfo, err := os.Stat(opts.Path)
if err == nil {
file.Size = targetInfo.Size()
file.IsDir = targetInfo.IsDir()
}
}
@@ -237,7 +205,7 @@ func (i *FileInfo) Checksum(algo string) error {
i.Checksums = map[string]string{}
}
reader, err := i.Fs.Open(i.Path)
reader, err := os.Open(i.Path)
if err != nil {
return err
}
@@ -266,23 +234,120 @@ func (i *FileInfo) Checksum(algo string) error {
// RealPath gets the real path for the file, resolving symlinks if supported.
func (i *FileInfo) RealPath() string {
if realPathFs, ok := i.Fs.(interface {
RealPath(name string) (fPath string, err error)
}); ok {
realPath, err := realPathFs.RealPath(i.Path)
if err == nil {
return realPath
}
realPath, err := filepath.EvalSymlinks(i.Path)
if err == nil {
return realPath
}
return i.Path
}
func GetRealPath(relativePath ...string) (string, bool, error) {
combined := []string{settings.Config.Server.Root}
for _, path := range relativePath {
combined = append(combined, strings.TrimPrefix(path, settings.Config.Server.Root))
}
joinedPath := filepath.Join(combined...)
// Convert relative path to absolute path
absolutePath, err := filepath.Abs(joinedPath)
if err != nil {
return "", false, err
}
if !Exists(absolutePath) {
return absolutePath, false, nil // return without error
}
// Resolve symlinks and get the real path
return resolveSymlinks(absolutePath)
}
func DeleteFiles(absPath string, opts FileOptions) error {
err := os.RemoveAll(absPath)
if err != nil {
return err
}
opts.Path = filepath.Dir(absPath)
err = RefreshFileInfo(opts)
if err != nil {
return errors.ErrEmptyKey
}
return nil
}
func WriteDirectory(opts FileOptions) error {
// Ensure the parent directories exist
err := os.MkdirAll(opts.Path, 0775)
if err != nil {
return err
}
opts.Path = filepath.Dir(opts.Path)
err = RefreshFileInfo(opts)
if err != nil {
return errors.ErrEmptyKey
}
return nil
}
func WriteFile(opts FileOptions, in io.Reader) error {
dst := opts.Path
parentDir := filepath.Dir(dst)
// Split the directory from the destination path
dir := filepath.Dir(dst)
// Create the directory and all necessary parents
err := os.MkdirAll(dir, 0775)
if err != nil {
return err
}
return i.Path
// Open the file for writing (create if it doesn't exist, truncate if it does)
file, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0775)
if err != nil {
return err
}
defer file.Close()
// Copy the contents from the reader to the file
_, err = io.Copy(file, in)
if err != nil {
return err
}
opts.Path = parentDir
err = RefreshFileInfo(opts)
if err != nil {
return errors.ErrEmptyKey
}
return nil
}
// resolveSymlinks resolves symlinks in the given path
func resolveSymlinks(path string) (string, bool, error) {
for {
// Get the file info
info, err := os.Lstat(path)
if err != nil {
return "", false, err
}
// Check if it's a symlink
if info.Mode()&os.ModeSymlink != 0 {
// Read the symlink target
target, err := os.Readlink(path)
if err != nil {
return "", false, err
}
// Resolve the target relative to the symlink's directory
path = filepath.Join(filepath.Dir(path), target)
} else {
// Not a symlink, so return the resolved path and check if it's a directory
return path, info.IsDir(), nil
}
}
}
// addContent reads and sets content based on the file type.
func (i *FileInfo) addContent(path string) error {
if !i.IsDir {
afs := &afero.Afero{Fs: i.Fs}
content, err := afs.ReadFile(path)
content, err := os.ReadFile(path)
if err != nil {
return err
}
@@ -301,6 +366,9 @@ func (i *FileInfo) addContent(path string) error {
// detectType detects the file type.
func (i *FileInfo) detectType(path string, modify, saveContent, readHeader bool) error {
if i.IsDir {
return nil
}
if IsNamedPipe(i.Mode) {
i.Type = "blob"
if saveContent {
@@ -345,7 +413,6 @@ func (i *FileInfo) detectType(path string, modify, saveContent, readHeader bool)
}
}
}
if i.Type == "" {
i.Type = "blob"
if saveContent {
@@ -358,15 +425,15 @@ func (i *FileInfo) detectType(path string, modify, saveContent, readHeader bool)
// readFirstBytes reads the first bytes of the file.
func (i *FileInfo) readFirstBytes() []byte {
reader, err := i.Fs.Open(i.Path)
file, err := os.Open(i.Path)
if err != nil {
i.Type = "blob"
return nil
}
defer reader.Close()
defer file.Close()
buffer := make([]byte, 512) //nolint:gomnd
n, err := reader.Read(buffer)
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
i.Type = "blob"
return nil
@@ -387,7 +454,8 @@ func (i *FileInfo) detectSubtitles(parentDir string) {
// Directory must have been deleted, remove it from the index
return
}
// Read the directory contents
defer dir.Close() // Ensure directory handle is closed
files, err := dir.Readdir(-1)
if err != nil {
return
@@ -412,8 +480,13 @@ func (i *FileInfo) detectSubtitles(parentDir string) {
// readListing reads the contents of a directory and fills the listing.
func (i *FileInfo) readListing(path string, checker rules.Checker, readHeader bool) error {
afs := &afero.Afero{Fs: i.Fs}
dir, err := afs.ReadDir(i.Path)
dir, err := os.Open(i.Path)
if err != nil {
return err
}
defer dir.Close()
files, err := dir.Readdir(-1)
if err != nil {
return err
}
@@ -425,7 +498,7 @@ func (i *FileInfo) readListing(path string, checker rules.Checker, readHeader bo
NumFiles: 0,
}
for _, f := range dir {
for _, f := range files {
name := f.Name()
fPath := filepath.Join(i.Path, name)
@@ -436,7 +509,7 @@ func (i *FileInfo) readListing(path string, checker rules.Checker, readHeader bo
isSymlink, isInvalidLink := false, false
if IsSymlink(f.Mode()) {
isSymlink = true
info, err := i.Fs.Stat(fPath)
info, err := os.Stat(fPath)
if err == nil {
f = info
} else {
@@ -478,6 +551,7 @@ func (i *FileInfo) readListing(path string, checker rules.Checker, readHeader bo
i.Listing = listing
return nil
}
func IsNamedPipe(mode os.FileMode) bool {
return mode&os.ModeNamedPipe != 0
}
@@ -498,3 +572,14 @@ func getMutex(path string) *sync.Mutex {
return pathMutexes[path]
}
func Exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
+76
View File
@@ -0,0 +1,76 @@
package files
import (
"os"
"path/filepath"
"strings"
"testing"
)
func Test_GetRealPath(t *testing.T) {
cwd, err := os.Getwd()
if err != nil {
return
}
trimPrefix := filepath.Dir(filepath.Dir(cwd)) + "/"
tests := []struct {
name string
paths []string
want struct {
path string
isDir bool
}
}{
{
name: "current directory",
paths: []string{
"./",
},
want: struct {
path string
isDir bool
}{
path: "backend/files",
isDir: true,
},
},
{
name: "current directory",
paths: []string{
"./file.go",
},
want: struct {
path string
isDir bool
}{
path: "backend/files/file.go",
isDir: false,
},
},
{
name: "other test case",
paths: []string{
"/mnt/doesnt/exist",
},
want: struct {
path string
isDir bool
}{
path: "/mnt/doesnt/exist",
isDir: false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
realPath, isDir, err := GetRealPath(tt.paths...)
adjustedRealPath := strings.TrimPrefix(realPath, trimPrefix)
if tt.want.path != adjustedRealPath || tt.want.isDir != isDir {
t.Errorf("expected %v:%v but got: %v:%v", tt.want.path, tt.want.isDir, adjustedRealPath, isDir)
}
if err != nil {
t.Error("got error", err)
}
})
}
}
+15 -7
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
@@ -15,6 +16,7 @@ type Directory struct {
Metadata map[string]FileInfo
Files string
}
type File struct {
Name string
IsDir bool
@@ -80,8 +82,7 @@ func indexingScheduler(intervalMinutes uint32) {
// Define a function to recursively index files and directories
func (si *Index) indexFiles(path string) error {
// Check if the current directory has been modified since the last indexing
path = strings.TrimSuffix(path, "/")
adjustedPath := makeIndexPath(path, si.Root)
adjustedPath := si.makeIndexPath(path, true)
dir, err := os.Open(path)
if err != nil {
// Directory must have been deleted, remove it from the index
@@ -114,7 +115,7 @@ func (si *Index) indexFiles(path string) error {
}
func (si *Index) InsertFiles(path string) {
adjustedPath := makeIndexPath(path, si.Root)
adjustedPath := si.makeIndexPath(path, true)
subDirectory := Directory{}
buffer := bytes.Buffer{}
@@ -130,9 +131,9 @@ func (si *Index) InsertFiles(path string) {
}
func (si *Index) InsertDirs(path string) {
adjustedPath := makeIndexPath(path, si.Root)
for _, f := range si.GetQuickList() {
if f.IsDir {
adjustedPath := si.makeIndexPath(path, true)
if _, exists := si.Directories[adjustedPath]; exists {
si.UpdateCount("dirs")
// Add or update the directory in the map
@@ -154,14 +155,21 @@ func (si *Index) InsertDirs(path string) {
}
}
func makeIndexPath(path string, root string) string {
if path == root {
func (si *Index) makeIndexPath(subPath string, isDir bool) string {
if si.Root == subPath {
return "/"
}
adjustedPath := strings.TrimPrefix(path, root+"/")
// clean path
subPath = strings.TrimSuffix(subPath, "/")
// remove index prefix
adjustedPath := strings.TrimPrefix(subPath, si.Root)
// remove trailing slash
adjustedPath = strings.TrimSuffix(adjustedPath, "/")
// add leading slash for root of index
if adjustedPath == "" {
adjustedPath = "/"
} else if !isDir {
adjustedPath = filepath.Dir(adjustedPath)
}
return adjustedPath
}
+1 -1
View File
@@ -65,7 +65,7 @@ func (si *Index) Search(search string, scope string, sourceSession string) ([]st
if count > maxSearchResults {
break
}
fullName := pathName + file
fullName := strings.TrimLeft(pathName+file, "/")
fileTypes := map[string]bool{}
matches, fileType := containsSearchTerm(fullName, searchTerm, *searchOptions, isDir, fileTypes)
+6 -27
View File
@@ -8,30 +8,12 @@ import (
"github.com/gtsteffaniak/filebrowser/settings"
)
// GetFileMetadata retrieves the FileInfo from the specified directory in the index.
func (si *Index) GetFileMetadata(adjustedPath string) (FileInfo, bool) {
si.mu.RLock()
dir, exists := si.Directories[adjustedPath]
si.mu.RUnlock()
if exists {
// Initialize the Metadata map if it is nil
if dir.Metadata == nil {
dir.Metadata = make(map[string]FileInfo)
si.SetDirectoryInfo(adjustedPath, dir)
return FileInfo{}, false
} else {
return dir.Metadata[adjustedPath], true
}
}
return FileInfo{}, false
}
// UpdateFileMetadata updates the FileInfo for the specified directory in the index.
func (si *Index) UpdateFileMetadata(adjustedPath string, info FileInfo) bool {
si.mu.Lock()
defer si.mu.Unlock()
dir, exists := si.Directories[adjustedPath]
if !exists {
if !exists || exists && dir.Metadata == nil {
// Initialize the Metadata map if it is nil
if dir.Metadata == nil {
dir.Metadata = make(map[string]FileInfo)
@@ -45,7 +27,6 @@ func (si *Index) UpdateFileMetadata(adjustedPath string, info FileInfo) bool {
// SetFileMetadata sets the FileInfo for the specified directory in the index.
// internal use only
func (si *Index) SetFileMetadata(adjustedPath string, info FileInfo) bool {
_, exists := si.Directories[adjustedPath]
if !exists {
return false
@@ -57,6 +38,7 @@ func (si *Index) SetFileMetadata(adjustedPath string, info FileInfo) bool {
// GetMetadataInfo retrieves the FileInfo from the specified directory in the index.
func (si *Index) GetMetadataInfo(adjustedPath string) (FileInfo, bool) {
fi := FileInfo{}
si.mu.RLock()
dir, exists := si.Directories[adjustedPath]
si.mu.RUnlock()
@@ -65,11 +47,11 @@ func (si *Index) GetMetadataInfo(adjustedPath string) (FileInfo, bool) {
if dir.Metadata == nil {
dir.Metadata = make(map[string]FileInfo)
si.SetDirectoryInfo(adjustedPath, dir)
} else {
fi = dir.Metadata[adjustedPath]
}
info, metadataExists := dir.Metadata[adjustedPath]
return info, metadataExists
}
return FileInfo{}, false
return fi, exists
}
// SetDirectoryInfo sets the directory information in the index.
@@ -84,10 +66,7 @@ func (si *Index) GetDirectoryInfo(adjustedPath string) (Directory, bool) {
si.mu.RLock()
dir, exists := si.Directories[adjustedPath]
si.mu.RUnlock()
if exists {
return dir, true
}
return Directory{}, false
return dir, exists
}
func (si *Index) RemoveDirectory(path string) {
+220
View File
@@ -0,0 +1,220 @@
package files
import (
"io/fs"
"os"
"testing"
"time"
)
// Mock for fs.FileInfo
type mockFileInfo struct {
name string
isDir bool
}
func (m mockFileInfo) Name() string { return m.name }
func (m mockFileInfo) Size() int64 { return 0 }
func (m mockFileInfo) Mode() os.FileMode { return 0 }
func (m mockFileInfo) ModTime() time.Time { return time.Now() }
func (m mockFileInfo) IsDir() bool { return m.isDir }
func (m mockFileInfo) Sys() interface{} { return nil }
var testIndex Index
// Test for GetFileMetadata
//func TestGetFileMetadata(t *testing.T) {
// t.Parallel()
// tests := []struct {
// name string
// adjustedPath string
// fileName string
// expectedName string
// expectedExists bool
// }{
// {
// name: "testpath exists",
// adjustedPath: "/testpath",
// fileName: "testfile.txt",
// expectedName: "testfile.txt",
// expectedExists: true,
// },
// {
// name: "testpath not exists",
// adjustedPath: "/testpath",
// fileName: "nonexistent.txt",
// expectedName: "",
// expectedExists: false,
// },
// {
// name: "File exists in /anotherpath",
// adjustedPath: "/anotherpath",
// fileName: "afile.txt",
// expectedName: "afile.txt",
// expectedExists: true,
// },
// {
// name: "File does not exist in /anotherpath",
// adjustedPath: "/anotherpath",
// fileName: "nonexistentfile.txt",
// expectedName: "",
// expectedExists: false,
// },
// {
// name: "Directory does not exist",
// adjustedPath: "/nonexistentpath",
// fileName: "testfile.txt",
// expectedName: "",
// expectedExists: false,
// },
// }
//
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// fileInfo, exists := testIndex.GetFileMetadata(tt.adjustedPath)
// if exists != tt.expectedExists || fileInfo.Name != tt.expectedName {
// t.Errorf("expected %v:%v but got: %v:%v", tt.expectedName, tt.expectedExists, //fileInfo.Name, exists)
// }
// })
// }
//}
// Test for UpdateFileMetadata
func TestUpdateFileMetadata(t *testing.T) {
index := &Index{
Directories: map[string]Directory{
"/testpath": {
Metadata: map[string]FileInfo{
"testfile.txt": {Name: "testfile.txt"},
"anotherfile.txt": {Name: "anotherfile.txt"},
},
},
},
}
info := FileInfo{Name: "testfile.txt"}
success := index.UpdateFileMetadata("/testpath", info)
if !success {
t.Fatalf("expected UpdateFileMetadata to succeed")
}
dir, exists := index.Directories["/testpath"]
if !exists || dir.Metadata["testfile.txt"].Name != "testfile.txt" {
t.Fatalf("expected testfile.txt to be updated in the directory metadata")
}
}
// Test for GetDirMetadata
func TestGetDirMetadata(t *testing.T) {
t.Parallel()
_, exists := testIndex.GetMetadataInfo("/testpath")
if !exists {
t.Fatalf("expected GetDirMetadata to return initialized metadata map")
}
_, exists = testIndex.GetMetadataInfo("/nonexistent")
if exists {
t.Fatalf("expected GetDirMetadata to return false for nonexistent directory")
}
}
// Test for SetDirectoryInfo
func TestSetDirectoryInfo(t *testing.T) {
index := &Index{
Directories: map[string]Directory{
"/testpath": {
Metadata: map[string]FileInfo{
"testfile.txt": {Name: "testfile.txt"},
"anotherfile.txt": {Name: "anotherfile.txt"},
},
},
},
}
dir := Directory{Metadata: map[string]FileInfo{"testfile.txt": {Name: "testfile.txt"}}}
index.SetDirectoryInfo("/newPath", dir)
storedDir, exists := index.Directories["/newPath"]
if !exists || storedDir.Metadata["testfile.txt"].Name != "testfile.txt" {
t.Fatalf("expected SetDirectoryInfo to store directory info correctly")
}
}
// Test for GetDirectoryInfo
func TestGetDirectoryInfo(t *testing.T) {
t.Parallel()
dir, exists := testIndex.GetDirectoryInfo("/testpath")
if !exists || dir.Metadata["testfile.txt"].Name != "testfile.txt" {
t.Fatalf("expected GetDirectoryInfo to return correct directory info")
}
_, exists = testIndex.GetDirectoryInfo("/nonexistent")
if exists {
t.Fatalf("expected GetDirectoryInfo to return false for nonexistent directory")
}
}
// Test for RemoveDirectory
func TestRemoveDirectory(t *testing.T) {
index := &Index{
Directories: map[string]Directory{
"/testpath": {},
},
}
index.RemoveDirectory("/testpath")
_, exists := index.Directories["/testpath"]
if exists {
t.Fatalf("expected directory to be removed")
}
}
// Test for UpdateCount
func TestUpdateCount(t *testing.T) {
index := &Index{}
index.UpdateCount("files")
if index.NumFiles != 1 {
t.Fatalf("expected NumFiles to be 1 after UpdateCount('files')")
}
if index.NumFiles != 1 {
t.Fatalf("expected NumFiles to be 1 after UpdateCount('files')")
}
index.UpdateCount("dirs")
if index.NumDirs != 1 {
t.Fatalf("expected NumDirs to be 1 after UpdateCount('dirs')")
}
index.UpdateCount("unknown")
// Just ensure it does not panic or update any counters
if index.NumFiles != 1 || index.NumDirs != 1 {
t.Fatalf("expected counts to remain unchanged for unknown type")
}
index.resetCount()
if index.NumFiles != 0 || index.NumDirs != 0 || !index.inProgress {
t.Fatalf("expected resetCount to reset counts and set inProgress to true")
}
}
func init() {
testIndex = Index{
NumFiles: 10,
NumDirs: 5,
inProgress: false,
Directories: map[string]Directory{
"/testpath": {
Metadata: map[string]FileInfo{
"testfile.txt": {Name: "testfile.txt"},
"anotherfile.txt": {Name: "anotherfile.txt"},
},
},
"/anotherpath": {
Metadata: map[string]FileInfo{
"afile.txt": {Name: "afile.txt"},
},
},
},
}
files := []fs.FileInfo{
mockFileInfo{name: "file1.txt", isDir: false},
mockFileInfo{name: "dir1", isDir: true},
}
testIndex.UpdateQuickList(files)
}
+10 -10
View File
@@ -2,23 +2,23 @@ package fileutils
import (
"os"
"path"
"github.com/spf13/afero"
"path/filepath"
)
// Copy copies a file or folder from one place to another.
func Copy(fs afero.Fs, src, dst string) error {
if src = path.Clean("/" + src); src == "" {
func Copy(src, dst string) error {
src = filepath.Clean(src)
if src == "" {
return os.ErrNotExist
}
if dst = path.Clean("/" + dst); dst == "" {
dst = filepath.Clean(dst)
if dst == "" {
return os.ErrNotExist
}
if src == "/" || dst == "/" {
// Prohibit copying from or to the virtual root directory.
// Prohibit copying from or to the root directory.
return os.ErrInvalid
}
@@ -26,14 +26,14 @@ func Copy(fs afero.Fs, src, dst string) error {
return os.ErrInvalid
}
info, err := fs.Stat(src)
info, err := os.Stat(src)
if err != nil {
return err
}
if info.IsDir() {
return CopyDir(fs, src, dst)
return CopyDir(src, dst)
}
return CopyFile(fs, src, dst)
return CopyFile(src, dst)
}
+15 -10
View File
@@ -2,27 +2,32 @@ package fileutils
import (
"errors"
"github.com/spf13/afero"
"os"
"path/filepath"
)
// CopyDir copies a directory from source to dest and all
// of its sub-directories. It doesn't stop if it finds an error
// during the copy. Returns an error if any.
func CopyDir(fs afero.Fs, source, dest string) error {
func CopyDir(source, dest string) error {
// Get properties of source.
srcinfo, err := fs.Stat(source)
srcinfo, err := os.Stat(source)
if err != nil {
return err
}
// Create the destination directory.
err = fs.MkdirAll(dest, srcinfo.Mode())
err = os.MkdirAll(dest, srcinfo.Mode())
if err != nil {
return err
}
dir, _ := fs.Open(source)
dir, err := os.Open(source)
if err != nil {
return err
}
defer dir.Close()
obs, err := dir.Readdir(-1)
if err != nil {
return err
@@ -31,18 +36,18 @@ func CopyDir(fs afero.Fs, source, dest string) error {
var errs []error
for _, obj := range obs {
fsource := source + "/" + obj.Name()
fdest := dest + "/" + obj.Name()
fsource := filepath.Join(source, obj.Name())
fdest := filepath.Join(dest, obj.Name())
if obj.IsDir() {
// Create sub-directories, recursively.
err = CopyDir(fs, fsource, fdest)
err = CopyDir(fsource, fdest)
if err != nil {
errs = append(errs, err)
}
} else {
// Perform the file copy.
err = CopyFile(fs, fsource, fdest)
err = CopyFile(fsource, fdest)
if err != nil {
errs = append(errs, err)
}
+24 -38
View File
@@ -5,24 +5,22 @@ import (
"os"
"path"
"path/filepath"
"github.com/spf13/afero"
)
// MoveFile moves file from src to dst.
// By default the rename filesystem system call is used. If src and dst point to different volumes
// the file copy is used as a fallback
func MoveFile(fs afero.Fs, src, dst string) error {
if fs.Rename(src, dst) == nil {
// MoveFile moves a file from src to dst.
// By default, the rename system call is used. If src and dst point to different volumes,
// the file copy is used as a fallback.
func MoveFile(src, dst string) error {
if os.Rename(src, dst) == nil {
return nil
}
// fallback
err := CopyFile(fs, src, dst)
err := CopyFile(src, dst)
if err != nil {
_ = fs.Remove(dst)
_ = os.Remove(dst)
return err
}
if err := fs.Remove(src); err != nil {
if err := os.Remove(src); err != nil {
return err
}
return nil
@@ -30,23 +28,22 @@ func MoveFile(fs afero.Fs, src, dst string) error {
// CopyFile copies a file from source to dest and returns
// an error if any.
func CopyFile(fs afero.Fs, source, dest string) error {
func CopyFile(source, dest string) error {
// Open the source file.
src, err := fs.Open(source)
src, err := os.Open(source)
if err != nil {
return err
}
defer src.Close()
// Makes the directory needed to create the dst
// file.
err = fs.MkdirAll(filepath.Dir(dest), 0666) //nolint:gomnd
// Makes the directory needed to create the dst file.
err = os.MkdirAll(filepath.Dir(dest), 0775) //nolint:gomnd
if err != nil {
return err
}
// Create the destination file.
dst, err := fs.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0775) //nolint:gomnd
dst, err := os.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) //nolint:gomnd
if err != nil {
return err
}
@@ -58,12 +55,12 @@ func CopyFile(fs afero.Fs, source, dest string) error {
return err
}
// Copy the mode
info, err := fs.Stat(source)
// Copy the mode.
info, err := os.Stat(source)
if err != nil {
return err
}
err = fs.Chmod(dest, info.Mode())
err = os.Chmod(dest, info.Mode())
if err != nil {
return err
}
@@ -71,7 +68,7 @@ func CopyFile(fs afero.Fs, source, dest string) error {
return nil
}
// CommonPrefix returns common directory path of provided files
// CommonPrefix returns the common directory path of provided files.
func CommonPrefix(sep byte, paths ...string) string {
// Handle special cases.
switch len(paths) {
@@ -81,30 +78,19 @@ func CommonPrefix(sep byte, paths ...string) string {
return path.Clean(paths[0])
}
// Note, we treat string as []byte, not []rune as is often
// done in Go. (And sep as byte, not rune). This is because
// most/all supported OS' treat paths as string of non-zero
// bytes. A filename may be displayed as a sequence of Unicode
// runes (typically encoded as UTF-8) but paths are
// not required to be valid UTF-8 or in any normalized form
// (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
// file names.
// Treat string as []byte, not []rune as is often done in Go.
c := []byte(path.Clean(paths[0]))
// We add a trailing sep to handle the case where the
// common prefix directory is included in the path list
// (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
// path.Clean will have cleaned off trailing / separators with
// the exception of the root directory, "/" (in which case we
// make it "//", but this will get fixed up to "/" bellow).
// Add a trailing sep to handle the case where the common prefix directory
// is included in the path list.
c = append(c, sep)
// Ignore the first path since it's already in c
// Ignore the first path since it's already in c.
for _, v := range paths[1:] {
// Clean up each path before testing it
// Clean up each path before testing it.
v = path.Clean(v) + string(sep)
// Find the first non-common byte and truncate c
// Find the first non-common byte and truncate c.
if len(v) < len(c) {
c = c[:len(v)]
}
@@ -116,7 +102,7 @@ func CommonPrefix(sep byte, paths ...string) string {
}
}
// Remove trailing non-separator characters and the final separator
// Remove trailing non-separator characters and the final separator.
for i := len(c) - 1; i >= 0; i-- {
if c[i] == sep {
c = c[:i]
+10 -10
View File
@@ -1,13 +1,13 @@
module github.com/gtsteffaniak/filebrowser
go 1.22.0
go 1.22.5
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/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568
github.com/goccy/go-yaml v1.11.3
github.com/goccy/go-yaml v1.12.0
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/google/go-cmp v0.6.0
github.com/gorilla/mux v1.8.1
@@ -15,13 +15,13 @@ require (
github.com/mholt/archiver/v3 v3.5.1
github.com/shirou/gopsutil/v3 v3.24.5
github.com/spf13/afero v1.11.0
github.com/spf13/cobra v1.8.0
github.com/spf13/cobra v1.8.1
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.9.0
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce
golang.org/x/crypto v0.24.0
golang.org/x/image v0.17.0
golang.org/x/text v0.16.0
golang.org/x/crypto v0.26.0
golang.org/x/image v0.19.0
golang.org/x/text v0.17.0
)
require (
@@ -47,10 +47,10 @@ require (
github.com/ulikunitz/xz v0.5.12 // indirect
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.etcd.io/bbolt v1.3.10 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect
go.etcd.io/bbolt v1.3.11 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/xerrors v0.0.0-20240716161551-93cc26a95ae9 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+21 -21
View File
@@ -7,7 +7,7 @@ github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/asdine/storm/v3 v3.2.1 h1:I5AqhkPK6nBZ/qJXySdI7ot5BlXSZ7qvDY1zAn5ZJac=
github.com/asdine/storm/v3 v3.2.1/go.mod h1:LEpXwGt4pIqrE/XcTvCnZHT5MgZCV6Ub9q7yQzOFWr0=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
@@ -51,8 +51,8 @@ github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD87
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
github.com/goccy/go-yaml v1.11.3 h1:B3W9IdWbvrUu2OYQGwvU1nZtvMQJPBKgBUuweJjLj6I=
github.com/goccy/go-yaml v1.11.3/go.mod h1:wKnAMd44+9JAAnGQpWVEgBzGt3YuTaQ4uXoHvE4m7WU=
github.com/goccy/go-yaml v1.12.0 h1:/1WHjnMsI1dlIBQutrvSMGZRQufVO3asrHfTwfACoPM=
github.com/goccy/go-yaml v1.12.0/go.mod h1:wKnAMd44+9JAAnGQpWVEgBzGt3YuTaQ4uXoHvE4m7WU=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
@@ -116,8 +116,8 @@ github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/i
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
@@ -136,14 +136,14 @@ github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMx
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
go.etcd.io/bbolt v1.3.10 h1:+BqfJTcCzTItrop8mq/lbzL8wSGtj94UO/3U31shqG0=
go.etcd.io/bbolt v1.3.10/go.mod h1:bK3UQLPJZly7IlNmV7uVHJDxfe5aK9Ll93e/74Y9oEQ=
go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0=
go.etcd.io/bbolt v1.3.11/go.mod h1:dksAq7YMXoljX0xu6VF5DMZGbhYYoLUalEiSySYAS4I=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.17.0 h1:nTRVVdajgB8zCMZVsViyzhnMKPwYeroEERRC64JuLco=
golang.org/x/image v0.17.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
golang.org/x/image v0.19.0 h1:D9FX4QWkLfkeqaC62SonffIIuYdOk/UE2XKUBgRIBIQ=
golang.org/x/image v0.19.0/go.mod h1:y0zrRqlQRWQ5PXaYCOMLTW2fpsxZ8Qh9I/ohnInJEys=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20191105084925-a882066a44e0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@@ -151,10 +151,10 @@ golang.org/x/net v0.0.0-20200320220750-118fecf932d8/go.mod h1:z5CRVTTTmAJ677TzLL
golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
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=
@@ -167,18 +167,18 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/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.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU=
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
golang.org/x/xerrors v0.0.0-20240716161551-93cc26a95ae9 h1:LLhsEBxRTBLuKlQxFBYUOU8xyFgXv6cOTp2HASDlsDk=
golang.org/x/xerrors v0.0.0-20240716161551-93cc26a95ae9/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
Binary file not shown.
+5 -9
View File
@@ -2,7 +2,6 @@ package http
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
@@ -127,11 +126,10 @@ var signupHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int,
return http.StatusBadRequest, nil
}
user := &users.User{
Username: info.Username,
Password: info.Password,
}
settings.Config.UserDefaults.Apply(user)
user := users.ApplyDefaults(users.User{})
user.Username = info.Username
user.Password = info.Password
userHome, err := d.settings.MakeUserDir(user.Username, user.Scope, d.server.Root)
if err != nil {
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
@@ -139,8 +137,7 @@ var signupHandler = func(w http.ResponseWriter, r *http.Request, d *data) (int,
}
user.Scope = userHome
log.Printf("new user: %s, home dir: [%s].", user.Username, userHome)
settings.Config.UserDefaults.Apply(user)
err = d.store.Users.Save(user)
err = d.store.Users.Save(&user)
if err == errors.ErrExist {
return http.StatusConflict, err
} else if err != nil {
@@ -157,7 +154,6 @@ var renewHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data
func printToken(w http.ResponseWriter, _ *http.Request, d *data, user *users.User) (int, error) {
duration, err := time.ParseDuration(settings.Config.Auth.TokenExpirationTime)
if err != nil {
fmt.Println("Error parsing duration:", err)
duration = time.Hour * 2
}
claims := &authToken{
+2 -2
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
"os"
"github.com/gorilla/mux"
@@ -46,7 +47,6 @@ func previewHandler(imgSvc ImgService, fileCache FileCache, enableThumbnails, re
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: "/" + vars["path"],
Modify: d.user.Perm.Modify,
Expand: true,
@@ -110,7 +110,7 @@ func handleImagePreview(
func createPreview(imgSvc ImgService, fileCache FileCache,
file *files.FileInfo, previewSize PreviewSize) ([]byte, error) {
fd, err := file.Fs.Open(file.Path)
fd, err := os.Open(file.Path)
if err != nil {
return nil, err
}
+19 -21
View File
@@ -2,13 +2,12 @@ package http
import (
"errors"
"fmt"
"net/http"
"net/url"
"path"
"path/filepath"
"strings"
"github.com/spf13/afero"
"golang.org/x/crypto/bcrypt"
"github.com/gtsteffaniak/filebrowser/files"
@@ -25,26 +24,20 @@ var withHashFile = func(fn handleFunc) handleFunc {
return errToStatus(err), err
}
if link.Hash != "" {
status, err := authenticateShareRequest(r, link)
if status != 0 || err != nil {
var status int
status, err = authenticateShareRequest(r, link)
if err != nil || status != 0 {
return status, err
}
}
d.user = &users.PublicUser
if path == "/" {
path = link.Path
} else if strings.HasPrefix("/"+path, link.Path) {
path = "/" + path
} else {
path = link.Path + "/" + path
realPath, isDir, err := files.GetRealPath(d.user.Scope, link.Path, path)
if err != nil {
return http.StatusNotFound, err
}
sharePath := settings.Config.Server.Root + path
lastComponent := filepath.Base(sharePath)
basePath := filepath.Dir(sharePath)
fsPath := afero.NewBasePathFs(afero.NewOsFs(), basePath)
file, err := files.FileInfoFaster(files.FileOptions{
Fs: fsPath,
Path: lastComponent,
Path: realPath,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: true,
ReadHeader: d.server.TypeDetectionByHeader,
@@ -63,14 +56,15 @@ func ifPathWithName(r *http.Request) (id, filePath string) {
pathElements := strings.Split(r.URL.Path, "/")
id = pathElements[0]
allButFirst := path.Join(pathElements[1:]...)
if len(pathElements) == 1 {
allButFirst = "/"
}
return id, allButFirst
}
var publicShareHandler = withHashFile(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
file := d.raw.(*files.FileInfo)
file, ok := d.raw.(*files.FileInfo)
if !ok {
return http.StatusInternalServerError, fmt.Errorf("failed to assert type *files.FileInfo")
}
file.Path = strings.TrimPrefix(file.Path, settings.Config.Server.Root)
if file.IsDir {
return renderJSON(w, r, file)
@@ -86,7 +80,11 @@ var publicUserGetHandler = func(w http.ResponseWriter, r *http.Request, d *data)
}
var publicDlHandler = withHashFile(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
file := d.raw.(*files.FileInfo)
file, ok := d.raw.(*files.FileInfo)
if !ok {
return http.StatusInternalServerError, fmt.Errorf("failed to assert type *files.FileInfo")
}
if !file.IsDir {
return rawFileHandler(w, r, file)
}
-5
View File
@@ -8,7 +8,6 @@ import (
"testing"
"github.com/asdine/storm/v3"
"github.com/spf13/afero"
"github.com/gtsteffaniak/filebrowser/settings"
"github.com/gtsteffaniak/filebrowser/share"
@@ -92,7 +91,6 @@ func TestPublicShareHandlerAuthentication(t *testing.T) {
storage.Users = &customFSUser{
Store: storage.Users,
fs: &afero.MemMapFs{},
}
recorder := httptest.NewRecorder()
@@ -122,7 +120,6 @@ func newHTTPRequest(t *testing.T, requestModifiers ...func(*http.Request)) *http
type customFSUser struct {
users.Store
fs afero.Fs
}
func (cu *customFSUser) Get(baseScope string, id interface{}) (*users.User, error) {
@@ -130,7 +127,5 @@ func (cu *customFSUser) Get(baseScope string, id interface{}) (*users.User, erro
if err != nil {
return nil, err
}
user.Fs = cu.fs
return user, nil
}
+10 -6
View File
@@ -5,6 +5,7 @@ import (
"log"
"net/http"
"net/url"
"os"
gopath "path"
"path/filepath"
"strings"
@@ -80,10 +81,13 @@ var rawHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data)
if !d.user.Perm.Download {
return http.StatusAccepted, nil
}
realPath, isDir, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
return http.StatusInternalServerError, err
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: r.URL.Path,
Path: realPath,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: d.server.TypeDetectionByHeader,
@@ -108,7 +112,7 @@ func addFile(ar archiver.Writer, d *data, path, commonPath string) error {
if !d.Check(path) {
return nil
}
info, err := d.user.Fs.Stat(path)
info, err := os.Stat(path)
if err != nil {
return err
}
@@ -117,7 +121,7 @@ func addFile(ar archiver.Writer, d *data, path, commonPath string) error {
return nil
}
file, err := d.user.Fs.Open(path)
file, err := os.Open(path)
if err != nil {
return err
}
@@ -198,7 +202,7 @@ func rawDirHandler(w http.ResponseWriter, r *http.Request, d *data, file *files.
}
func rawFileHandler(w http.ResponseWriter, r *http.Request, file *files.FileInfo) (int, error) {
fd, err := file.Fs.Open(file.Path)
fd, err := os.Open(file.Path)
if err != nil {
return http.StatusInternalServerError, err
}
+74 -133
View File
@@ -3,7 +3,6 @@ package http
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
@@ -12,7 +11,6 @@ import (
"strings"
"github.com/shirou/gopsutil/v3/disk"
"github.com/spf13/afero"
"github.com/gtsteffaniak/filebrowser/errors"
"github.com/gtsteffaniak/filebrowser/files"
@@ -20,9 +18,13 @@ import (
)
var resourceGetHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
realPath, isDir, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
return http.StatusNotFound, err
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: r.URL.Path,
Path: realPath,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: true,
ReadHeader: d.server.TypeDetectionByHeader,
@@ -32,19 +34,16 @@ var resourceGetHandler = withUser(func(w http.ResponseWriter, r *http.Request, d
if err != nil {
return errToStatus(err), err
}
if file.IsDir {
file.Listing.Sorting = d.user.Sorting
return renderJSON(w, r, file)
}
if checksum := r.URL.Query().Get("checksum"); checksum != "" {
err := file.Checksum(checksum)
if err == errors.ErrInvalidOption {
return http.StatusBadRequest, nil
} else if err != nil {
return http.StatusInternalServerError, err
if !file.IsDir {
if checksum := r.URL.Query().Get("checksum"); checksum != "" {
err := file.Checksum(checksum)
if err == errors.ErrInvalidOption {
return http.StatusBadRequest, nil
} else if err != nil {
return http.StatusInternalServerError, err
}
}
}
return renderJSON(w, r, file)
})
@@ -53,15 +52,19 @@ func resourceDeleteHandler(fileCache FileCache) handleFunc {
if r.URL.Path == "/" || !d.user.Perm.Delete {
return http.StatusForbidden, nil
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: r.URL.Path,
realPath, isDir, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
return http.StatusNotFound, err
}
fileOpts := files.FileOptions{
Path: realPath,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: d.server.TypeDetectionByHeader,
Checker: d,
})
}
file, err := files.FileInfoFaster(fileOpts)
if err != nil {
return errToStatus(err), err
}
@@ -72,14 +75,10 @@ func resourceDeleteHandler(fileCache FileCache) handleFunc {
return errToStatus(err), err
}
err = d.RunHook(func() error {
return d.user.Fs.RemoveAll(r.URL.Path)
}, "delete", r.URL.Path, "", d.user)
err = files.DeleteFiles(realPath, fileOpts)
if err != nil {
return errToStatus(err), err
}
return http.StatusOK, nil
})
}
@@ -89,21 +88,27 @@ func resourcePostHandler(fileCache FileCache) handleFunc {
if !d.user.Perm.Create || !d.Check(r.URL.Path) {
return http.StatusForbidden, nil
}
// Directories creation on POST.
if strings.HasSuffix(r.URL.Path, "/") {
err := d.user.Fs.MkdirAll(r.URL.Path, 0775) //nolint:gomnd
return errToStatus(err), err
realPath, isDir, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
return http.StatusNotFound, err
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: r.URL.Path,
fileOpts := files.FileOptions{
Path: realPath,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: d.server.TypeDetectionByHeader,
Checker: d,
})
}
// Directories creation on POST.
if strings.HasSuffix(r.URL.Path, "/") {
err = files.WriteDirectory(fileOpts) // Assign to the existing `err` variable
if err != nil {
return errToStatus(err), err
}
return http.StatusOK, nil
}
file, err := files.FileInfoFaster(fileOpts)
if err == nil {
if r.URL.Query().Get("override") != "true" {
return http.StatusConflict, nil
@@ -119,22 +124,7 @@ func resourcePostHandler(fileCache FileCache) handleFunc {
return errToStatus(err), err
}
}
err = d.RunHook(func() error {
info, writeErr := writeFile(d.user.Fs, r.URL.Path, r.Body)
if writeErr != nil {
return writeErr
}
etag := fmt.Sprintf(`"%x%x"`, info.ModTime().UnixNano(), info.Size())
w.Header().Set("ETag", etag)
return nil
}, "upload", r.URL.Path, "", d.user)
if err != nil {
_ = d.user.Fs.RemoveAll(r.URL.Path)
}
err = files.WriteFile(fileOpts, r.Body)
return errToStatus(err), err
})
}
@@ -149,27 +139,23 @@ var resourcePutHandler = withUser(func(w http.ResponseWriter, r *http.Request, d
return http.StatusMethodNotAllowed, nil
}
exists, err := afero.Exists(d.user.Fs, r.URL.Path)
realPath, isDir, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
return http.StatusInternalServerError, err
return http.StatusNotFound, err
}
if !exists {
return http.StatusNotFound, nil
fileOpts := files.FileOptions{
Path: realPath,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: d.server.TypeDetectionByHeader,
Checker: d,
}
err = d.RunHook(func() error {
info, writeErr := writeFile(d.user.Fs, r.URL.Path, r.Body)
if writeErr != nil {
return writeErr
}
etag := fmt.Sprintf(`"%x%x"`, info.ModTime().UnixNano(), info.Size())
w.Header().Set("ETag", etag)
return nil
}, "save", r.URL.Path, "", d.user)
err = files.WriteFile(fileOpts, r.Body)
return errToStatus(err), err
})
// TODO fix and verify this function still works in tests
func resourcePatchHandler(fileCache FileCache) handleFunc {
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
src := r.URL.Path
@@ -185,28 +171,20 @@ func resourcePatchHandler(fileCache FileCache) handleFunc {
if dst == "/" || src == "/" {
return http.StatusForbidden, nil
}
err = checkParent(src, dst)
if err != nil {
return http.StatusBadRequest, err
}
override := r.URL.Query().Get("override") == "true"
rename := r.URL.Query().Get("rename") == "true"
if !override && !rename {
if _, err = d.user.Fs.Stat(dst); err == nil {
if _, err = os.Stat(dst); err == nil {
return http.StatusConflict, nil
}
}
if rename {
dst = addVersionSuffix(dst, d.user.Fs)
dst = addVersionSuffix(dst)
}
// Permission for overwriting the file
if override && !d.user.Perm.Modify {
return http.StatusForbidden, nil
}
err = d.RunHook(func() error {
return patchAction(r.Context(), action, src, dst, d, fileCache)
}, action, src, dst, d.user)
@@ -215,69 +193,22 @@ func resourcePatchHandler(fileCache FileCache) handleFunc {
})
}
func checkParent(src, dst string) error {
rel, err := filepath.Rel(src, dst)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
if !strings.HasPrefix(rel, "../") && rel != ".." && rel != "." {
return errors.ErrSourceIsParent
}
return nil
}
func addVersionSuffix(source string, fs afero.Fs) string {
func addVersionSuffix(source string) string {
counter := 1
dir, name := path.Split(source)
ext := filepath.Ext(name)
base := strings.TrimSuffix(name, ext)
for {
if _, err := fs.Stat(source); err != nil {
if _, err := os.Stat(source); err != nil {
break
}
renamed := fmt.Sprintf("%s(%d)%s", base, counter, ext)
source = path.Join(dir, renamed)
counter++
}
return source
}
func writeFile(fs afero.Fs, dst string, in io.Reader) (os.FileInfo, error) {
dir, _ := path.Split(dst)
err := fs.MkdirAll(dir, 0775) //nolint:gomnd
if err != nil {
return nil, err
}
file, err := fs.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0775) //nolint:gomnd
if err != nil {
return nil, err
}
defer file.Close()
_, err = io.Copy(file, in)
if err != nil {
return nil, err
}
// Gets the info about the file.
info, err := file.Stat()
if err != nil {
return nil, err
}
//files.RefreshFileInfo(files.FileOptions{
// Fs: info,
//})
return info, nil
}
func delThumbs(ctx context.Context, fileCache FileCache, file *files.FileInfo) error {
for _, previewSizeName := range PreviewSizeNames() {
size, _ := ParsePreviewSize(previewSizeName)
@@ -297,17 +228,24 @@ func patchAction(ctx context.Context, action, src, dst string, d *data, fileCach
return errors.ErrPermissionDenied
}
return fileutils.Copy(d.user.Fs, src, dst)
return fileutils.Copy(src, dst)
case "rename":
if !d.user.Perm.Rename {
return errors.ErrPermissionDenied
}
src = path.Clean("/" + src)
dst = path.Clean("/" + dst)
realDest, _, err := files.GetRealPath(d.user.Scope, dst)
if err != nil {
return err
}
realSrc, isDir, err := files.GetRealPath(d.user.Scope, src)
if err != nil {
return err
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: src,
Path: realSrc,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: false,
@@ -323,7 +261,7 @@ func patchAction(ctx context.Context, action, src, dst string, d *data, fileCach
return err
}
return fileutils.MoveFile(d.user.Fs, src, dst)
return fileutils.MoveFile(realSrc, realDest)
default:
return fmt.Errorf("unsupported action %s: %w", action, errors.ErrInvalidRequestParams)
}
@@ -335,9 +273,13 @@ type DiskUsageResponse struct {
}
var diskUsage = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
realPath, isDir, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
return http.StatusNotFound, err
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: r.URL.Path,
Path: realPath,
IsDir: isDir,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: false,
@@ -353,7 +295,6 @@ var diskUsage = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (
Used: 0,
})
}
usage, err := disk.UsageWithContext(r.Context(), fPath)
if err != nil {
return errToStatus(err), err
+4 -8
View File
@@ -15,20 +15,17 @@ type settingsData struct {
Defaults settings.UserDefaults `json:"defaults"`
Rules []rules.Rule `json:"rules"`
Frontend settings.Frontend `json:"frontend"`
Shell []string `json:"shell"`
Commands map[string][]string `json:"commands"`
}
var settingsGetHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
data := &settingsData{
Signup: settings.Config.Auth.Signup,
CreateUserDir: settings.Config.Server.CreateUserDir,
UserHomeBasePath: settings.Config.Server.UserHomeBasePath,
Signup: d.settings.Auth.Signup,
CreateUserDir: d.settings.Server.CreateUserDir,
UserHomeBasePath: d.settings.Server.UserHomeBasePath,
Defaults: d.settings.UserDefaults,
Rules: d.settings.Rules,
Frontend: d.settings.Frontend,
Shell: d.settings.Shell,
Commands: d.settings.Commands,
}
return renderJSON(w, r, data)
@@ -46,8 +43,7 @@ var settingsPutHandler = withAdmin(func(w http.ResponseWriter, r *http.Request,
d.settings.UserDefaults = req.Defaults
d.settings.Rules = req.Rules
d.settings.Frontend = req.Frontend
d.settings.Shell = req.Shell
d.settings.Commands = req.Commands
d.settings.Auth.Signup = req.Signup
err = d.store.Settings.Save(d.settings)
return errToStatus(err), err
})
+7 -1
View File
@@ -34,6 +34,7 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
"Color": d.settings.Frontend.Color,
"BaseURL": d.server.BaseURL,
"Version": version.Version,
"CommitSHA": version.CommitSHA,
"StaticURL": path.Join(d.server.BaseURL, "/static"),
"Signup": settings.Config.Auth.Signup,
"NoAuth": d.settings.Auth.Method == "noauth",
@@ -64,7 +65,12 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
if err != nil {
return http.StatusInternalServerError, err
}
auther := raw.(*auth.JSONAuth)
auther, ok := raw.(*auth.JSONAuth)
if !ok {
return http.StatusInternalServerError, fmt.Errorf("failed to assert type *auth.JSONAuth")
}
if auther.ReCaptcha != nil {
data["ReCaptcha"] = auther.ReCaptcha.Key != "" && auther.ReCaptcha.Secret != ""
data["ReCaptchaHost"] = auther.ReCaptcha.Host
+17 -4
View File
@@ -13,6 +13,7 @@ import (
"golang.org/x/text/language"
"github.com/gtsteffaniak/filebrowser/errors"
"github.com/gtsteffaniak/filebrowser/files"
"github.com/gtsteffaniak/filebrowser/users"
)
@@ -129,15 +130,21 @@ var userPostHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *
return http.StatusBadRequest, errors.ErrEmptyPassword
}
newUser := users.ApplyDefaults(*req.Data)
userHome, err := d.settings.MakeUserDir(req.Data.Username, req.Data.Scope, d.server.Root)
if err != nil {
log.Printf("create user: failed to mkdir user home dir: [%s]", userHome)
return http.StatusInternalServerError, err
}
req.Data.Scope = userHome
newUser.Scope = userHome
log.Printf("user: %s, home dir: [%s].", req.Data.Username, userHome)
err = d.store.Users.Save(req.Data)
_, _, err = files.GetRealPath(d.server.Root, req.Data.Scope)
if err != nil {
log.Println("user path is not valid", req.Data.Scope)
return http.StatusBadRequest, nil
}
err = d.store.Users.Save(&newUser)
if err != nil {
return http.StatusInternalServerError, err
}
@@ -155,6 +162,10 @@ var userPutHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request
if req.Data.ID != d.raw.(uint) {
return http.StatusBadRequest, nil
}
_, _, err = files.GetRealPath(d.server.Root, req.Data.Scope)
if err != nil {
return http.StatusBadRequest, nil
}
if len(req.Which) == 0 || req.Which[0] == "all" {
req.Which = []string{}
@@ -165,7 +176,9 @@ var userPutHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.Name != "Password" && field.Name != "Fs" {
if field.Name == "Password" && req.Data.Password != "" {
req.Which = append(req.Which, field.Name)
} else if field.Name != "Password" && field.Name != "Fs" {
req.Which = append(req.Which, field.Name)
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ checkExit() {
if command -v go &> /dev/null
then
printf "\n == Running tests == \n"
go test -race -v ./...
go test -race -parallel -v ./...
checkExit
else
echo "ERROR: unable to perform tests"
+3 -2
View File
@@ -7,6 +7,7 @@ import (
"os/exec"
"strings"
"github.com/gtsteffaniak/filebrowser/files"
"github.com/gtsteffaniak/filebrowser/settings"
"github.com/gtsteffaniak/filebrowser/users"
)
@@ -19,8 +20,8 @@ type Runner struct {
// RunHook runs the hooks for the before and after event.
func (r *Runner) RunHook(fn func() error, evt, path, dst string, user *users.User) error {
path = user.FullPath(path)
dst = user.FullPath(dst)
path, _, _ = files.GetRealPath(user.Scope, path)
dst, _, _ = files.GetRealPath(user.Scope, dst)
if r.Enabled {
if val, ok := r.Commands["before_"+evt]; ok {
+13 -20
View File
@@ -3,10 +3,9 @@ package settings
import (
"log"
"os"
"strings"
"path/filepath"
"github.com/goccy/go-yaml"
"github.com/gtsteffaniak/filebrowser/users"
)
var Config Settings
@@ -19,7 +18,16 @@ func Initialize(configFile string) {
log.Fatalf("Error unmarshaling YAML data: %v", err)
}
Config.UserDefaults.Perm = Config.UserDefaults.Permissions
Config.Server.Root = strings.TrimSuffix(Config.Server.Root, "/")
// Convert relative path to absolute path
realRoot, err := filepath.Abs(Config.Server.Root)
if err != nil {
log.Fatalf("Error getting root path: %v", err)
}
_, err = os.Stat(realRoot)
if err != nil {
log.Fatalf("ERROR: Configured Root Path does not exist! %v", err)
}
Config.Server.Root = realRoot
}
func loadConfigFile(configFile string) []byte {
@@ -77,8 +85,9 @@ func setDefaults() Settings {
HideDotfiles: true,
DarkMode: false,
DisableSettings: false,
ViewMode: "normal",
Locale: "en",
Permissions: users.Permissions{
Permissions: Permissions{
Create: false,
Rename: false,
Modify: false,
@@ -90,19 +99,3 @@ func setDefaults() Settings {
},
}
}
// Apply applies the default options to a user.
func (d *UserDefaults) Apply(u *users.User) {
u.StickySidebar = d.StickySidebar
u.DisableSettings = d.DisableSettings
u.DarkMode = d.DarkMode
u.Scope = d.Scope
u.Locale = d.Locale
u.ViewMode = d.ViewMode
u.SingleClick = d.SingleClick
u.Perm = d.Perm
u.Sorting = d.Sorting
u.Commands = d.Commands
u.HideDotfiles = d.HideDotfiles
u.DateFormat = d.DateFormat
}
+4 -6
View File
@@ -6,16 +6,14 @@ import (
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/spf13/afero"
)
var (
invalidFilenameChars = regexp.MustCompile(`[^0-9A-Za-z@_\-.]`)
dashes = regexp.MustCompile(`[\-]+`)
dashes = regexp.MustCompile(`[\-]+`)
)
// MakeUserDir makes the user directory according to settings.
@@ -32,8 +30,8 @@ func (s *Settings) MakeUserDir(username, userScope, serverRoot string) (string,
userScope = path.Join("/", userScope)
fs := afero.NewBasePathFs(afero.NewOsFs(), serverRoot)
if err := fs.MkdirAll(userScope, os.ModePerm); err != nil {
fullPath := filepath.Join(serverRoot, userScope)
if err := os.MkdirAll(fullPath, os.ModePerm); err != nil {
return "", fmt.Errorf("failed to create user home dir: [%s]: %w", userScope, err)
}
return userScope, nil
-4
View File
@@ -65,10 +65,6 @@ func (s *Storage) Save(set *Settings) error {
set.Rules = []rules.Rule{}
}
if set.Shell == nil {
set.Shell = []string{}
}
if set.Commands == nil {
set.Commands = map[string][]string{}
}
+17 -6
View File
@@ -2,7 +2,6 @@ package settings
import (
"github.com/gtsteffaniak/filebrowser/rules"
"github.com/gtsteffaniak/filebrowser/users"
)
type Settings struct {
@@ -75,15 +74,27 @@ type UserDefaults struct {
Scope string `json:"scope"`
Locale string `json:"locale"`
ViewMode string `json:"viewMode"`
GallerySize int `json:"gallerySize"`
SingleClick bool `json:"singleClick"`
Rules []rules.Rule `json:"rules"`
Sorting struct {
By string `json:"by"`
Asc bool `json:"asc"`
} `json:"sorting"`
Perm users.Permissions `json:"perm"`
Permissions users.Permissions `json:"permissions"`
Commands []string `json:"commands,omitempty"`
HideDotfiles bool `json:"hideDotfiles"`
DateFormat bool `json:"dateFormat"`
Perm Permissions `json:"perm"`
Permissions Permissions `json:"permissions"`
Commands []string `json:"commands,omitempty"`
HideDotfiles bool `json:"hideDotfiles"`
DateFormat bool `json:"dateFormat"`
}
type Permissions struct {
Admin bool `json:"admin"`
Execute bool `json:"execute"`
Create bool `json:"create"`
Rename bool `json:"rename"`
Modify bool `json:"modify"`
Delete bool `json:"delete"`
Share bool `json:"share"`
Download bool `json:"download"`
}
+1 -21
View File
@@ -1,7 +1,6 @@
package users
import (
"log"
"sync"
"time"
@@ -54,9 +53,6 @@ func (s *Storage) Get(baseScope string, id interface{}) (user *User, err error)
if err != nil {
return
}
if err := user.Clean(baseScope); err != nil {
return nil, err
}
return user, err
}
@@ -66,23 +62,12 @@ func (s *Storage) Gets(baseScope string) ([]*User, error) {
if err != nil {
return nil, err
}
for _, user := range users {
if err := user.Clean(baseScope); err != nil { //nolint:govet
return nil, err
}
}
return users, err
}
// Update updates a user in the database.
func (s *Storage) Update(user *User, fields ...string) error {
err := user.Clean("")
if err != nil {
return err
}
err = s.back.Update(user, fields...)
err := s.back.Update(user, fields...)
if err != nil {
return err
}
@@ -137,11 +122,6 @@ func (s *Storage) DeleteRule(userID string, ruleID string) error {
// Save saves the user in a storage.
func (s *Storage) Save(user *User) error {
log.Println("Saving new user:", user.Username)
if err := user.Clean(""); err != nil {
return err
}
return s.back.Save(user)
}
+37 -54
View File
@@ -1,25 +1,12 @@
package users
import (
"path/filepath"
"regexp"
"github.com/spf13/afero"
"github.com/gtsteffaniak/filebrowser/rules"
"github.com/gtsteffaniak/filebrowser/settings"
)
type Permissions struct {
Admin bool `json:"admin"`
Execute bool `json:"execute"`
Create bool `json:"create"`
Rename bool `json:"rename"`
Modify bool `json:"modify"`
Delete bool `json:"delete"`
Share bool `json:"share"`
Download bool `json:"download"`
}
// SortingSettings represents the sorting settings.
type Sorting struct {
By string `json:"by"`
@@ -28,24 +15,24 @@ type Sorting struct {
// User describes a user.
type User struct {
StickySidebar bool `json:"stickySidebar"`
DarkMode bool `json:"darkMode"`
DisableSettings bool `json:"disableSettings"`
ID uint `storm:"id,increment" json:"id"`
Username string `storm:"unique" json:"username"`
Password string `json:"password"`
Scope string `json:"scope"`
Locale string `json:"locale"`
LockPassword bool `json:"lockPassword"`
ViewMode string `json:"viewMode"`
SingleClick bool `json:"singleClick"`
Perm Permissions `json:"perm"`
Commands []string `json:"commands"`
Sorting Sorting `json:"sorting"`
Fs afero.Fs `json:"-" yaml:"-"`
Rules []rules.Rule `json:"rules"`
HideDotfiles bool `json:"hideDotfiles"`
DateFormat bool `json:"dateFormat"`
StickySidebar bool `json:"stickySidebar"`
DarkMode bool `json:"darkMode"`
DisableSettings bool `json:"disableSettings"`
ID uint `storm:"id,increment" json:"id"`
Username string `storm:"unique" json:"username"`
Password string `json:"password"`
Scope string `json:"scope"`
Locale string `json:"locale"`
LockPassword bool `json:"lockPassword"`
ViewMode string `json:"viewMode"`
SingleClick bool `json:"singleClick"`
Perm settings.Permissions `json:"perm"`
Commands []string `json:"commands"`
Sorting Sorting `json:"sorting"`
Rules []rules.Rule `json:"rules"`
HideDotfiles bool `json:"hideDotfiles"`
DateFormat bool `json:"dateFormat"`
GallerySize int `json:"gallerySize"`
}
var PublicUser = User{
@@ -54,8 +41,7 @@ var PublicUser = User{
Scope: "./",
ViewMode: "normal",
LockPassword: true,
Fs: afero.NewMemMapFs(),
Perm: Permissions{
Perm: settings.Permissions{
Create: false,
Rename: false,
Modify: false,
@@ -71,26 +57,6 @@ func (u *User) GetRules() []rules.Rule {
return u.Rules
}
// Clean cleans up a user and verifies if all its fields
// are alright to be saved.
//
//nolint:gocyclo
func (u *User) Clean(baseScope string) error {
if u.Fs == nil {
scope := u.Scope
scope = filepath.Join(baseScope, filepath.Join("/", scope)) //nolint:gocritic
u.Fs = afero.NewBasePathFs(afero.NewOsFs(), scope)
}
return nil
}
// FullPath gets the full path for a user's relative path.
func (u *User) FullPath(path string) string {
return afero.FullBaseFsPath(u.Fs.(*afero.BasePathFs), path)
}
// CanExecute checks if an user can execute a specific command.
func (u *User) CanExecute(command string) bool {
if !u.Perm.Execute {
@@ -105,3 +71,20 @@ func (u *User) CanExecute(command string) bool {
return false
}
// Apply applies the default options to a user.
func ApplyDefaults(u User) User {
u.StickySidebar = settings.Config.UserDefaults.StickySidebar
u.DisableSettings = settings.Config.UserDefaults.DisableSettings
u.DarkMode = settings.Config.UserDefaults.DarkMode
u.Scope = settings.Config.UserDefaults.Scope
u.Locale = settings.Config.UserDefaults.Locale
u.ViewMode = settings.Config.UserDefaults.ViewMode
u.SingleClick = settings.Config.UserDefaults.SingleClick
u.Perm = settings.Config.UserDefaults.Perm
u.Sorting = settings.Config.UserDefaults.Sorting
u.Commands = settings.Config.UserDefaults.Commands
u.HideDotfiles = settings.Config.UserDefaults.HideDotfiles
u.DateFormat = settings.Config.UserDefaults.DateFormat
return u
}
+3 -4
View File
@@ -1,8 +1,7 @@
package version
var (
// Version is the current File Browser version.
Version = "(0.2.7)"
// CommitSHA is the commmit sha.
CommitSHA = "(unknown)"
// Dynamically updated during build via build args
Version = "untracked"
CommitSHA = "untracked"
)
-8
View File
@@ -35,9 +35,7 @@ auth:
tokenExpirationTime: 2h
header: ""
method: json
command: ""
signup: false
shell: ""
frontend:
name: ""
disableExternal: false
@@ -63,7 +61,6 @@ userDefaults:
delete: true
share: true
download: true
commands: []
hideDotfiles: false
dateFormat: false
```
@@ -165,10 +162,6 @@ userDefaults:
- `oath` - oath authentication
- `noauth` - no authentication/login required.
- `command`: Deprecated: This is the authentication command.
- `shell`: This is the shell configuration.
- `Signup`: This boolean value indicates whether user signup is enabled on the login page. NOTE: Be mindful of `userDefaults` settings if enabled. Default: `false`
- `AdminUsername`: This is the username of the admin user. Default: `admin`
@@ -227,7 +220,6 @@ userDefaults:
- `download`: This boolean value determines whether download permissions are granted.
- `commands`: Deprecated: This is a list of commands.
- `hideDotfiles`: This boolean value determines whether dotfiles are hidden. (`true` or `false`)
+1
View File
@@ -0,0 +1 @@
frontend
+4 -2
View File
@@ -9,13 +9,14 @@
},
"scripts": {
"dev": "vite dev",
"build": "vite build",
"build": "vite build && cp -R dist/ ../backend/cmd/",
"build-docker": "vite build",
"watch": "vite build --watch",
"typecheck": "vue-tsc -p ./tsconfig.json --noEmit",
"lint": "npm run typecheck && eslint src/",
"lint:fix": "eslint --fix src/",
"format": "prettier --write .",
"test": "playwright test"
"test": "npx playwright test"
},
"dependencies": {
"ace-builds": "^1.24.2",
@@ -31,6 +32,7 @@
"vue-router": "^4.3.0"
},
"devDependencies": {
"@playwright/test": "^1.42.1",
"@intlify/unplugin-vue-i18n": "^4.0.0",
"@vitejs/plugin-vue": "^5.0.4",
"@vue/eslint-config-typescript": "^13.0.0",
+43
View File
@@ -0,0 +1,43 @@
import { defineConfig, devices } from "@playwright/test";
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: "./tests",
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: "line",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: "http://127.0.0.1",
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
/* Set default locale to English (US) */
locale: "en-US",
},
/* Configure projects for major browsers */
projects: [
{
name: "firefox",
use: { ...devices["Desktop Firefox"] },
},
],
});
+3 -3
View File
@@ -9,7 +9,7 @@
<script src="[{[ .ReCaptchaHost ]}]/recaptcha/api.js?render=explicit" data-vite-ignore></script>
[{[ end ]}]
<title>[{[ if .Name -]}][{[ .Name ]}][{[ else ]}]File Browser[{[ end ]}]</title>
<title>[{[ if .Name -]}][{[ .Name ]}][{[ else ]}]FileBrowser Quantum[{[ end ]}]</title>
<link rel="icon" type="image/png" sizes="256x256" href="[{[ .StaticURL ]}]/img/icons/favicon-256x256.png">
@@ -33,8 +33,8 @@
var fullStaticURL = window.location.origin + window.FileBrowser.StaticURL;
var dynamicManifest = {
"name": window.FileBrowser.Name || 'File Browser',
"short_name": window.FileBrowser.Name || 'File Browser',
"name": window.FileBrowser.Name || 'FileBrowser Quantum',
"short_name": window.FileBrowser.Name || 'FileBrowser',
"icons": [
{
"src": fullStaticURL + "/img/icons/android-chrome-256x256.png",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "File Browser",
"short_name": "File Browser",
"name": "FileBrowser",
"short_name": "FileBrowser",
"icons": [
{
"src": "./img/icons/android-chrome-192x192.png",
+5 -4
View File
@@ -3,17 +3,18 @@
</template>
<script>
import { onMounted } from 'vue';
import { onMounted } from "vue";
import { mutations } from "@/store"; // Import your store's mutations
mutations.setLoading("main-app", true);
export default {
name: "app",
computed: {},
setup() {
onMounted(() => {
mutations.setLoading(false); // Call your mutation or method to set loading to false
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');
const loadingDiv = document.getElementById("loading");
if (loadingDiv) {
loadingDiv.remove();
}
+158 -102
View File
@@ -1,122 +1,151 @@
import { createURL, fetchURL, removePrefix } from "./utils";
import { baseURL } from "@/utils/constants";
import { state } from "@/store";
import { notify } from "@/notify";
export async function fetch(url,content=false) {
url = removePrefix(url);
// Notify if errors occur
export async function fetch(url, content = false) {
try {
url = removePrefix(url);
const res = await fetchURL(`/api/resources${url}?content=${content}`, {});
const res = await fetchURL(`/api/resources${url}?content=${content}`, {});
const data = await res.json();
data.url = `/files${url}`;
let data = await res.json();
data.url = `/files${url}`;
if (data.isDir) {
if (!data.url.endsWith("/")) data.url += "/";
data.items = data.items.map((item, index) => {
item.index = index;
item.url = `${data.url}${encodeURIComponent(item.name)}`;
if (data.isDir) {
if (!data.url.endsWith("/")) data.url += "/";
data.items = data.items.map((item, index) => {
item.index = index;
item.url = `${data.url}${encodeURIComponent(item.name)}`;
if (item.isDir) {
item.url += "/";
}
if (item.isDir) {
item.url += "/";
}
return item;
});
}
return item;
});
return data;
} catch (err) {
notify.showError(err.message || "Error fetching data");
throw err;
}
return data;
}
async function resourceAction(url, method, content) {
url = removePrefix(url);
try {
url = removePrefix(url);
let opts = { method };
let opts = { method };
if (content) {
opts.body = content;
if (content) {
opts.body = content;
}
const res = await fetchURL(`/api/resources${url}`, opts);
return res;
} catch (err) {
notify.showError(err.message || "Error performing resource action");
throw err;
}
const res = await fetchURL(`/api/resources${url}`, opts);
return res;
}
export async function remove(url) {
return resourceAction(url, "DELETE");
try {
return await resourceAction(url, "DELETE");
} catch (err) {
notify.showError(err.message || "Error deleting resource");
throw err;
}
}
export async function put(url, content = "") {
return resourceAction(url, "PUT", content);
try {
return await resourceAction(url, "PUT", content);
} catch (err) {
notify.showError(err.message || "Error putting resource");
throw err;
}
}
export function download(format, ...files) {
let url = `${baseURL}/api/raw`;
try {
let url = `${baseURL}/api/raw`;
if (files.length === 1) {
url += removePrefix(files[0]) + "?";
} else {
let arg = "";
if (files.length === 1) {
url += removePrefix(files[0]) + "?";
} else {
let arg = "";
for (let file of files) {
arg += removePrefix(file) + ",";
for (let file of files) {
arg += removePrefix(file) + ",";
}
arg = arg.substring(0, arg.length - 1);
arg = encodeURIComponent(arg);
url += `/?files=${arg}&`;
}
arg = arg.substring(0, arg.length - 1);
arg = encodeURIComponent(arg);
url += `/?files=${arg}&`;
}
if (format) {
url += `algo=${format}&`;
}
if (format) {
url += `algo=${format}&`;
}
if (state.jwt) {
url += `auth=${state.jwt}&`;
}
if (state.jwt) {
url += `auth=${state.jwt}&`;
window.open(url);
} catch (err) {
notify.showError(err.message || "Error downloading files");
}
window.open(url);
}
export async function post(url, content = "", overwrite = false, onupload) {
url = removePrefix(url);
try {
url = removePrefix(url);
let bufferContent;
if (
content instanceof Blob &&
!["http:", "https:"].includes(window.location.protocol)
) {
bufferContent = await new Response(content).arrayBuffer();
}
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open(
"POST",
`${baseURL}/api/resources${url}?override=${overwrite}`,
true
);
request.setRequestHeader("X-Auth", state.jwt);
if (typeof onupload === "function") {
request.upload.onprogress = onupload;
let bufferContent;
if (
content instanceof Blob &&
!["http:", "https:"].includes(window.location.protocol)
) {
bufferContent = await new Response(content).arrayBuffer();
}
request.onload = () => {
if (request.status === 200) {
resolve(request.responseText);
} else if (request.status === 409) {
reject(request.status);
} else {
reject(request.responseText);
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open(
"POST",
`${baseURL}/api/resources${url}?override=${overwrite}`,
true
);
request.setRequestHeader("X-Auth", state.jwt);
if (typeof onupload === "function") {
request.upload.onprogress = onupload;
}
};
request.onerror = () => {
reject(new Error("001 Connection aborted"));
};
request.onload = () => {
if (request.status === 200) {
resolve(request.responseText);
} else if (request.status === 409) {
reject(request.status);
} else {
reject(request.responseText);
}
};
request.send(bufferContent || content);
});
request.onerror = () => {
reject(new Error("001 Connection aborted"));
};
request.send(bufferContent || content);
});
} catch (err) {
notify.showError(err.message || "Error posting resource");
throw err;
}
}
function moveCopy(items, copy = false, overwrite = false, rename = false) {
@@ -131,7 +160,10 @@ function moveCopy(items, copy = false, overwrite = false, rename = false) {
promises.push(resourceAction(url, "PATCH"));
}
return Promise.all(promises);
return Promise.all(promises).catch((err) => {
notify.showError(err.message || "Error moving/copying resources");
throw err;
});
}
export function move(items, overwrite = false, rename = false) {
@@ -143,44 +175,68 @@ export function copy(items, overwrite = false, rename = false) {
}
export async function checksum(url, algo) {
const data = await resourceAction(`${url}?checksum=${algo}`, "GET");
return (await data.json()).checksums[algo];
try {
const data = await resourceAction(`${url}?checksum=${algo}`, "GET");
return (await data.json()).checksums[algo];
} catch (err) {
notify.showError(err.message || "Error fetching checksum");
throw err;
}
}
export function getDownloadURL(file, inline) {
const params = {
...(inline && { inline: "true" }),
};
try {
const params = {
...(inline && { inline: "true" }),
};
return createURL("api/raw" + file.path, params);
return createURL("api/raw" + file.path, params);
} catch (err) {
notify.showError(err.message || "Error getting download URL");
throw err;
}
}
export function getPreviewURL(file, size) {
const params = {
inline: "true",
key: Date.parse(file.modified),
};
try {
const params = {
inline: "true",
key: Date.parse(file.modified),
};
return createURL("api/preview/" + size + file.path, params);
return createURL("api/preview/" + size + file.path, params);
} catch (err) {
notify.showError(err.message || "Error getting preview URL");
throw err;
}
}
export function getSubtitlesURL(file) {
const params = {
inline: "true",
};
try {
const params = {
inline: "true",
};
const subtitles = [];
for (const sub of file.subtitles) {
subtitles.push(createURL("api/raw" + sub, params));
const subtitles = [];
for (const sub of file.subtitles) {
subtitles.push(createURL("api/raw" + sub, params));
}
return subtitles;
} catch (err) {
notify.showError(err.message || "Error fetching subtitles URL");
throw err;
}
return subtitles;
}
export async function usage(url) {
url = removePrefix(url);
try {
url = removePrefix(url);
const res = await fetchURL(`/api/usage${url}`, {});
return await res.json();
const res = await fetchURL(`/api/usage${url}`, {});
return await res.json();
} catch (err) {
notify.showError(err.message || "Error fetching usage data");
throw err;
}
}
+2 -1
View File
@@ -84,5 +84,6 @@ export function getDownloadURL(share, inline = false) {
if (share.path == undefined) {
share.path = ""
}
return createURL("api/public/dl/" + share.hash + "/"+share.path, params, false);
const path = share.path.replace("/share/"+share.hash +"/","")
return createURL("api/public/dl/" + share.hash + "/"+path, params, false);
}
+19 -18
View File
@@ -1,27 +1,28 @@
import { fetchURL, removePrefix } from "./utils";
import url from "../utils/url";
import { notify } from "@/notify"; // Import notify for error handling
export default async function search(base, query) {
base = removePrefix(base);
query = encodeURIComponent(query);
try {
base = removePrefix(base);
query = encodeURIComponent(query);
if (!base.endsWith("/")) {
base += "/";
}
let res = await fetchURL(`/api/search${base}?query=${query}`, {});
let data = await res.json();
data = data.map((item) => {
item.url = `/files${base}` + url.encodePath(item.path);
if (item.dir) {
item.url += "/";
if (!base.endsWith("/")) {
base += "/";
}
return item;
});
const res = await fetchURL(`/api/search${base}?query=${query}`, {});
return data;
let data = await res.json();
data = data.map((item) => {
item.url = `/files${base}` + url.encodePath(item.path);
return item;
});
return data;
} catch (err) {
notify.showError(err.message || "Error occurred during search");
throw err;
}
}
+57 -28
View File
@@ -1,47 +1,76 @@
import { fetchURL, fetchJSON } from "@/api/utils";
import { notify } from "@/notify"; // Import notify for error handling
export async function getAllUsers() {
return await fetchJSON(`/api/users`, {});
try {
return await fetchJSON(`/api/users`, {});
} catch (err) {
notify.showError(err.message || "Failed to fetch users");
throw err; // Re-throw to handle further if needed
}
}
export async function get(id) {
return fetchJSON(`/api/users/${id}`, {});
try {
return await fetchJSON(`/api/users/${id}`, {});
} catch (err) {
notify.showError(err.message || `Failed to fetch user with ID: ${id}`);
throw err;
}
}
export async function create(user) {
const res = await fetchURL(`/api/users`, {
method: "POST",
body: JSON.stringify({
what: "user",
which: [],
data: user,
}),
});
try {
const res = await fetchURL(`/api/users`, {
method: "POST",
body: JSON.stringify({
what: "user",
which: [],
data: user,
}),
});
if (res.status === 201) {
return res.headers.get("Location");
if (res.status === 201) {
return res.headers.get("Location");
} else {
throw new Error("Failed to create user");
}
} catch (err) {
notify.showError(err.message || "Error creating user");
throw err;
}
}
export async function update(user, which = ["all"]) {
if (which[0] != "password") {
user.password = "";
try {
// List of keys to exclude from the "which" array
const excludeKeys = ["id", "name"];
// Filter out the keys from "which"
which = which.filter(item => !excludeKeys.includes(item));
if (user.username === "publicUser") {
return;
}
await fetchURL(`/api/users/${user.id}`, {
method: "PUT",
body: JSON.stringify({
what: "user",
which: which,
data: user,
}),
});
} catch (err) {
notify.showError(err.message || `Failed to update user with ID: ${user.id}`);
throw err;
}
if (user.username == "publicUser") {
return
}
await fetchURL(`/api/users/${user.id}`, {
method: "PUT",
body: JSON.stringify({
what: "user",
which: which,
data: user,
}),
});
}
export async function remove(id) {
await fetchURL(`/api/users/${id}`, {
method: "DELETE",
});
try {
await fetchURL(`/api/users/${id}`, {
method: "DELETE",
});
} catch (err) {
notify.showError(err.message || `Failed to delete user with ID: ${id}`);
throw err;
}
}
+2 -2
View File
@@ -2,7 +2,7 @@ import { state } from "@/store";
import { renew, logout } from "@/utils/auth";
import { baseURL } from "@/utils/constants";
import { encodePath } from "@/utils/url";
import { showError } from "@/notify";
import { notify } from "@/notify";
export async function fetchURL(url, opts, auth = true) {
opts = opts || {};
@@ -51,7 +51,7 @@ export async function fetchJSON(url, opts) {
if (res.status === 200) {
return res.json();
} else {
showError("unable to fetch : " + url + "status" + res.status);
notify.showError("unable to fetch : " + url + "status" + res.status);
throw new Error(res.status);
}
}
File renamed without changes.
+29 -8
View File
@@ -14,20 +14,46 @@
<component :is="element" :to="link.url">{{ link.name }}</component>
</span>
<action style="display: contents" v-if="showShare" icon="share" show="share" />
<div v-if="isCardView">
Size:
<input
v-model="gallerySize"
type="range"
id="gallary-size"
name="gallary-size"
:value="gallerySize"
min="0"
max="10"
/>
</div>
</div>
</template>
<script>
import { state, mutations } from "@/store"; // Import mutations as well
import Action from "@/components/header/Action.vue";
import { state, mutations, getters } from "@/store"; // Import mutations as well
import Action from "@/components/Action.vue";
export default {
name: "breadcrumbs",
components: {
Action,
},
data() {
return {
gallerySize: state.user.gallerySize,
};
},
watch: {
gallerySize(newValue) {
this.gallerySize = parseInt(newValue, 0); // Update the user object
mutations.setGallerySize(this.gallerySize);
},
},
props: ["base", "noLink"],
computed: {
isCardView() {
return getters.isCardView();
},
items() {
const relativePath = state.route.path.replace(this.base, "");
let parts = relativePath.split("/");
@@ -81,11 +107,6 @@ export default {
return state.user?.perm && state.user?.perm.share; // Access from state directly
},
},
methods: {
// Example of a method using mutations
updateUserPermissions(newPerms) {
mutations.updateUser({ perm: newPerms })
},
},
methods: { },
};
</script>
+230
View File
@@ -0,0 +1,230 @@
<template>
<div
id="context-menu"
ref="contextMenu"
v-show="showContext"
:style="{
top: `${top}px`,
left: `${left}px`,
}"
class="button"
:class="{ 'dark-mode': isDarkMode, mobile: isMobile }"
>
<div v-if="selectedCount > 0" class="button selected-count-header">
<span>{{ selectedCount }} selected</span>
</div>
<action
v-if="!headerButtons.select"
icon="create_new_folder"
:label="$t('sidebar.newFolder')"
@action="showHover('newDir')"
/>
<action
v-if="!headerButtons.select"
icon="note_add"
:label="$t('sidebar.newFile')"
@action="showHover('newFile')"
/>
<action
v-if="!headerButtons.select"
icon="file_upload"
:label="$t('buttons.upload')"
@action="uploadFunc"
/>
<action
v-if="headerButtons.select"
icon="info"
:label="$t('buttons.info')"
show="info"
/>
<action
v-if="!isMultiple"
icon="check_circle"
:label="$t('buttons.selectMultiple')"
@action="toggleMultipleSelection"
/>
<action
v-if="headerButtons.download"
icon="file_download"
:label="$t('buttons.download')"
@action="startDownload"
:counter="selectedCount"
/>
<action
v-if="headerButtons.share"
icon="share"
:label="$t('buttons.share')"
show="share"
/>
<action
v-if="headerButtons.rename"
icon="mode_edit"
:label="$t('buttons.rename')"
show="rename"
/>
<action
v-if="headerButtons.copy"
icon="content_copy"
:label="$t('buttons.copyFile')"
show="copy"
/>
<action
v-if="headerButtons.move"
icon="forward"
:label="$t('buttons.moveFile')"
show="move"
/>
<action
v-if="headerButtons.delete"
icon="delete"
:label="$t('buttons.delete')"
show="delete"
/>
</div>
</template>
<script>
import downloadFiles from "@/utils/download";
import { state, getters, mutations } from "@/store"; // Import your custom store
import Action from "@/components/Action.vue";
export default {
name: "ContextMenu",
components: {
Action,
},
data() {
return {
posX: 0,
posY: 0,
};
},
computed: {
isMultiple() {
return state.multiple;
},
user() {
return state.user;
},
isMobile() {
return getters.isMobile();
},
showContext() {
if (getters.currentPromptName() == "ContextMenu" && state.prompts != []) {
this.setPositions();
return true;
}
return false;
},
top() {
// Ensure the context menu stays within the viewport
return Math.min(
this.posY,
window.innerHeight - (this.$refs.contextMenu?.clientHeight ?? 0)
);
},
left() {
return Math.min(
this.posX,
window.innerWidth - (this.$refs.contextMenu?.clientWidth ?? 0)
);
},
isDarkMode() {
return getters.isDarkMode();
},
headerButtons() {
return {
select: state.selected.length > 0,
upload: state.user.perm?.create && state.selected.length > 0,
download: state.user.perm.download && state.selected.length > 0,
delete: state.selected.length > 0 && state.user.perm.delete,
rename: state.selected.length === 1 && state.user.perm.rename,
share: state.selected.length === 1 && state.user.perm.share,
move: state.selected.length > 0 && state.user.perm.rename,
copy: state.selected.length > 0 && state.user.perm?.create,
};
},
selectedCount() {
return getters.selectedCount();
},
},
methods: {
uploadFunc() {
mutations.showHover("upload");
},
showHover(value) {
return mutations.showHover(value);
},
setPositions() {
const contextProps = getters.currentPrompt().props;
this.posX = contextProps.posX;
this.posY = contextProps.posY;
},
toggleMultipleSelection() {
mutations.setMultiple(!state.multiple);
mutations.closeHovers();
},
startDownload() {
downloadFiles();
},
},
};
</script>
<style scoped>
#context-menu {
position: absolute;
z-index: 1000;
background-color: white;
max-width: 20em;
min-width: 15em;
min-height: 4em;
height: auto;
display: flex;
flex-direction: column;
justify-content: center;
}
#context-menu.mobile {
top: 50% !important;
left: 50% !important;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.selected-count-header {
border-radius: 0.5em;
cursor: unset;
margin-bottom: 0.5em;
}
#context-menu .action {
width: auto;
display: flex;
align-items: center;
}
#context-menu > span {
display: inline-block;
margin-left: 1em;
color: #6f6f6f;
margin-right: auto;
}
#context-menu .action span {
display: none;
}
/* File selection */
#context-menu.dark-mode {
background: var(--surfaceSecondary) !important;
}
#context-menu.dark-mode span {
color: var(--textPrimary) !important;
}
</style>
-168
View File
@@ -1,168 +0,0 @@
<template>
<div v-if="selectedCount > 0" id="file-selection" :class="{ 'dark-mode': isDarkMode }">
<span>{{ selectedCount }} selected</span>
<div>
<action
v-if="headerButtons.select"
icon="info"
:label="$t('buttons.info')"
show="info"
/>
<action
v-if="headerButtons.select"
icon="check_circle"
:label="$t('buttons.selectMultiple')"
@action="toggleMultipleSelection"
/>
<action
v-if="headerButtons.download"
icon="file_download"
:label="$t('buttons.download')"
@action="download"
:counter="selectedCount"
/>
<action
v-if="headerButtons.share"
icon="share"
:label="$t('buttons.share')"
show="share"
/>
<action
v-if="headerButtons.rename"
icon="mode_edit"
:label="$t('buttons.rename')"
show="rename"
/>
<action
v-if="headerButtons.copy"
icon="content_copy"
:label="$t('buttons.copyFile')"
show="copy"
/>
<action
v-if="headerButtons.move"
icon="forward"
:label="$t('buttons.moveFile')"
show="move"
/>
<action
v-if="headerButtons.delete"
icon="delete"
:label="$t('buttons.delete')"
show="delete"
/>
</div>
</div>
</template>
<script>
import { state, getters, mutations } from "@/store"; // Import your custom store
import { files as api } from "@/api";
import Action from "@/components/header/Action.vue";
export default {
name: "fileSelection",
components: {
Action,
},
computed: {
isDarkMode() {
return getters.isDarkMode();
},
headerButtons() {
return {
select: state.selected.length > 0,
upload: state.user.perm?.create && state.selected.length > 0,
download: state.user.perm.download && state.selected.length > 0,
delete: state.selected.length > 0 && state.user.perm.delete,
rename: state.selected.length === 1 && state.user.perm.rename,
share: state.selected.length === 1 && state.user.perm.share,
move: state.selected.length > 0 && state.user.perm.rename,
copy: state.selected.length > 0 && state.user.perm?.create,
};
},
selectedCount() {
return getters.selectedCount();
},
},
methods: {
toggleMultipleSelection() {
mutations.setMultiple(!state.multiple);
mutations.closeHovers();
},
download() {
if (getters.isSingleFileSelected()) {
api.download(null, getters.selectedDownloadUrl());
return;
}
mutations.showHover({
name: "download",
confirm: (format) => {
mutations.closeHovers();
let files = [];
if (state.selected.length > 0) {
for (let i of state.selected) {
files.push(state.req.items[i].url);
}
} else {
files.push(state.route.path);
}
try {
api.download(format, ...files);
showSuccess("download started");
} catch (e) {
showError("error downloading", e);
}
},
});
},
},
};
</script>
<style>
@media (min-width: 800px) {
#file-selection {
bottom: 4em;
}
}
#file-selection .action {
border-radius: 50%;
width: auto;
}
#file-selection > span {
display: inline-block;
margin-left: 1em;
color: #6f6f6f;
margin-right: auto;
}
#file-selection .action span {
display: none;
}
/* File Selection */
#file-selection {
box-shadow: rgba(0, 0, 0, 0.3) 0px 2em 50px 10px;
position: fixed;
bottom: 4em;
left: 50%;
transform: translateX(-50%);
align-items: center;
background: #fff;
max-width: 30em;
z-index: 3;
border-radius: 1em;
display: flex;
width: 90%;
}
/* File selection */
#file-selection.dark-mode {
background: var(--surfaceSecondary) !important;
}
#file-selection.dark-mode span {
color: var(--textPrimary) !important;
}
</style>
+11
View File
@@ -219,3 +219,14 @@ export default {
},
};
</script>
<style>
.vue-simple-progress {
margin: 0.5em;
}
.vue-simple-progress,
.vue-simple-progress-bar {
border-radius: 0.5em;
}
</style>
+21 -58
View File
@@ -1,7 +1,7 @@
<template>
<div id="search" @click="open" :class="{ active, ongoing, 'dark-mode': isDarkMode }">
<div id="search" :class="{ active, ongoing, 'dark-mode': isDarkMode }">
<!-- Search input section -->
<div id="input">
<div id="input" @click="open">
<!-- Close button visible when search is active -->
<button
v-if="active"
@@ -16,6 +16,7 @@
<i v-else class="material-icons">search</i>
<!-- Input field for search -->
<input
id="main-input"
class="main-input"
type="text"
@keyup.exact="keyup"
@@ -29,23 +30,13 @@
</div>
<!-- Search results for mobile -->
<div
v-if="state.isMobile && active"
id="result"
:class="{ hidden: !active }"
ref="result"
>
<div v-if="isMobile && active" id="result" :class="{ hidden: !active }" ref="result">
<div id="result-list">
<div class="button" style="width: 100%">Search Context: {{ getContext }}</div>
<!-- List of search results -->
<ul v-show="results.length > 0">
<li
v-for="(s, k) in results"
:key="k"
@click.stop.prevent="navigateTo(s.url)"
style="cursor: pointer"
>
<router-link to="#" event="">
<li v-for="(s, k) in results" :key="k" style="cursor: pointer">
<router-link :to="s.url">
<i v-if="s.dir" class="material-icons folder-icons"> folder </i>
<i v-else-if="s.audio" class="material-icons audio-icons"> volume_up </i>
<i v-else-if="s.image" class="material-icons image-icons"> photo </i>
@@ -102,7 +93,7 @@
</div>
<!-- Search results for desktop -->
<div v-show="!state.isMobile && active" id="result-desktop" ref="result">
<div v-show="!isMobile && active" id="result-desktop" ref="result">
<div class="searchContext">Search Context: {{ getContext }}</div>
<div id="result-list">
<div>
@@ -182,13 +173,8 @@
</div>
<!-- List of search results -->
<ul v-show="results.length > 0">
<li
v-for="(s, k) in results"
:key="k"
@click.stop.prevent="navigateTo(s.url)"
style="cursor: pointer"
>
<router-link to="#" event="">
<li v-for="(s, k) in results" :key="k" style="cursor: pointer">
<router-link :to="s.url">
<i v-if="s.dir" class="material-icons folder-icons"> folder </i>
<i v-else-if="s.audio" class="material-icons audio-icons"> volume_up </i>
<i v-else-if="s.image" class="material-icons image-icons"> photo </i>
@@ -209,7 +195,6 @@
import ButtonGroup from "./ButtonGroup.vue";
import { search } from "@/api";
import { getters, mutations, state } from "@/store";
import { showError } from "@/notify";
var boxes = {
folder: { label: "folders", icon: "folder" },
@@ -263,34 +248,20 @@ export default {
this.submit();
},
active(active) {
// this is hear to allow for animation
const resultList = document.getElementById("result-list");
if (!active) {
resultList.classList.remove("active");
this.value = "";
event.stopPropagation();
mutations.closeHovers();
return;
}
setTimeout(() => {
resultList.classList.add("active");
document.getElementById("main-input").focus();
}, 100);
},
currentPrompt(val, old) {
this.active = val?.prompt === "search";
if (old?.prompt === "search" && !this.active) {
if (this.reload) {
this.setReload(true);
}
document.body.style.overflow = "auto";
this.ongoing = false;
this.results = [];
this.value = "";
this.active = false;
this.$refs.input.blur();
} else if (this.active) {
this.reload = false;
this.$refs.input.focus();
document.body.style.overflow = "hidden";
}
},
value() {
if (this.results.length) {
this.ongoing = false;
@@ -306,12 +277,8 @@ export default {
return this.isTypeSelectDisabled;
},
active() {
console.log("calling active ", getters.currentPromptName());
return getters.currentPromptName() == "search";
},
showOverlay() {
return getters.currentPrompt() !== null && getters.currentPromptName() !== "more";
},
isDarkMode() {
return getters.isDarkMode();
},
@@ -348,11 +315,6 @@ export default {
},
},
methods: {
async navigateTo(url) {
mutations.closeHovers();
await this.$nextTick();
setTimeout(() => this.$router.push(url), 10);
},
basePath(str, isDir) {
let parts = str.replace(/(\/$|^\/)/, "").split("/");
if (parts.length <= 1) {
@@ -366,6 +328,7 @@ export default {
if (isDir) {
parts = "/" + parts; // fix weird rtl thing
}
return parts;
},
baseName(str) {
@@ -373,7 +336,9 @@ export default {
return parts.pop();
},
open() {
mutations.showHover("search");
if (!this.active) {
mutations.showHover("search");
}
},
close(event) {
this.value = "";
@@ -434,11 +399,9 @@ export default {
}
let path = state.route.path;
this.ongoing = true;
try {
this.results = await search(path, searchTypesFull + this.value);
} catch (error) {
showError(error);
}
this.results = await search(path, searchTypesFull + this.value);
this.ongoing = false;
if (this.results.length == 0) {
this.noneMessage = "No results found in indexed search.";
-460
View File
@@ -1,460 +0,0 @@
<template>
<nav
id="sidebar"
:class="{ active: active, 'dark-mode': isDarkMode, sticky: user?.stickySidebar }"
>
<div class="card">
<div class="card-wrapper">
<button
v-if="user.username"
@click="navigateTo('/settings/profile')"
class="action"
>
<i class="material-icons">person</i>
<span>{{ user.username }}</span>
</button>
</div>
</div>
<div class="card">
<div class="card-wrapper" @mouseleave="resetHoverTextToDefault">
<span>{{ hoverText }}</span>
<div class="quick-toggles">
<div
:class="{ active: user?.singleClick }"
@click="toggleClick"
@mouseover="updateHoverText('Toggle single click')"
>
<i class="material-icons">ads_click</i>
</div>
<div
:class="{ active: user?.darkMode }"
@click="toggleDarkMode"
@mouseover="updateHoverText('Toggle dark mode')"
>
<i class="material-icons">dark_mode</i>
</div>
<div
:class="{ active: user?.stickySidebar }"
@click="toggleSticky"
@mouseover="updateHoverText('Toggle sticky sidebar')"
v-if="!isMobile"
>
<i class="material-icons">push_pin</i>
</div>
</div>
</div>
</div>
<!-- Section for logged-in users -->
<div v-if="isLoggedIn" class="sidebar-scroll-list">
<!-- Buttons visible if user has create permission -->
<div v-if="user.perm?.create">
<!-- New Folder button -->
<button
@click="showHover('newDir')"
class="action"
:aria-label="$t('sidebar.newFolder')"
:title="$t('sidebar.newFolder')"
>
<i class="material-icons">create_new_folder</i>
<span>{{ $t("sidebar.newFolder") }}</span>
</button>
<!-- New File button -->
<button
@click="showHover('newFile')"
class="action"
:aria-label="$t('sidebar.newFile')"
:title="$t('sidebar.newFile')"
>
<i class="material-icons">note_add</i>
<span>{{ $t("sidebar.newFile") }}</span>
</button>
<!-- Upload button -->
<button id="upload-button" @click="uploadFunc" class="action">
<i class="material-icons">file_upload</i>
<span>Upload file</span>
</button>
</div>
<!-- Settings and Logout buttons -->
<div>
<!-- Settings button -->
<button
class="action"
@click="navigateTo('/settings/global')"
:aria-label="$t('sidebar.settings')"
:title="$t('sidebar.settings')"
>
<i class="material-icons">settings_applications</i>
<span>{{ $t("sidebar.settings") }}</span>
</button>
<!-- Logout button -->
<button
v-if="canLogout"
@click="logout"
class="action"
id="logout"
:aria-label="$t('sidebar.logout')"
:title="$t('sidebar.logout')"
>
<i class="material-icons">exit_to_app</i>
<span>{{ $t("sidebar.logout") }}</span>
</button>
</div>
<div v-if="isLoggedIn" class="sources card">
<span>Sources</span>
<div class="inner-card">
<!-- My Files button -->
<button
class="action"
@click="navigateTo('/files/')"
:aria-label="$t('sidebar.myFiles')"
:title="$t('sidebar.myFiles')"
>
<i class="material-icons">folder</i>
<span>{{ $t("sidebar.myFiles") }}</span>
<div class="usage-info">
<progress-bar :val="usage.usedPercentage" size="medium"></progress-bar>
<span style="text-align: center">{{ usage.usedPercentage }}%</span>
<span>{{ usage.used }} of {{ usage.total }} used</span>
</div>
</button>
</div>
</div>
</div>
<!-- Section for non-logged-in users -->
<div v-else class="sidebar-scroll-list">
<!-- Login button -->
<router-link
class="action"
to="/login"
:aria-label="$t('sidebar.login')"
:title="$t('sidebar.login')"
>
<i class="material-icons">exit_to_app</i>
<span>{{ $t("sidebar.login") }}</span>
</router-link>
<!-- Signup button, if signup is enabled -->
<router-link
v-if="signup"
class="action"
to="/login"
:aria-label="$t('sidebar.signup')"
:title="$t('sidebar.signup')"
>
<i class="material-icons">person_add</i>
<span>{{ $t("sidebar.signup") }}</span>
</router-link>
</div>
<div class="buffer"></div>
<div class="credits">
<span>
<a
rel="noopener noreferrer"
target="_blank"
href="https://github.com/gtsteffaniak/filebrowser"
>
File Browser
</a>
</span>
<span>{{ version }}</span>
<span>
<a @click="help">{{ $t("sidebar.help") }}</a>
</span>
</div>
</nav>
</template>
<script>
import * as auth from "@/utils/auth";
import {
version,
signup,
disableExternal,
disableUsedPercentage,
noAuth,
loginPage,
} from "@/utils/constants";
import { files, users } from "@/api";
import ProgressBar from "@/components/ProgressBar.vue";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { state, getters, mutations } from "@/store"; // Import your custom store
import { showError } from "@/notify";
export default {
name: "sidebar",
components: {
ProgressBar,
},
data() {
return {
hoverText: "Quick Toggles", // Initially empty
};
},
mounted() {
if (getters.isLoggedIn()) {
this.updateUsage();
}
},
computed: {
isMobile() {
return getters.isMobile();
},
isFiles() {
return getters.isFiles();
},
user() {
if (!getters.isLoggedIn()) {
return {};
}
return state.user;
},
isDarkMode() {
return getters.isDarkMode();
},
isLoggedIn() {
return getters.isLoggedIn();
},
currentPrompt() {
return getters.currentPrompt();
},
active() {
return getters.isSidebarVisible() && getters.currentPromptName() == null;
},
signup: () => signup,
version: () => version,
disableExternal: () => disableExternal,
disableUsedPercentage: () => disableUsedPercentage,
canLogout: () => !noAuth && loginPage,
usage: () => state.usage,
route: () => state.route,
},
watch: {
route() {
if (!getters.isLoggedIn()) {
return;
}
if (!state.user.stickySidebar) {
mutations.closeSidebar();
}
},
},
methods: {
updateHoverText(text) {
this.hoverText = text;
},
resetHoverTextToDefault() {
this.hoverText = "Quick Toggles"; // Reset to default hover text
},
toggleClick() {
mutations.updateUser({ singleClick: !state.user.singleClick });
},
toggleDarkMode() {
mutations.toggleDarkMode();
},
toggleSticky() {
let newSettings = state.user;
newSettings.stickySidebar = !state.user.stickySidebar;
users.update(newSettings, ["stickySidebar"]);
},
async updateUsage() {
if (!getters.isLoggedIn()) {
return;
}
let path = getters.getRoutePath();
let usageStats = { used: "0 B", total: "0 B", usedPercentage: 0 };
if (this.disableUsedPercentage) {
return usageStats;
}
try {
let usage = await files.usage(path);
usageStats = {
used: getHumanReadableFilesize(usage.used / 1024),
total: getHumanReadableFilesize(usage.total / 1024),
usedPercentage: Math.round((usage.used / usage.total) * 100),
};
} catch (error) {
showError("Error fetching usage", error);
}
mutations.setUsage(usageStats);
},
showHover(value) {
return mutations.showHover(value);
},
navigateTo(path) {
this.$router.push({ path: path }, () => {});
mutations.closeHovers();
},
// Show the help overlay
help() {
mutations.showHover("help");
},
uploadFunc() {
mutations.showHover("upload");
},
// Logout the user
logout: auth.logout,
},
};
</script>
<style>
.sidebar-scroll-list {
overflow: scroll;
margin-bottom: 0px !important;
}
#sidebar {
top: 0;
display: flex;
flex-direction: column;
padding: 1em;
padding-top: 5em;
width: 20em;
position: fixed;
z-index: 4;
left: -20em;
height: 100%;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
transition: 0.5s ease;
background-color: #ededed;
}
#sidebar.sticky {
z-index: 3;
}
@supports (backdrop-filter: none) {
nav {
background-color: transparent;
backdrop-filter: blur(16px) invert(0.1);
}
}
.usage-info {
padding: 0.5em;
}
body.rtl nav {
left: unset;
right: -17em;
}
#sidebar.active {
left: 0;
}
#sidebar.rtl nav.active {
left: unset;
right: 0;
}
#sidebar > div {
border-top: 1px solid rgba(0, 0, 0, 0.05);
margin-bottom: 0.5em;
}
#sidebar .card {
overflow: unset !important;
}
#sidebar .action {
width: 100%;
display: block;
white-space: nowrap;
height: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
body.rtl .action {
direction: rtl;
text-align: right;
}
#sidebar .action > * {
vertical-align: middle;
}
/* * * * * * * * * * * * * * * *
* FOOTER *
* * * * * * * * * * * * * * * */
.credits {
font-size: 1em;
color: var(--textSecondary);
padding-left: 1em;
}
.credits > span {
display: block;
margin-top: 0.5em;
margin-left: 0;
}
.credits a,
.credits a:hover {
color: inherit;
cursor: pointer;
}
.buffer {
flex-grow: 1;
}
.quick-toggles {
display: flex;
justify-content: space-evenly;
width: 100%;
margin-top: 0.5em !important;
}
.quick-toggles button {
border-radius: 10em;
cursor: pointer;
flex: none;
}
.card-wrapper {
display: flex !important;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 1em !important;
min-height: 4em;
box-shadow: 0 2px 2px #00000024, 0 1px 5px #0000001f, 0 3px 1px -2px #0003;
/* overflow: auto; */
border-radius: 1em;
height: 100%;
}
.sources {
padding: 1em;
}
.inner-card {
border-radius: 0.5em;
padding: 0px !important;
}
.quick-toggles div {
border-radius: 10em;
background-color: var(--surfaceSecondary);
}
.quick-toggles div i {
font-size: 2em;
padding: 0.25em;
border-radius: 10em;
cursor: pointer;
}
button.action {
border-radius: 0.5em;
}
.quick-toggles .active {
background-color: var(--blue) !important;
border-radius: 10em;
}
</style>
+34 -73
View File
@@ -10,20 +10,23 @@
@mouseup="mouseUp"
@wheel="wheelMove"
>
<div v-if="!isLoaded">Loading image...</div>
<img
v-if="!isTiff"
v-if="!isTiff && isLoaded"
:src="src"
class="image-ex-img image-ex-img-center"
class="image-ex-img"
ref="imgex"
@load="onLoad"
/>
<canvas v-else ref="imgex" class="image-ex-img"></canvas>
<canvas v-else-if="isLoaded" ref="imgex" class="image-ex-img"></canvas>
</div>
</template>
<script>
import { state, mutations } from "@/store";
import throttle from "@/utils/throttle";
import { showError } from "@/notify";
import { notify } from "@/notify";
export default {
props: {
src: String,
@@ -82,8 +85,17 @@ export default {
window.removeEventListener("resize", this.onResize);
document.removeEventListener("mouseup", this.onMouseUp);
},
computed: {
isLoaded() {
return !("preview-img" in state.loading);
},
},
watch: {
src: function () {
if (this.src == undefined || this.$refs.imgex == undefined) {
mutations.setLoading("preview-img", false);
return;
}
this.isTiff = this.checkIfTiff(this.src);
if (this.isTiff) {
this.decodeTiff(this.src);
@@ -94,6 +106,8 @@ export default {
this.scale = 1;
this.setZoom();
this.setCenter();
mutations.setLoading("preview-img", false);
this.showSpinner = false;
},
},
methods: {
@@ -117,40 +131,9 @@ export default {
imgex.onload = () => URL.revokeObjectURL(imgex.src); // Clean up URL object after loading
}
} catch (error) {
showError("Error decoding TIFF");
console.error("Error decoding TIFF:", error);
notify.showError("Error decoding TIFF");
}
},
onLoad() {
let img = this.$refs.imgex;
this.imageLoaded = true;
if (img === undefined) {
return;
}
img.classList.remove("image-ex-img-center");
this.setCenter();
img.classList.add("image-ex-img-ready");
document.addEventListener("mouseup", this.onMouseUp);
let realSize = img.naturalWidth;
let displaySize = img.offsetWidth;
// Image is in portrait orientation
if (img.naturalHeight > img.naturalWidth) {
realSize = img.naturalHeight;
displaySize = img.offsetHeight;
}
// Scale needed to display the image on full size
const fullScale = realSize / displaySize;
// Full size plus additional zoom
this.maxScale = fullScale + 4;
},
onMouseUp() {
this.inDrag = false;
},
@@ -258,32 +241,19 @@ export default {
}
},
doMove(x, y) {
let style = this.$refs.imgex.style;
let posX = this.pxStringToNumber(style.left) + x;
let posY = this.pxStringToNumber(style.top) + y;
style.left = posX + "px";
style.top = posY + "px";
this.position.relative.x = Math.abs(this.position.center.x - posX);
this.position.relative.y = Math.abs(this.position.center.y - posY);
if (posX < this.position.center.x) {
this.position.relative.x = this.position.relative.x * -1;
}
if (posY < this.position.center.y) {
this.position.relative.y = this.position.relative.y * -1;
}
this.position.relative.x += x;
this.position.relative.y += y;
// Update the transform with separate translate and scale values
this.$refs.imgex.style.transform = `translate(${this.position.relative.x}px, ${this.position.relative.y}px) scale(${this.scale})`;
},
wheelMove(event) {
this.scale += -Math.sign(event.deltaY) * this.zoomStep;
this.setZoom();
},
setZoom() {
this.scale = this.scale < this.minScale ? this.minScale : this.scale;
this.scale = this.scale > this.maxScale ? this.maxScale : this.scale;
this.$refs.imgex.style.transform = `scale(${this.scale})`;
this.scale = Math.max(this.minScale, Math.min(this.maxScale, this.scale));
// Update the transform with both translate and scale values
this.$refs.imgex.style.transform = `translate(${this.position.relative.x}px, ${this.position.relative.y}px) scale(${this.scale})`;
},
pxStringToNumber(style) {
return +style.replace("px", "");
@@ -294,26 +264,17 @@ export default {
<style>
.image-ex-container {
margin: auto;
overflow: hidden;
position: relative;
max-width: 100%; /* Image container max width */
max-height: 100%; /* Image container max height */
overflow: hidden; /* Hide overflow if image exceeds container */
position: relative; /* Required for absolute positioning of child */
display: flex;
justify-content: center;
}
.image-ex-img {
max-width: 100%; /* Image max width */
max-height: 100%; /* Image max height */
position: absolute;
}
.image-ex-img-center {
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
transition: none;
}
.image-ex-img-ready {
left: 0;
top: 0;
transition: transform 0.1s ease;
}
</style>
+22 -38
View File
@@ -1,47 +1,46 @@
<template>
<div
:class="{ activebutton: this.isMaximized && this.isSelected }"
class="item"
<component
:is="isSelected || user.singleClick ? 'a' : 'div'"
:href="isSelected || user.singleClick ? url : undefined"
:class="{
item: true,
activebutton: isMaximized && isSelected,
}"
role="button"
tabindex="0"
:draggable="isDraggable"
@dragstart="dragStart"
@dragover="dragOver"
@drop="drop"
@click="itemClick"
:data-dir="isDir"
:data-type="type"
:aria-label="name"
:aria-selected="isSelected"
@click="isSelected || user.singleClick ? toggleClick() : itemClick($event)"
>
<div
@click="toggleClick"
:class="{ activetitle: this.isMaximized && this.isSelected }"
>
<div @click="toggleClick" :class="{ activetitle: isMaximized && isSelected }">
<img
v-if="readOnly === undefined && type === 'image' && isThumbsEnabled && isInView"
v-lazy="thumbnailUrl"
:class="{ activeimg: this.isMaximized && this.isSelected }"
:class="{ activeimg: isMaximized && isSelected }"
ref="thumbnail"
/>
<i
:class="{ iconActive: this.isMaximized && this.isSelected }"
:class="{ iconActive: isMaximized && isSelected }"
v-else
class="material-icons"
></i>
</div>
<div :class="{ activecontent: this.isMaximized && this.isSelected }">
<div class="text" :class="{ activecontent: isMaximized && isSelected }">
<p class="name">{{ name }}</p>
<p v-if="isDir" class="size" data-order="-1">&mdash;</p>
<p v-else class="size" :data-order="humanSize()">{{ humanSize() }}</p>
<p class="modified">
<time :datetime="modified">{{ humanTime() }}</time>
</p>
</div>
</div>
</component>
</template>
<style>
@@ -75,7 +74,7 @@ import { state, getters, mutations } from "@/store"; // Import your custom store
export default {
name: "item",
data: function () {
data() {
return {
isThumbnailInView: false,
isMaximized: false,
@@ -100,27 +99,12 @@ export default {
selected() {
return state.selected;
},
req() {
return state.req;
},
jwt() {
return state.jwt;
},
selectedCount() {
return getters.selectedCount();
},
isClicked() {
if (state.user.singleClick || !this.allowedView) {
return false;
}
return !this.isMaximized;
},
allowedView() {
return state.user.viewMode != "gallery" && state.user.viewMode != "normal";
},
singleClick() {
return this.readOnly == undefined && state.user.singleClick;
},
isSelected() {
return this.selected.indexOf(this.index) !== -1;
},
@@ -183,18 +167,18 @@ export default {
toggleClick() {
this.isMaximized = this.isClicked;
},
humanSize: function () {
humanSize() {
return this.type == "invalid_link"
? "invalid link"
: getHumanReadableFilesize(this.size);
},
humanTime: function () {
humanTime() {
if (this.readOnly == undefined && state.user.dateFormat) {
return fromNow(this.modified, state.user.locale).format("L LT");
}
return fromNow(this.modified, state.user.locale);
},
dragStart: function () {
dragStart() {
if (getters.selectedCount() === 0) {
mutations.addSelected(this.index);
return;
@@ -205,7 +189,7 @@ export default {
mutations.addSelected(this.index);
}
},
dragOver: function (event) {
dragOver(event) {
if (!this.canDrop) return;
event.preventDefault();
@@ -219,7 +203,7 @@ export default {
el.style.opacity = 1;
},
drop: async function (event) {
async drop(event) {
if (!this.canDrop) return;
event.preventDefault();
@@ -278,11 +262,11 @@ export default {
action(overwrite, rename);
},
itemClick: function (event) {
itemClick(event) {
if (this.singleClick && !state.multiple) this.open();
else this.click(event);
},
click: function (event) {
click(event) {
if (!this.singleClick && getters.selectedCount() !== 0) event.preventDefault();
setTimeout(() => {
@@ -323,7 +307,7 @@ export default {
mutations.resetSelected();
mutations.addSelected(this.index);
},
open: function () {
open() {
this.$router.push({ path: this.url });
},
},
+2 -2
View File
@@ -52,7 +52,7 @@ import FileList from "./FileList.vue";
import { files as api } from "@/api";
import buttons from "@/utils/buttons";
import * as upload from "@/utils/upload";
import { showError } from "@/notify";
import { notify } from "@/notify";
export default {
name: "copy",
@@ -102,7 +102,7 @@ export default {
})
.catch((e) => {
buttons.done("copy");
showError(e);
notify.showError(e);
});
};
+4 -2
View File
@@ -33,7 +33,7 @@
import { files as api } from "@/api";
import buttons from "@/utils/buttons";
import { state, getters, mutations } from "@/store";
import { showError } from "@/notify";
import { notify } from "@/notify";
export default {
name: "delete",
@@ -59,6 +59,7 @@ export default {
if (!this.isListing) {
await api.remove(state.route.path);
buttons.success("delete");
showSuccess("Deleted item successfully");
this.currentPrompt?.confirm();
this.closeHovers();
@@ -78,10 +79,11 @@ export default {
await Promise.all(promises);
buttons.success("delete");
showSuccess("Deleted item successfully");
mutations.setReload(true); // Handle reload as needed
} catch (e) {
buttons.done("delete");
showError(e);
notify.showError(e);
if (this.isListing) mutations.setReload(true); // Handle reload as needed
}
},
@@ -21,7 +21,7 @@
</template>
<script>
import { users as api } from "@/api";
import { showSuccess,showError } from "@/notify";
import { notify } from "@/notify";
import buttons from "@/utils/buttons";
import { state, mutations, getters } from "@/store";
@@ -40,12 +40,12 @@ export default {
event.preventDefault();
try {
await api.remove(this.user.id);
this.$router.push({ path: "/settings/users" });
showSuccess(this.$t("settings.userDeleted"));
this.$router.push({ path: "/settings",hash:"#users-main" });
notify.showSuccess(this.$t("settings.userDeleted"));
} catch (e) {
e.message === "403"
? showError(this.$t("errors.forbidden"), false)
: showError(e);
? notify.showError(this.$t("errors.forbidden"), false)
: notify.showError(e);
}
},
closeHovers() {
@@ -80,7 +80,7 @@ export default {
mutations.setReload(true); // Handle reload as needed
} catch (e) {
buttons.done("delete");
showError(e);
notify.showError(e);
if (this.isListing) mutations.setReload(true); // Handle reload as needed
}
},
+1 -2
View File
@@ -24,7 +24,6 @@
import { state, mutations } from "@/store";
import url from "@/utils/url";
import { files } from "@/api";
import { showError } from "@/notify";
export default {
name: "file-list",
@@ -86,7 +85,7 @@ export default {
// content.
let uri = event.currentTarget.dataset.url;
files.fetch(uri).then(this.fillOptions).catch(showError);
files.fetch(uri).then(this.fillOptions);
},
touchstart(event) {
let url = event.currentTarget.dataset.url;
+2 -7
View File
@@ -75,7 +75,6 @@ import { getHumanReadableFilesize } from "@/utils/filesizes";
import { formatTimestamp } from "@/utils/moment";
import { files as api } from "@/api";
import { state, getters, mutations } from "@/store"; // Import your custom store
import { showError } from "@/notify";
export default {
name: "info",
@@ -146,12 +145,8 @@ export default {
link = state.route.path;
}
try {
const hash = await api.checksum(link, algo);
event.target.innerHTML = hash;
} catch (e) {
showError(e);
}
const hash = await api.checksum(link, algo);
event.target.innerHTML = hash;
},
},
};
+2 -4
View File
@@ -52,7 +52,7 @@ import FileList from "./FileList.vue";
import { files as api } from "@/api";
import buttons from "@/utils/buttons";
import * as upload from "@/utils/upload";
import { showError } from "@/notify";
import { notify } from "@/notify";
export default {
name: "move",
@@ -95,7 +95,7 @@ export default {
})
.catch((e) => {
buttons.done("move");
showError(e);
notify.showError(e);
});
};
@@ -111,14 +111,12 @@ export default {
confirm: (event, option) => {
overwrite = option == "overwrite";
rename = option == "rename";
event.preventDefault();
mutations.closeHovers();
action(overwrite, rename);
mutations.setReload(true);
},
});
return;
}
+6 -11
View File
@@ -39,7 +39,6 @@
import { files as api } from "@/api";
import url from "@/utils/url";
import { getters, mutations, state } from "@/store"; // Import your custom store
import { showError } from "@/notify";
export default {
name: "new-dir",
@@ -87,16 +86,12 @@ export default {
uri += encodeURIComponent(this.name) + "/";
uri = uri.replace("//", "/");
try {
await api.post(uri);
if (this.redirect) {
this.$router.push({ path: uri });
} else if (!this.base) {
const res = await api.fetch(url.removeLastDir(uri) + "/");
mutations.updateRequest(res);
}
} catch (e) {
showError(e);
await api.post(uri);
if (this.redirect) {
this.$router.push({ path: uri });
} else if (!this.base) {
const res = await api.fetch(url.removeLastDir(uri) + "/");
mutations.updateRequest(res);
}
mutations.closeHovers();
+2 -6
View File
@@ -73,12 +73,8 @@ export default {
uri += encodeURIComponent(this.name);
uri = uri.replace("//", "/");
try {
await api.post(uri);
this.$router.push({ path: uri });
} catch (e) {
showError(e);
}
await api.post(uri);
this.$router.push({ path: uri });
mutations.closeHovers();
},
+1 -1
View File
@@ -25,7 +25,7 @@ import Share from "./Share.vue";
import Upload from "./Upload.vue";
import ShareDelete from "./ShareDelete.vue";
import DeleteUser from "./DeleteUser.vue";
import Sidebar from "../Sidebar.vue";
import Sidebar from "../sidebar/Sidebar.vue";
import buttons from "@/utils/buttons";
import { state, getters, mutations } from "@/store"; // Import your custom store
+6 -10
View File
@@ -98,18 +98,14 @@ export default {
newLink = url.removeLastDir(oldLink) + "/" + encodeURIComponent(this.name);
try {
await api.move([{ from: oldLink, to: newLink }]);
if (!this.isListing) {
this.$router.push({ path: newLink });
return;
}
mutations.setReload(true);
} catch (e) {
showError(e);
await api.move([{ from: oldLink, to: newLink }]);
if (!this.isListing) {
this.$router.push({ path: newLink });
return;
}
mutations.setReload(true);
mutations.closeHovers();
},
},
@@ -7,29 +7,32 @@
<div class="card-content">
<p>{{ $t("prompts.replaceMessage") }}</p>
</div>
<div class="card-action">
<button
class="button button--flat button--grey"
@click="(event) => currentPrompt.confirm(event, 'rename')"
@click="closeHovers"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
tabindex="3"
>
{{ $t("buttons.cancel") }}
</button>
<button
class="button button--flat button--blue"
@click="(event) => currentPrompt.confirm(event, 'overwrite')"
@click="(event) => currentPrompt.confirm(event, 'rename')"
:aria-label="$t('buttons.rename')"
:title="$t('buttons.rename')"
tabindex="2"
>
{{ $t("buttons.rename") }}
</button>
<button
id="focus-prompt"
class="button button--flat button--red"
@click="(event) => showConfirm(event, 'overwrite')"
@click="(event) => currentPrompt.confirm(event, 'overwrite')"
:aria-label="$t('buttons.replace')"
:title="$t('buttons.replace')"
tabindex="1"
>
{{ $t("buttons.replace") }}
</button>
+25 -37
View File
@@ -120,7 +120,7 @@
</div>
</template>
<script>
import { showSuccess, showError } from "@/notify";
import { notify } from "@/notify";
import { state, getters, mutations } from "@/store";
import { share as api, pub as pub_api } from "@/api";
import { fromNow } from "@/utils/moment";
@@ -173,22 +173,18 @@ export default {
},
},
async beforeMount() {
try {
const links = await api.get(this.url);
this.links = links;
this.sort();
const links = await api.get(this.url);
this.links = links;
this.sort();
if (this.links.length === 0) {
this.listing = false;
}
} catch (e) {
showError(e);
if (this.links.length === 0) {
this.listing = false;
}
},
mounted() {
this.clip = new Clipboard(".copy-clipboard");
this.clip.on("success", () => {
showSuccess(this.$t("success.linkCopied"));
notify.showSuccess(this.$t("success.linkCopied"));
});
},
beforeUnmount() {
@@ -198,38 +194,30 @@ export default {
async submit() {
let isPermanent = !this.time || this.time === 0;
try {
let res = null;
let res = null;
if (isPermanent) {
res = await api.create(this.url, this.password);
} else {
res = await api.create(this.url, this.password, this.time, this.unit);
}
this.links.push(res);
this.sort();
this.time = "";
this.unit = "hours";
this.password = "";
this.listing = true;
} catch (e) {
showError(e);
if (isPermanent) {
res = await api.create(this.url, this.password);
} else {
res = await api.create(this.url, this.password, this.time, this.unit);
}
this.links.push(res);
this.sort();
this.time = "";
this.unit = "hours";
this.password = "";
this.listing = true;
},
async deleteLink(event, link) {
event.preventDefault();
try {
await api.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash);
await api.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash);
if (this.links.length === 0) {
this.listing = false;
}
} catch (e) {
showError(e);
if (this.links.length === 0) {
this.listing = false;
}
},
humanTime(time) {
+7 -8
View File
@@ -68,7 +68,7 @@ export default {
handleFiles(event);
};
const handleFiles = (event) => {
const handleFiles = async (event) => {
mutations.closeHovers();
const files = event.target.files;
if (!files) return;
@@ -94,21 +94,20 @@ export default {
if (conflict) {
mutations.showHover({
name: "replace",
action: (event) => {
action: async (event) => {
event.preventDefault();
mutations.closeHovers();
upload.handleFiles(uploadFiles, path, false);
await upload.handleFiles(uploadFiles, path, false);
},
confirm: (event) => {
confirm: async (event) => {
event.preventDefault();
mutations.closeHovers();
upload.handleFiles(uploadFiles, path, true);
await upload.handleFiles(uploadFiles, path, true);
},
});
return;
} else {
await upload.handleFiles(uploadFiles, path, true);
}
upload.handleFiles(uploadFiles, path, true);
mutations.setReload(true);
};
+42 -27
View File
@@ -7,6 +7,7 @@
type="text"
v-model="user.username"
id="username"
@input="emitUpdate"
/>
</p>
@@ -18,22 +19,24 @@
:placeholder="passwordPlaceholder"
v-model="user.password"
id="password"
@input="emitUpdate"
/>
</p>
<p>
<label for="scope">{{ $t("settings.scope") }}</label>
<input
:disabled="createUserDirData"
:disabled="createUserDir"
:placeholder="scopePlaceholder"
class="input input--block"
type="text"
v-model="user.scope"
id="scope"
@input="emitUpdate"
/>
</p>
<p class="small" v-if="displayHomeDirectoryCheckbox">
<input type="checkbox" v-model="createUserDirData" />
<input type="checkbox" v-model="createUserDir" />
{{ $t("settings.createUserHomeDirectory") }}
</p>
@@ -43,25 +46,27 @@
class="input input--block"
id="locale"
v-model:locale="user.locale"
@input="emitUpdate"
></languages>
</p>
<p v-if="!isDefault">
<input
type="checkbox"
:disabled="user.perm.admin"
:disabled="user.perm?.admin"
v-model="user.lockPassword"
@input="emitUpdate"
/>
{{ $t("settings.lockPassword") }}
</p>
<permissions :perm="user.perm" />
<permissions :perm="localUser.perm" />
<commands v-if="isExecEnabled" v-model:commands="user.commands" />
<div v-if="!isDefault">
<h3>{{ $t("settings.rules") }}</h3>
<p class="small">{{ $t("settings.rulesHelp") }}</p>
<rules v-model:rules="user.rules" />
<rules v-model:rules="user.rules" @input="emitUpdate" />
</div>
</div>
</template>
@@ -74,23 +79,42 @@ import Commands from "./Commands.vue";
import { enableExec } from "@/utils/constants";
export default {
name: "user",
data() {
return {
createUserDirData: false,
originalUserScope: "/",
};
},
name: "UserForm",
components: {
Permissions,
Languages,
Rules,
Commands,
},
props: ["user", "createUserDir", "isNew", "isDefault"],
created() {
this.originalUserScope = this.user.scope;
this.createUserDirData = this.createUserDir;
data() {
return {
createUserDir: false,
originalUserScope: ".",
localUser: { ...this.user },
};
},
props: {
user: Object, // Define user as a prop
isDefault: Boolean,
isNew: Boolean,
},
watch: {
user: {
handler(newUser) {
console.log("UserForm: user changed", newUser);
this.localUser = { ...newUser }; // Watch for changes in the parent and update the local copy
},
immediate: true,
deep: true,
},
"user.perm.admin": function (newValue) {
if (newValue) {
this.user.lockPassword = false;
}
},
createUserDir(newVal) {
this.user.scope = newVal ? "" : this.originalUserScope;
},
},
computed: {
passwordPlaceholder() {
@@ -99,7 +123,7 @@ export default {
scopePlaceholder() {
return this.createUserDir
? this.$t("settings.userScopeGenerationPlaceholder")
: "";
: "./";
},
displayHomeDirectoryCheckbox() {
return this.isNew && this.createUserDir;
@@ -108,14 +132,5 @@ export default {
return enableExec; // Removed arrow function
},
},
watch: {
"user.perm.admin": function () {
if (!this.user.perm.admin) return;
this.user.lockPassword = false;
},
createUserDirData(newVal) {
this.user.scope = newVal ? "" : this.originalUserScope;
},
},
};
</script>
</script>
+283
View File
@@ -0,0 +1,283 @@
<template>
<div class="card clickable" style="min-height: 4em">
<div class="card-wrapper user-card">
<div @click="navigateTo('/settings#profile-main')" class="inner-card">
<i class="material-icons">person</i>
{{ user.username }}
<i class="material-icons">settings</i>
</div>
<div class="inner-card">
<i v-if="canLogout" @click="logout" class="material-icons">exit_to_app</i>
</div>
</div>
</div>
<div class="card" style="min-height: 6em">
<div class="card-wrapper" @mouseleave="resetHoverTextToDefault">
<span>{{ hoverText }}</span>
<div class="quick-toggles">
<div
:class="{ active: user?.singleClick }"
@click="toggleClick"
@mouseover="updateHoverText('Toggle single click')"
>
<i class="material-icons">ads_click</i>
</div>
<div
:class="{ active: user?.darkMode }"
@click="toggleDarkMode"
@mouseover="updateHoverText('Toggle dark mode')"
>
<i class="material-icons">dark_mode</i>
</div>
<div
:class="{ active: isStickySidebar }"
@click="toggleSticky"
@mouseover="updateHoverText('Toggle sticky sidebar')"
v-if="!isMobile"
>
<i class="material-icons">push_pin</i>
</div>
</div>
</div>
</div>
<!-- Section for logged-in users -->
<div v-if="isLoggedIn" class="sidebar-scroll-list">
<div v-if="isLoggedIn" class="sources card">
<span>Sources</span>
<div class="inner-card">
<!-- My Files button -->
<button
class="action"
@click="navigateTo('/files/')"
:aria-label="$t('sidebar.myFiles')"
:title="$t('sidebar.myFiles')"
>
<i class="material-icons">folder</i>
<span>{{ $t("sidebar.myFiles") }}</span>
<div>
<progress-bar :val="usage.usedPercentage" size="medium"></progress-bar>
<div class="usage-info">
<span>{{ usage.usedPercentage }}%</span>
<span>{{ usage.used }} of {{ usage.total }} used</span>
</div>
</div>
</button>
</div>
</div>
</div>
<!-- Section for non-logged-in users -->
<div v-else class="sidebar-scroll-list">
<!-- Login button -->
<router-link
class="action"
to="/login"
:aria-label="$t('sidebar.login')"
:title="$t('sidebar.login')"
>
<i class="material-icons">exit_to_app</i>
<span>{{ $t("sidebar.login") }}</span>
</router-link>
<!-- Signup button, if signup is enabled -->
<router-link
v-if="signup"
class="action"
to="/login"
:aria-label="$t('sidebar.signup')"
:title="$t('sidebar.signup')"
>
<i class="material-icons">person_add</i>
<span>{{ $t("sidebar.signup") }}</span>
</router-link>
</div>
</template>
<script>
import * as auth from "@/utils/auth";
import {
version,
commitSHA,
signup,
disableExternal,
disableUsedPercentage,
noAuth,
loginPage,
} from "@/utils/constants";
import { files } 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 {
name: "SidebarGeneral",
components: {
ProgressBar,
},
data() {
return {
hoverText: "Quick Toggles", // Initially empty
};
},
mounted() {
if (getters.isLoggedIn()) {
this.updateUsage();
}
},
computed: {
isSettings: () => getters.isSettings(),
isStickySidebar: () => getters.isStickySidebar(),
isMobile: () => getters.isMobile(),
isFiles: () => getters.isFiles(),
user: () => (getters.isLoggedIn() ? state.user : {}),
isDarkMode: () => getters.isDarkMode(),
isLoggedIn: () => getters.isLoggedIn(),
currentPrompt: () => getters.currentPrompt(),
active: () => getters.isSidebarVisible(),
signup: () => signup,
version: () => version,
commitSHA: () => commitSHA,
disableExternal: () => disableExternal,
disableUsedPercentage: () => disableUsedPercentage,
canLogout: () => !noAuth && loginPage,
usage: () => state.usage,
route: () => state.route,
},
watch: {
route() {
if (!getters.isLoggedIn()) {
return;
}
if (!this.isStickySidebar) {
mutations.closeSidebar();
}
},
},
methods: {
updateHoverText(text) {
this.hoverText = text;
},
resetHoverTextToDefault() {
this.hoverText = "Quick Toggles"; // Reset to default hover text
},
toggleClick() {
mutations.updateCurrentUser({ singleClick: !state.user.singleClick });
},
toggleDarkMode() {
mutations.toggleDarkMode();
},
toggleSticky() {
mutations.updateCurrentUser({ stickySidebar: !state.user.stickySidebar });
},
async updateUsage() {
if (!getters.isLoggedIn()) {
return;
}
let path = getters.getRoutePath();
let usageStats = { used: "0 B", total: "0 B", usedPercentage: 0 };
if (this.disableUsedPercentage) {
return usageStats;
}
let usage = await files.usage(path);
usageStats = {
used: getHumanReadableFilesize(usage.used / 1024),
total: getHumanReadableFilesize(usage.total / 1024),
usedPercentage: Math.round((usage.used / usage.total) * 100),
};
mutations.setUsage(usageStats);
},
navigateTo(path) {
const hashIndex = path.indexOf("#");
if (hashIndex !== -1) {
// Extract the hash
const hash = path.substring(hashIndex);
// Remove the hash from the path
const cleanPath = path.substring(0, hashIndex);
this.$router.push({ path: cleanPath, hash: hash }, () => {});
} else {
this.$router.push({ path: path }, () => {});
}
mutations.closeHovers();
},
// Show the help overlay
help() {
mutations.showHover("help");
},
// Logout the user
logout: auth.logout,
},
};
</script>
<style>
.user-card {
flex-direction: row !important;
justify-content: space-between !important;
}
.quick-toggles {
display: flex;
justify-content: space-evenly;
width: 100%;
margin-top: 0.5em !important;
}
.quick-toggles button {
border-radius: 10em;
cursor: pointer;
flex: none;
}
.sources {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
padding: 1em;
margin-top: 0.5em !important;
}
.sources .inner-card {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
width: 100%;
}
.usage-info {
display: flex;
flex-direction: column;
text-align: center;
}
.quick-toggles div {
border-radius: 10em;
background-color: var(--surfaceSecondary);
}
.quick-toggles div i {
font-size: 2em;
padding: 0.25em;
border-radius: 10em;
cursor: pointer;
}
button.action {
border-radius: 0.5em;
}
.quick-toggles .active {
background-color: var(--blue) !important;
border-radius: 10em;
}
.inner-card {
display: flex;
align-items: center;
padding: 0px !important;
}
</style>
@@ -0,0 +1,52 @@
<template>
<div
v-for="setting in settings"
:key="setting.id + '-sidebar'"
:id="setting.id + '-sidebar'"
class="card clickable"
@click="setView(setting.id + '-main')"
:class="{ 'active-settings': active(setting.id + '-main') }"
>
<div v-if="shouldShow(setting)" class="card-wrapper">{{ setting.label }}</div>
</div>
</template>
<script>
import { state, getters, mutations } from "@/store";
import { settings } from "@/utils/constants";
import { router } from "@/router";
export default {
name: "SidebarSettings",
data() {
return {
settings, // Initialize the settings array in data
};
},
computed: {
currentHash: () => getters.currentHash(),
},
methods: {
shouldShow(setting) {
const perm = setting?.perm || {};
// Check if all keys in setting.perm exist in state.user.perm and have truthy values
return Object.keys(perm).every((key) => state.user.perm[key]);
},
active: (view) => state.activeSettingsView === view,
setView(view) {
if (state.route.path != "/settings") {
router.push({ path: "/settings", hash: "#" + view }, () => {});
} else {
mutations.setActiveSettingsView(view);
}
},
},
};
</script>
<style>
.active-settings {
font-weight: bold;
/* border-color: white; */
border-style: solid;
}
</style>
+172
View File
@@ -0,0 +1,172 @@
<template>
<nav id="sidebar" :class="{ active: active, 'dark-mode': isDarkMode }">
<SidebarSettings v-if="isSettings"></SidebarSettings>
<SidebarGeneral v-else-if="isLoggedIn"></SidebarGeneral>
<div class="buffer"></div>
<div class="credits">
<span>
<a
rel="noopener noreferrer"
target="_blank"
href="https://github.com/gtsteffaniak/filebrowser"
>
FileBrowser Quantum
</a>
</span>
<span>
<a
:href="'https://github.com/gtsteffaniak/filebrowser/releases/'"
:title="commitSHA"
>
({{ version }})
</a>
</span>
<span>
<a @click="help">{{ $t("sidebar.help") }}</a>
</span>
</div>
</nav>
</template>
<script>
import { version, commitSHA } from "@/utils/constants";
import { getters, mutations } from "@/store"; // Import your custom store
import SidebarGeneral from "./General.vue";
import SidebarSettings from "./Settings.vue";
export default {
name: "sidebar",
components: {
SidebarGeneral,
SidebarSettings,
},
computed: {
version: () => version,
commitSHA: () => commitSHA,
isDarkMode: () => getters.isDarkMode(),
isLoggedIn: () => getters.isLoggedIn(),
isSettings: () => getters.isSettings(),
active: () => getters.isSidebarVisible(),
},
methods: {
// Show the help overlay
help() {
mutations.showHover("help");
},
},
};
</script>
<style>
.sidebar-scroll-list {
overflow: auto;
margin-bottom: 0px !important;
}
#sidebar {
display: flex;
flex-direction: column;
padding: 1em;
width: 20em;
position: fixed;
z-index: 4;
left: -20em;
height: 100%;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
transition: 0.5s ease;
top: 4em;
padding-bottom: 4em;
background-color: rgb(255 255 255 / 50%) !important;
}
#sidebar.dark-mode {
background-color: rgb(37 49 55 / 33%) !important;
}
#sidebar.sticky {
z-index: 3;
}
@supports (backdrop-filter: none) {
nav {
backdrop-filter: blur(16px) invert(0.1);
}
}
body.rtl nav {
left: unset;
right: -17em;
}
#sidebar.active {
left: 0;
}
#sidebar.rtl nav.active {
left: unset;
right: 0;
}
#sidebar .action {
width: 100%;
display: block;
white-space: nowrap;
height: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
body.rtl .action {
direction: rtl;
text-align: right;
}
#sidebar .action > * {
vertical-align: middle;
}
/* * * * * * * * * * * * * * * *
* FOOTER *
* * * * * * * * * * * * * * * */
.credits {
font-size: 1em;
color: var(--textSecondary);
padding-left: 1em;
padding-bottom: 1em;
}
.credits > span {
display: block;
margin-top: 0.5em;
margin-left: 0;
}
.credits a,
.credits a:hover {
color: inherit;
cursor: pointer;
}
.buffer {
flex-grow: 1;
}
.card-wrapper {
display: flex !important;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 1em !important;
min-height: 4em;
box-shadow: 0 2px 2px #00000024, 0 1px 5px #0000001f, 0 3px 1px -2px #0003;
/* overflow: auto; */
border-radius: 1em;
height: 100%;
}
.clickable {
cursor: pointer;
}
.clickable:hover {
box-shadow: 0 2px 2px #00000024, 0 1px 5px #0000001f, 0 3px 1px -2px #0003;
}
</style>
+12 -7
View File
@@ -92,7 +92,9 @@ main > div {
}
.breadcrumbs {
height: 3em;
overflow-x: auto;
height: auto;
min-height: 3em;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
display: flex;
align-items: center;
@@ -162,22 +164,25 @@ button:disabled {
}
#popup-notification {
color: white;
border-radius: 1em;
color: #fff;
position: fixed;
max-width: 90vw;
height: 4em;
bottom: 0;
right: -20em; /* Start off-screen */
right: -20em;
display: flex;
padding: 1em;
padding: 0.5em;
align-items: center;
transition: right 1s ease; /* Animate the 'right' property */
transition: right 1s ease;
z-index: 5;
margin: 1em;
height: auto;
}
#popup-notification-content {
color: white;
padding: 0;
padding-left: .5em;
padding: 1em;
}
#popup-notification.success {
+4
View File
@@ -103,6 +103,10 @@
border-color: var(--divider) !important;
}
.dark-mode #listingView.gallery .item .text {
text-shadow: 0 0 2px black;
}
/* Listing item modified text */
.dark-mode #listingView .item .modified {
color: var(--textSecondary);
+2 -1
View File
@@ -303,6 +303,7 @@ body.rtl .card .card-title>*:first-child {
height: 100%;
width: 100%;
z-index: 4;
top: 0;
animation: .3s show ease-in;
}
@@ -482,4 +483,4 @@ body.rtl .card .card-title>*:first-child {
body.rtl .credits {
text-align: right;
direction: ltr;
}
}
+2 -5
View File
@@ -9,16 +9,13 @@ header {
display: flex;
align-items: center;
justify-content: space-between;
background-color: white;
border-bottom: 1px solid rgba(0, 0, 0, 0.075);
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
background-color: rgb(255 255 255 / 50%) !important;
padding: 0.5em;
}
@supports (backdrop-filter: none) {
header {
background-color: transparent;
backdrop-filter: blur(16px) invert(0.1);
backdrop-filter: blur(16px);
}
}
+30 -32
View File
@@ -36,6 +36,7 @@ body.rtl #listingView {
align-items: center;
cursor: pointer;
user-select: none;
overflow:hidden;
}
#listingView .item div:last-of-type {
@@ -53,10 +54,6 @@ body.rtl #listingView {
font-size: 0.9em;
}
#listingView .item .name {
font-weight: bold;
}
#listingView .item i {
font-size: 4em;
margin-right: 0.1em;
@@ -103,7 +100,6 @@ body.rtl #listingView {
box-shadow: rgba(0, 0, 0, 0.06) 0px 1px 3px, rgba(0, 0, 0, 0.12) 0px 1px 2px;
}
#listingView.list .item,
#listingView.compact .item {
max-width: 100%;
@@ -122,25 +118,49 @@ body.rtl #listingView {
width: 100%;
}
#listingView.gallery .item div:first-of-type {
#listingView.gallery .item div {
width: 100%;
height: 12em;
height: 100%;
position: absolute;
padding: 0.5em;
}
#listingView.gallery .item {
min-width: 12em;
min-height: 12em;
padding: 0;
}
#listingView.normal .item,
#listingView.gallery .item {
transition: width 0.25s, height 0.25s;
}
#listingView.gallery .item .text {
width: 100%;
height: 100%;
display:flex;
min-width: 12em;
min-height: 12em;
text-shadow: 0 0 2px white;
}
#listingView.gallery .item div:last-of-type {
position: absolute;
bottom: 0.5em;
padding: 1em;
width: calc(100% - 1em);
text-align: center;
display: block;
}
#listingView.gallery .item[data-type=image] div:last-of-type {
color: white;
background: linear-gradient(#0000, #0009);
}
#listingView.gallery .item i {
display:flex !important;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
width: 100%;
margin-right: 0;
font-size: 8em;
@@ -388,25 +408,3 @@ body.rtl #listingView {
#listingView.list .header .active {
font-weight: bold;
}
#listingView #multiple-selection {
position: fixed;
bottom: -4em;
left: 0;
z-index: 99999;
width: 100%;
background-color: var(--blue);
height: 4em;
padding: 0.5em 0.5em 0.5em 1em;
justify-content: space-between;
transition: .2s ease bottom;
}
#listingView #multiple-selection.active {
bottom: 0;
}
#listingView #multiple-selection p,
#listingView #multiple-selection i {
color: var(--item-selected);
}
+2
View File
@@ -43,6 +43,8 @@
padding: .5em;
text-align: center;
animation: .2s opac forwards;
margin-bottom: 0.5em;
border-radius: 1em;
}
@keyframes opac {
+1
View File
@@ -174,6 +174,7 @@
"video": "Video"
},
"settings": {
"UserManagement": "User Management",
"admin": "Admin",
"administrator": "Administrator",
"allowCommands": "Execute commands",
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more