Compare commits

...
16 Commits
Author SHA1 Message Date
Graham Steffaniak edcbb909c4 Update search behavior (#194) 2024-08-24 19:10:39 -05:00
Graham Steffaniak 5bb316c0a3 adjusted frontend test 2024-08-24 16:44:21 -05:00
Graham Steffaniak e7f1f6f768 moved comparison chart 2024-08-24 16:27:19 -05:00
Graham Steffaniak 18eaa7b539 Squashed commit of the following:
commit a9e27fa93cd367a98964b282e73bdcf5b3345c1f
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 24 16:22:54 2024 -0500

    updated

commit 5f10bbc36dba06e5617e770116d4bd226be5520d
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 24 16:16:58 2024 -0500

    fixed sidebar

commit 72320068a4be2034d0c82e941bcddefc77c79c11
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 24 15:33:44 2024 -0500

    fix backend bug

commit ed1722381bbce4802ad7f8687a6fb650c3b9c516
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 24 13:53:53 2024 -0500

    updated file previews

commit 46dafa964c996991fc1eb0fea0c72c0bd527aeca
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 24 12:15:38 2024 -0500

    updated with bugfixes

commit a31f1a431dc1e0ca9bb6f5b942a4b33b792687b6
Author: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Date:   Sat Aug 24 11:04:40 2024 -0500

    updated with resizable gallery (#192)

commit d4df3ceb05
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Wed Aug 21 19:28:29 2024 -0500

    dev release

commit 48a25c6878
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Wed Aug 21 19:23:47 2024 -0500

    updated

commit e9789e3624
Author: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Date:   Wed Aug 21 19:18:39 2024 -0500

    change branding (#191)

commit 6e4a7d3eb0
Author: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Date:   Wed Aug 21 17:54:31 2024 -0500

    Update readme comparison (#190)

commit f81dbcf4d2
Author: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Date:   Wed Aug 21 14:02:04 2024 -0500

    Settings UI update (#189)

commit 110b4a02f0
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 17 19:04:08 2024 -0500

    updated

commit 0c9faa808a
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 17 19:01:32 2024 -0500

    updated

commit 967b2c2299
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 17 18:59:56 2024 -0500

    updated workflow

commit 008828055c
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 17 18:52:03 2024 -0500

    updated

commit bf8a2a83f4
Author: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Date:   Sun Aug 11 10:39:18 2024 -0500

    Goreleaser versioning and docker versioning (#187)

commit 1640e8bbfd
Author: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Date:   Sun Aug 11 10:39:00 2024 -0500

    Update deps (#188)

commit 9cbd2a709c
Merge: 03e0bc05 2f6c8b0b
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 10 19:29:02 2024 -0500

    Merge branch 'dev_v0.2.8' of github.com:gtsteffaniak/filebrowser into dev_v0.2.8

commit 03e0bc0555
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 10 19:28:27 2024 -0500

    updated linting

commit 2f6c8b0b89
Author: Graham Steffaniak <42989099+gtsteffaniak@users.noreply.github.com>
Date:   Sat Aug 10 19:27:18 2024 -0500

    changed permissions and backend requirements (#185)

commit 13ed6fe0ff
Author: Graham Steffaniak <gtsteff@gmail.com>
Date:   Sat Aug 10 19:22:29 2024 -0500

    updated sidebar behavior

commit ee5b785c07
Author: Graham Steffaniak <graham.steffaniak@autodesk.com>
Date:   Fri Aug 9 17:59:28 2024 -0500

    updated file behaviors

commit fa6b6df407
Author: Graham Steffaniak <graham.steffaniak@autodesk.com>
Date:   Tue Aug 6 07:22:05 2024 -0500

    updated

commit 1c81e22433
Author: Graham Steffaniak <graham.steffaniak@autodesk.com>
Date:   Tue Aug 6 07:21:00 2024 -0500

    as regular test

commit bfb364b946
Author: Graham Steffaniak <graham.steffaniak@autodesk.com>
Date:   Tue Aug 6 07:16:02 2024 -0500

    updated

commit 90daa56090
Author: Graham Steffaniak <graham.steffaniak@autodesk.com>
Date:   Mon Aug 5 16:37:39 2024 -0500

    updated
2024-08-24 16:24:34 -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
Graham Steffaniak 43b45203d0 workflow update (#169) 2024-08-04 10:28:38 -05:00
Graham Steffaniak af407068b6 Fix workflows (#165) 2024-08-04 09:56:18 -05:00
Graham Steffaniak 865fb4e243 ismobile fix (#163) 2024-08-03 15:43:08 -05:00
Graham Steffaniak c616b1473a updated ismobile 2024-08-03 15:38:43 -05:00
Graham Steffaniak 0479670c52 fix overlay bug, share bug (#161) 2024-08-03 15:04:50 -05:00
Graham Steffaniak fa3ed6b948 v0.2.7 update 2024-08-03 10:34:12 -05:00
Graham Steffaniak d8085c1f1b updated default config (#152) 2024-07-30 13:13:47 -05:00
Graham Steffaniak dc5da5662f fix default config (#151) 2024-07-30 13:09:34 -05:00
Graham Steffaniak b4bba3391d V0.2.6 (#150) 2024-07-30 12:45:27 -05:00
Graham Steffaniak 62f3953aea V0.2.5 (#125) 2024-06-12 14:51:13 -05:00
165 changed files with 6105 additions and 13607 deletions

No files matched your search

-5
View File
@@ -1,5 +0,0 @@
# These owners will be the default owners for everything in the repo.
# Unless a later match takes precedence, @o1egl will be requested for
# review when someone opens a pull request.
* @o1egl
-76
View File
@@ -1,76 +0,0 @@
name: dev
on:
push:
branches:
- 'dev_v*'
jobs:
test-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: cd backend && go test -race -v ./...
lint-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.2
- run: cd backend && golangci-lint run
format-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: cd backend && go fmt ./...
lint-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '20'
- run: cd frontend && npm i eslint
- run: cd frontend && npm run lint
push_dev_to_registry:
name: Push dev image
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
# 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:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
with:
images: gtstef/filebrowser
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+14 -46
View File
@@ -1,48 +1,12 @@
name: main job
name: main release
on:
push:
branches:
- 'main'
- "main"
jobs:
test-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: cd backend && go test -race -v ./...
lint-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.2
- run: cd backend && golangci-lint run
format-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: cd backend && go fmt ./...
lint-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '20'
- run: cd frontend && npm i eslint
- run: cd frontend && npm run lint
push_latest_to_registry:
needs: [lint-frontend, lint-backend, test-backend, format-backend]
name: Push latest
runs-on: ubuntu-latest
steps:
@@ -52,12 +16,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:
@@ -65,15 +23,25 @@ jobs:
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
uses: docker/metadata-action@v5
with:
images: gtstef/filebrowser
- name: Get latest release tag and commit SHA
id: get_tag_and_sha
run: |
latest_tag=$(git describe --tags `git rev-list --tags --max-count=1`)
latest_commit=$(git rev-list -n 1 $latest_tag)
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
echo "latest_commit=${latest_commit}" >> $GITHUB_ENV
- name: Build and push
uses: docker/build-push-action@v5
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: 'gtstef/filebrowser:latest'
labels: ${{ steps.meta.outputs.labels }}
labels: ${{ steps.meta.outputs.labels }}
-79
View File
@@ -1,79 +0,0 @@
name: pr-merge
on:
pull_request:
branches:
- 'main'
- 'dev_v*'
- 'v[0-9]+.[0-9]+.[0-9]+'
jobs:
test-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: cd backend && go test -race -v ./...
lint-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.2
- run: cd backend && golangci-lint run
format-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: 1.22.0
- run: cd backend && go fmt ./...
lint-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '20'
- run: cd frontend && npm i eslint
- run: cd frontend && npm run lint
push_pr_to_registry:
name: Push PR
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
# 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:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
with:
images: gtstef/filebrowser
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+56
View File
@@ -0,0 +1,56 @@
name: pr-request
on:
pull_request:
branches:
- "main"
- "v[0-9]+.[0-9]+.[0-9]+"
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
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: Build and push
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
version=${{ steps.meta.outputs.version }}
commitSHA=${{ steps.meta.outputs.revision }}
+44
View File
@@ -0,0 +1,44 @@
name: dev tests
on:
push:
branches:
- "*"
jobs:
test-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 'stable'
- working-directory: backend
run: go test -race -v ./...
lint-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22.5'
- uses: golangci/golangci-lint-action@v5
with:
version: v1.60
working-directory: backend
format-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 'stable'
- working-directory: backend
run: go fmt ./...
lint-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- working-directory: frontend
run: npm i eslint && npm run lint
+32 -42
View File
@@ -1,47 +1,41 @@
name: release
name: version release
on:
push:
branches:
- 'v[0-9]+.[0-9]+.[0-9]+'
- "v[0-9]+.[0-9]+.[0-9]+"
permissions:
contents: write
jobs:
test-backend:
create_release:
name: Create Release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
- name: Checkout code
uses: actions/checkout@v4
with:
go-version: 1.22.0
- run: cd backend && go test -race -v ./...
lint-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
token: ${{ secrets.PAT }}
- name: Extract branch name
shell: bash
run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT
id: extract_branch
- uses: actions/setup-go@v5
with:
go-version: 1.22.0
- run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.2
- run: cd backend && golangci-lint run
format-backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
go-version: 1.22.2
- name: Create Release
uses: softprops/action-gh-release@v2
with:
go-version: 1.22.0
- run: cd backend && go fmt ./...
lint-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '20'
- run: cd frontend && npm i eslint
- run: cd frontend && npm run lint
target_commitish: ${{ steps.extract_branch.outputs.branch }}
token: ${{ secrets.PAT }}
tag_name: ${{ steps.extract_branch.outputs.branch }}
prerelease: false
draft: false
generate_release_notes: true
name: ${{ steps.extract_branch.outputs.branch }}
push_release_to_registry:
needs: [lint-frontend, lint-backend, test-backend, format-backend]
name: Push release
runs-on: ubuntu-latest
steps:
@@ -51,21 +45,14 @@ 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 }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
uses: docker/metadata-action@v5
with:
images: gtstef/filebrowser
- name: Strip v from version number
@@ -76,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_OUTPUT
- 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: ${{ steps.modify-json.outputs.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
+31
View File
@@ -0,0 +1,31 @@
name: tag
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
update_tag:
name: Update Release tag
runs-on: ubuntu-latest
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:
args: release --clean
workdir: backend
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+5
View File
@@ -6,8 +6,13 @@ rice-box.go
/filebrowser
/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
+42 -2
View File
@@ -2,12 +2,52 @@
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.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
- **Change**: make search view and button behavior more consistent.
- **Fix**: [upload file bug](https://github.com/gtsteffaniak/filebrowser/issues/153)
- **Fix**: user lock out bug introduced in 0.2.6
- **Fix**: many minor state related issues.
## v0.2.6
This change focuses on minimizing and simplifying build process.
- **Change**: Migrated to Vite / Vue 3
- **Change**: removed npm modules
- replaced vuex with custom state management via src/store
- replaced noty with simple card popup notifications
- replaced moment with simple date formatter where needed
- replaced vue-simple-progress with vue component
- **Feature**: improved error logging
- backend errors show the root function that called them during the error
- frontend errors print errors to console that fail try/catch
- all frontend errors via popup notification & print to console as well
- **Fix**: Allow editing blank text based files in editor
- tweaked listing styles
- Feature: Allow disabling the index via configuration yaml
## v0.2.5
- Fix: delete user prompt works using native hovers.
## v0.2.4
- Faature: [create-folder-feature](https://github.com/gtsteffaniak/filebrowser/pull/105)
- Feature: [create-folder-feature](https://github.com/gtsteffaniak/filebrowser/pull/105)
- Feature: [playable shared video](https://github.com/filebrowser/filebrowser/issues/2537)
- Feature: photos, videos, and audio get embedded preview on share instead of icon
- FIX: sharable link bug, now uses special publicUser
- Fix: sharable link bug, now uses special publicUser
- Bump go version to 1.22
- In prep for vue3 migration, npm modules removed:
- js-base64
+15 -14
View File
@@ -1,22 +1,23 @@
FROM node:slim as nbuild
FROM golang:1.22-alpine AS base
ARG VERSION
ARG REVISION
WORKDIR /app
COPY ./frontend/package*.json ./
RUN npm ci --maxsockets 1
COPY ./frontend/ ./
RUN npm run build
COPY ./backend ./
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 golang:1.22-alpine as base
FROM node:slim AS nbuild
WORKDIR /app
COPY ./backend ./
RUN go get -u golang.org/x/net
RUN go build -ldflags="-w -s" -o filebrowser .
COPY ./frontend/package.json ./
RUN npm i --maxsockets 1
COPY ./frontend/ ./
RUN npm run build-docker
FROM alpine:latest
ARG app="/app/filebrowser"
RUN apk --no-cache add \
ca-certificates \
mailcap
WORKDIR /
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/
ENTRYPOINT [ "./filebrowser" ]
+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
+127 -50
View File
@@ -2,54 +2,78 @@
<a href="https://opensource.org/license/apache-2-0/"><img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" alt="License: Apache-2.0"></a>
</p>
<p align="center">
<img src="frontend/public/img/icons/favicon-256x256.png" width="100" title="Login With Custom URL">
<img src="frontend/public/img/icons/favicon-256x256.png" width="100" title="Login With Custom URL">
</p>
<h3 align="center">Filebrowser - A modern file manager for the web</h3>
<h3 align="center">Filebrowser Quantum - A modern web-based file manager</h3>
<p align="center">
<img width="800" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/899152cf-3e69-4179-aa82-752af2df3fc6" title="Main Screenshot">
<img width="800" src="https://github.com/user-attachments/assets/8ba93582-aba2-4996-8ac3-25f763a2e596" title="Main Screenshot">
</p>
> [!WARNING]
> Starting with v0.2.0, *ALL* configuration is done via `filebrowser.yaml` configuration file.
> Starting with v0.2.4 *ALL* share links need to be re-created (due to security fix).
> Starting with v0.2.0, *ALL* configuration is done via `filebrowser.yaml`
> Configuration file.
> 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
- realtime results as you type
- Works with more type filters
- interactive results page.
2. [x] Revamped and simplified GUI navbar and sidebar menu.
3. [x] **IMPORTANT** Revamped configuration via `filebrowser.yml` config file.
4. [x] More configurations possible at a per-user level
- <img width="450" alt="image" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/625bd7c4-5ee9-4011-aaae-2a388ab0813b">
5. [x] Additional compact view mode as well as refreshed view mode styles.
1. [x] Enhanced lightning fast indexed search
- Real-time results as you type
- Works with more type filters
- 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 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
and it 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 own
directory. It can be used as a standalone app.
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 asthetics and performance. Improved search,
simplified ui (without removing features) and more secure and up-to-date
build are just a few examples.
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.
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
- Improving performance and faster feedback when making changes.
- Minimize external dependencies and standard library usage.
- Of course -- adding much-needed features.
## Look
<p align="center">
<img width="500" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/35cdeb3b-ab79-4b04-8001-8f51f6ea06bb" title="Dark mode">
<img width="500" alt="image" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/55fa4f5c-440e-4a97-b711-96139208a163">
<img width="500" alt="image" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/c76f4100-949b-4e17-a3e6-e410fb8ec08f">
<img width="500" alt="image" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/0bde26f3-fa90-411e-bd0b-abaa47506d62">
<img width="560" alt="image" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/71d8f2b8-6fe6-4fdc-8aac-503d08c28d86">
One way you can observe the improved user experience is how I changed
the UI. The Navbar is simplified to a three-component system :
1. (Left) The slide-out action panel button
2. (Middle) The powerful search bar.
3. (Right) The view change toggle.
All other functions are moved either into the action menu or popup menus.
If the action does not depend on context, it will exist in the slide-out
action panel. If the action is available based on context, it will show up as
a popup menu.
<p align="center">
<img width="800" src="https://github.com/gtsteffaniak/filebrowser/assets/42989099/899152cf-3e69-4179-aa82-752af2df3fc6" title="Main Screenshot">
<img width="800" src="https://github.com/user-attachments/assets/18c02d03-5c60-4e15-9c32-3cfe058a0c49" title="Main Screenshot">
<img width="800" src="https://github.com/user-attachments/assets/75226dc4-9802-46f0-9e3c-e4403d3275da" title="Main Screenshot">
</p>
## Install
Using docker:
@@ -60,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
@@ -101,43 +125,96 @@ volumes:
```
Not using docker (not recommended)
Not using docker (not recommended), download your binary from releases and run with your custom config file:
```
./filebrowser -f <filebrowser.yml or other /path/to/config.yaml>
./filebrowser -c <filebrowser.yml or other /path/to/config.yaml>
```
## Configuration
All configuration is now done via a single configuration file: `filebrowser.yaml`, here is an example minimal [configuration file](./backend/filebrowser.yaml).
All configuration is now done via a single configuration file:
`filebrowser.yaml`, here is an example of minimal [configuration
file](./backend/filebrowser.yaml).
View the [Configuration Help Page](./configuration.md) for available configuration options and other help.
View the [Configuration Help Page](./configuration.md) for available
configuration options and other help.
## Migration from filebrowser/filebrowser
If you are currently using filebrowser from the filebrowser/filebrowser repo, 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:
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:
1. Create a configuration file as mentioned above.
2. Copy your database file from the original filebrowser to the path of the new one.
3. Update the configuration file to use the database (under server in filebrowser.yml)
4. If you are using docker, update the docker-compose file or docker run command to use the config file as described in the install section above.
5. If you are not using docker, just make sure you run filebrowser -f filebrowser.yml and have valid filebrowser config.
2. Copy your database file from the original filebrowser to the path of
the new one.
3. Update the configuration file to use the database (under server in
filebrowser.yml)
4. If you are using docker, update the docker-compose file or docker run
command to use the config file as described in the install section
above.
5. If you are not using docker, just make sure you run filebrowser -c
filebrowser.yml and have a valid filebrowser config.
The filebrowser 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.
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.
### background & help
The original project filebrowser/filebrowser used multiple different ways to configure the server.
This was confusing and difficult to work with from a user and from a developer's perspective.
So I completely redesigned the program to use one single human-readable config file.
## Comparison Chart
I understand many coming from the original fork may notice differences which make using this improved version more difficult. If you notice issues that you believe should be fixed, please open an issue here and it will very likely be addressed with a PR within a few weeks.
This version of filebrowser is going through a configuration overhaul as mentioned above. Certain features related to rules and commands may not work as they do on the original filebrowser. The purpose of this is to create a more consistent experience where configuration is done via files rather than running commands, so that it's very clear what the current state of the configuration is. When running commands its not clear what the configuration is.
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
+43
View File
@@ -0,0 +1,43 @@
# .goreleaser.yaml
project_name: filebrowser
version: 2
builds:
# 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
goarch:
- amd64
- arm
- arm64
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
+4
View File
@@ -0,0 +1,4 @@
# Ignore everything in this directory
*
# Except this file
!.gitignore
+58 -27
View File
@@ -3,6 +3,7 @@ package cmd
import (
"crypto/tls"
"flag"
"fmt"
"io/fs"
"log"
"net"
@@ -12,9 +13,10 @@ import (
"strconv"
"syscall"
"embed"
"github.com/spf13/pflag"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/gtsteffaniak/filebrowser/auth"
@@ -26,6 +28,11 @@ import (
"github.com/gtsteffaniak/filebrowser/users"
)
//go:embed dist/*
var assets embed.FS
var nonEmbededFS = os.Getenv("FILEBROWSER_NO_EMBEDED") == "true"
type dirFS struct {
http.Dir
}
@@ -41,6 +48,7 @@ func init() {
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
log.Println("Initializing with config file:", *configFlag)
log.Println("Embeded Frontend:", !nonEmbededFS)
settings.Initialize(*configFlag)
}
@@ -55,58 +63,81 @@ 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, true)
go files.InitializeIndex(serverConfig.IndexingInterval, serverConfig.Indexing)
_, err := os.Stat(serverConfig.Root)
checkErr(err)
checkErr(fmt.Sprint("cmd os.Stat ", serverConfig.Root), err)
var listener net.Listener
address := serverConfig.Address + ":" + strconv.Itoa(serverConfig.Port)
switch {
case serverConfig.Socket != "":
listener, err = net.Listen("unix", serverConfig.Socket)
checkErr(err)
checkErr("net.Listen", err)
socketPerm, err := cmd.Flags().GetUint32("socket-perm") //nolint:govet
checkErr(err)
checkErr("cmd.Flags().GetUint32", err)
err = os.Chmod(serverConfig.Socket, os.FileMode(socketPerm))
checkErr(err)
checkErr("os.Chmod", err)
case serverConfig.TLSKey != "" && serverConfig.TLSCert != "":
cer, err := tls.LoadX509KeyPair(serverConfig.TLSCert, serverConfig.TLSKey) //nolint:govet
checkErr(err)
checkErr("tls.LoadX509KeyPair", err)
listener, err = tls.Listen("tcp", address, &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cer}},
)
checkErr(err)
checkErr("tls.Listen", err)
default:
listener, err = net.Listen("tcp", address)
checkErr(err)
checkErr("net.Listen", err)
}
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(err)
defer listener.Close()
log.Println("Listening on", listener.Addr().String())
//nolint: gosec
if err := http.Serve(listener, handler); err != nil {
log.Fatal(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}),
}
func StartFilebrowser() {
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
log.Fatal("Error starting filebrowser:", err)
}
}
@@ -121,16 +152,16 @@ func quickSetup(d pythonData) {
settings.Config.Auth.Key = generateKey()
if settings.Config.Auth.Method == "noauth" {
err := d.store.Auth.Save(&auth.NoAuth{})
checkErr(err)
checkErr("d.store.Auth.Save", err)
} else {
settings.Config.Auth.Method = "password"
err := d.store.Auth.Save(&auth.JSONAuth{})
checkErr(err)
checkErr("d.store.Auth.Save", err)
}
err := d.store.Settings.Save(&settings.Config)
checkErr(err)
checkErr("d.store.Settings.Save", err)
err = d.store.Settings.SaveServer(&settings.Config.Server)
checkErr(err)
checkErr("d.store.Settings.SaveServer", err)
user := &users.User{}
settings.Config.UserDefaults.Apply(user)
user.Username = settings.Config.Auth.AdminUsername
@@ -150,5 +181,5 @@ func quickSetup(d pythonData) {
Admin: true,
}
err = d.store.Users.Save(user)
checkErr(err)
checkErr("d.store.Users.Save", err)
}
+4 -4
View File
@@ -42,23 +42,23 @@ including 'index_end'.`,
},
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
i, err := strconv.Atoi(args[0])
checkErr(err)
checkErr("strconv.Atoi", err)
f := i
if len(args) == 2 { //nolint:gomnd
f, err = strconv.Atoi(args[1])
checkErr(err)
checkErr("strconv.Atoi", err)
}
user := func(u *users.User) {
u.Rules = append(u.Rules[:i], u.Rules[f+1:]...)
err := d.store.Users.Save(u)
checkErr(err)
checkErr("d.store.Users.Save", err)
}
global := func(s *settings.Settings) {
s.Rules = append(s.Rules[:i], s.Rules[f+1:]...)
err := d.store.Settings.Save(s)
checkErr(err)
checkErr("d.store.Settings.Save", err)
}
runRules(d.store, cmd, user, global)
+2 -2
View File
@@ -33,7 +33,7 @@ func runRules(st *storage.Storage, cmd *cobra.Command, usersFn func(*users.User)
id := getUserIdentifier(cmd.Flags())
if id != nil {
user, err := st.Users.Get("", id)
checkErr(err)
checkErr("st.Users.Get", err)
if usersFn != nil {
usersFn(user)
@@ -44,7 +44,7 @@ func runRules(st *storage.Storage, cmd *cobra.Command, usersFn func(*users.User)
}
s, err := st.Settings.Get()
checkErr(err)
checkErr("st.Settings.Get", err)
if globalFn != nil {
globalFn(s)
+2 -2
View File
@@ -44,13 +44,13 @@ var rulesAddCmd = &cobra.Command{
user := func(u *users.User) {
u.Rules = append(u.Rules, rule)
err := d.store.Users.Save(u)
checkErr(err)
checkErr("d.store.Users.Save", err)
}
global := func(s *settings.Settings) {
s.Rules = append(s.Rules, rule)
err := d.store.Settings.Save(s)
checkErr(err)
checkErr("d.store.Settings.Save", err)
}
runRules(d.store, cmd, user, global)
+4 -4
View File
@@ -22,19 +22,19 @@ var usersAddCmd = &cobra.Command{
LockPassword: mustGetBool(cmd.Flags(), "lockPassword"),
}
servSettings, err := d.store.Settings.GetServer()
checkErr(err)
checkErr("d.store.Settings.GetServer()", err)
// since getUserDefaults() polluted s.Defaults.Scope
// which makes the Scope not the one saved in the db
// we need the right s.Defaults.Scope here
s2, err := d.store.Settings.Get()
checkErr(err)
checkErr("d.store.Settings.Get()", err)
userHome, err := s2.MakeUserDir(user.Username, user.Scope, servSettings.Root)
checkErr(err)
checkErr("s2.MakeUserDir", err)
user.Scope = userHome
err = d.store.Users.Save(user)
checkErr(err)
checkErr("d.store.Users.Save", err)
printUsers([]*users.User{user})
}, pythonConfig{}),
}
+2 -2
View File
@@ -16,9 +16,9 @@ path to the file where you want to write the users.`,
Args: jsonYamlArg,
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
list, err := d.store.Users.Gets("")
checkErr(err)
checkErr("d.store.Users.Gets", err)
err = marshal(args[0], list)
checkErr(err)
checkErr("marshal", err)
}, pythonConfig{}),
}
+1 -1
View File
@@ -46,6 +46,6 @@ var findUsers = python(func(cmd *cobra.Command, args []string, d pythonData) {
list, err = d.store.Users.Gets("")
}
checkErr(err)
checkErr("findUsers", err)
printUsers(list)
}, pythonConfig{})
+10 -13
View File
@@ -27,28 +27,23 @@ list or set it to 0.`,
Args: jsonYamlArg,
Run: python(func(cmd *cobra.Command, args []string, d pythonData) {
fd, err := os.Open(args[0])
checkErr(err)
checkErr("os.Open", err)
defer fd.Close()
list := []*users.User{}
err = unmarshal(args[0], &list)
checkErr(err)
for _, user := range list {
err = user.Clean("")
checkErr(err)
}
checkErr("unmarshal", err)
if mustGetBool(cmd.Flags(), "replace") {
oldUsers, err := d.store.Users.Gets("")
checkErr(err)
checkErr("d.store.Users.Gets", err)
err = marshal("users.backup.json", list)
checkErr(err)
checkErr("marshal users.backup.json", err)
for _, user := range oldUsers {
err = d.store.Users.Delete(user.ID)
checkErr(err)
checkErr("d.store.Users.Delete", err)
}
}
@@ -60,7 +55,8 @@ list or set it to 0.`,
// User exists in DB.
if err == nil {
if !overwrite {
checkErr(errors.New("user " + strconv.Itoa(int(user.ID)) + " is already registred"))
newErr := errors.New("user " + strconv.Itoa(int(user.ID)) + " is already registered")
checkErr("", newErr)
}
// If the usernames mismatch, check if there is another one in the DB
@@ -68,7 +64,8 @@ list or set it to 0.`,
// operation
if user.Username != onDB.Username {
if conflictuous, err := d.store.Users.Get("", user.Username); err == nil { //nolint:govet
checkErr(usernameConflictError(user.Username, conflictuous.ID, user.ID))
newErr := usernameConflictError(user.Username, conflictuous.ID, user.ID)
checkErr("usernameConflictError", newErr)
}
}
} else {
@@ -78,7 +75,7 @@ list or set it to 0.`,
}
err = d.store.Users.Save(user)
checkErr(err)
checkErr("d.store.Users.Save", err)
}
}, pythonConfig{}),
}
+1 -1
View File
@@ -25,7 +25,7 @@ var usersRmCmd = &cobra.Command{
err = d.store.Users.Delete(id)
}
checkErr(err)
checkErr("usersRmCmd", err)
fmt.Println("user deleted successfully")
}, pythonConfig{}),
}
+2 -2
View File
@@ -29,10 +29,10 @@ options you want to change.`,
} else {
user, err = d.store.Users.Get("", username)
}
checkErr(err)
checkErr("d.store.Users.Get", err)
err = d.store.Users.Update(user)
checkErr(err)
checkErr("d.store.Users.Update", err)
printUsers([]*users.User{user})
}, pythonConfig{}),
}
+12 -10
View File
@@ -3,6 +3,7 @@ package cmd
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path/filepath"
@@ -17,33 +18,33 @@ import (
"github.com/gtsteffaniak/filebrowser/storage/bolt"
)
func checkErr(err error) {
func checkErr(source string, err error) {
if err != nil {
log.Fatal(err)
log.Fatalf("%s: %v", source, err)
}
}
func mustGetString(flags *pflag.FlagSet, flag string) string {
s, err := flags.GetString(flag)
checkErr(err)
checkErr("mustGetString", err)
return s
}
func mustGetBool(flags *pflag.FlagSet, flag string) bool {
b, err := flags.GetBool(flag)
checkErr(err)
checkErr("mustGetBool", err)
return b
}
func mustGetUint(flags *pflag.FlagSet, flag string) uint {
b, err := flags.GetUint(flag)
checkErr(err)
checkErr("mustGetUint", err)
return b
}
func generateKey() []byte {
k, err := settings.GenerateKey()
checkErr(err)
checkErr("generateKey", err)
return k
}
@@ -96,18 +97,19 @@ func python(fn pythonFunc, cfg pythonConfig) cobraFunc {
data.hadDB = exists
db, err := storm.Open(path)
checkErr(err)
checkErr(fmt.Sprintf("storm.Open path %v", path), err)
defer db.Close()
data.store, err = bolt.NewStorage(db)
checkErr(err)
checkErr("bolt.NewStorage", err)
fn(cmd, args, data)
}
}
func marshal(filename string, data interface{}) error {
fd, err := os.Create(filename)
checkErr(err)
checkErr("os.Create", err)
defer fd.Close()
switch ext := filepath.Ext(filename); ext {
@@ -125,7 +127,7 @@ func marshal(filename string, data interface{}) error {
func unmarshal(filename string, data interface{}) error {
fd, err := os.Open(filename)
checkErr(err)
checkErr("os.Open", err)
defer fd.Close()
switch ext := filepath.Ext(filename); ext {
+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
+179 -77
View File
@@ -6,21 +6,21 @@ import (
"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,7 @@ type FileInfo struct {
// FileOptions are the options when getting a file info.
type FileOptions struct {
Fs afero.Fs
Path string
Path string // realpath
Modify bool
Expand bool
ReadHeader bool
@@ -91,7 +89,7 @@ func NewFileInfo(opts FileOptions) (*FileInfo, error) {
}
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
@@ -123,7 +121,7 @@ func FileInfoFaster(opts FileOptions) (*FileInfo, error) {
if exists && !opts.Content {
// Check if the cache time is less than 1 second
if time.Since(info.CacheTime) > time.Second {
go refreshFileInfo(opts)
go RefreshFileInfo(opts)
}
// refresh cache after
return &info, nil
@@ -133,7 +131,7 @@ func FileInfoFaster(opts FileOptions) (*FileInfo, error) {
file, err := NewFileInfo(opts)
return file, err
}
updated := refreshFileInfo(opts)
updated := RefreshFileInfo(opts)
if !updated {
file, err := NewFileInfo(opts)
return file, err
@@ -146,7 +144,7 @@ func FileInfoFaster(opts FileOptions) (*FileInfo, error) {
}
}
func refreshFileInfo(opts FileOptions) bool {
func RefreshFileInfo(opts FileOptions) bool {
if !opts.Checker.Check(opts.Path) {
return false
}
@@ -166,60 +164,37 @@ func refreshFileInfo(opts FileOptions) bool {
if err != nil {
return false
}
//_, exists := index.GetFileMetadata(adjustedPath)
return index.UpdateFileMetadata(adjustedPath, *file)
} else {
//_, exists := index.GetFileMetadata(adjustedPath)
return index.UpdateFileMetadata(adjustedPath, *file)
}
}
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
}
}
info, err := os.Lstat(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{
Path: opts.Path,
Name: info.Name(),
ModTime: info.ModTime(),
Mode: info.Mode(),
Size: info.Size(),
Extension: filepath.Ext(info.Name()),
Token: opts.Token,
}
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,
if info.IsDir() {
file.IsDir = true
}
if info.Mode()&os.ModeSymlink != 0 {
file.IsSymlink = true
targetInfo, err := os.Stat(path)
if err == nil {
file.Size = targetInfo.Size()
file.IsDir = targetInfo.IsDir()
}
}
@@ -237,7 +212,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,37 +241,147 @@ 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, 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 "", err
}
if !Exists(absolutePath) {
return absolutePath, 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
}
parentDir := filepath.Dir(absPath)
opts.Path = parentDir
updated := RefreshFileInfo(opts)
if !updated {
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)
updated := RefreshFileInfo(opts)
if !updated {
return errors.ErrEmptyKey
}
return i.Path
return nil
}
func WriteFile(opts FileOptions, in io.Reader) error {
fmt.Println("writing file", opts.Path)
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
}
// 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
}
fmt.Println("refreshing info for ", parentDir)
opts.Path = parentDir
updated := RefreshFileInfo(opts)
if !updated {
return errors.ErrEmptyKey
}
return nil
}
// resolveSymlinks resolves symlinks in the given path
func resolveSymlinks(path string) (string, error) {
for {
// Get the file info
info, err := os.Lstat(path)
if err != nil {
return "", 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 "", err
}
// Resolve the target relative to the symlink's directory
path = filepath.Join(filepath.Dir(path), target)
} else {
// Not a symlink, so we are done
return path, 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
}
c := string(string(content))
if !utf8.ValidString(c) {
stringContent := string(content)
if !utf8.ValidString(stringContent) {
return nil
}
i.Content = string(c)
if stringContent == "" {
i.Content = "empty-file-x6OlSil"
return nil
}
i.Content = stringContent
}
return nil
}
// 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 {
@@ -341,7 +426,6 @@ func (i *FileInfo) detectType(path string, modify, saveContent, readHeader bool)
}
}
}
if i.Type == "" {
i.Type = "blob"
if saveContent {
@@ -354,15 +438,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
@@ -383,7 +467,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
@@ -408,8 +493,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
}
@@ -421,7 +511,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)
@@ -432,7 +522,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 {
@@ -474,6 +564,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
}
@@ -494,3 +585,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
}
+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)
+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]
+6
View File
@@ -0,0 +1,6 @@
{
"name": "frontend",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}
+16 -16
View File
@@ -1,27 +1,27 @@
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
github.com/marusama/semaphore/v2 v2.5.0
github.com/mholt/archiver/v3 v3.5.1
github.com/shirou/gopsutil/v3 v3.24.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.8.4
github.com/stretchr/testify v1.9.0
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce
golang.org/x/crypto v0.18.0
golang.org/x/image v0.15.0
golang.org/x/text v0.14.0
golang.org/x/crypto v0.26.0
golang.org/x/image v0.19.0
golang.org/x/text v0.17.0
)
require (
@@ -30,27 +30,27 @@ require (
github.com/dsnet/compress v0.0.2-0.20210315054119-f66993602bf5 // indirect
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 // indirect
github.com/fatih/color v1.16.0 // indirect
github.com/fatih/color v1.17.0 // indirect
github.com/go-errors/errors v1.5.1 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/golang/geo v0.0.0-20230421003525-6adc56603217 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/klauspost/compress v1.17.6 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/klauspost/pgzip v1.2.6 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/nwaples/rardecode v1.1.3 // indirect
github.com/pierrec/lz4/v4 v4.1.21 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect
github.com/ulikunitz/xz v0.5.11 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
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.8 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect
go.etcd.io/bbolt v1.3.10 // 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
)
+41 -51
View File
@@ -8,8 +8,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/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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=
@@ -36,8 +35,8 @@ github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349 h1:DilThiXje
github.com/dsoprea/go-utility/v2 v2.0.0-20221003172846-a3e1774ef349/go.mod h1:4GC5sXji84i/p+irqghpPFZBF8tRN/Q7+700G0/DLe8=
github.com/fatih/color v1.10.0 h1:s36xzo75JdqLaaWoiEHk767eHiwo0598uUxyfiPkDsg=
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4=
github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
@@ -57,8 +56,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=
@@ -77,8 +76,6 @@ github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEW
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
@@ -90,8 +87,8 @@ github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c
github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.11.4 h1:kz40R/YWls3iqT9zX9AHN3WoVsrAWVyui5sxuLqiXqU=
github.com/klauspost/compress v1.11.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.17.6 h1:60eq2E/jlfwQXtvZEeBUYADs+BwKBWURIY+Gj2eRGjI=
github.com/klauspost/compress v1.17.6/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE=
github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
@@ -104,7 +101,6 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
github.com/marusama/semaphore/v2 v2.5.0 h1:o/1QJD9DBYOWRnDhPwDVAXQn6mQYD0gZaS1Tpx6DJGM=
github.com/marusama/semaphore/v2 v2.5.0/go.mod h1:z9nMiNUekt/LTpTUQdpp+4sJeYqUGpwMHfW0Z8V8fnQ=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
@@ -130,54 +126,47 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b h1:0LFwY6Q3gMACTjAbMZBjXAqTOzOwFaj2Ld6cjeQ7Rig=
github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shirou/gopsutil/v3 v3.24.1 h1:R3t6ondCEvmARp3wxODhXMTLC/klMa87h2PHUw5m7QI=
github.com/shirou/gopsutil/v3 v3.24.1/go.mod h1:UU7a2MSBQa+kW1uuDq8DeEBS8kmrnQwsv2b5O513rwU=
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
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/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce h1:fb190+cK2Xz/dvi9Hv8eCYJYvIGUTN2/KLq1pT6CjEc=
github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4=
github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.9 h1:RsKRIA2MO8x56wkkcd3LbtcE/uMszhb6DpRf+3uwa3I=
github.com/ulikunitz/xz v0.5.9/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.11 h1:kpFauv27b6ynzBNT/Xy+1k+fK4WswhN/6PN5WhFAGw8=
github.com/ulikunitz/xz v0.5.11/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.12 h1:37Nm15o69RwBkXM0J6A5OlE67RZTfzUxTj8fB3dfcsc=
github.com/ulikunitz/xz v0.5.12/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/vmihailenco/msgpack v4.0.4+incompatible h1:dSLoQfGFAo3F6OoNhwUmLwVgaUXK79GlxNBwueZn0xI=
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
github.com/yusufpapurcu/wmi v1.2.3 h1:E1ctvB7uKFMOJw3fdOW32DwGE9I7t++CRUEMKvFoFiw=
github.com/yusufpapurcu/wmi v1.2.3/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
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 h1:hi1bXHMVrlQh6WwxAy+qZCV/SYIlqo+Ushwdpa4tAKg=
go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA=
go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
go.etcd.io/bbolt v1.3.10 h1:+BqfJTcCzTItrop8mq/lbzL8wSGtj94UO/3U31shqG0=
go.etcd.io/bbolt v1.3.10/go.mod h1:bK3UQLPJZly7IlNmV7uVHJDxfe5aK9Ll93e/74Y9oEQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
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.15.0 h1:kOELfmgrmJlw4Cdb7g/QGuB3CvDrXbqEIww/pNtNBm8=
golang.org/x/image v0.15.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE=
golang.org/x/image v0.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ=
golang.org/x/image v0.18.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=
@@ -185,10 +174,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.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
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/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-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -203,22 +192,24 @@ 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.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.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.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
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-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8=
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=
@@ -231,6 +222,5 @@ gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Binary file not shown.
+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
}
+20 -22
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"
@@ -20,33 +19,27 @@ import (
var withHashFile = func(fn handleFunc) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
id, path := ifPathWithName(r)
fmt.Println(id, path)
link, err := d.store.Share.GetByHash(id)
if err != nil {
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) // Assign to the existing `err` variable
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, 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,
Modify: d.user.Perm.Modify,
Expand: false,
Expand: true,
ReadHeader: d.server.TypeDetectionByHeader,
Checker: d,
Token: link.Token,
@@ -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
}
+9 -6
View File
@@ -5,6 +5,7 @@ import (
"log"
"net/http"
"net/url"
"os"
gopath "path"
"path/filepath"
"strings"
@@ -80,10 +81,12 @@ var rawHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data)
if !d.user.Perm.Download {
return http.StatusAccepted, nil
}
realPath, 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,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: d.server.TypeDetectionByHeader,
@@ -108,7 +111,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 +120,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 +201,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
}
+63 -119
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, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
fmt.Println("unable to get real path", d.user.Scope, r.URL.Path)
return http.StatusNotFound, err
}
file, err := files.FileInfoFaster(files.FileOptions{
Fs: d.user.Fs,
Path: r.URL.Path,
Path: realPath,
Modify: d.user.Perm.Modify,
Expand: true,
ReadHeader: d.server.TypeDetectionByHeader,
@@ -53,15 +55,18 @@ 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, err := files.GetRealPath(d.user.Scope, r.URL.Path)
if err != nil {
return http.StatusNotFound, err
}
fileOpts := files.FileOptions{
Path: realPath,
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 +77,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 +90,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, 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,
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 +126,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,28 +141,22 @@ 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, 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,
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
@@ -186,29 +172,22 @@ 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 {
fmt.Println("hook", src, dst)
return patchAction(r.Context(), action, src, dst, d, fileCache)
}, action, src, dst, d.user)
@@ -216,65 +195,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
}
return info, nil
}
func delThumbs(ctx context.Context, fileCache FileCache, file *files.FileInfo) error {
for _, previewSizeName := range PreviewSizeNames() {
size, _ := ParsePreviewSize(previewSizeName)
@@ -294,17 +230,23 @@ 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, 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,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: false,
@@ -320,7 +262,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)
}
@@ -332,9 +274,12 @@ type DiskUsageResponse struct {
}
var diskUsage = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
realPath, 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,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: false,
@@ -350,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
})
+6 -2
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",
@@ -65,7 +66,10 @@ func handleWithStaticData(w http.ResponseWriter, _ *http.Request, d *data, fSys
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 != ""
@@ -104,7 +108,7 @@ func getStaticHandlers(store *storage.Storage, server *settings.Server, assetsFs
}
w.Header().Set("x-xss-protection", "1; mode=block")
return handleWithStaticData(w, r, d, assetsFs, "index.html", "text/html; charset=utf-8")
return handleWithStaticData(w, r, d, assetsFs, "public/index.html", "text/html; charset=utf-8")
}, "", store, server)
static = handle(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
+24 -20
View File
@@ -2,8 +2,10 @@ package http
import (
"encoding/json"
"fmt"
"log"
"net/http"
"reflect"
"sort"
"strconv"
@@ -12,6 +14,7 @@ import (
"golang.org/x/text/language"
"github.com/gtsteffaniak/filebrowser/errors"
"github.com/gtsteffaniak/filebrowser/files"
"github.com/gtsteffaniak/filebrowser/users"
)
@@ -135,7 +138,11 @@ var userPostHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *
}
req.Data.Scope = userHome
log.Printf("user: %s, home dir: [%s].", req.Data.Username, userHome)
_, err = files.GetRealPath(d.server.Root, req.Data.Scope)
if err != nil {
fmt.Println("user path is not valid", req.Data.Scope)
return http.StatusBadRequest, nil
}
err = d.store.Users.Save(req.Data)
if err != nil {
return http.StatusInternalServerError, err
@@ -154,31 +161,29 @@ 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 || (len(req.Which) == 1 && req.Which[0] == "all") {
if !d.user.Perm.Admin {
return http.StatusForbidden, nil
}
if req.Data.Password != "" {
req.Data.Password, err = users.HashPwd(req.Data.Password)
} else {
var suser *users.User
suser, err = d.store.Users.Get(d.server.Root, d.raw.(uint))
req.Data.Password = suser.Password
}
if err != nil {
return http.StatusInternalServerError, err
}
if len(req.Which) == 0 || req.Which[0] == "all" {
req.Which = []string{}
v := reflect.ValueOf(req.Data)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.Name != "Password" && field.Name != "Fs" {
req.Which = append(req.Which, field.Name)
}
}
}
for k, v := range req.Which {
v = cases.Title(language.English, cases.NoLower).String(v)
req.Which[k] = v
if v == "Password" {
if !d.user.Perm.Admin && d.user.LockPassword {
return http.StatusForbidden, nil
@@ -195,7 +200,6 @@ var userPutHandler = withSelfOrAdmin(func(w http.ResponseWriter, r *http.Request
}
}
}
err = d.store.Users.Update(req.Data, req.Which...)
if err != nil {
return http.StatusInternalServerError, err
+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 {
+3
View File
@@ -58,6 +58,7 @@ func setDefaults() Settings {
Database: "database.db",
Log: "stdout",
Root: "/srv",
Indexing: true,
},
Auth: Auth{
TokenExpirationTime: "2h",
@@ -70,6 +71,7 @@ func setDefaults() Settings {
},
},
UserDefaults: UserDefaults{
StickySidebar: true,
Scope: ".",
LockPassword: false,
HideDotfiles: true,
@@ -91,6 +93,7 @@ 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
+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{}
}
+3
View File
@@ -54,6 +54,7 @@ type Server struct {
Root string `json:"root"`
UserHomeBasePath string `json:"userHomeBasePath"`
CreateUserDir bool `json:"createUserDir"`
Indexing bool `json:"indexing"`
}
type Frontend struct {
@@ -67,12 +68,14 @@ type Frontend struct {
// UserDefaults is a type that holds the default values
// for some fields on User.
type UserDefaults struct {
StickySidebar bool `json:"stickySidebar"`
DarkMode bool `json:"darkMode"`
LockPassword bool `json:"lockPassword"`
DisableSettings bool `json:"disableSettings,omitempty"`
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 {
+1 -3
View File
@@ -55,7 +55,6 @@ func (st usersBackend) Update(user *users.User, fields ...string) error {
if len(fields) == 0 {
return st.Save(user)
}
for _, field := range fields {
userField := reflect.ValueOf(user).Elem().FieldByName(field)
if !userField.IsValid() {
@@ -63,10 +62,9 @@ func (st usersBackend) Update(user *users.User, fields ...string) error {
}
val := userField.Interface()
if err := st.db.UpdateField(user, field, val); err != nil {
return err
return fmt.Errorf("Error updating user field: %s, error: %v", field, err.Error())
}
}
return nil
}
+1 -19
View File
@@ -54,9 +54,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 +63,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
}
@@ -138,10 +124,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)
}
+2 -25
View File
@@ -1,11 +1,8 @@
package users
import (
"path/filepath"
"regexp"
"github.com/spf13/afero"
"github.com/gtsteffaniak/filebrowser/rules"
)
@@ -28,6 +25,7 @@ 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"`
@@ -41,10 +39,10 @@ type User struct {
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"`
GallerySize int `json:"gallerySize"`
}
var PublicUser = User{
@@ -53,7 +51,6 @@ var PublicUser = User{
Scope: "./",
ViewMode: "normal",
LockPassword: true,
Fs: afero.NewMemMapFs(),
Perm: Permissions{
Create: false,
Rename: false,
@@ -70,26 +67,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 {
+3 -4
View File
@@ -1,8 +1,7 @@
package version
var (
// Version is the current File Browser version.
Version = "(0.2.4)"
// CommitSHA is the commmit sha.
CommitSHA = "(unknown)"
// Dynamically updated during build via build args
Version = "untracked"
CommitSHA = "untracked"
)
+3 -8
View File
@@ -11,6 +11,7 @@ server:
CreateUserDir: false
UserHomeBasePath: ""
indexingInterval: 5
indexing: true
numImageProcessors: 4
socket: ""
tlsKey: ""
@@ -34,9 +35,7 @@ auth:
tokenExpirationTime: 2h
header: ""
method: json
command: ""
signup: false
shell: ""
frontend:
name: ""
disableExternal: false
@@ -62,7 +61,6 @@ userDefaults:
delete: true
share: true
download: true
commands: []
hideDotfiles: false
dateFormat: false
```
@@ -113,6 +111,8 @@ userDefaults:
- `indexingInterval`: This is the time in minutes the system waits before checking for filesystem changes. Default: `5`
- `indexing`: This enables or disables indexing. (Note: search will not work without indexing) Default: `true`
- `numImageProcessors`: This is the number of image processors available. Default: `4`
- `socket`: This is the socket configuration.
@@ -162,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`
@@ -224,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`)
+26
View File
@@ -0,0 +1,26 @@
{
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/eslint-config-typescript"
],
"rules": {
"vue/multi-word-component-names": "off",
"vue/no-mutating-props": [
"error",
{
"shallowOnly": true
}
]
// no-undef is already included in
// @vue/eslint-config-typescript
},
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
}
}
-16
View File
@@ -1,16 +0,0 @@
env:
browser: true
es2021: true
extends:
- eslint:recommended
- plugin:vue/vue3-essential
parserOptions:
ecmaVersion: latest
sourceType: module
plugins:
- vue
rules:
vue/multi-word-component-names: off
vue/no-reserved-component-names: warn
vue/no-mutating-props: off
vue/no-deprecated-v-bind-sync: warn
-3
View File
@@ -1,3 +0,0 @@
module.exports = {
presets: ["@vue/app"],
};
+1
View File
@@ -0,0 +1 @@
frontend
-47
View File
@@ -1,47 +0,0 @@
{
"name": "filebrowser-frontend",
"version": "2.0.0",
"private": true,
"scripts": {
// vue 3 changes needed
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"fix": "npx vue-cli-service lint",
"watch": "vue-cli-service build --watch",
"lint": "eslint --ext .vue,.js src/",
"lint:fix": "eslint --ext .vue,.js --fix src/",
"format": "prettier --write ."
},
"dependencies": {
"ace-builds": "^1.24.2",
"clipboard": "^2.0.4",
"css-vars-ponyfill": "^2.4.3",
"file-loader": "^6.2.0", // UNNECESSARY IN VITE
X"js-base64": "^2.5.1", // REPLACE WITH EQUIVALENT JS
"lodash.clonedeep": "^4.5.0", // TOO OLD - REPLACE WITH JS
"lodash.throttle": "^4.1.1", // TOO OLD - REPLACE WITH JS
"material-icons": "^1.10.5",
"moment": "^2.29.4", // REPLACE WITH EQUIVALENT JS
"normalize.css": "^8.0.1", // REPLACE WITH EQUIVALENT JS
"noty": "^3.2.0-beta", // REPLACE WITH EQUIVALENT JS
X"pretty-bytes": "^6.0.0", // REPLACE WITH EQUIVALENT JS
"qrcode.vue": "^1.7.0", // UPDATE TO LATEST for VUE3
"utif": "^3.1.0", // SPIKE investigate replacement
"vue": "^2.6.10", // UPDATE to vue 3
"vue-async-computed": "^3.9.0", // REPLACE WITH EQUIVALENT JS
"vue-i18n": "^8.15.3", // REMOVE
"vue-lazyload": "^1.3.3", // REMOVE
"vue-router": "^3.1.3", // UPDATE to vue 3 @vue4 https://www.npmjs.com/package/vue-router
"vue-simple-progress": "^1.1.1", // REPLACE WITH EQUIVALENT JS
"vuex": "^3.1.2", // SPIKE: HOW TO REMOVE
"vuex-router-sync": "^5.0.0", // SPIKE: HOW TO REMOVE
X"whatwg-fetch": "^3.6.2"
},
"devDependencies": {
"@vue/cli-service": "^5.0.8", // REMOVE for VUE3
"compression-webpack-plugin": "^10.0.0", // REPLACE VUE3
"eslint": "^8.51.0",
"eslint-plugin-vue": "^9.17.0",
"vue-template-compiler": "^2.6.10" // REPLACE VUE3
}
}
-8520
View File
File diff suppressed because it is too large. Load diff
+31 -26
View File
@@ -1,15 +1,22 @@
{
"name": "filebrowser-frontend",
"version": "2.0.0",
"version": "3.0.0",
"private": true,
"type": "module",
"engines": {
"npm": ">=7.0.0",
"node": ">=18.0.0"
},
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"fix": "npx vue-cli-service lint",
"watch": "vue-cli-service build --watch",
"lint": "eslint --ext .vue,.js src/",
"lint:fix": "eslint --ext .vue,.js --fix src/",
"format": "prettier --write ."
"dev": "vite dev",
"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": "npx playwright test"
},
"dependencies": {
"ace-builds": "^1.24.2",
@@ -17,25 +24,23 @@
"css-vars-ponyfill": "^2.4.3",
"file-loader": "^6.2.0",
"material-icons": "^1.10.5",
"moment": "^2.29.4",
"normalize.css": "^8.0.1",
"noty": "^3.2.0-beta",
"qrcode.vue": "^1.7.0",
"utif": "^3.1.0",
"vue": "^2.6.10",
"vue-async-computed": "^3.9.0",
"vue-i18n": "^8.15.3",
"vue-lazyload": "^1.3.3",
"vue-router": "^3.1.3",
"vue-simple-progress": "^1.1.1",
"vuex": "^3.1.2",
"vuex-router-sync": "^5.0.0"
"qrcode.vue": "^3.4.1",
"vue": "^3.4.21",
"vue-i18n": "^9.10.2",
"vue-lazyload": "^3.0.0",
"vue-router": "^4.3.0"
},
"devDependencies": {
"@vue/cli-service": "^5.0.8",
"compression-webpack-plugin": "^10.0.0",
"eslint": "^8.51.0",
"eslint-plugin-vue": "^9.17.0",
"vue-template-compiler": "^2.6.10"
"@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",
"eslint": "^8.57.0",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-vue": "^9.24.0",
"vite": "^5.2.7",
"vite-plugin-compression2": "^1.0.0",
"vue-tsc": "^2.0.7"
}
}
}
+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"] },
},
],
});
+4 -2
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
[{[ if .ReCaptcha -]}]
<script src="[{[ .ReCaptchaHost ]}]/recaptcha/api.js?render=explicit"></script>
<script src="[{[ .ReCaptchaHost ]}]/recaptcha/api.js?render=explicit" data-vite-ignore></script>
[{[ end ]}]
<title>[{[ if .Name -]}][{[ .Name ]}][{[ else ]}]File Browser[{[ end ]}]</title>
@@ -121,7 +121,7 @@
<div id="app"></div>
[{[ if .darkMode -]}]
<div id="loading dark-mode">
<div id="loading" class="dark-mode">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
@@ -136,6 +136,8 @@
<div class="bounce3"></div>
</div>
</div> [{[ end ]}]
<script type="module" src="/src/main.ts"></script>
[{[ if .CSS -]}]
<link rel="stylesheet" href="[{[ .StaticURL ]}]/custom.css" />
[{[ end ]}]
+15 -5
View File
@@ -1,15 +1,25 @@
<template>
<router-view></router-view>
<router-view></router-view>
</template>
<script>
// eslint-disable-next-line no-undef
__webpack_public_path__ = window.FileBrowser.StaticURL + "/";
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(() => {
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");
if (loadingDiv) {
loadingDiv.remove();
}
});
},
};
</script>
+2 -2
View File
@@ -1,13 +1,13 @@
import { removePrefix } from "./utils";
import { baseURL } from "@/utils/constants";
import store from "@/store";
import { state } from "@/store";
const ssl = window.location.protocol === "https:";
const protocol = ssl ? "wss:" : "ws:";
export default function command(url, command, onmessage, onclose) {
url = removePrefix(url);
url = `${protocol}//${window.location.host}${baseURL}/api/command${url}?auth=${store.state.jwt}`;
url = `${protocol}//${window.location.host}${baseURL}/api/command${url}?auth=${state.jwt}`;
let conn = new window.WebSocket(url);
conn.onopen = () => conn.send(command);
+4 -4
View File
@@ -1,6 +1,6 @@
import { createURL, fetchURL, removePrefix } from "./utils";
import { baseURL } from "@/utils/constants";
import store from "@/store";
import { state } from "@/store";
export async function fetch(url,content=false) {
url = removePrefix(url);
@@ -70,8 +70,8 @@ export function download(format, ...files) {
url += `algo=${format}&`;
}
if (store.state.jwt) {
url += `auth=${store.state.jwt}&`;
if (state.jwt) {
url += `auth=${state.jwt}&`;
}
window.open(url);
@@ -95,7 +95,7 @@ export async function post(url, content = "", overwrite = false, onupload) {
`${baseURL}/api/resources${url}?override=${overwrite}`,
true
);
request.setRequestHeader("X-Auth", store.state.jwt);
request.setRequestHeader("X-Auth", state.jwt);
if (typeof onupload === "function") {
request.upload.onprogress = onupload;
-5
View File
@@ -15,11 +15,6 @@ export default async function search(base, query) {
data = data.map((item) => {
item.url = `/files${base}` + url.encodePath(item.path);
if (item.dir) {
item.url += "/";
}
return item;
});
+1
View File
@@ -18,6 +18,7 @@ export async function remove(hash) {
export async function create(url, password = "", expires = "", unit = "hours") {
url = removePrefix(url);
url = `/api/share${url}`;
expires = String(expires);
if (expires !== "") {
url += `?expires=${expires}&unit=${unit}`;
}
+8 -2
View File
@@ -1,6 +1,6 @@
import { fetchURL, fetchJSON } from "./utils";
import { fetchURL, fetchJSON } from "@/api/utils";
export async function getAll() {
export async function getAllUsers() {
return await fetchJSON(`/api/users`, {});
}
@@ -24,6 +24,12 @@ export async function create(user) {
}
export async function update(user, which = ["all"]) {
if (which[0] != "password") {
user.password = "";
}
if (user.username == "publicUser") {
return
}
await fetchURL(`/api/users/${user.id}`, {
method: "PUT",
body: JSON.stringify({
+10 -9
View File
@@ -1,7 +1,8 @@
import store from "@/store";
import { state } from "@/store";
import { renew, logout } from "@/utils/auth";
import { baseURL } from "@/utils/constants";
import { encodePath } from "@/utils/url";
import { showError } from "@/notify";
export async function fetchURL(url, opts, auth = true) {
opts = opts || {};
@@ -13,21 +14,22 @@ export async function fetchURL(url, opts, auth = true) {
try {
res = await fetch(`${baseURL}${url}`, {
headers: {
"X-Auth": store.state.jwt,
"sessionId": store.state.sessionId,
"userScope": store.state.user.scope,
"X-Auth": state.jwt,
"sessionId": state.sessionId,
"userScope": state.user.scope,
...headers,
},
...rest,
});
} catch {
} catch (e) {
console.error(e)
const error = new Error("000 No connection");
error.status = res.status;
throw error;
}
if (auth && res.headers.get("X-Renew-Token") === "true") {
await renew(store.state.jwt);
await renew(state.jwt);
}
if (res.status < 200 || res.status > 299) {
@@ -46,17 +48,16 @@ export async function fetchURL(url, opts, auth = true) {
export async function fetchJSON(url, opts) {
const res = await fetchURL(url, opts);
if (res.status === 200) {
return res.json();
} else {
showError("unable to fetch : " + url + "status" + res.status);
throw new Error(res.status);
}
}
export function removePrefix(url) {
url = url.split("/").splice(2).join("/");
if (url === "") url = "/";
if (url[0] !== "/") url = "/" + url;
return url;
@@ -70,7 +71,7 @@ export function createURL(endpoint, params = {}, auth = true) {
const url = new URL(prefix + encodePath(endpoint), origin);
const searchParams = {
...(auth && { auth: store.state.jwt }),
...(auth && { auth: state.jwt }),
...params,
};
+39 -10
View File
@@ -14,24 +14,48 @@
<component :is="element" :to="link.url">{{ link.name }}</component>
</span>
<action style="display: contents" v-if="showShare" icon="share" show="share" />
<div v-if="isResizableView">
Size:
<input
v-model="gallerySize"
type="range"
id="gallary-size"
name="gallary-size"
:value="gallerySize"
min="0"
max="10"
/>
</div>
</div>
</template>
<script>
import { mapState } from "vuex";
import Action from "@/components/header/Action";
import { state, mutations, getters } from "@/store"; // Import mutations as well
import Action from "@/components/header/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: {
...mapState(["req", "user"]),
isResizableView() {
return getters.isResizableView();
},
items() {
const relativePath = this.$route.path.replace(this.base, "");
const relativePath = state.route.path.replace(this.base, "");
let parts = relativePath.split("/");
if (parts[0] === "") {
@@ -76,13 +100,18 @@ export default {
return "router-link";
},
showShare() {
if (this.$route.path.startsWith("/share")) {
return;
// Ensure user properties are accessed safely
if (state.route.path.startsWith("/share")) {
return false;
}
return this.user.perm.share;
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 });
},
},
};
</script>
<style></style>
+16 -11
View File
@@ -1,14 +1,18 @@
<template>
<div class="button-group">
<button
v-for="(btn, index) in buttons"
:key="index"
:disabled="isDisabled"
:class="{ active: activeButton === index && !isDisabled }"
@click="setActiveButton(index, btn.label)"
>
{{ btn.label }}
<button v-if="isDisabled" disabled>
No options for folders
</button>
<template v-else>
<button
v-for="(btn, index) in buttons"
:key="index"
:class="{ active: activeButton === index }"
@click="setActiveButton(index, btn.label)"
>
{{ btn.label }}
</button>
</template>
</div>
</template>
@@ -36,15 +40,12 @@ export default {
methods: {
setActiveButton(index, label) {
if (label == "Only Folders" && this.activeButton != index) {
console.log("Only Folders && this.activeButton != index");
this.$emit("disableAll");
}
if (label == "Only Folders" && this.activeButton == index) {
console.log("Only Folders && this.activeButton == index");
this.$emit("enableAll");
}
if (label == "Only Files" && this.activeButton != index) {
console.log("Only Files && this.activeButton != index");
this.$emit("enableAll");
}
// If the clicked button is already active, de-select it
@@ -106,6 +107,10 @@ button:hover {
background: #e0e0e0;
}
button:disabled {
cursor: not-allowed !important;
}
button.active {
background-color: var(--blue) !important;
color: #ffffff;
+168
View File
@@ -0,0 +1,168 @@
<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>
+232
View File
@@ -0,0 +1,232 @@
<!-- This component taken directly from vue-simple-progress
since it didnt support Vue 3 but the component itself does
https://raw.githubusercontent.com/dzwillia/vue-simple-progress/master/src/components/Progress.vue -->
<template>
<div>
<div
class="vue-simple-progress-text"
:style="text_style"
v-if="text.length > 0 && textPosition == 'top'"
>
{{ text }}
</div>
<div class="vue-simple-progress" :style="progress_style">
<div
class="vue-simple-progress-text"
:style="text_style"
v-if="text.length > 0 && textPosition == 'middle'"
>
{{ text }}
</div>
<div
style="position: relative; left: -9999px"
:style="text_style"
v-if="text.length > 0 && textPosition == 'inside'"
>
{{ text }}
</div>
<div class="vue-simple-progress-bar" :style="bar_style">
<div :style="text_style" v-if="text.length > 0 && textPosition == 'inside'">
{{ text }}
</div>
</div>
</div>
<div
class="vue-simple-progress-text"
:style="text_style"
v-if="text.length > 0 && textPosition == 'bottom'"
>
{{ text }}
</div>
</div>
</template>
<script>
// We're leaving this untouched as you can read in the beginning
var isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
export default {
name: "progress-bar",
props: {
val: {
default: 0,
},
max: {
default: 100,
},
size: {
// either a number (pixel width/height) or 'tiny', 'small',
// 'medium', 'large', 'huge', 'massive' for common sizes
default: 3,
},
"bg-color": {
type: String,
default: "#eee",
},
"bar-color": {
type: String,
default: "#2196f3", // match .blue color to Material Design's 'Blue 500' color
},
"bar-transition": {
type: String,
default: "all 0.5s ease",
},
"bar-border-radius": {
type: Number,
default: 0,
},
spacing: {
type: Number,
default: 4,
},
text: {
type: String,
default: "",
},
"text-align": {
type: String,
default: "center", // 'left', 'right'
},
"text-position": {
type: String,
default: "bottom", // 'bottom', 'top', 'middle', 'inside'
},
"font-size": {
type: Number,
default: 13,
},
"text-fg-color": {
type: String,
default: "#222",
},
},
computed: {
pct() {
var pct = (this.val / this.max) * 100;
pct = pct.toFixed(2);
return Math.min(pct, this.max);
},
size_px() {
switch (this.size) {
case "tiny":
return 2;
case "small":
return 4;
case "medium":
return 8;
case "large":
return 12;
case "big":
return 16;
case "huge":
return 32;
case "massive":
return 64;
}
return isNumber(this.size) ? this.size : 32;
},
text_padding() {
switch (this.size) {
case "tiny":
case "small":
case "medium":
case "large":
case "big":
case "huge":
case "massive":
return Math.min(Math.max(Math.ceil(this.size_px / 8), 3), 12);
}
return isNumber(this.spacing) ? this.spacing : 4;
},
text_font_size() {
switch (this.size) {
case "tiny":
case "small":
case "medium":
case "large":
case "big":
case "huge":
case "massive":
return Math.min(Math.max(Math.ceil(this.size_px * 1.4), 11), 32);
}
return isNumber(this.fontSize) ? this.fontSize : 13;
},
progress_style() {
var style = {
background: this.bgColor,
};
if (this.textPosition == "middle" || this.textPosition == "inside") {
style["position"] = "relative";
style["min-height"] = this.size_px + "px";
style["z-index"] = "-2";
}
if (this.barBorderRadius > 0) {
style["border-radius"] = this.barBorderRadius + "px";
}
return style;
},
bar_style() {
var style = {
background: this.barColor,
width: this.pct + "%",
height: this.size_px + "px",
transition: this.barTransition,
};
if (this.barBorderRadius > 0) {
style["border-radius"] = this.barBorderRadius + "px";
}
if (this.textPosition == "middle" || this.textPosition == "inside") {
style["position"] = "absolute";
style["top"] = "0";
style["height"] = "100%";
(style["min-height"] = this.size_px + "px"), (style["z-index"] = "-1");
}
return style;
},
text_style() {
var style = {
color: this.textFgColor,
"font-size": this.text_font_size + "px",
"text-align": this.textAlign,
};
if (
this.textPosition == "top" ||
this.textPosition == "middle" ||
this.textPosition == "inside"
)
style["padding-bottom"] = this.text_padding + "px";
if (
this.textPosition == "bottom" ||
this.textPosition == "middle" ||
this.textPosition == "inside"
)
style["padding-top"] = this.text_padding + "px";
return style;
},
},
};
</script>
<style>
.vue-simple-progress {
margin: 0.5em;
}
.vue-simple-progress,
.vue-simple-progress-bar {
border-radius: 0.5em;
}
</style>
+291 -302
View File
@@ -1,10 +1,8 @@
<template>
<div
id="search"
@click="open"
v-bind:class="{ active, ongoing, 'dark-mode': isDarkMode }"
>
<div id="input">
<div id="search" :class="{ active, ongoing, 'dark-mode': isDarkMode }">
<!-- Search input section -->
<div id="input" @click="open">
<!-- Close button visible when search is active -->
<button
v-if="active"
class="action"
@@ -14,7 +12,9 @@
>
<i class="material-icons">close</i>
</button>
<!-- Search icon when search is not active -->
<i v-else class="material-icons">search</i>
<!-- Input field for search -->
<input
class="main-input"
type="text"
@@ -27,17 +27,15 @@
:placeholder="$t('search.search')"
/>
</div>
<!-- Search results for mobile -->
<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>
@@ -50,15 +48,18 @@
</router-link>
</li>
</ul>
<!-- Loading icon when search is ongoing -->
<p v-show="isEmpty && isRunning" id="renew">
<i class="material-icons spin">autorenew</i>
</p>
<!-- Message when no results are found -->
<div v-show="isEmpty && !isRunning">
<div class="searchPrompt" v-show="isEmpty && !isRunning">
<p>{{ noneMessage }}</p>
</div>
</div>
<template v-if="isEmpty">
<div v-if="isEmpty">
<!-- Reset filters button -->
<button
class="mobile-boxes"
v-if="value.length === 0 && !showBoxes"
@@ -66,7 +67,8 @@
>
Reset filters
</button>
<template v-if="value.length === 0 && showBoxes">
<!-- Box types when no search input is present -->
<div v-if="value.length === 0 && showBoxes">
<div class="boxes">
<h3>{{ $t("search.types") }}</h3>
<div>
@@ -84,45 +86,18 @@
</div>
</div>
</div>
</template>
</template>
</div>
</div>
</div>
</div>
<!-- Search results for desktop -->
<div v-show="!isMobile && active" id="result-desktop" ref="result">
<div class="searchContext">Search Context: {{ getContext }}</div>
<div id="result-list">
<template>
<p v-show="isEmpty && isRunning" id="renew">
<i class="material-icons spin">autorenew</i>
</p>
<div class="searchPrompt" v-show="isEmpty && !isRunning">
<p>{{ noneMessage }}</p>
<div class="helpButton" @click="toggleHelp()">Help</div>
</div>
<div class="helpText" v-if="showHelp">
<p>
Search occurs on each character you type (3 character minimum for search
terms).
</p>
<p>
<b>The index:</b> Search utilizes the index which automatically gets updated
on the configured interval (default: 5 minutes). Searching when the program
has just started may result in incomplete results.
</p>
<p>
<b>Filter by type:</b> You can have multiple type filters by adding
<code>type:condition</code> followed by search terms.
</p>
<p>
<b>Multiple Search terms:</b> Additional terms separated by <code>|</code>,
for example <code>"test|not"</code> searches for both terms independently.
</p>
<p>
<b>File size:</b> Searching files by size may have significantly longer
search times.
</p>
</div>
<template>
<div>
<div>
<!-- Button groups for filtering search results -->
<ButtonGroup
:buttons="folderSelect"
@button-clicked="addToTypes"
@@ -136,7 +111,8 @@
@remove-button-clicked="removeFromTypes"
:isDisabled="isTypeSelectDisabled"
/>
<div class="sizeConstraints">
<!-- Inputs for filtering by file size -->
<div v-if="!foldersOnly" class="sizeConstraints">
<div class="sizeInputWrapper">
<p>Smaller Than:</p>
<input
@@ -159,16 +135,45 @@
<p>MB</p>
</div>
</div>
</template>
</template>
</div>
</div>
<!-- Loading icon when search is ongoing -->
<p v-show="isEmpty && isRunning" id="renew">
<i class="material-icons spin">autorenew</i>
</p>
<!-- Message when no results are found -->
<div class="searchPrompt" v-show="isEmpty && !isRunning">
<p>{{ noneMessage }}</p>
<div class="helpButton" @click="toggleHelp()">Help</div>
</div>
<!-- Help text section -->
<div class="helpText" v-if="showHelp">
<p>
Search occurs on each character you type (3 character minimum for search
terms).
</p>
<p>
<b>The index:</b> Search utilizes the index which automatically gets updated
on the configured interval (default: 5 minutes). Searching when the program
has just started may result in incomplete results.
</p>
<p>
<b>Filter by type:</b> You can have multiple type filters by adding
<code>type:condition</code> followed by search terms.
</p>
<p>
<b>Multiple Search terms:</b> Additional terms separated by <code>|</code>,
for example <code>"test|not"</code> searches for both terms independently.
</p>
<p>
<b>File size:</b> Searching files by size may have significantly longer search
times.
</p>
</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>
@@ -185,6 +190,226 @@
</div>
</div>
</template>
<script>
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" },
file: { label: "files", icon: "insert_drive_file" },
archive: { label: "archives", icon: "archive" },
image: { label: "images", icon: "photo" },
audio: { label: "audio files", icon: "volume_up" },
video: { label: "videos", icon: "movie" },
doc: { label: "documents", icon: "picture_as_pdf" },
};
export default {
components: {
ButtonGroup,
},
name: "search",
data: function () {
return {
largerThan: "",
smallerThan: "",
noneMessage: "Start typing 3 or more characters to begin searching.",
searchTypes: "",
isTypeSelectDisabled: false,
showHelp: false,
folderSelect: [
{ label: "Only Folders", value: "type:folder" },
{ label: "Only Files", value: "type:file" },
],
typeSelect: [
{ label: "Photos", value: "type:image" },
{ label: "Audio", value: "type:audio" },
{ label: "Videos", value: "type:video" },
{ label: "Documents", value: "type:doc" },
{ label: "Archives", value: "type:archive" },
],
value: "",
ongoing: false,
results: [],
reload: false,
scrollable: null,
};
},
watch: {
largerThan() {
this.submit();
},
smallerThan() {
this.submit();
},
searchTypes() {
this.submit();
},
active(active) {
const resultList = document.getElementById("result-list");
if (!active) {
resultList.classList.remove("active");
return;
}
setTimeout(() => {
resultList.classList.add("active");
}, 100);
},
value() {
if (this.results.length) {
this.ongoing = false;
this.results = [];
}
},
},
computed: {
isMobile() {
return state.isMobile;
},
foldersOnly() {
return this.isTypeSelectDisabled;
},
active() {
return getters.currentPromptName() == "search";
},
isDarkMode() {
return getters.isDarkMode();
},
showBoxes() {
return this.searchTypes == "";
},
boxes() {
return boxes;
},
isEmpty() {
return this.results.length === 0;
},
text() {
if (this.ongoing) {
return "";
}
return this.value === ""
? this.$t("search.typeToSearch")
: this.$t("search.pressToSearch");
},
isRunning() {
return this.ongoing;
},
searchHelp() {
return this.showHelp;
},
getContext() {
let path = state.route.path;
path = path.slice(1);
path = "./" + path.substring(path.indexOf("/") + 1);
path = path.replace(/\/+$/, "") + "/";
return path;
},
},
methods: {
basePath(str, isDir) {
let parts = str.replace(/(\/$|^\/)/, "").split("/");
if (parts.length <= 1) {
if (isDir) {
return "/";
}
return "";
}
parts.pop();
parts = parts.join("/") + "/";
if (isDir) {
parts = "/" + parts; // fix weird rtl thing
}
return parts;
},
baseName(str) {
let parts = str.replace(/(\/$|^\/)/, "").split("/");
return parts.pop();
},
open() {
if (!this.active) {
mutations.showHover("search");
}
},
close(event) {
this.value = "";
event.stopPropagation();
mutations.closeHovers();
},
keyup(event) {
if (event.keyCode === 27) {
this.close(event);
return;
}
this.results.length === 0;
},
addToTypes(string) {
if (this.searchTypes.includes(string)) {
return true;
}
if (string == null || string == "") {
return false;
}
this.searchTypes = this.searchTypes + string + " ";
},
resetSearchFilters() {
this.searchTypes = "";
},
removeFromTypes(string) {
if (string == null || string == "") {
return false;
}
this.searchTypes = this.searchTypes.replace(string + " ", "");
if (state.isMobile) {
this.$refs.input.focus();
}
},
folderSelectClicked() {
this.isTypeSelectDisabled = true; // Disable the other ButtonGroup
},
resetButtonGroups() {
this.isTypeSelectDisabled = false;
},
async submit(event) {
this.showHelp = false;
if (event != undefined) {
event.preventDefault();
}
if (this.value === "" || this.value.length < 3) {
this.ongoing = false;
this.results = [];
this.noneMessage = "Not enough characters to search (min 3)";
return;
}
let searchTypesFull = this.searchTypes;
if (this.largerThan != "") {
searchTypesFull = searchTypesFull + "type:largerThan=" + this.largerThan + " ";
}
if (this.smallerThan != "") {
searchTypesFull = searchTypesFull + "type:smallerThan=" + this.smallerThan + " ";
}
let path = state.route.path;
this.ongoing = true;
try {
this.results = await search(path, searchTypesFull + this.value);
} catch (error) {
showError(error);
}
this.ongoing = false;
if (this.results.length == 0) {
this.noneMessage = "No results found in indexed search.";
}
},
toggleHelp() {
this.showHelp = !this.showHelp;
},
},
};
</script>
<style>
.main-input {
@@ -198,6 +423,7 @@
color: white;
border-left: 1px solid gray;
border-right: 1px solid gray;
word-wrap: break-word;
}
#result-desktop > #result-list {
@@ -262,8 +488,8 @@
/* Search */
#search {
background-color: unset;
z-index: 3;
background-color: unset !important;
z-index: 5;
position: fixed;
top: 0.5em;
min-width: 35em;
@@ -383,6 +609,10 @@ body.rtl #search #result ul > * {
border-bottom-left-radius: 0;
}
input.sizeInput:disabled {
cursor: not-allowed;
}
/* Search Input Placeholder */
#search::-webkit-input-placeholder {
color: rgba(255, 255, 255, 0.5);
@@ -509,244 +739,3 @@ body.rtl #search .boxes h3 {
align-items: center;
}
</style>
<script>
import ButtonGroup from "./ButtonGroup.vue";
import { mapState, mapGetters, mapMutations } from "vuex";
import { search } from "@/api";
import { darkMode } from "@/utils/constants";
var boxes = {
folder: { label: "folders", icon: "folder" },
file: { label: "files", icon: "insert_drive_file" },
archive: { label: "archives", icon: "archive" },
image: { label: "images", icon: "photo" },
audio: { label: "audio files", icon: "volume_up" },
video: { label: "videos", icon: "movie" },
doc: { label: "documents", icon: "picture_as_pdf" },
};
export default {
components: {
ButtonGroup,
},
name: "search",
data: function () {
return {
largerThan: "",
smallerThan: "",
noneMessage: "Start typing 3 or more characters to begin searching.",
searchTypes: "",
isTypeSelectDisabled: false,
showHelp: false,
folderSelect: [
{ label: "Only Folders", value: "type:folder" },
{ label: "Only Files", value: "type:file" },
],
typeSelect: [
{ label: "Photos", value: "type:image" },
{ label: "Audio", value: "type:audio" },
{ label: "Videos", value: "type:video" },
{ label: "Documents", value: "type:doc" },
{ label: "Archives", value: "type:archive" },
],
value: "",
width: window.innerWidth,
active: false,
ongoing: false,
results: [],
reload: false,
scrollable: null,
};
},
watch: {
active(active) {
const resultList = document.getElementById("result-list");
if (!active) {
resultList.classList.remove("active");
return;
}
setTimeout(() => {
resultList.classList.add("active");
}, 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;
this.results = [];
}
},
},
computed: {
...mapState(["user"]),
...mapGetters(["isListing", "currentPrompt", "currentPromptName"]),
showOverlay: function () {
return this.currentPrompt !== null && this.currentPrompt.prompt !== "more";
},
isDarkMode() {
return this.user && Object.prototype.hasOwnProperty.call(this.user, "darkMode")
? this.user.darkMode
: darkMode;
},
showBoxes() {
return this.searchTypes == "";
},
boxes() {
return boxes;
},
isEmpty() {
return this.results.length === 0;
},
text() {
if (this.ongoing) {
return "";
}
return this.value === ""
? this.$t("search.typeToSearch")
: this.$t("search.pressToSearch");
},
isMobile() {
return this.width <= 800;
},
isRunning() {
return this.ongoing;
},
searchHelp() {
return this.showHelp;
},
getContext() {
let path = this.$route.path;
path = path.slice(1);
path = "./" + path.substring(path.indexOf("/") + 1);
path = path.replace(/\/+$/, "") + "/";
return path;
},
},
mounted() {
window.addEventListener("resize", this.handleResize);
this.handleResize(); // Call this once to set the initial width
},
methods: {
...mapMutations(["showHover", "closeHovers", "setReload"]),
handleResize() {
this.width = window.innerWidth;
},
async navigateTo(url) {
this.closeHovers();
await this.$nextTick();
setTimeout(() => this.$router.push(url), 0);
},
basePath(str, isDir) {
let parts = str.replace(/(\/$|^\/)/, "").split("/");
if (parts.length <= 1) {
if (isDir) {
return "/";
}
return "";
}
parts.pop();
parts = parts.join("/") + "/";
if (isDir) {
parts = "/" + parts; // fix weird rtl thing
}
return parts;
},
baseName(str) {
let parts = str.replace(/(\/$|^\/)/, "").split("/");
return parts.pop();
},
open() {
this.$store.commit("showHover", "search");
},
close(event) {
event.stopPropagation();
this.closeHovers();
},
keyup(event) {
if (event.keyCode === 27) {
this.close(event);
return;
}
this.results.length === 0;
},
addToTypes(string) {
if (this.searchTypes.includes(string)) {
return true;
}
if (string == null || string == "") {
return false;
}
this.searchTypes = this.searchTypes + string + " ";
},
resetSearchFilters() {
this.searchTypes = "";
},
removeFromTypes(string) {
if (string == null || string == "") {
return false;
}
this.searchTypes = this.searchTypes.replace(string + " ", "");
if (this.isMobile) {
this.$refs.input.focus();
}
},
folderSelectClicked() {
this.isTypeSelectDisabled = true; // Disable the other ButtonGroup
},
resetButtonGroups() {
this.isTypeSelectDisabled = false;
},
async submit(event) {
this.showHelp = false;
event.preventDefault();
if (this.value === "" || this.value.length < 3) {
this.ongoing = false;
this.results = [];
this.noneMessage = "Not enough characters to search (min 3)";
return;
}
let searchTypesFull = this.searchTypes;
if (this.largerThan != "") {
searchTypesFull = searchTypesFull + "type:largerThan=" + this.largerThan + " ";
}
if (this.smallerThan != "") {
searchTypesFull = searchTypesFull + "type:smallerThan=" + this.smallerThan + " ";
}
let path = this.$route.path;
this.ongoing = true;
try {
this.results = await search(path, searchTypesFull + this.value);
} catch (error) {
this.$showError(error);
}
this.ongoing = false;
if (this.results.length == 0) {
this.noneMessage = "No results found in indexed search.";
}
},
toggleHelp() {
this.showHelp = !this.showHelp;
},
},
};
</script>
-233
View File
@@ -1,233 +0,0 @@
<template>
<nav :class="{ active, 'dark-mode': isDarkMode }">
<template v-if="isLogged">
<button
class="action"
@click="toRoot"
:aria-label="$t('sidebar.myFiles')"
:title="$t('sidebar.myFiles')"
>
<i class="material-icons">folder</i>
<span>{{ $t("sidebar.myFiles") }}</span>
</button>
<div v-if="user.perm.create">
<button
@click="$store.commit('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>
<button
@click="$store.commit('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>
<button id="upload-button" @click="upload($event)" class="action">
<i class="material-icons">file_upload</i>
<span>Upload file</span>
</button>
</div>
<div>
<button
class="action"
@click="toSettings"
:aria-label="$t('sidebar.settings')"
:title="$t('sidebar.settings')"
>
<i class="material-icons">settings_applications</i>
<span>{{ $t("sidebar.settings") }}</span>
</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>
</template>
<template v-else>
<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>
<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>
</template>
<div
class="credits"
v-if="$router.currentRoute.path.includes('/files/') && !disableUsedPercentage"
>
<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>
<br />
<span v-if="disableExternal">File Browser</span>
<span v-else>
<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 { mapState, mapGetters } from "vuex";
import * as upload from "@/utils/upload";
import * as auth from "@/utils/auth";
import {
version,
signup,
disableExternal,
disableUsedPercentage,
noAuth,
loginPage,
} from "@/utils/constants";
import { files as api } from "@/api";
import ProgressBar from "vue-simple-progress";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { darkMode } from "@/utils/constants";
export default {
name: "sidebar",
components: {
ProgressBar,
},
computed: {
...mapState(["user"]),
isDarkMode() {
return this.user && Object.prototype.hasOwnProperty.call(this.user, "darkMode")
? this.user.darkMode
: darkMode;
},
...mapGetters(["isLogged", "currentPrompt"]),
active() {
return this.currentPrompt?.prompt === "sidebar";
},
signup: () => signup,
version: () => version,
disableExternal: () => disableExternal,
disableUsedPercentage: () => disableUsedPercentage,
canLogout: () => !noAuth && loginPage,
},
asyncComputed: {
usage: {
async get() {
let path = this.$route.path.endsWith("/")
? this.$route.path
: this.$route.path + "/";
let usageStats = { used: 0, total: 0, usedPercentage: 0 };
if (this.disableUsedPercentage) {
return usageStats;
}
try {
let usage = await api.usage(path);
usageStats = {
used: getHumanReadableFilesize(usage.used / 1024),
total: getHumanReadableFilesize(usage.total / 1024),
usedPercentage: Math.round((usage.used / usage.total) * 100),
};
} catch (error) {
this.$showError(error);
}
return usageStats;
},
default: { used: "0 B", total: "0 B", usedPercentage: 0 },
shouldUpdate() {
return this.$router.currentRoute.path.includes("/files/");
},
},
},
methods: {
toRoot() {
this.$router.push({ path: "/files/" }, () => {});
this.$store.commit("closeHovers");
},
toSettings() {
this.$router.push({ path: "/settings" }, () => {});
this.$store.commit("closeHovers");
},
help() {
this.$store.commit("showHover", "help");
},
upload: function () {
if (
typeof window.DataTransferItem !== "undefined" &&
typeof DataTransferItem.prototype.webkitGetAsEntry !== "undefined"
) {
this.$store.commit("showHover", "upload");
} else {
document.getElementById("upload-input").click();
}
},
uploadInput(event) {
this.$store.commit("closeHovers");
let files = event.currentTarget.files;
let folder_upload =
files[0].webkitRelativePath !== undefined && files[0].webkitRelativePath !== "";
if (folder_upload) {
for (let i = 0; i < files.length; i++) {
let file = files[i];
files[i].fullPath = file.webkitRelativePath;
}
}
let path = this.$route.path.endsWith("/")
? this.$route.path
: this.$route.path + "/";
let conflict = upload.checkConflict(files, this.req.items);
if (conflict) {
this.$store.commit("showHover", {
prompt: "replace",
confirm: (event) => {
event.preventDefault();
this.$store.commit("closeHovers");
upload.handleFiles(files, path, true);
},
});
return;
}
upload.handleFiles(files, path);
},
logout: auth.logout,
},
};
</script>
+66 -87
View File
@@ -10,18 +10,23 @@
@mouseup="mouseUp"
@wheel="wheelMove"
>
<div v-if="!isLoaded">Loading image...</div>
<img
src=""
class="image-ex-img image-ex-img-center"
v-if="!isTiff && isLoaded"
:src="src"
class="image-ex-img"
ref="imgex"
@load="onLoad"
/>
<canvas v-else-if="isLoaded" ref="imgex" class="image-ex-img"></canvas>
</div>
</template>
<script>
import throttle from "@/utils/throttle";
import UTIF from "utif";
<script>
import { state, mutations, getters } from "@/store";
import throttle from "@/utils/throttle";
import { showError } from "@/notify";
export default {
props: {
src: String,
@@ -55,15 +60,18 @@ export default {
},
maxScale: 4,
minScale: 0.25,
isTiff: false, // Determine if the image is a TIFF
};
},
mounted() {
if (!this.decodeUTIF()) {
this.isTiff = this.checkIfTiff(this.src);
if (this.isTiff) {
this.decodeTiff(this.src);
} else {
this.$refs.imgex.src = this.src;
}
let container = this.$refs.container;
this.classList.forEach((className) => container.classList.add(className));
// set width and height if they are zero
if (getComputedStyle(container).width === "0px") {
container.style.width = "100%";
}
@@ -77,61 +85,55 @@ 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.decodeUTIF()) {
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);
} else {
this.$refs.imgex.src = this.src;
}
this.scale = 1;
this.setZoom();
this.setCenter();
mutations.setLoading("preview-img", false);
this.showSpinner = false;
},
},
methods: {
// Modified from UTIF.replaceIMG
decodeUTIF() {
checkIfTiff(src) {
const sufs = ["tif", "tiff", "dng", "cr2", "nef"];
let suff = document.location.pathname.split(".").pop().toLowerCase();
if (sufs.indexOf(suff) == -1) return false;
let xhr = new XMLHttpRequest();
UTIF._xhrs.push(xhr);
UTIF._imgs.push(this.$refs.imgex);
xhr.open("GET", this.src);
xhr.responseType = "arraybuffer";
xhr.onload = UTIF._imgLoaded;
xhr.send();
return true;
const suff = src.split(".").pop().toLowerCase();
return sufs.includes(suff);
},
onLoad() {
let img = this.$refs.imgex;
async decodeTiff(src) {
try {
const response = await fetch(src);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const blob = await response.blob(); // Convert response to a blob
const imgex = this.$refs.imgex;
this.imageLoaded = true;
if (img === undefined) {
return;
if (imgex) {
// Create a URL for the blob and set it as the image source
imgex.src = URL.createObjectURL(blob);
imgex.onload = () => URL.revokeObjectURL(imgex.src); // Clean up URL object after loading
}
} catch (error) {
showError("Error decoding TIFF");
console.error("Error decoding TIFF:", error);
}
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;
@@ -146,9 +148,7 @@ export default {
let container = this.$refs.container;
let img = this.$refs.imgex;
this.position.center.x = Math.floor(
(container.clientWidth - img.clientWidth) / 2
);
this.position.center.x = Math.floor((container.clientWidth - img.clientWidth) / 2);
this.position.center.y = Math.floor(
(container.clientHeight - img.clientHeight) / 2
);
@@ -242,32 +242,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", "");
@@ -275,28 +262,20 @@ export default {
},
};
</script>
<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>
+66 -58
View File
@@ -1,6 +1,6 @@
<template>
<div
:class="{ activebutton: this.isMaximized && this.isSelected}"
:class="{ activebutton: this.isMaximized && this.isSelected }"
class="item"
role="button"
tabindex="0"
@@ -18,21 +18,23 @@
@click="toggleClick"
:class="{ activetitle: this.isMaximized && this.isSelected }"
>
<img
v-if="readOnly === undefined && type === 'image' && isThumbsEnabled && isInView"
v-lazy="thumbnailUrl"
:class="{ activeimg: this.isMaximized && this.isSelected }"
ref="thumbnail"
/>
<i :class="{ iconActive: this.isMaximized && this.isSelected }" v-else class="material-icons"></i>
<img
v-if="readOnly === undefined && type === 'image' && isThumbsEnabled && isInView"
v-lazy="thumbnailUrl"
:class="{ activeimg: this.isMaximized && this.isSelected }"
ref="thumbnail"
/>
<i
:class="{ iconActive: this.isMaximized && this.isSelected }"
v-else
class="material-icons"
></i>
</div>
<div :class="{ activecontent: this.isMaximized && this.isSelected }">
<div class="text" :class="{ activecontent: this.isMaximized && this.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>
@@ -64,10 +66,10 @@
<script>
import { enableThumbs } from "@/utils/constants";
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { mapMutations, mapGetters, mapState } from "vuex";
import moment from "moment";
import { fromNow } from "@/utils/moment";
import { files as api } from "@/api";
import * as upload from "@/utils/upload";
import { state, getters, mutations } from "@/store"; // Import your custom store
export default {
name: "item",
@@ -90,32 +92,44 @@ export default {
"path",
],
computed: {
...mapState(["user", "selected", "req", "jwt"]),
...mapGetters(["selectedCount"]),
user() {
return state.user;
},
selected() {
return state.selected;
},
req() {
return state.req;
},
jwt() {
return state.jwt;
},
selectedCount() {
return getters.selectedCount();
},
isClicked() {
if (this.user.singleClick || !this.allowedView ) {
if (state.user.singleClick || !this.allowedView) {
return false;
}
// Assuming toggleClick returns a boolean value
return !this.isMaximized;
},
allowedView() {
return this.user.viewMode != "gallery" && this.user.viewMode != "normal"
return state.user.viewMode != "gallery" && state.user.viewMode != "normal";
},
singleClick() {
return this.readOnly == undefined && this.user.singleClick;
return this.readOnly == undefined && state.user.singleClick;
},
isSelected() {
return this.selected.indexOf(this.index) !== -1;
},
isDraggable() {
return this.readOnly == undefined && this.user.perm.rename;
return this.readOnly == undefined && state.user.perm?.rename;
},
canDrop() {
if (!this.isDir || this.readOnly !== undefined) return false;
for (let i of this.selected) {
if (this.req.items[i].url === this.url) {
if (state.req.items[i].url === this.url) {
return false;
}
}
@@ -123,12 +137,12 @@ export default {
return true;
},
thumbnailUrl() {
let path = this.req.path
if (this.req.path == "/") {
path = ""
let path = state.req.path;
if (state.req.path == "/") {
path = "";
}
const file = {
path: path +"/"+this.name,
path: path + "/" + this.name,
modified: this.modified,
};
@@ -144,7 +158,7 @@ export default {
mounted() {
const observer = new IntersectionObserver(this.handleIntersect, {
root: null,
rootMargin: '0px',
rootMargin: "0px",
threshold: 0.5, // Adjust threshold as needed
});
@@ -156,7 +170,7 @@ export default {
},
methods: {
handleIntersect(entries, observer) {
entries.forEach(entry => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
this.isThumbnailInView = true;
// Stop observing once thumbnail is in view
@@ -167,27 +181,26 @@ export default {
toggleClick() {
this.isMaximized = this.isClicked;
},
...mapMutations(["addSelected", "removeSelected", "resetSelected"]),
humanSize: function () {
return this.type == "invalid_link"
? "invalid link"
: getHumanReadableFilesize(this.size);
},
humanTime: function () {
if (this.readOnly == undefined && this.user.dateFormat) {
return moment(this.modified).format("L LT");
if (this.readOnly == undefined && state.user.dateFormat) {
return fromNow(this.modified, state.user.locale).format("L LT");
}
return moment(this.modified).fromNow();
return fromNow(this.modified, state.user.locale);
},
dragStart: function () {
if (this.selectedCount === 0) {
this.addSelected(this.index);
if (getters.selectedCount() === 0) {
mutations.addSelected(this.index);
return;
}
if (!this.isSelected) {
this.resetSelected();
this.addSelected(this.index);
mutations.resetSelected();
mutations.addSelected(this.index);
}
},
dragOver: function (event) {
@@ -208,7 +221,7 @@ export default {
if (!this.canDrop) return;
event.preventDefault();
if (this.selectedCount === 0) return;
if (getters.selectedCount() === 0) return;
let el = event.target;
for (let i = 0; i < 5; i++) {
@@ -221,9 +234,9 @@ export default {
for (let i of this.selected) {
items.push({
from: this.req.items[i].url,
to: this.url + encodeURIComponent(this.req.items[i].name),
name: this.req.items[i].name,
from: state.req.items[i].url,
to: this.url + encodeURIComponent(state.req.items[i].name),
name: state.req.items[i].name,
});
}
@@ -235,9 +248,9 @@ export default {
api
.move(items, overwrite, rename)
.then(() => {
this.$store.commit("setReload", true);
mutations.setReload(true);
})
.catch(this.$showError);
.catch(showError);
};
let conflict = upload.checkConflict(items, baseItems);
@@ -246,14 +259,14 @@ export default {
let rename = false;
if (conflict) {
this.$store.commit("showHover", {
prompt: "replace-rename",
mutations.showHover({
name: "replace-rename",
confirm: (event, option) => {
overwrite = option == "overwrite";
rename = option == "rename";
event.preventDefault();
this.$store.commit("closeHovers");
mutations.closeHovers();
action(overwrite, rename);
},
});
@@ -264,11 +277,11 @@ export default {
action(overwrite, rename);
},
itemClick: function (event) {
if (this.singleClick && !this.$store.state.multiple) this.open();
if (this.singleClick && !state.multiple) this.open();
else this.click(event);
},
click: function (event) {
if (!this.singleClick && this.selectedCount !== 0) event.preventDefault();
if (!this.singleClick && getters.selectedCount() !== 0) event.preventDefault();
setTimeout(() => {
this.touches = 0;
@@ -279,8 +292,8 @@ export default {
this.open();
}
if (this.$store.state.selected.indexOf(this.index) !== -1) {
this.removeSelected(this.index);
if (state.selected.indexOf(this.index) !== -1) {
mutations.removeSelected(this.index);
return;
}
@@ -297,21 +310,16 @@ export default {
}
for (; fi <= la; fi++) {
if (this.$store.state.selected.indexOf(fi) == -1) {
this.addSelected(fi);
if (state.selected.indexOf(fi) == -1) {
mutations.addSelected(fi);
}
}
return;
}
if (
!this.singleClick &&
!event.ctrlKey &&
!event.metaKey &&
!this.$store.state.multiple
)
this.resetSelected();
this.addSelected(this.index);
if (!this.singleClick && !event.ctrlKey && !event.metaKey && !state.multiple)
mutations.resetSelected();
mutations.addSelected(this.index);
},
open: function () {
this.$router.push({ path: this.url });
+6 -2
View File
@@ -7,13 +7,15 @@
</template>
<script>
import { mutations } from "@/store"; // Import your custom store
export default {
name: "action",
props: ["icon", "label", "counter", "show"],
methods: {
action: function () {
if (this.show) {
this.$store.commit("showHover", this.show);
mutations.showHover(this.show);
}
this.$emit("action");
},
@@ -21,4 +23,6 @@ export default {
};
</script>
<style></style>
<style>
</style>
+22 -15
View File
@@ -27,7 +27,7 @@
<div>
<button
class="button button--flat button--grey"
@click="$store.commit('closeHovers')"
@click="closeHovers"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
@@ -47,11 +47,12 @@
</template>
<script>
import { mapState } from "vuex";
import { mutations, state } from "@/store";
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";
export default {
name: "copy",
@@ -62,7 +63,14 @@ export default {
dest: null,
};
},
computed: mapState(["req", "selected", "user"]),
computed: {
user() {
return state.user;
},
closeHovers() {
return mutations.closeHovers();
},
},
methods: {
copy: async function (event) {
event.preventDefault();
@@ -71,9 +79,9 @@ export default {
// Create a new promise for each file.
for (let item of this.selected) {
items.push({
from: this.req.items[item].url,
to: this.dest + encodeURIComponent(this.req.items[item].name),
name: this.req.items[item].name,
from: store.req.items[item].url,
to: this.dest + encodeURIComponent(store.req.items[item].name),
name: store.req.items[item].name,
});
}
@@ -85,9 +93,8 @@ export default {
.then(() => {
buttons.success("copy");
if (this.$route.path === this.dest) {
this.$store.commit("setReload", true);
if (state.route.path === this.dest) {
mutations.setReload(true);
return;
}
@@ -95,12 +102,12 @@ export default {
})
.catch((e) => {
buttons.done("copy");
this.$showError(e);
showError(e);
});
};
if (this.$route.path === this.dest) {
this.$store.commit("closeHovers");
if (state.route.path === this.dest) {
mutations.closeHovers();
action(false, true);
return;
@@ -113,14 +120,14 @@ export default {
let rename = false;
if (conflict) {
this.$store.commit("showHover", {
prompt: "replace-rename",
mutations.showHover({
name: "replace-rename",
confirm: (event, option) => {
overwrite = option == "overwrite";
rename = option == "rename";
event.preventDefault();
this.$store.commit("closeHovers");
mutations.closeHovers();
action(overwrite, rename);
},
});
+25 -13
View File
@@ -10,7 +10,7 @@
</div>
<div class="card-action">
<button
@click="$store.commit('closeHovers')"
@click="closeHovers"
class="button button--flat button--grey"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
@@ -30,25 +30,36 @@
</template>
<script>
import { mapGetters, mapMutations, mapState } from "vuex";
import { files as api } from "@/api";
import buttons from "@/utils/buttons";
import { state, getters, mutations } from "@/store";
import { showError,showSuccess } from "@/notify";
export default {
name: "delete",
computed: {
...mapGetters(["isListing", "selectedCount", "currentPrompt"]),
...mapState(["req", "selected"]),
isListing() {
return getters.isListing();
},
selectedCount() {
return getters.selectedCount();
},
currentPrompt() {
return getters.currentPrompt();
},
},
methods: {
...mapMutations(["closeHovers"]),
submit: async function () {
closeHovers() {
mutations.closeHovers();
},
async submit() {
buttons.loading("delete");
try {
if (!this.isListing) {
await api.remove(this.$route.path);
await api.remove(state.route.path);
buttons.success("delete");
showSuccess("Deleted item successfully")
this.currentPrompt?.confirm();
this.closeHovers();
@@ -57,22 +68,23 @@ export default {
this.closeHovers();
if (this.selectedCount === 0) {
if (getters.selectedCount() === 0) {
return;
}
let promises = [];
for (let index of this.selected) {
promises.push(api.remove(this.req.items[index].url));
for (let index of state.selected) {
promises.push(api.remove(state.req.items[index].url));
}
await Promise.all(promises);
buttons.success("delete");
this.$store.commit("setReload", true);
showSuccess("Deleted item successfully")
mutations.setReload(true); // Handle reload as needed
} catch (e) {
buttons.done("delete");
this.$showError(e);
if (this.isListing) this.$store.commit("setReload", true);
showError(e);
if (this.isListing) mutations.setReload(true); // Handle reload as needed
}
},
},
@@ -0,0 +1,89 @@
<template>
<div class="card floating">
<div class="card-content">
<p>Are you sure you want to delete this user?</p>
</div>
<div class="card-action">
<button
class="button button--flat button--grey"
@click="closeHovers"
v-focus
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
{{ $t("buttons.cancel") }}
</button>
<button class="button button--flat" @click="deleteUser">
{{ $t("buttons.delete") }}
</button>
</div>
</div>
</template>
<script>
import { users as api } from "@/api";
import { showSuccess,showError } from "@/notify";
import buttons from "@/utils/buttons";
import { state, mutations, getters } from "@/store";
export default {
name: "delete",
computed: {
currentPrompt() {
return getters.currentPrompt();
},
user() {
return this.currentPrompt?.props?.user;
},
},
methods: {
async deleteUser(event) {
event.preventDefault();
try {
await api.remove(this.user.id);
this.$router.push({ path: "/settings/users" });
showSuccess(this.$t("settings.userDeleted"));
} catch (e) {
e.message === "403"
? showError(this.$t("errors.forbidden"), false)
: showError(e);
}
},
closeHovers() {
mutations.closeHovers();
},
submit: async function () {
buttons.loading("delete");
try {
if (!this.isListing) {
await api.remove(this.$route.path);
buttons.success("delete");
this.currentPrompt?.confirm();
this.closeHovers();
return;
}
this.closeHovers();
if (getters.selectedCount() === 0) {
return;
}
let promises = [];
for (let index of this.selected) {
promises.push(api.remove(state.req.items[index].url));
}
await Promise.all(promises);
buttons.success("delete");
mutations.setReload(true); // Handle reload as needed
} catch (e) {
buttons.done("delete");
showError(e);
if (this.isListing) mutations.setReload(true); // Handle reload as needed
}
},
},
};
</script>
+6 -4
View File
@@ -3,7 +3,6 @@
<div class="card-title">
<h2>{{ $t("prompts.download") }}</h2>
</div>
<div class="card-content">
<p>{{ $t("prompts.downloadMessage") }}</p>
@@ -21,7 +20,7 @@
</template>
<script>
import { mapGetters } from "vuex";
import { getters } from "@/store"; // Import your custom store
export default {
name: "download",
@@ -39,6 +38,9 @@ export default {
};
},
computed: {
...mapGetters(["currentPrompt"]),
},};
currentPrompt() {
return getters.currentPrompt();
},
},
};
</script>
+8 -8
View File
@@ -21,9 +21,10 @@
</template>
<script>
import { mapState } from "vuex";
import { state, mutations } from "@/store";
import url from "@/utils/url";
import { files } from "@/api";
import { showError } from "@/notify";
export default {
name: "file-list",
@@ -39,13 +40,12 @@ export default {
};
},
computed: {
...mapState(["req", "user"]),
nav() {
return decodeURIComponent(this.current);
},
},
mounted() {
this.fillOptions(this.req);
this.fillOptions(state.req);
},
methods: {
fillOptions(req) {
@@ -86,7 +86,7 @@ export default {
// content.
let uri = event.currentTarget.dataset.url;
files.fetch(uri).then(this.fillOptions).catch(this.$showError);
files.fetch(uri).then(this.fillOptions).catch(showError);
},
touchstart(event) {
let url = event.currentTarget.dataset.url;
@@ -114,7 +114,7 @@ export default {
}
},
itemClick: function (event) {
if (this.user.singleClick) this.next(event);
if (state.user.singleClick) this.next(event);
else this.select(event);
},
select: function (event) {
@@ -130,13 +130,13 @@ export default {
this.$emit("update:selected", this.selected);
},
createDir: async function () {
this.$store.commit("showHover", {
prompt: "newDir",
mutations.showHover({
name: "newDir",
action: null,
confirm: null,
props: {
redirect: false,
base: this.current === this.$route.path ? null : this.current,
base: this.current === state.route.path ? null : this.current,
},
});
},
+11 -2
View File
@@ -21,7 +21,7 @@
<div class="card-action">
<button
type="submit"
@click="$store.commit('closeHovers')"
@click="closeHovers"
class="button button--flat"
:aria-label="$t('buttons.ok')"
:title="$t('buttons.ok')"
@@ -33,5 +33,14 @@
</template>
<script>
export default { name: "help" };
import { mutations } from "@/store"; // Import the mutations
export default {
name: "help",
computed: {
closeHovers() {
return mutations.closeHovers; // Return the closeHovers mutation
},
},
};
</script>
+51 -45
View File
@@ -33,33 +33,25 @@
<p>
<strong>MD5: </strong
><code
><a @click="checksum($event, 'md5')">{{
$t("prompts.show")
}}</a></code
><a @click="checksum($event, 'md5')">{{ $t("prompts.show") }}</a></code
>
</p>
<p>
<strong>SHA1: </strong
><code
><a @click="checksum($event, 'sha1')">{{
$t("prompts.show")
}}</a></code
><a @click="checksum($event, 'sha1')">{{ $t("prompts.show") }}</a></code
>
</p>
<p>
<strong>SHA256: </strong
><code
><a @click="checksum($event, 'sha256')">{{
$t("prompts.show")
}}</a></code
><a @click="checksum($event, 'sha256')">{{ $t("prompts.show") }}</a></code
>
</p>
<p>
<strong>SHA512: </strong
><code
><a @click="checksum($event, 'sha512')">{{
$t("prompts.show")
}}</a></code
><a @click="checksum($event, 'sha512')">{{ $t("prompts.show") }}</a></code
>
</p>
</template>
@@ -68,7 +60,7 @@
<div class="card-action">
<button
type="submit"
@click="$store.commit('closeHovers')"
@click="closeHovers"
class="button button--flat"
:aria-label="$t('buttons.ok')"
:title="$t('buttons.ok')"
@@ -78,73 +70,87 @@
</div>
</div>
</template>
<script>
import { getHumanReadableFilesize } from "@/utils/filesizes";
import { mapState, mapGetters } from "vuex";
import moment from "moment";
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",
computed: {
...mapState(["req", "selected"]),
...mapGetters(["selectedCount", "isListing"]),
humanSize: function () {
if (this.selectedCount === 0 || !this.isListing) {
return getHumanReadableFilesize(this.req.size);
closeHovers() {
return mutations.closeHovers;
},
req() {
return state.req;
},
selected() {
return state.selected;
},
selectedCount() {
return getters.selectedCount();
},
isListing() {
return getters.isListing();
},
humanSize() {
if (getters.selectedCount() === 0 || !this.isListing) {
return getHumanReadableFilesize(state.req.size);
}
let sum = 0;
for (let selected of this.selected) {
sum += this.req.items[selected].size;
sum += state.req.items[selected].size;
}
return getHumanReadableFilesize(sum);
},
humanTime: function () {
if (this.selectedCount === 0) {
return moment(this.req.modified).fromNow();
humanTime() {
if (getters.selectedCount() === 0) {
return formatTimestamp(state.req.modified, state.user.locale);
}
return moment(this.req.items[this.selected[0]].modified).fromNow();
return formatTimestamp(
state.req.items[this.selected[0]].modified,
state.user.locale
);
},
modTime: function () {
return new Date(Date.parse(this.req.modified)).toLocaleString();
modTime() {
return new Date(Date.parse(state.req.modified)).toLocaleString();
},
name: function () {
return this.selectedCount === 0
? this.req.name
: this.req.items[this.selected[0]].name;
name() {
return getters.selectedCount() === 0
? state.req.name
: state.req.items[this.selected[0]].name;
},
dir: function () {
dir() {
return (
this.selectedCount > 1 ||
(this.selectedCount === 0
? this.req.isDir
: this.req.items[this.selected[0]].isDir)
getters.selectedCount() > 1 ||
(getters.selectedCount() === 0
? state.req.isDir
: state.req.items[this.selected[0]].isDir)
);
},
},
methods: {
checksum: async function (event, algo) {
async checksum(event, algo) {
event.preventDefault();
let link;
if (this.selectedCount) {
link = this.req.items[this.selected[0]].url;
if (getters.selectedCount()) {
link = state.req.items[this.selected[0]].url;
} else {
link = this.$route.path;
link = state.route.path;
}
try {
const hash = await api.checksum(link, algo);
// eslint-disable-next-line
event.target.innerHTML = hash
event.target.innerHTML = hash;
} catch (e) {
this.$showError(e);
showError(e);
}
},
},
+22 -14
View File
@@ -26,7 +26,7 @@
<div>
<button
class="button button--flat button--grey"
@click="$store.commit('closeHovers')"
@click="closeHovers"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
@@ -47,11 +47,12 @@
</template>
<script>
import { mapState } from "vuex";
import { mutations, state } from "@/store";
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";
export default {
name: "move",
@@ -62,32 +63,39 @@ export default {
dest: null,
};
},
computed: mapState(["req", "selected", "user"]),
computed: {
user() {
return state.user;
},
closeHovers() {
return mutations.closeHovers();
},
},
methods: {
move: async function (event) {
event.preventDefault();
let items = [];
for (let item of this.selected) {
for (let item of state.selected) {
items.push({
from: this.req.items[item].url,
to: this.dest + encodeURIComponent(this.req.items[item].name),
name: this.req.items[item].name,
from: state.req.items[item].url,
to: this.dest + encodeURIComponent(state.req.items[item].name),
name: state.req.items[item].name,
});
}
let action = async (overwrite, rename) => {
buttons.loading("move");
await api
.move(items, overwrite, rename)
.then(() => {
buttons.success("move");
this.$router.push({ path: this.dest });
mutations.setReload(true);
})
.catch((e) => {
buttons.done("move");
this.$showError(e);
showError(e);
});
};
@@ -98,22 +106,22 @@ export default {
let rename = false;
if (conflict) {
this.$store.commit("showHover", {
prompt: "replace-rename",
mutations.showHover({
name: "replace-rename",
confirm: (event, option) => {
overwrite = option == "overwrite";
rename = option == "rename";
event.preventDefault();
this.$store.commit("closeHovers");
mutations.closeHovers();
action(overwrite, rename);
mutations.setReload(true);
},
});
return;
}
action(overwrite, rename);
},
},
};
+19 -11
View File
@@ -18,7 +18,7 @@
<div class="card-action">
<button
class="button button--flat button--grey"
@click="$store.commit('closeHovers')"
@click="closeHovers"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
@@ -35,11 +35,11 @@
</div>
</div>
</template>
<script>
import { mapGetters } from "vuex";
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",
@@ -53,23 +53,31 @@ export default {
default: null,
},
},
data: function () {
data() {
return {
name: "",
};
},
computed: {
...mapGetters(["isFiles", "isListing"]),
isFiles() {
return getters.isFiles();
},
isListing() {
return getters.isListing();
},
},
methods: {
submit: async function (event) {
closeHovers() {
return mutations.closeHovers();
},
async submit(event) {
event.preventDefault();
if (this.new === "") return;
if (this.name === "") return;
// Build the path of the new directory.
let uri;
if (this.base) uri = this.base;
else if (this.isFiles) uri = this.$route.path + "/";
else if (getters.isFiles()) uri = state.route.path + "/";
else uri = "/";
if (!this.isListing) {
@@ -85,13 +93,13 @@ export default {
this.$router.push({ path: uri });
} else if (!this.base) {
const res = await api.fetch(url.removeLastDir(uri) + "/");
this.$store.commit("updateRequest", res);
mutations.updateRequest(res);
}
} catch (e) {
this.$showError(e);
showError(e);
}
this.$store.commit("closeHovers");
mutations.closeHovers();
},
},
};
+19 -12
View File
@@ -18,7 +18,7 @@
<div class="card-action">
<button
class="button button--flat button--grey"
@click="$store.commit('closeHovers')"
@click="closeHovers"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
@@ -35,29 +35,36 @@
</div>
</div>
</template>
<script>
import { mapGetters } from "vuex";
import { state } from "@/store";
import { files as api } from "@/api";
import url from "@/utils/url";
import { getters, mutations } from "@/store"; // Import your custom store
export default {
name: "new-file",
data: function () {
data() {
return {
name: "",
};
},
computed: {
...mapGetters(["isFiles", "isListing"]),
isFiles() {
return getters.isFiles();
},
isListing() {
return getters.isListing();
},
closeHovers() {
return mutations.closeHovers;
},
},
methods: {
submit: async function (event) {
async submit(event) {
event.preventDefault();
if (this.new === "") return;
// Build the path of the new directory.
let uri = this.isFiles ? this.$route.path + "/" : "/";
if (this.name === "") return;
// Build the path of the new file.
let uri = getters.isFiles() ? state.route.path + "/" : "/";
if (!this.isListing) {
uri = url.removeLastDir(uri) + "/";
@@ -70,10 +77,10 @@ export default {
await api.post(uri);
this.$router.push({ path: uri });
} catch (e) {
this.$showError(e);
showError(e);
}
this.$store.commit("closeHovers");
mutations.closeHovers();
},
},
};
+32 -15
View File
@@ -5,8 +5,7 @@
:ref="currentPromptName"
:is="currentPromptName"
v-bind="currentPrompt.props"
>
</component>
/>
</div>
</template>
@@ -25,9 +24,10 @@ import ReplaceRename from "./ReplaceRename.vue";
import Share from "./Share.vue";
import Upload from "./Upload.vue";
import ShareDelete from "./ShareDelete.vue";
import Sidebar from "../Sidebar.vue";
import { mapGetters, mapState } from "vuex";
import DeleteUser from "./DeleteUser.vue";
import Sidebar from "../sidebar/Sidebar.vue";
import buttons from "@/utils/buttons";
import { state, getters, mutations } from "@/store"; // Import your custom store
export default {
name: "prompts",
@@ -47,31 +47,33 @@ export default {
Upload,
ShareDelete,
Sidebar,
DeleteUser,
},
data: function () {
data() {
return {
pluginData: {
buttons,
store: this.$store,
store: state, // Directly use state
router: this.$router,
},
};
},
created() {
window.addEventListener("keydown", (event) => {
if (this.currentPrompt == null) return;
let currentPrompt = getters.currentPrompt();
if (!currentPrompt) return;
let prompt = this.$refs.currentComponent;
let prompt = this.$refs[currentPrompt.name];
// Esc!
if (event.keyCode === 27) {
event.stopImmediatePropagation();
this.$store.commit("closeHovers");
mutations.closeHovers();
}
// Enter
if (event.keyCode == 13) {
switch (this.currentPrompt.prompt) {
if (event.keyCode === 13) {
switch (currentPrompt.name) {
case "delete":
prompt.submit();
break;
@@ -89,10 +91,25 @@ export default {
});
},
computed: {
...mapState(["plugins"]),
...mapGetters(["currentPrompt", "currentPromptName"]),
showOverlay: function () {
return this.currentPrompt !== null && this.currentPrompt.prompt !== "more";
currentPromptName() {
if (getters.currentPromptName() == null) {
return "";
}
return getters.currentPromptName();
},
currentPrompt() {
if (getters.currentPrompt() == null) {
return {
props: {},
};
}
return getters.currentPrompt();
},
plugins() {
return state.plugins;
},
showOverlay() {
return getters.currentPromptName() !== "more";
},
},
methods: {},
+31 -21
View File
@@ -21,7 +21,7 @@
<div class="card-action">
<button
class="button button--flat button--grey"
@click="$store.commit('closeHovers')"
@click="closeHovers"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
>
@@ -39,15 +39,14 @@
</div>
</div>
</template>
<script>
import { mapState, mapGetters } from "vuex";
import url from "@/utils/url";
import { files as api } from "@/api";
import { state, getters, mutations } from "@/store";
export default {
name: "rename",
data: function () {
data() {
return {
name: "",
};
@@ -56,37 +55,48 @@ export default {
this.name = this.oldName();
},
computed: {
...mapState(["req", "selected", "selectedCount"]),
...mapGetters(["isListing"]),
req() {
return state.req;
},
selected() {
return state.selected;
},
selectedCount() {
return state.selectedCount;
},
isListing() {
return getters.isListing();
},
closeHovers() {
return mutations.closeHovers;
},
},
methods: {
cancel: function () {
this.$store.commit("closeHovers");
cancel() {
mutations.closeHovers();
},
oldName: function () {
oldName() {
if (!this.isListing) {
return this.req.name;
return state.req.name;
}
if (this.selectedCount === 0 || this.selectedCount > 1) {
// This shouldn't happen.
if (getters.selectedCount() === 0 || getters.selectedCount() > 1) {
return;
}
return this.req.items[this.selected[0]].name;
return state.req.items[this.selected[0]].name;
},
submit: async function () {
async submit() {
let oldLink = "";
let newLink = "";
if (!this.isListing) {
oldLink = this.req.url;
oldLink = state.req.url;
} else {
oldLink = this.req.items[this.selected[0]].url;
oldLink = state.req.items[this.selected[0]].url;
}
newLink =
url.removeLastDir(oldLink) + "/" + encodeURIComponent(this.name);
newLink = url.removeLastDir(oldLink) + "/" + encodeURIComponent(this.name);
try {
await api.move([{ from: oldLink, to: newLink }]);
@@ -95,12 +105,12 @@ export default {
return;
}
this.$store.commit("setReload", true);
mutations.setReload(true);
} catch (e) {
this.$showError(e);
showError(e);
}
this.$store.commit("closeHovers");
mutations.closeHovers();
},
},
};
+6 -3
View File
@@ -28,12 +28,15 @@
</div>
</div>
</template>
<script>
import { mapGetters } from "vuex";
import { getters } from "@/store"; // Import your custom store
export default {
name: "replace",
computed: mapGetters(["currentPrompt"]),
computed: {
currentPrompt() {
return getters.currentPrompt(); // Access the getter directly from the store
},
},
};
</script>
@@ -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>
@@ -38,9 +41,14 @@
</template>
<script>
import { mapGetters } from "vuex";
import { getters } from "@/store"; // Import your custom store
export default {
name: "replace-rename",
computed: mapGetters(["currentPrompt"]),
computed: {
currentPrompt() {
return getters.currentPrompt(); // Access the getter directly from the store
},
},
};
</script>
+41 -27
View File
@@ -58,7 +58,7 @@
<div class="card-action">
<button
class="button button--flat button--grey"
@click="$store.commit('closeHovers')"
@click="closeHovers"
:aria-label="$t('buttons.close')"
:title="$t('buttons.close')"
>
@@ -119,16 +119,16 @@
</template>
</div>
</template>
<script>
import { mapState, mapGetters } from "vuex";
import { showSuccess, showError } from "@/notify";
import { state, getters, mutations } from "@/store";
import { share as api, pub as pub_api } from "@/api";
import moment from "moment";
import { fromNow } from "@/utils/moment";
import Clipboard from "clipboard";
export default {
name: "share",
data: function () {
data() {
return {
time: "",
unit: "hours",
@@ -139,22 +139,35 @@ export default {
};
},
computed: {
...mapState(["req", "selected", "selectedCount"]),
...mapGetters(["isListing", "selectedCount"]),
closeHovers() {
return mutations.closeHovers;
},
req() {
return state.req; // Access state directly
},
selected() {
return state.selected; // Access state directly
},
selectedCount() {
return state.selected.length; // Compute selectedCount directly from state
},
isListing() {
return getters.isListing(); // Access getter directly from the store
},
url() {
if (!this.isListing) {
return this.$route.path;
return state.route.path;
}
if (this.selectedCount != 1) {
if (getters.selectedCount() !== 1) {
// selecting current view image
return this.$route.path;
return state.route.path;
}
return this.req.items[this.selected[0]].url;
return state.req.items[this.selected[0]].url;
},
getContext() {
let path = this.$route.path.replace("/files/", "./");
if (this.selectedCount == 1) {
path = path + this.req.items[this.selected[0]].name;
let path = state.route.path.replace("/files/", "./");
if (getters.selectedCount() === 1) {
path = path + state.req.items[this.selected[0]].name;
}
return path;
},
@@ -165,25 +178,25 @@ export default {
this.links = links;
this.sort();
if (this.links.length == 0) {
if (this.links.length === 0) {
this.listing = false;
}
} catch (e) {
this.$showError(e);
showError(e);
}
},
mounted() {
this.clip = new Clipboard(".copy-clipboard");
this.clip.on("success", () => {
this.$showSuccess(this.$t("success.linkCopied"));
showSuccess(this.$t("success.linkCopied"));
});
},
beforeUnmount() {
this.clip.destroy();
},
methods: {
submit: async function () {
let isPermanent = !this.time || this.time == 0;
async submit() {
let isPermanent = !this.time || this.time === 0;
try {
let res = null;
@@ -203,30 +216,30 @@ export default {
this.listing = true;
} catch (e) {
this.$showError(e);
showError(e);
}
},
deleteLink: async function (event, link) {
async deleteLink(event, link) {
event.preventDefault();
try {
await api.remove(link.hash);
this.links = this.links.filter((item) => item.hash !== link.hash);
if (this.links.length == 0) {
if (this.links.length === 0) {
this.listing = false;
}
} catch (e) {
this.$showError(e);
showError(e);
}
},
humanTime(time) {
return moment(time * 1000).fromNow();
return fromNow(time, state.user.locale);
},
buildLink(share) {
return api.getShareURL(share);
},
hasDownloadLink() {
return this.selected.length === 1 && !this.req.items[this.selected[0]].isDir;
return this.selected.length === 1 && !state.req.items[this.selected[0]].isDir;
},
buildDownloadLink(share) {
return pub_api.getDownloadURL(share);
@@ -239,8 +252,9 @@ export default {
});
},
switchListing() {
if (this.links.length == 0 && !this.listing) {
this.$store.commit("closeHovers");
if (this.links.length === 0 && !this.listing) {
// Access the store directly if needed
mutations.closeHovers();
}
this.listing = !this.listing;
@@ -5,7 +5,7 @@
</div>
<div class="card-action">
<button
@click="$store.commit('closeHovers')"
@click="closeHovers"
class="button button--flat button--grey"
:aria-label="$t('buttons.cancel')"
:title="$t('buttons.cancel')"
@@ -23,16 +23,21 @@
</div>
</div>
</template>
<script>
import { mapGetters } from "vuex";
import { getters } from "@/store"; // Import your custom store
export default {
name: "share-delete",
computed: {
...mapGetters(["currentPrompt"]),
closeHovers() {
return mutations.closeHovers();
},
currentPrompt() {
return getters.currentPrompt();
},
},
methods: {
submit: function () {
submit() {
this.currentPrompt?.confirm();
},
},
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more