Compare commits
248 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cce6823f25 | |||
| f5f9378dd6 | |||
| 21d2025c8d | |||
| 44b5194214 | |||
| e3cf66945e | |||
| 630a77bba9 | |||
| 6e8bb4a48c | |||
| c1bbdcb9c3 | |||
| b4ea1af7e9 | |||
| 32e02a7ff1 | |||
| 9962bae913 | |||
| 253b368622 | |||
| a3ee9ec884 | |||
| ad8f53051a | |||
| 3a294726a8 | |||
| b8a990f078 | |||
| 085936a018 | |||
| 488619f9fe | |||
| b45a0dca3c | |||
| 5ed24e8e40 | |||
| 811d91b6f4 | |||
| fc95133c6b | |||
| 8514ea379f | |||
| 8102da5a7e | |||
| 5e6d7761aa | |||
| 60837d2dd7 | |||
| 59f1bf3f9c | |||
| 448dcbd16c | |||
| 88d8a4b952 | |||
| d7b4ef75de | |||
| 84deb379e7 | |||
| 109f374269 | |||
| a2d09762b3 | |||
| f83babb494 | |||
| 36878ee42b | |||
| c6e8eee77d | |||
| e098b0ba5d | |||
| 46c7870be4 | |||
| a5cf8d718c | |||
| 79c048319d | |||
| 4830f43bab | |||
| 3b6f6abb1c | |||
| 15a5663934 | |||
| 834c42ba75 | |||
| d7b18c8513 | |||
| c335903233 | |||
| d57520c66d | |||
| 8d2e3a5ade | |||
| 733d6d519f | |||
| 05686bf271 | |||
| a237fba8c7 | |||
| b8fdb4202f | |||
| 7b5dddfc06 | |||
| f8186ba015 | |||
| b2f2dfdcf9 | |||
| 5270661bb5 | |||
| 67ea231f39 | |||
| 58d497eab1 | |||
| e52d7f44b2 | |||
| 6982184ab6 | |||
| 4009a5c3e1 | |||
| a55152250b | |||
| bccbb9420c | |||
| d3478026c2 | |||
| 3fe17d1156 | |||
| 2dab56e19e | |||
| d9b14adc8d | |||
| c1dbde574a | |||
| a39bf0e2f4 | |||
| 37c25bb383 | |||
| e866b008ee | |||
| 904b167c8e | |||
| f9e8438297 | |||
| 390d077644 | |||
| 2a90457e29 | |||
| 9481fd10af | |||
| d5ecbadbcc | |||
| 8155a9a19f | |||
| a79c1bf028 | |||
| af021aefa7 | |||
| 2d6cf95647 | |||
| 541e8b3d8b | |||
| 77a73a91be | |||
| 81cc067b3d | |||
| cd94895b93 | |||
| 311684f05f | |||
| 870d2dcc49 | |||
| 2cc191336b | |||
| a4c7fd4e39 | |||
| 6794091617 | |||
| 24aec5e1de | |||
| ef5329f8f7 | |||
| e61a7f9464 | |||
| 4a80618320 | |||
| da6c822a9c | |||
| b6a2b085d9 | |||
| e49f2d08b0 | |||
| 15d52e4c76 | |||
| 323f6794e1 | |||
| ae19470f0f | |||
| d53ee6836b | |||
| 569d2650ea | |||
| 6d7441473a | |||
| d8cb3ec00a | |||
| acee769474 | |||
| da5a1dae04 | |||
| ab13daef40 | |||
| e5e710f1b9 | |||
| 054f9ef643 | |||
| 67d957c109 | |||
| 9d2871eae9 | |||
| d801f7c2da | |||
| 768be7ce15 | |||
| 6fc02ce46d | |||
| 00a098b7c8 | |||
| 5e417f6220 | |||
| 4b36131a8c | |||
| 7e8b570f1c | |||
| 1cc232e6c6 | |||
| 97d0aab2f5 | |||
| 318f76f439 | |||
| eee83b5cb8 | |||
| 54191b76e5 | |||
| 550bf74438 | |||
| 89bb99e78c | |||
| 413a2a8f30 | |||
| ac15e39ae1 | |||
| 1602136eeb | |||
| b04029abf9 | |||
| adf2936ab8 | |||
| 94111846f4 | |||
| 6099b67d4b | |||
| 19e3c63fa7 | |||
| 90baf0aef8 | |||
| 3ffd3c6a41 | |||
| 18046b6db6 | |||
| 5b112d81ad | |||
| 689b96bf11 | |||
| da63e134d6 | |||
| 1c06774617 | |||
| 522f5916b1 | |||
| 39b2cc62eb | |||
| da3f424019 | |||
| a875613b76 | |||
| de2d86f752 | |||
| ef69268736 | |||
| deac242e74 | |||
| 90eccbc5b5 | |||
| 4d682e073f | |||
| 0dbf7033f4 | |||
| 024f749aa4 | |||
| 1977a255bf | |||
| 53ded6888e | |||
| 2b8e2669d0 | |||
| 29a45afd81 | |||
| e13504ec6c | |||
| f5231ecd3d | |||
| 7615a26d3f | |||
| af03b54b3b | |||
| 43a4485926 | |||
| 977a923936 | |||
| 95f134eb27 | |||
| cb14a87783 | |||
| 9fdfc8ad0b | |||
| 04a4299930 | |||
| ad6c2afbc2 | |||
| bc1d8c8e6f | |||
| d1f3d38835 | |||
| 3f4e650a1e | |||
| 2b1e4672d8 | |||
| 2698c12399 | |||
| 1d2e5de54a | |||
| 31b7bf5de2 | |||
| c6e0668882 | |||
| c32e8ffa8d | |||
| 1b7020f9bd | |||
| 13e3dc529a | |||
| 38d334bee3 | |||
| dbe38ed7e8 | |||
| 3a1dab3507 | |||
| a803c7d251 | |||
| bed48a9839 | |||
| 18b1996a92 | |||
| 400daae874 | |||
| f0a59ea7a1 | |||
| d182dd18c6 | |||
| 88763ebb8e | |||
| 18ea7ae4e2 | |||
| bf9d8d9b85 | |||
| 06b7d3e8a6 | |||
| cda98f6c0c | |||
| 6be4f29f08 | |||
| 31874768eb | |||
| 2c240a84cf | |||
| 2e897bff63 | |||
| 7b1105aa22 | |||
| 77aacf7941 | |||
| 77e4d1093a | |||
| 181b53205b | |||
| 9a72c23516 | |||
| a171a5b5cb | |||
| 3a2154c3ab | |||
| 6824668f76 | |||
| 85f7b120ca | |||
| 8d2a55c868 | |||
| f5f5cca1ba | |||
| cf04a57e6d | |||
| a832d89a14 | |||
| 02bf30c393 | |||
| 47c03527d0 | |||
| 92a4657459 | |||
| 6d0d4a8adc | |||
| a395b3ed60 | |||
| 8830222e10 | |||
| ffc4e92f96 | |||
| 5674e5681e | |||
| ba03d9e490 | |||
| eb54cb9403 | |||
| debd82a288 | |||
| 319817983e | |||
| a31f704274 | |||
| c3eb2d869c | |||
| 49584c22a5 | |||
| 63bf2367c2 | |||
| b5200ec372 | |||
| 05d6aaf7d0 | |||
| 28b51f7b8d | |||
| 487b0d9689 | |||
| 1daeef8c14 | |||
| a632eb2cc9 | |||
| 5a64dcf327 | |||
| 99997b75e9 | |||
| c75564fc98 | |||
| 57e2d5c331 | |||
| 8628e13e45 | |||
| d0f3b41558 | |||
| c37294dec0 | |||
| 343be4249b | |||
| 9a1c8b74f9 | |||
| 19d0cff28c | |||
| 29bf818a27 | |||
| 769db97654 | |||
| 1df79f0699 | |||
| d81ffd8435 | |||
| ac85abcb13 | |||
| 613022453d | |||
| 45c0fbb462 | |||
| b011d88b3d |
@@ -2,6 +2,8 @@
|
||||
.gitignore
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
Dockerfile.dev
|
||||
data
|
||||
README.md
|
||||
|
||||
frontend/.svelte-kit
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
- package-ecosystem: gomod
|
||||
directory: "/backend"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
commit-message:
|
||||
prefix: go-dep
|
||||
- package-ecosystem: npm
|
||||
directory: "/frontend"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
commit-message:
|
||||
prefix: npm-dep
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
commit-message:
|
||||
prefix: gh-action
|
||||
@@ -3,14 +3,14 @@ name: Mirror Sync
|
||||
on:
|
||||
push:
|
||||
branches: ["master"]
|
||||
tags:
|
||||
- '*'
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 */24 * * *"
|
||||
jobs:
|
||||
codeberg:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: pixta-dev/repository-mirroring-action@v1
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
name: Dependabot auto-merge
|
||||
on:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
dependabot:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.actor == 'dependabot[bot]' }}
|
||||
steps:
|
||||
- name: Dependabot metadata
|
||||
id: metadata
|
||||
uses: dependabot/fetch-metadata@v1
|
||||
with:
|
||||
github-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
- name: Enable auto-merge for Dependabot PRs
|
||||
if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} || ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}}
|
||||
run: gh pr merge --auto --rebase "$PR_URL"
|
||||
env:
|
||||
PR_URL: ${{github.event.pull_request.html_url}}
|
||||
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
@@ -1,9 +1,9 @@
|
||||
name: v3 build
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "3.*.*"
|
||||
- "*.*.*"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
steps:
|
||||
# pull code
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -25,15 +25,16 @@ jobs:
|
||||
# build sveltekit frontend
|
||||
- name: Build frontend
|
||||
run: |
|
||||
npm --prefix=./frontend i
|
||||
UPSNAP_VERSION=${GITHUB_REF##*/} npm --prefix=./frontend run build
|
||||
npm i -g pnpm
|
||||
pnpm --prefix=./frontend i
|
||||
PUBLIC_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
|
||||
cp -r ./frontend/build/* ./backend/pb_public/
|
||||
|
||||
# setup go
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: ">=1.20"
|
||||
go-version: ">=1.21.1"
|
||||
|
||||
# build
|
||||
- name: Run GoReleaser
|
||||
@@ -52,7 +53,7 @@ jobs:
|
||||
steps:
|
||||
# pull code
|
||||
- name: Check Out Repo
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# image tags
|
||||
- name: Docker meta
|
||||
@@ -87,7 +88,7 @@ jobs:
|
||||
# build and push
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v3
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7
|
||||
@@ -100,7 +100,7 @@ web_modules/
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
#.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
@@ -193,6 +193,7 @@ package
|
||||
# End of https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
|
||||
|
||||
build
|
||||
data
|
||||
|
||||
backend/pb_data
|
||||
backend/pb_public/*
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
FROM node:alpine as node
|
||||
WORKDIR /app
|
||||
COPY frontend/ .
|
||||
RUN npm i -g pnpm &&\
|
||||
pnpm i &&\
|
||||
pnpm run build
|
||||
|
||||
FROM golang:alpine as go
|
||||
WORKDIR /app
|
||||
COPY backend/ .
|
||||
COPY --from=node /app/build ./pb_public
|
||||
ENV CGO_ENABLED=0
|
||||
RUN go build -o upsnap main.go &&\
|
||||
chmod +x upsnap
|
||||
|
||||
FROM alpine:3
|
||||
RUN apk update &&\
|
||||
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
|
||||
rm -rf /var/cache/apk/*
|
||||
WORKDIR /app
|
||||
COPY --from=go /app/upsnap upsnap
|
||||
HEALTHCHECK --interval=10s \
|
||||
CMD curl -fs "http://localhost:8090/api/health" || exit 1
|
||||
ENTRYPOINT ["./upsnap", "serve", "--http=0.0.0.0:8090"]
|
||||
@@ -4,33 +4,36 @@
|
||||
|
||||
<div align="center" width="100%">
|
||||
<h2>UpSnap</h2>
|
||||
<p>A simple wake on lan app written with SvelteKit, Go, PocketBase and nmap.</p>
|
||||
<p>A simple wake on lan web app written with SvelteKit, Go and PocketBase.</p>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/upsnap" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/downloads/seriousm4x/upsnap/total" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/go-mod/go-version/seriousm4x/UpSnap?filename=backend/go.mod" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/v/release/seriousm4x/upsnap?display_name=tag" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/deploy.yml/badge.svg?event=push" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/release.yml/badge.svg?event=push" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
|
||||
</div>
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- Dashboard to wake up devices with one click
|
||||
- Set timed wake and shutdown events via cron
|
||||
- Add custom ports to devices which will be pinged
|
||||
- Discover devices by scanning network
|
||||
- User/Password protected login
|
||||
- Dark/light or system prefered color scheme
|
||||
- [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7, arm/v6
|
||||
- 🚀 One-Click Device Wake-Up Dashboard
|
||||
- ⏰ Timed Events via Cron for Automation
|
||||
- 🔌 Ping Any Port You Choose
|
||||
- 🔍 Discover Devices with Network Scanning (nmap required)
|
||||
- 👤 Secured User Management
|
||||
- 🎨 29 Themes
|
||||
- 🐳 [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7, arm/v6
|
||||
- 🏠 Self-Hostable, No Cloud Bullshit!
|
||||
|
||||
## 📸 Screenshots
|
||||
|
||||
| Dark | Light |
|
||||
| ------------------------------ | ------------------------------- |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
| Dark | Light |
|
||||
| --------------------------------- | ---------------------------------- |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
## 🚀 Run the binary
|
||||
|
||||
@@ -38,7 +41,7 @@ Just download the latest binary from the [release page](https://github.com/serio
|
||||
|
||||
For more options check `./upsnap --help` or visit [PocketBase documentation](https://pocketbase.io/docs).
|
||||
|
||||
If you need network discovery, make sure to have `nmap` installed and run upsnap as root/admin.
|
||||
If you want to use network discovery, make sure to have `nmap` installed and run UpSnap as root/admin.
|
||||
|
||||
## 🐳 Run in docker
|
||||
|
||||
@@ -71,27 +74,9 @@ upsnap.example.com {
|
||||
}
|
||||
```
|
||||
|
||||
## 🔒 Authorisation
|
||||
## 🔒 User permissions
|
||||
|
||||
**Since version 3.1 authorisation is enabled by default.**
|
||||
|
||||
User management is done through the PocketBase webinterface at [http://localhost:8090/\_/](http://localhost:8090/_/). This is mainly for internal use, such as within a home or corporate network. For external use please see below.
|
||||
|
||||
- To manage users, click the "Collections" icon on the left and select "users".
|
||||
- To manage admins, click the "Settings" icon on the left and select "Admin".
|
||||
|
||||
Api permissions listed by user role:
|
||||
|
||||
| Api | Unauthorized | Users | Admins |
|
||||
| ---------------- | ------------ | ----- | ------ |
|
||||
| List/Search Rule | ❌ | ✅ | ✅ |
|
||||
| View Rule | ❌ | ✅ | ✅ |
|
||||
| Create Rule | ❌ | ❌ | ✅ |
|
||||
| Delete Rule | ❌ | ❌ | ✅ |
|
||||
| Manage Rule | ❌ | ❌ | ✅ |
|
||||
| Wake devices | ❌ | ✅ | ✅ |
|
||||
| Shutdown devices | ❌ | ✅ | ✅ |
|
||||
| Scan network | ❌ | ❌ | ✅ |
|
||||
UpSnap offers unique access for each user, per device. While admins have all permissions, they can assign specific rights to users such as displaying/hiding a device, accessing device editing, deleting and powering devices on/off.
|
||||
|
||||
## 🌍 Exposing to the open web
|
||||
|
||||
@@ -122,3 +107,7 @@ pnpm run dev
|
||||
```
|
||||
|
||||
Open up [http://localhost:5173/](http://localhost:5173/), create an admin user and add some devices.
|
||||
|
||||
## 🌟 Star History
|
||||
|
||||
[](https://star-history.com/#seriousm4x/UpSnap&Date)
|
||||
|
||||
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 326 KiB |
|
Before Width: | Height: | Size: 324 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 230 KiB |
|
Before Width: | Height: | Size: 223 KiB |
|
Before Width: | Height: | Size: 150 KiB |
|
Before Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 41 KiB |
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
for i in *.png; do
|
||||
magick -quality 100 "$i" "$(basename "$i" .png)".webp
|
||||
rm "$i"
|
||||
done
|
||||
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 690 KiB |
|
Before Width: | Height: | Size: 696 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 32 KiB |
@@ -1,5 +1,5 @@
|
||||
release:
|
||||
# draft: true
|
||||
#draft: true
|
||||
prerelease: auto
|
||||
before:
|
||||
hooks:
|
||||
@@ -9,7 +9,7 @@ builds:
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
ldflags:
|
||||
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Version }}
|
||||
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Tag }}
|
||||
goos:
|
||||
- linux
|
||||
- windows
|
||||
@@ -33,4 +33,23 @@ checksum:
|
||||
snapshot:
|
||||
name_template: "{{ .Version }}"
|
||||
changelog:
|
||||
use: github
|
||||
sort: asc
|
||||
groups:
|
||||
- title: Features
|
||||
regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
|
||||
order: 0
|
||||
- title: "Bug fixes"
|
||||
regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$'
|
||||
order: 1
|
||||
- title: "Go dependencies"
|
||||
regexp: '^.*?go-dep(\([[:word:]]+\))??!?:.+$'
|
||||
order: 2
|
||||
- title: "Npm dependencies"
|
||||
regexp: '^.*?npm-dep(\([[:word:]]+\))??!?:.+$'
|
||||
order: 3
|
||||
- title: "Github Actions"
|
||||
regexp: '^.*?gh-action(\([[:word:]]+\))??!?:.+$'
|
||||
order: 4
|
||||
- title: Others
|
||||
order: 999
|
||||
|
||||
@@ -8,11 +8,14 @@ import (
|
||||
"github.com/seriousm4x/upsnap/networking"
|
||||
)
|
||||
|
||||
var Devices []*models.Record
|
||||
var PingRunning bool = false
|
||||
var WakeShutdownRunning bool = false
|
||||
var CronPing *cron.Cron
|
||||
var CronWakeShutdown *cron.Cron
|
||||
|
||||
func RunPing(app *pocketbase.PocketBase) {
|
||||
PingRunning = true
|
||||
|
||||
settingsPrivateRecords, err := app.Dao().FindRecordsByExpr("settings_private")
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
@@ -21,51 +24,66 @@ func RunPing(app *pocketbase.PocketBase) {
|
||||
// init cronjob
|
||||
CronPing = cron.New()
|
||||
CronPing.AddFunc(settingsPrivateRecords[0].GetString("interval"), func() {
|
||||
// skip cron if no realtime clients connected
|
||||
// skip cron if no realtime clients connected and lazy_ping is turned on
|
||||
realtimeClients := len(app.SubscriptionsBroker().Clients())
|
||||
if realtimeClients == 0 {
|
||||
if realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping") {
|
||||
return
|
||||
}
|
||||
|
||||
devices, err := app.Dao().FindRecordsByExpr("devices")
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
// expand ports field
|
||||
expandFetchFunc := func(c *models.Collection, ids []string) ([]*models.Record, error) {
|
||||
return app.Dao().FindRecordsByIds(c.Id, ids, nil)
|
||||
}
|
||||
merr := app.Dao().ExpandRecords(Devices, []string{"ports"}, expandFetchFunc)
|
||||
merr := app.Dao().ExpandRecords(devices, []string{"ports"}, expandFetchFunc)
|
||||
if len(merr) > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, device := range Devices {
|
||||
// ping
|
||||
go func(device *models.Record) {
|
||||
oldStatus := device.Get("status")
|
||||
newStatus := networking.PingDevice(device)
|
||||
if newStatus {
|
||||
if oldStatus == "offline" || oldStatus == "" {
|
||||
device.Set("status", "online")
|
||||
app.Dao().SaveRecord(device)
|
||||
for _, device := range devices {
|
||||
// ping device
|
||||
go func(d *models.Record) {
|
||||
status := d.GetString("status")
|
||||
if status == "pending" {
|
||||
return
|
||||
}
|
||||
if networking.PingDevice(d) {
|
||||
if status == "online" {
|
||||
return
|
||||
}
|
||||
d.Set("status", "online")
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
} else {
|
||||
if oldStatus == "online" || oldStatus == "" {
|
||||
device.Set("status", "offline")
|
||||
app.Dao().SaveRecord(device)
|
||||
if status == "offline" {
|
||||
return
|
||||
}
|
||||
d.Set("status", "offline")
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}
|
||||
}(device)
|
||||
|
||||
// scan ports
|
||||
go func(device *models.Record) {
|
||||
ports, err := app.Dao().FindRecordsByIds("ports", device.GetStringSlice("ports"))
|
||||
// ping ports
|
||||
go func(d *models.Record) {
|
||||
ports, err := app.Dao().FindRecordsByIds("ports", d.GetStringSlice("ports"))
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
for _, port := range ports {
|
||||
isUp := networking.CheckPort(device.GetString("ip"), port.GetString("number"))
|
||||
isUp := networking.CheckPort(d.GetString("ip"), port.GetString("number"))
|
||||
if isUp != port.GetBool("status") {
|
||||
port.Set("status", isUp)
|
||||
app.Dao().SaveRecord(port)
|
||||
device.RefreshUpdated()
|
||||
app.Dao().SaveRecord(device)
|
||||
if err := app.Dao().SaveRecord(port); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}(device)
|
||||
@@ -75,56 +93,86 @@ func RunPing(app *pocketbase.PocketBase) {
|
||||
}
|
||||
|
||||
func RunWakeShutdown(app *pocketbase.PocketBase) {
|
||||
WakeShutdownRunning = true
|
||||
|
||||
CronWakeShutdown = cron.New()
|
||||
for _, device := range Devices {
|
||||
wake_cron := device.GetString("wake_cron")
|
||||
wake_cron_enabled := device.GetBool("wake_cron_enabled")
|
||||
shutdown_cron := device.GetString("shutdown_cron")
|
||||
shutdown_cron_enabled := device.GetBool("shutdown_cron_enabled")
|
||||
devices, err := app.Dao().FindRecordsByExpr("devices")
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
return
|
||||
}
|
||||
for _, device := range devices {
|
||||
dev := device
|
||||
wake_cron := dev.GetString("wake_cron")
|
||||
wake_cron_enabled := dev.GetBool("wake_cron_enabled")
|
||||
shutdown_cron := dev.GetString("shutdown_cron")
|
||||
shutdown_cron_enabled := dev.GetBool("shutdown_cron_enabled")
|
||||
|
||||
if wake_cron_enabled && wake_cron != "" {
|
||||
// avoid using last element
|
||||
// https://github.com/robfig/cron/issues/115
|
||||
go func(d *models.Record) {
|
||||
_, err := CronWakeShutdown.AddFunc(wake_cron, func() {
|
||||
d.Set("status", "pending")
|
||||
app.Dao().SaveRecord(d)
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
if err := networking.WakeDevice(d); err != nil {
|
||||
logger.Error.Println(err)
|
||||
d.Set("status", "offline")
|
||||
app.Dao().SaveRecord(d)
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
} else {
|
||||
d.Set("status", "online")
|
||||
app.Dao().SaveRecord(d)
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
}(device)
|
||||
}(dev)
|
||||
}
|
||||
|
||||
if shutdown_cron_enabled && shutdown_cron != "" {
|
||||
// avoid using last element
|
||||
// https://github.com/robfig/cron/issues/115
|
||||
go func(d *models.Record) {
|
||||
_, err := CronWakeShutdown.AddFunc(shutdown_cron, func() {
|
||||
d.Set("status", "pending")
|
||||
app.Dao().SaveRecord(d)
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
if err := networking.ShutdownDevice(d); err != nil {
|
||||
logger.Error.Println(err)
|
||||
d.Set("status", "online")
|
||||
app.Dao().SaveRecord(d)
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
} else {
|
||||
d.Set("status", "offline")
|
||||
app.Dao().SaveRecord(d)
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
}(device)
|
||||
}(dev)
|
||||
}
|
||||
}
|
||||
CronWakeShutdown.Run()
|
||||
}
|
||||
|
||||
func StopAll() {
|
||||
if PingRunning {
|
||||
logger.Info.Println("stopping ping cronjob")
|
||||
ctx := CronPing.Stop()
|
||||
<-ctx.Done()
|
||||
|
||||
}
|
||||
if WakeShutdownRunning {
|
||||
logger.Info.Println("stopping wake/shutdown cronjob")
|
||||
ctx := CronWakeShutdown.Stop()
|
||||
<-ctx.Done()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +1,43 @@
|
||||
module github.com/seriousm4x/upsnap
|
||||
|
||||
go 1.19
|
||||
go 1.21
|
||||
|
||||
toolchain go1.21.1
|
||||
|
||||
require (
|
||||
github.com/labstack/echo/v5 v5.0.0-20220201181537-ed2888cfa198
|
||||
github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61
|
||||
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
|
||||
github.com/pocketbase/dbx v1.10.0
|
||||
github.com/pocketbase/pocketbase v0.16.3
|
||||
github.com/prometheus-community/pro-bing v0.1.0
|
||||
github.com/pocketbase/dbx v1.10.1
|
||||
github.com/pocketbase/pocketbase v0.18.3
|
||||
github.com/prometheus-community/pro-bing v0.3.0
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/AlecAivazis/survey/v2 v2.3.6 // indirect
|
||||
github.com/AlecAivazis/survey/v2 v2.3.7 // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/aws/aws-sdk-go v1.44.273 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.18.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.18.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.13.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.67 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.33 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.34 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.28 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.14.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.33.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.12.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.19.0 // indirect
|
||||
github.com/aws/smithy-go v1.13.5 // indirect
|
||||
github.com/aws/aws-sdk-go v1.45.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.21.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.13 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.18.39 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.13.37 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.83 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.41 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.35 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.42 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.1.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.36 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.35 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.15.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.38.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.13.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.15.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.21.5 // indirect
|
||||
github.com/aws/smithy-go v1.14.2 // indirect
|
||||
github.com/disintegration/imaging v1.6.2 // indirect
|
||||
github.com/domodwyer/mailyak/v3 v3.6.0 // indirect
|
||||
github.com/domodwyer/mailyak/v3 v3.6.2 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/fatih/color v1.15.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
@@ -44,9 +46,9 @@ require (
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/google/uuid v1.3.1 // indirect
|
||||
github.com/google/wire v0.5.0 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.10.0 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/josharian/native v1.1.0 // indirect
|
||||
@@ -56,7 +58,7 @@ require (
|
||||
github.com/mattn/go-sqlite3 v1.14.17 // indirect
|
||||
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
|
||||
github.com/mdlayher/packet v1.1.2 // indirect
|
||||
github.com/mdlayher/socket v0.4.1 // indirect
|
||||
github.com/mdlayher/socket v0.5.0 // indirect
|
||||
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/spf13/cast v1.5.1 // indirect
|
||||
@@ -65,33 +67,32 @@ require (
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
gocloud.dev v0.29.0 // indirect
|
||||
golang.org/x/crypto v0.9.0 // indirect
|
||||
golang.org/x/image v0.7.0 // indirect
|
||||
golang.org/x/mod v0.10.0 // indirect
|
||||
golang.org/x/net v0.10.0 // indirect
|
||||
golang.org/x/oauth2 v0.8.0 // indirect
|
||||
golang.org/x/sync v0.2.0 // indirect
|
||||
golang.org/x/sys v0.8.0 // indirect
|
||||
golang.org/x/term v0.8.0 // indirect
|
||||
golang.org/x/text v0.9.0 // indirect
|
||||
gocloud.dev v0.34.0 // indirect
|
||||
golang.org/x/crypto v0.13.0 // indirect
|
||||
golang.org/x/image v0.12.0 // indirect
|
||||
golang.org/x/mod v0.12.0 // indirect
|
||||
golang.org/x/net v0.15.0 // indirect
|
||||
golang.org/x/oauth2 v0.12.0 // indirect
|
||||
golang.org/x/sync v0.3.0 // indirect
|
||||
golang.org/x/sys v0.12.0 // indirect
|
||||
golang.org/x/term v0.12.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
golang.org/x/tools v0.9.2 // indirect
|
||||
golang.org/x/tools v0.13.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
|
||||
google.golang.org/api v0.125.0 // indirect
|
||||
google.golang.org/appengine v1.6.7 // indirect
|
||||
google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
||||
google.golang.org/grpc v1.55.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
google.golang.org/api v0.139.0 // indirect
|
||||
google.golang.org/appengine v1.6.8 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d // indirect
|
||||
google.golang.org/grpc v1.58.0 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
lukechampine.com/uint128 v1.3.0 // indirect
|
||||
modernc.org/cc/v3 v3.40.0 // indirect
|
||||
modernc.org/ccgo/v3 v3.16.13 // indirect
|
||||
modernc.org/libc v1.22.6 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
modernc.org/cc/v3 v3.41.0 // indirect
|
||||
modernc.org/ccgo/v3 v3.16.15 // indirect
|
||||
modernc.org/libc v1.24.1 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.7.1 // indirect
|
||||
modernc.org/opt v0.1.3 // indirect
|
||||
modernc.org/sqlite v1.22.1 // indirect
|
||||
modernc.org/strutil v1.1.3 // indirect
|
||||
modernc.org/sqlite v1.25.0 // indirect
|
||||
modernc.org/strutil v1.2.0 // indirect
|
||||
modernc.org/token v1.1.0 // indirect
|
||||
)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
jsonData := `{
|
||||
"id": "djqp3uxrac2ores",
|
||||
"created": "2023-06-29 10:39:59.291Z",
|
||||
"updated": "2023-06-29 10:39:59.291Z",
|
||||
"name": "groups",
|
||||
"type": "base",
|
||||
"system": false,
|
||||
"schema": [
|
||||
{
|
||||
"system": false,
|
||||
"id": "b3oaemnp",
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}
|
||||
],
|
||||
"indexes": [],
|
||||
"listRule": "@request.auth.id != \"\"",
|
||||
"viewRule": "@request.auth.id != \"\"",
|
||||
"createRule": null,
|
||||
"updateRule": null,
|
||||
"deleteRule": null,
|
||||
"options": {}
|
||||
}`
|
||||
|
||||
collection := &models.Collection{}
|
||||
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return daos.New(db).SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add
|
||||
new_groups := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "rk2vrn57",
|
||||
"name": "groups",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"collectionId": "djqp3uxrac2ores",
|
||||
"cascadeDelete": false,
|
||||
"minSelect": null,
|
||||
"maxSelect": null,
|
||||
"displayFields": []
|
||||
}
|
||||
}`), new_groups)
|
||||
collection.Schema.AddField(new_groups)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("rk2vrn57")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := map[string]any{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"allowEmailAuth": true,
|
||||
"allowOAuth2Auth": true,
|
||||
"allowUsernameAuth": true,
|
||||
"exceptEmailDomains": [],
|
||||
"manageRule": null,
|
||||
"minPasswordLength": 8,
|
||||
"onlyEmailDomains": [],
|
||||
"requireEmail": false
|
||||
}`), &options)
|
||||
collection.SetOptions(options)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := map[string]any{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"allowEmailAuth": true,
|
||||
"allowOAuth2Auth": false,
|
||||
"allowUsernameAuth": true,
|
||||
"exceptEmailDomains": [],
|
||||
"manageRule": null,
|
||||
"minPasswordLength": 8,
|
||||
"onlyEmailDomains": [],
|
||||
"requireEmail": false
|
||||
}`), &options)
|
||||
collection.SetOptions(options)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.CreateRule = types.Pointer("@request.data.password:isset = false")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := map[string]any{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"allowEmailAuth": true,
|
||||
"allowOAuth2Auth": true,
|
||||
"allowUsernameAuth": true,
|
||||
"exceptEmailDomains": [],
|
||||
"manageRule": null,
|
||||
"minPasswordLength": 5,
|
||||
"onlyEmailDomains": [],
|
||||
"requireEmail": false
|
||||
}`), &options)
|
||||
collection.SetOptions(options)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
options := map[string]any{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"allowEmailAuth": true,
|
||||
"allowOAuth2Auth": true,
|
||||
"allowUsernameAuth": true,
|
||||
"exceptEmailDomains": [],
|
||||
"manageRule": null,
|
||||
"minPasswordLength": 8,
|
||||
"onlyEmailDomains": [],
|
||||
"requireEmail": false
|
||||
}`), &options)
|
||||
collection.SetOptions(options)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.Name = "device_groups"
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.Name = "groups"
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
jsonData := `{
|
||||
"id": "7emu7fnnwuim2ua",
|
||||
"created": "2023-08-10 21:19:39.520Z",
|
||||
"updated": "2023-08-10 21:19:39.520Z",
|
||||
"name": "permissions",
|
||||
"type": "base",
|
||||
"system": false,
|
||||
"schema": [
|
||||
{
|
||||
"system": false,
|
||||
"id": "tzxtuykz",
|
||||
"name": "user",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"collectionId": "27do0wbcuyfmbmx",
|
||||
"cascadeDelete": false,
|
||||
"minSelect": null,
|
||||
"maxSelect": 1,
|
||||
"displayFields": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "nd1ekexz",
|
||||
"name": "create",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "z79gcpy3",
|
||||
"name": "read",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"collectionId": "z5lghx2r3tm45n1",
|
||||
"cascadeDelete": false,
|
||||
"minSelect": null,
|
||||
"maxSelect": null,
|
||||
"displayFields": [
|
||||
"name"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "t7wwbk2c",
|
||||
"name": "update",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"collectionId": "z5lghx2r3tm45n1",
|
||||
"cascadeDelete": false,
|
||||
"minSelect": null,
|
||||
"maxSelect": null,
|
||||
"displayFields": [
|
||||
"name"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "b4u0gqa7",
|
||||
"name": "delete",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"collectionId": "z5lghx2r3tm45n1",
|
||||
"cascadeDelete": false,
|
||||
"minSelect": null,
|
||||
"maxSelect": null,
|
||||
"displayFields": [
|
||||
"name"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "nyeqt3fn",
|
||||
"name": "power",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"collectionId": "z5lghx2r3tm45n1",
|
||||
"cascadeDelete": false,
|
||||
"minSelect": null,
|
||||
"maxSelect": null,
|
||||
"displayFields": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"indexes": [
|
||||
"CREATE UNIQUE INDEX ` + "`" + `idx_2GIk1Fo` + "`" + ` ON ` + "`" + `permissions` + "`" + ` (` + "`" + `user` + "`" + `)"
|
||||
],
|
||||
"listRule": "@request.auth.id = user.id",
|
||||
"viewRule": "@request.auth.id = user.id",
|
||||
"createRule": null,
|
||||
"updateRule": null,
|
||||
"deleteRule": "@request.auth.id = user.id",
|
||||
"options": {}
|
||||
}`
|
||||
|
||||
collection := &models.Collection{}
|
||||
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return daos.New(db).SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("7emu7fnnwuim2ua")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.read.id")
|
||||
|
||||
collection.ViewRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.read.id")
|
||||
|
||||
collection.CreateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
collection.UpdateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.update.id")
|
||||
|
||||
collection.DeleteRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.delete.id")
|
||||
|
||||
// add
|
||||
new_created_by := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "naciykac",
|
||||
"name": "created_by",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"collectionId": "27do0wbcuyfmbmx",
|
||||
"cascadeDelete": false,
|
||||
"minSelect": null,
|
||||
"maxSelect": 1,
|
||||
"displayFields": [
|
||||
"username"
|
||||
]
|
||||
}
|
||||
}`), new_created_by)
|
||||
collection.Schema.AddField(new_created_by)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = nil
|
||||
|
||||
collection.ViewRule = nil
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("naciykac")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.CreateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
collection.UpdateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
collection.DeleteRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("qqvyfrex")
|
||||
|
||||
// add
|
||||
new_status := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "qmiatdwa",
|
||||
"name": "status",
|
||||
"type": "select",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"maxSelect": 1,
|
||||
"values": [
|
||||
"pending",
|
||||
"online",
|
||||
"offline"
|
||||
]
|
||||
}
|
||||
}`), new_status)
|
||||
collection.Schema.AddField(new_status)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add
|
||||
del_status := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "qqvyfrex",
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}`), del_status)
|
||||
collection.Schema.AddField(del_status)
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("qmiatdwa")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = types.Pointer("@request.auth.id = id")
|
||||
|
||||
collection.ViewRule = types.Pointer("@request.auth.id = id")
|
||||
|
||||
collection.UpdateRule = types.Pointer("@request.auth.id = id")
|
||||
|
||||
collection.DeleteRule = types.Pointer("@request.auth.id = id")
|
||||
|
||||
// add
|
||||
new_avatar := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "i1qnezoa",
|
||||
"name": "avatar",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 0,
|
||||
"max": 9
|
||||
}
|
||||
}`), new_avatar)
|
||||
collection.Schema.AddField(new_avatar)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = nil
|
||||
|
||||
collection.ViewRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("i1qnezoa")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add
|
||||
new_lazy_ping := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "yjyq5pvg",
|
||||
"name": "lazy_ping",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
}`), new_lazy_ping)
|
||||
collection.Schema.AddField(new_lazy_ping)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("yjyq5pvg")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.CreateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
collection.UpdateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
collection.DeleteRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.read.id")
|
||||
|
||||
collection.ViewRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.read.id")
|
||||
|
||||
collection.CreateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
|
||||
|
||||
collection.UpdateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.update.id")
|
||||
|
||||
collection.DeleteRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.delete.id")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = nil
|
||||
|
||||
collection.ViewRule = nil
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add
|
||||
new_sol_enabled := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "ueieydw5",
|
||||
"name": "sol_enabled",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
}`), new_sol_enabled)
|
||||
collection.Schema.AddField(new_sol_enabled)
|
||||
|
||||
// add
|
||||
new_sol_auth := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "yfszwhpw",
|
||||
"name": "sol_auth",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
}`), new_sol_auth)
|
||||
collection.Schema.AddField(new_sol_auth)
|
||||
|
||||
// add
|
||||
new_sol_user := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "dbcmnrmp",
|
||||
"name": "sol_user",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}`), new_sol_user)
|
||||
collection.Schema.AddField(new_sol_user)
|
||||
|
||||
// add
|
||||
new_sol_password := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "hvz8stfy",
|
||||
"name": "sol_password",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}`), new_sol_password)
|
||||
collection.Schema.AddField(new_sol_password)
|
||||
|
||||
// add
|
||||
new_sol_port := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "6kfqheid",
|
||||
"name": "sol_port",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), new_sol_port)
|
||||
collection.Schema.AddField(new_sol_port)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("ueieydw5")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("yfszwhpw")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("dbcmnrmp")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("hvz8stfy")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("6kfqheid")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_number := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "8nwuncgg",
|
||||
"name": "number",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_number)
|
||||
collection.Schema.AddField(edit_number)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_number := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "8nwuncgg",
|
||||
"name": "number",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_number)
|
||||
collection.Schema.AddField(edit_number)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_sol_port := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "6kfqheid",
|
||||
"name": "sol_port",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_sol_port)
|
||||
collection.Schema.AddField(edit_sol_port)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_sol_port := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "6kfqheid",
|
||||
"name": "sol_port",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_sol_port)
|
||||
collection.Schema.AddField(edit_sol_port)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package networking
|
||||
|
||||
import (
|
||||
"net"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
@@ -16,8 +17,14 @@ func PingDevice(device *models.Record) bool {
|
||||
return false
|
||||
}
|
||||
pinger.Count = 1
|
||||
pinger.Timeout = 500 * 1000000 // 500ms
|
||||
pinger.SetPrivileged(true)
|
||||
pinger.Timeout = 500 * time.Millisecond
|
||||
|
||||
// windows needs privileged permissions.
|
||||
// If you have issues on linux, see here: https://github.com/prometheus-community/pro-bing#linux
|
||||
if runtime.GOOS == "windows" {
|
||||
pinger.SetPrivileged(true)
|
||||
}
|
||||
|
||||
err = pinger.Run()
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
|
||||
@@ -35,7 +35,7 @@ func ShutdownDevice(device *models.Record) error {
|
||||
return fmt.Errorf("%s", stderr.String())
|
||||
}
|
||||
|
||||
// check state every second for 2 min
|
||||
// check state every seconds for 2 min
|
||||
start := time.Now()
|
||||
for {
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package networking
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
"github.com/seriousm4x/upsnap/logger"
|
||||
)
|
||||
|
||||
type SolResponse struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func SleepDevice(device *models.Record) (SolResponse, error) {
|
||||
logger.Info.Println("sleep triggered for", device.GetString("name"))
|
||||
|
||||
var solResp SolResponse
|
||||
var url string
|
||||
|
||||
if device.GetBool("sol_auth") {
|
||||
url = fmt.Sprintf("http://%s:%s@%s:%d/sleep?format=JSON",
|
||||
device.GetString("sol_user"), device.GetString("sol_password"), device.GetString("ip"), device.GetInt("sol_port"))
|
||||
} else {
|
||||
url = fmt.Sprintf("http://%s:%d/sleep?format=JSON", device.GetString("ip"), device.GetInt("sol_port"))
|
||||
}
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return solResp, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return solResp, err
|
||||
}
|
||||
|
||||
var solResp SolResponse
|
||||
if err := json.Unmarshal(body, &solResp); err != nil {
|
||||
return solResp, err
|
||||
}
|
||||
|
||||
return solResp, errors.New("status code was not 200")
|
||||
}
|
||||
|
||||
return solResp, nil
|
||||
}
|
||||
@@ -15,7 +15,7 @@ func WakeDevice(device *models.Record) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// check state every second for 2 min
|
||||
// check state every seconds for 2 min
|
||||
start := time.Now()
|
||||
for {
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
@@ -20,16 +21,74 @@ func HandlerWake(c echo.Context) error {
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
go func(*models.Record) {
|
||||
record.Set("status", "pending")
|
||||
App.Dao().SaveRecord(record)
|
||||
if err := networking.WakeDevice(record); err != nil {
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
go func(r *models.Record) {
|
||||
if err := networking.WakeDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
record.Set("status", "offline")
|
||||
r.Set("status", "offline")
|
||||
} else {
|
||||
record.Set("status", "online")
|
||||
r.Set("status", "online")
|
||||
}
|
||||
if err := App.Dao().SaveRecord(r); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}(record)
|
||||
return c.JSON(http.StatusOK, record)
|
||||
}
|
||||
|
||||
func HandlerSleep(c echo.Context) error {
|
||||
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
resp, err := networking.SleepDevice(record)
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
record.Set("status", "online")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
return apis.NewBadRequestError(resp.Message, nil)
|
||||
}
|
||||
record.Set("status", "offline")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, nil)
|
||||
}
|
||||
|
||||
func HandlerReboot(c echo.Context) error {
|
||||
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
go func(r *models.Record) {
|
||||
if err := networking.ShutdownDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
r.Set("status", "online")
|
||||
} else {
|
||||
time.Sleep(15 * time.Second) // some devices might not respond to ping but are still shutting down
|
||||
if err := networking.WakeDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
r.Set("status", "offline")
|
||||
} else {
|
||||
r.Set("status", "online")
|
||||
}
|
||||
}
|
||||
if err := App.Dao().SaveRecord(r); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
App.Dao().SaveRecord(record)
|
||||
}(record)
|
||||
return c.JSON(http.StatusOK, record)
|
||||
}
|
||||
@@ -39,16 +98,20 @@ func HandlerShutdown(c echo.Context) error {
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
go func(*models.Record) {
|
||||
record.Set("status", "pending")
|
||||
App.Dao().SaveRecord(record)
|
||||
if err := networking.ShutdownDevice(record); err != nil {
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
go func(r *models.Record) {
|
||||
if err := networking.ShutdownDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
record.Set("status", "online")
|
||||
r.Set("status", "online")
|
||||
} else {
|
||||
record.Set("status", "offline")
|
||||
r.Set("status", "offline")
|
||||
}
|
||||
if err := App.Dao().SaveRecord(r); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
App.Dao().SaveRecord(record)
|
||||
}(record)
|
||||
return c.JSON(http.StatusOK, record)
|
||||
}
|
||||
@@ -95,9 +158,10 @@ func HandlerScan(c echo.Context) error {
|
||||
}
|
||||
|
||||
type Device struct {
|
||||
Name string `json:"name"`
|
||||
IP string `json:"ip"`
|
||||
MAC string `json:"mac"`
|
||||
Name string `json:"name"`
|
||||
IP string `json:"ip"`
|
||||
MAC string `json:"mac"`
|
||||
MACVendor string `json:"mac_vendor"`
|
||||
}
|
||||
|
||||
// extract info from struct into data
|
||||
@@ -121,15 +185,27 @@ func HandlerScan(c echo.Context) error {
|
||||
dev.MAC = addr.Addr
|
||||
}
|
||||
if addr.Vendor != "" {
|
||||
dev.Name = addr.Vendor
|
||||
dev.MACVendor = addr.Vendor
|
||||
} else {
|
||||
dev.MACVendor = "Unknown"
|
||||
}
|
||||
}
|
||||
|
||||
if dev.IP == "" || dev.MAC == "" {
|
||||
continue
|
||||
}
|
||||
if dev.Name == "" {
|
||||
dev.Name = "Unknown"
|
||||
|
||||
names, err := net.LookupAddr(dev.IP)
|
||||
if err != nil || len(names) == 0 {
|
||||
dev.Name = dev.MACVendor
|
||||
} else {
|
||||
dev.Name = strings.TrimSuffix(names[0], ".")
|
||||
}
|
||||
|
||||
if dev.Name == "" && dev.MACVendor == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
res.Devices = append(res.Devices, dev)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package pb
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
)
|
||||
|
||||
func RequireUpSnapPermission() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
admin, _ := c.Get(apis.ContextAdminKey).(*models.Admin)
|
||||
if admin != nil {
|
||||
return next(c)
|
||||
}
|
||||
|
||||
user, _ := c.Get(apis.ContextAuthRecordKey).(*models.Record)
|
||||
if user == nil {
|
||||
return apis.NewUnauthorizedError("The request requires admin or record authorization token to be set.", nil)
|
||||
}
|
||||
|
||||
deviceId := c.PathParam("id")
|
||||
|
||||
// find record where user has device with power permission
|
||||
res, err := App.Dao().FindFirstRecordByFilter("permissions",
|
||||
fmt.Sprintf("user.id = '%s' && power.id ?= '%s'", user.Id, deviceId))
|
||||
if res == nil || err != nil {
|
||||
return apis.NewForbiddenError("You are not allowed to perform this request.", nil)
|
||||
}
|
||||
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package pb
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -25,38 +26,54 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
App.RootCmd.Version = Version
|
||||
|
||||
// auto migrate db
|
||||
migratecmd.MustRegister(App, App.RootCmd, &migratecmd.Options{
|
||||
migratecmd.MustRegister(App, App.RootCmd, migratecmd.Config{
|
||||
Automigrate: true,
|
||||
})
|
||||
|
||||
// event hooks
|
||||
App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
|
||||
// set static website path
|
||||
e.Router.GET("/*", apis.StaticDirectoryHandler(distDirFS, true))
|
||||
|
||||
// add wake route to api
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/wake/:id",
|
||||
Handler: HandlerWake,
|
||||
Middlewares: []echo.MiddlewareFunc{
|
||||
apis.ActivityLogger(App),
|
||||
apis.RequireAdminOrRecordAuth("users"),
|
||||
RequireUpSnapPermission(),
|
||||
},
|
||||
})
|
||||
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/sleep/:id",
|
||||
Handler: HandlerSleep,
|
||||
Middlewares: []echo.MiddlewareFunc{
|
||||
apis.ActivityLogger(App),
|
||||
RequireUpSnapPermission(),
|
||||
},
|
||||
})
|
||||
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/reboot/:id",
|
||||
Handler: HandlerReboot,
|
||||
Middlewares: []echo.MiddlewareFunc{
|
||||
apis.ActivityLogger(App),
|
||||
RequireUpSnapPermission(),
|
||||
},
|
||||
})
|
||||
|
||||
// add shutdown route to api
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/shutdown/:id",
|
||||
Handler: HandlerShutdown,
|
||||
Middlewares: []echo.MiddlewareFunc{
|
||||
apis.ActivityLogger(App),
|
||||
apis.RequireAdminOrRecordAuth("users"),
|
||||
RequireUpSnapPermission(),
|
||||
},
|
||||
})
|
||||
|
||||
// add network scan route to api
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/scan",
|
||||
@@ -67,34 +84,27 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
},
|
||||
})
|
||||
|
||||
// import environment and set settings
|
||||
if err := importSettings(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// reset device states and run ping cronjob
|
||||
if err := resetDeviceStates(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// run cronjobs
|
||||
go cronjobs.RunPing(App)
|
||||
go cronjobs.RunWakeShutdown(App)
|
||||
|
||||
// restart ping cronjobs or wake/shutdown cronjobs on model update
|
||||
// add event hook before starting server.
|
||||
// using this outside App.OnBeforeServe() would not work
|
||||
App.OnModelAfterUpdate().Add(func(e *core.ModelEvent) error {
|
||||
App.OnModelAfterUpdate("settings_private", "devices").Add(func(e *core.ModelEvent) error {
|
||||
if e.Model.TableName() == "settings_private" {
|
||||
for _, job := range cronjobs.CronPing.Entries() {
|
||||
cronjobs.CronPing.Remove(job.ID)
|
||||
}
|
||||
go cronjobs.RunPing(App)
|
||||
} else if e.Model.TableName() == "devices" {
|
||||
if err := refreshDeviceList(); err != nil {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
for _, job := range cronjobs.CronWakeShutdown.Entries() {
|
||||
cronjobs.CronWakeShutdown.Remove(job.ID)
|
||||
}
|
||||
@@ -105,17 +115,33 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
return nil
|
||||
})
|
||||
|
||||
// refresh the device list on database events
|
||||
App.OnModelAfterCreate().Add(func(e *core.ModelEvent) error {
|
||||
if e.Model.TableName() == "_admins" {
|
||||
if err := setSetupCompleted(); err != nil {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := refreshDeviceList(); err != nil {
|
||||
return nil
|
||||
} else if e.Model.TableName() == "devices" {
|
||||
// when a device is created, give the user all rights to the device he just created
|
||||
deviceRec := e.Model.(*models.Record)
|
||||
userId := deviceRec.GetString("created_by")
|
||||
|
||||
var permissionRec *models.Record
|
||||
permissionRec, err := App.Dao().FindFirstRecordByFilter("permissions",
|
||||
fmt.Sprintf("user.id = '%s'", userId))
|
||||
if err != nil && err.Error() != "sql: no rows in result set" {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
} else if permissionRec != nil {
|
||||
permissionRec.Set("read", append(permissionRec.GetStringSlice("read"), deviceRec.Id))
|
||||
permissionRec.Set("update", append(permissionRec.GetStringSlice("update"), deviceRec.Id))
|
||||
permissionRec.Set("delete", append(permissionRec.GetStringSlice("delete"), deviceRec.Id))
|
||||
permissionRec.Set("power", append(permissionRec.GetStringSlice("power"), deviceRec.Id))
|
||||
if err := App.Dao().SaveRecord(permissionRec); err != nil {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -126,23 +152,21 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := refreshDeviceList(); err != nil {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// start pocketbase
|
||||
App.OnTerminate().Add(func(e *core.TerminateEvent) error {
|
||||
cronjobs.StopAll()
|
||||
return nil
|
||||
})
|
||||
|
||||
if err := App.Start(); err != nil {
|
||||
logger.Error.Fatalln(err)
|
||||
}
|
||||
}
|
||||
|
||||
func importSettings() error {
|
||||
// get first settingsPrivate record
|
||||
settingsPrivateRecords, err := App.Dao().FindRecordsByExpr("settings_private")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -156,7 +180,6 @@ func importSettings() error {
|
||||
settingsPrivate = settingsPrivateRecords[0]
|
||||
}
|
||||
|
||||
// get first settingsPublic record
|
||||
settingsPublicRecords, err := App.Dao().FindRecordsByExpr("settings_public")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -182,18 +205,15 @@ func importSettings() error {
|
||||
interval = os.Getenv("UPSNAP_INTERVAL")
|
||||
}
|
||||
|
||||
// set private settings
|
||||
settingsPrivate.Set("interval", interval)
|
||||
if scanRange := os.Getenv("UPSNAP_SCAN_RANGE"); scanRange != "" {
|
||||
settingsPrivate.Set("scan_range", scanRange)
|
||||
}
|
||||
|
||||
// set public settings
|
||||
if websiteTitle := os.Getenv("UPSNAP_WEBSITE_TITLE"); websiteTitle != "" {
|
||||
settingsPublic.Set("website_title", websiteTitle)
|
||||
}
|
||||
|
||||
// save records
|
||||
if err := App.Dao().SaveRecord(settingsPrivate); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -215,20 +235,12 @@ func resetDeviceStates() error {
|
||||
return err
|
||||
}
|
||||
for _, device := range devices {
|
||||
device.Set("status", "offline")
|
||||
if err := App.Dao().SaveRecord(device); err != nil {
|
||||
d := device
|
||||
d.Set("status", "offline")
|
||||
if err := App.Dao().SaveRecord(d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cronjobs.Devices = devices
|
||||
return nil
|
||||
}
|
||||
|
||||
func refreshDeviceList() error {
|
||||
var err error
|
||||
if cronjobs.Devices, err = App.Dao().FindRecordsByExpr("devices"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
version: "3"
|
||||
services:
|
||||
upsnap:
|
||||
container_name: upsnap
|
||||
build:
|
||||
dockerfile: Dockerfile.dev
|
||||
network_mode: host
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- ./data:/app/pb_data
|
||||
# # To use a non-root user, create the mountpoint first before starting
|
||||
# # the container (mkdir data) so that it has the right permissions.
|
||||
# user: 1000:1000
|
||||
# environment:
|
||||
# - TZ=Europe/Berlin # Set container timezone for cron schedules
|
||||
# - UPSNAP_INTERVAL=@every 10s # Sets the interval in which the devices are pinged
|
||||
# - UPSNAP_SCAN_RANGE=192.168.1.0/24 # Scan range is used for device discovery on local network
|
||||
# - UPSNAP_WEBSITE_TITLE=Custom name # Custom website title
|
||||
# # dns is used for name resolution during network scan
|
||||
# dns:
|
||||
# - 192.18.0.1
|
||||
# - 192.18.0.2
|
||||
# # you can change the listen ip:port inside the container like this:
|
||||
# entrypoint: /bin/sh -c "./upsnap serve --http 0.0.0.0:5000"
|
||||
# healthcheck:
|
||||
# test: curl -fs "http://localhost:5000/api/health" || exit 1
|
||||
# interval: 10s
|
||||
# # or install custom packages for shutdown
|
||||
# entrypoint: /bin/sh -c "apk update && apk add --no-cache <YOUR_PACKAGE> && rm -rf /var/cache/apk/* && ./upsnap serve --http 0.0.0.0:8090"
|
||||
@@ -2,17 +2,23 @@ version: "3"
|
||||
services:
|
||||
upsnap:
|
||||
container_name: upsnap
|
||||
image: ghcr.io/seriousm4x/upsnap:3
|
||||
image: ghcr.io/seriousm4x/upsnap:4
|
||||
network_mode: host
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- ./data:/app/pb_data
|
||||
# # To use a non-root user, create the mountpoint first (mkdir data) so that it has the right permission.
|
||||
# user: 1000:1000
|
||||
# environment:
|
||||
# - TZ=Europe/Berlin # Set container timezone for cron schedules
|
||||
# - UPSNAP_INTERVAL=@every 10s # Sets the interval in which the devices are pinged
|
||||
# - UPSNAP_SCAN_RANGE=192.168.1.0/24 # Scan range is used for device discovery on local network
|
||||
# - UPSNAP_WEBSITE_TITLE=Custom name # Custom website title
|
||||
# you can change the listen ip:port inside the container like this:
|
||||
# # dns is used for name resolution during network scan
|
||||
# dns:
|
||||
# - 192.18.0.1
|
||||
# - 192.18.0.2
|
||||
# # you can change the listen ip:port inside the container like this:
|
||||
# entrypoint: /bin/sh -c "./upsnap serve --http 0.0.0.0:5000"
|
||||
# healthcheck:
|
||||
# test: curl -fs "http://localhost:5000/api/health" || exit 1
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
PUBLIC_VERSION=""
|
||||
@@ -4,11 +4,10 @@ node_modules
|
||||
/.svelte-kit
|
||||
/package
|
||||
.env
|
||||
.env.\*
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Ignore files for PNPM, NPM and YARN
|
||||
|
||||
pnpm-lock.yaml
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: ['eslint:recommended', 'prettier'],
|
||||
plugins: ['svelte3'],
|
||||
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
|
||||
parserOptions: {
|
||||
sourceType: 'module',
|
||||
ecmaVersion: 2020
|
||||
},
|
||||
env: {
|
||||
browser: true,
|
||||
es2017: true,
|
||||
node: true
|
||||
}
|
||||
root: true,
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:svelte/recommended',
|
||||
'prettier'
|
||||
],
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['@typescript-eslint'],
|
||||
parserOptions: {
|
||||
sourceType: 'module',
|
||||
ecmaVersion: 2020,
|
||||
extraFileExtensions: ['.svelte']
|
||||
},
|
||||
env: {
|
||||
browser: true,
|
||||
es2017: true,
|
||||
node: true
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ['*.svelte'],
|
||||
parser: 'svelte-eslint-parser',
|
||||
parserOptions: {
|
||||
parser: '@typescript-eslint/parser'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
/build
|
||||
/.svelte-kit
|
||||
/package
|
||||
.env.*
|
||||
!.env.example
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
@@ -0,0 +1 @@
|
||||
_
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
cd frontend && npx lint-staged
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
engine-strict=true
|
||||
resolution-mode=highest
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"useTabs": false,
|
||||
"tabWidth": 4,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"semi": true,
|
||||
"printWidth": 100
|
||||
"useTabs": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"printWidth": 100,
|
||||
"plugins": ["prettier-plugin-svelte"],
|
||||
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
||||
}
|
||||
|
||||
@@ -1,44 +1,49 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"prepare": "cd .. && husky install frontend/.husky",
|
||||
"lint": "prettier --ignore-path ../.gitignore --check --plugin-search-dir=. . && eslint --fix .",
|
||||
"format": "prettier --ignore-path ../.gitignore --write --plugin-search-dir=. ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-static": "^1.0.6",
|
||||
"@sveltejs/kit": "^1.20.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.59.8",
|
||||
"@typescript-eslint/parser": "^5.59.8",
|
||||
"eslint": "^8.41.0",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
"eslint-plugin-svelte3": "^4.0.0",
|
||||
"husky": "^8.0.3",
|
||||
"lint-staged": "^13.2.2",
|
||||
"prettier": "^2.8.8",
|
||||
"prettier-plugin-svelte": "^2.10.1",
|
||||
"svelte": "^3.59.1",
|
||||
"svelte-preprocess": "^5.0.4",
|
||||
"typescript": "^4.9.5",
|
||||
"vite": "^4.3.9"
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@fortawesome/free-solid-svg-icons": "^6.4.0",
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"bootstrap": "5.3.0",
|
||||
"date-fns": "^2.30.0",
|
||||
"pocketbase": "^0.10.2",
|
||||
"sass": "^1.62.1",
|
||||
"svelte-fa": "^3.0.4"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{js,svelte}": "eslint --fix --ignore-path ../.gitignore .",
|
||||
"*.{js,css,md,svelte,scss}": "prettier --write --ignore-path ../.gitignore --plugin-search-dir=. ."
|
||||
}
|
||||
"name": "upsnap-frontend",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||
"lint": "eslint --fix --cache --ignore-path ../.gitignore .",
|
||||
"format": "prettier --write --cache --cache-strategy content --ignore-path ../.gitignore .",
|
||||
"prepare": "cd .. && husky install frontend/.husky"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-static": "^2.0.3",
|
||||
"@sveltejs/kit": "^1.24.1",
|
||||
"@typescript-eslint/eslint-plugin": "^6.6.0",
|
||||
"@typescript-eslint/parser": "^6.6.0",
|
||||
"autoprefixer": "^10.4.15",
|
||||
"daisyui": "^3.7.3",
|
||||
"eslint": "^8.49.0",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-svelte": "^2.33.1",
|
||||
"husky": "^8.0.3",
|
||||
"postcss": "^8.4.29",
|
||||
"prettier": "^3.0.3",
|
||||
"prettier-plugin-svelte": "^3.0.3",
|
||||
"svelte": "^4.2.0",
|
||||
"svelte-check": "^3.5.1",
|
||||
"tailwindcss": "^3.3.3",
|
||||
"tslib": "^2.6.2",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^4.4.9"
|
||||
},
|
||||
"type": "module",
|
||||
"lint-staged": {
|
||||
"*.{js,svelte}": "eslint --fix --cache --ignore-path ../.gitignore .",
|
||||
"*.{js,css,md,svelte,scss}": "prettier --write --cache --cache-strategy content --ignore-path ../.gitignore ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@fortawesome/free-solid-svg-icons": "^6.4.2",
|
||||
"date-fns": "^2.30.0",
|
||||
"pocketbase": "^0.18.0",
|
||||
"svelte-fa": "^3.0.4",
|
||||
"svelte-french-toast": "^1.2.0",
|
||||
"theme-change": "^2.5.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -0,0 +1,12 @@
|
||||
// See https://kit.svelte.dev/docs/types#app
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface Platform {}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -1,12 +1,30 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" class="h-100">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width" />
|
||||
%sveltekit.head%
|
||||
<script>
|
||||
const darkTheme = 'dark';
|
||||
const lightTheme = 'cupcake';
|
||||
const preferesDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
const theme = localStorage.getItem('theme')
|
||||
? localStorage.getItem('theme')
|
||||
: preferesDark
|
||||
? darkTheme
|
||||
: lightTheme;
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
|
||||
<body data-sveltekit-preload-data="hover" class="h-100">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
window
|
||||
.matchMedia('(prefers-color-scheme: dark)')
|
||||
.addEventListener('change', ({ matches }) => {
|
||||
matches
|
||||
? document.documentElement.setAttribute('data-theme', darkTheme)
|
||||
: document.documentElement.setAttribute('data-theme', lightTheme);
|
||||
});
|
||||
</script>
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
<script>
|
||||
import { dev } from '$app/environment';
|
||||
import { parseISO, formatDistance } from 'date-fns';
|
||||
import { pocketbase } from '@stores/pocketbase';
|
||||
import Fa from 'svelte-fa/src/fa.svelte';
|
||||
import {
|
||||
faPowerOff,
|
||||
faEllipsisVertical,
|
||||
faCircle,
|
||||
faCircleUp,
|
||||
faCircleDown,
|
||||
faLock
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { sortPorts } from '../sorts';
|
||||
|
||||
export let device;
|
||||
export let now;
|
||||
|
||||
function shutdown() {
|
||||
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/shutdown/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.baseToken
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function wake() {
|
||||
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/wake/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.baseToken
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 g-4">
|
||||
<div
|
||||
class="card border-0 rounded-5 px-3 py-2 shadow-sm"
|
||||
class:offline={device.status == 'offline' ? true : false}
|
||||
class:online={device.status == 'online' ? true : false}
|
||||
class:pending={device.status == 'pending' ? true : false}
|
||||
>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-auto me-auto">
|
||||
{#if device.status === 'offline'}
|
||||
<span class="text-danger" on:click={() => wake()} on:keydown={() => wake()}>
|
||||
<div role="button">
|
||||
<Fa icon={faPowerOff} class="fs-4 power-hover" />
|
||||
</div>
|
||||
</span>
|
||||
{:else if device.status === 'online'}
|
||||
{#if device.shutdown_cmd !== ''}
|
||||
<span
|
||||
class="text-success"
|
||||
on:click={() => shutdown()}
|
||||
on:keydown={() => shutdown()}
|
||||
>
|
||||
<div role="button">
|
||||
<Fa icon={faPowerOff} class="fs-4 power-hover" />
|
||||
</div>
|
||||
</span>
|
||||
{:else}
|
||||
<span class="text-success">
|
||||
<div>
|
||||
<Fa icon={faPowerOff} class="fs-4" />
|
||||
</div>
|
||||
</span>
|
||||
{/if}
|
||||
{:else if device.status === 'pending'}
|
||||
<div
|
||||
class="spinner-border text-warning"
|
||||
style="width: 23px;height: 23px;"
|
||||
role="status"
|
||||
>
|
||||
<span class="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="col-auto fs-5">
|
||||
<a
|
||||
href="/device/{device.id}"
|
||||
class="text-reset text-center ellipsis power-hover"
|
||||
>
|
||||
<Fa icon={faEllipsisVertical} />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{#if device.link}
|
||||
<p class="m-0 fw-bold fs-5">
|
||||
<a class="text-reset" target="_blank" rel="noreferrer" href={device.link}
|
||||
>{device.name}</a
|
||||
>
|
||||
</p>
|
||||
{:else}
|
||||
<p class="m-0 fw-bold fs-5">{device.name}</p>
|
||||
{/if}
|
||||
<p class="text-muted mb-2">{device.ip}</p>
|
||||
{#if device?.expand?.ports}
|
||||
<div class="mb-2">
|
||||
{#each device.expand.ports.sort(sortPorts) as port}
|
||||
<p class="m-0">
|
||||
<Fa
|
||||
icon={faCircle}
|
||||
class="me-1 {port.status ? 'port-up' : 'port-down'}"
|
||||
/>{port.name}
|
||||
<span class="text-muted">({port.number})</span>
|
||||
</p>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.wake_cron !== ''}
|
||||
<span
|
||||
class="badge rounded-pill {device.wake_cron_enabled
|
||||
? 'text-bg-success'
|
||||
: 'text-bg-danger'}"
|
||||
data-toggle="tooltip"
|
||||
title="Wake cron {device.wake_cron_enabled ? 'enabled' : 'disabled'}"
|
||||
>
|
||||
<Fa icon={faCircleUp} class="me-1" />
|
||||
{device.wake_cron}
|
||||
</span>
|
||||
{/if}
|
||||
{#if device.shutdown_cron !== ''}
|
||||
<span
|
||||
class="badge rounded-pill {device.shutdown_cron_enabled
|
||||
? 'text-bg-success'
|
||||
: 'text-bg-danger'}"
|
||||
data-toggle="tooltip"
|
||||
title="Shutdown cron {device.shutdown_cron_enabled ? 'enabled' : 'disabled'}"
|
||||
>
|
||||
<Fa icon={faCircleDown} class="me-1" />
|
||||
{device.shutdown_cron}
|
||||
</span>
|
||||
{/if}
|
||||
{#if device.password !== ''}
|
||||
<span
|
||||
class="badge rounded-pill text-bg-secondary"
|
||||
data-toggle="tooltip"
|
||||
title="Wake password set"
|
||||
>
|
||||
<Fa icon={faLock} class="mx-1" />
|
||||
</span>
|
||||
{/if}
|
||||
<p
|
||||
class="text-muted m-0"
|
||||
data-toggle="tooltip"
|
||||
title="Last status change: {device.updated}"
|
||||
>
|
||||
{formatDistance(parseISO(device.updated), now, {
|
||||
includeSeconds: true,
|
||||
addSuffix: true
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,391 +0,0 @@
|
||||
<script>
|
||||
import { goto } from '$app/navigation';
|
||||
import { pocketbase, devices } from '@stores/pocketbase';
|
||||
import Fa from 'svelte-fa/src/fa.svelte';
|
||||
import { faEye, faEyeSlash, faPlus, faTrashCan } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
export let device;
|
||||
export let mode;
|
||||
|
||||
let timeout;
|
||||
let button = {
|
||||
state: 'none',
|
||||
error: ''
|
||||
};
|
||||
let deleteButton = {
|
||||
state: 'none',
|
||||
error: ''
|
||||
};
|
||||
let newPort = {
|
||||
name: '',
|
||||
number: null
|
||||
};
|
||||
let passwordShow = false;
|
||||
$: passwordType = passwordShow ? 'text' : 'password';
|
||||
|
||||
async function addOrUpdateDevice() {
|
||||
button.state = 'waiting';
|
||||
try {
|
||||
// validate password length
|
||||
if (
|
||||
device.password.length != 0 &&
|
||||
device.password.length != 4 &&
|
||||
device.password.length != 6
|
||||
) {
|
||||
throw 'Password must be 0, 4 or 6 characters long';
|
||||
}
|
||||
|
||||
// add ports not in db
|
||||
for (let i = 0; i < device.expand.ports.length; i++) {
|
||||
const port = device.expand.ports[i];
|
||||
if (!port.id) {
|
||||
const result = await $pocketbase.collection('ports').create(port);
|
||||
device.ports = [...device.ports, result.id];
|
||||
} else {
|
||||
await $pocketbase.collection('ports').update(port.id, port);
|
||||
}
|
||||
}
|
||||
|
||||
// create or update device
|
||||
if (mode === 'add') {
|
||||
await $pocketbase.collection('devices').create(device);
|
||||
} else {
|
||||
await $pocketbase.collection('devices').update(device.id, device);
|
||||
}
|
||||
|
||||
// show button with timeout
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => {
|
||||
button.state = 'none';
|
||||
}, 3000);
|
||||
button.state = 'success';
|
||||
} catch (error) {
|
||||
clearTimeout(timeout);
|
||||
setTimeout(() => {
|
||||
button.error = '';
|
||||
button.state = 'none';
|
||||
}, 3000);
|
||||
button.error = error;
|
||||
button.state = 'failed';
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteDevice() {
|
||||
deleteButton.state = 'waiting';
|
||||
try {
|
||||
await $pocketbase.collection('devices').delete(device.id);
|
||||
device.ports.forEach(async (port) => {
|
||||
await $pocketbase.collection('ports').delete(port);
|
||||
});
|
||||
delete $devices[device.id];
|
||||
goto('/');
|
||||
} catch (error) {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(() => {
|
||||
deleteButton.error = '';
|
||||
deleteButton.state = 'none';
|
||||
}, 3000);
|
||||
deleteButton.error = error;
|
||||
deleteButton.state = 'failed';
|
||||
}
|
||||
}
|
||||
|
||||
async function deletePort(idx) {
|
||||
// delete port from db if it has an id
|
||||
// ports with id exist in db, ports without id are not created yet
|
||||
const port = device.expand.ports[idx];
|
||||
if (port.id) {
|
||||
await $pocketbase.collection('ports').delete(port.id);
|
||||
const i = device.ports.indexOf(port.id);
|
||||
if (i !== -1) {
|
||||
device.ports.splice(i, 1);
|
||||
device.ports = device.ports;
|
||||
}
|
||||
}
|
||||
device.expand.ports.splice(idx, 1);
|
||||
device.expand.ports = device.expand.ports;
|
||||
}
|
||||
|
||||
function addPort() {
|
||||
device.expand.ports = [...device.expand.ports, JSON.parse(JSON.stringify(newPort))];
|
||||
newPort.name = '';
|
||||
newPort.number = null;
|
||||
}
|
||||
|
||||
function onPasswordInput(event) {
|
||||
device.password = event.target.value;
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="m-0 mt-4 p-4 shadow-sm">
|
||||
<h3 class="mb-3">{mode === 'add' ? 'Add new device' : device.name}</h3>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<form on:submit|preventDefault={addOrUpdateDevice}>
|
||||
<h5>Required:</h5>
|
||||
<div class="input-group mb-1">
|
||||
<span class="input-group-text">Name</span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="Office Pc"
|
||||
aria-label="Name"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="text"
|
||||
required
|
||||
bind:value={device.name}
|
||||
/>
|
||||
</div>
|
||||
<div class="input-group mb-1">
|
||||
<span class="input-group-text">IP</span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="192.168.1.34"
|
||||
aria-label="IP"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="text"
|
||||
required
|
||||
bind:value={device.ip}
|
||||
/>
|
||||
</div>
|
||||
<div class="input-group mb-1">
|
||||
<span class="input-group-text">MAC</span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="aa:bb:cc:dd:ee:ff"
|
||||
aria-label="MAC"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="text"
|
||||
required
|
||||
bind:value={device.mac}
|
||||
/>
|
||||
</div>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">Netmask</span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="Most likely 255.255.255.0 or 255.255.0.0"
|
||||
aria-label="Netmask"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="text"
|
||||
required
|
||||
bind:value={device.netmask}
|
||||
/>
|
||||
</div>
|
||||
<h5 class="mt-4">Optional:</h5>
|
||||
{#if device?.expand?.ports}
|
||||
{#each device.expand.ports as port, idx}
|
||||
<div class="input-group mb-1">
|
||||
<span class="input-group-text">Port</span>
|
||||
<input
|
||||
type="text"
|
||||
aria-label="Name"
|
||||
class="form-control"
|
||||
placeholder="Name"
|
||||
bind:value={port.name}
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="65535"
|
||||
aria-label="Number"
|
||||
class="form-control"
|
||||
placeholder="Number"
|
||||
bind:value={port.number}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-outline-secondary"
|
||||
on:click={() => deletePort(idx)}
|
||||
>
|
||||
<Fa icon={faTrashCan} />
|
||||
</button>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
<div class="input-group mb-3">
|
||||
<span class="input-group-text">Port</span>
|
||||
<input
|
||||
type="text"
|
||||
aria-label="Name"
|
||||
class="form-control"
|
||||
placeholder="Name"
|
||||
bind:value={newPort.name}
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="65535"
|
||||
aria-label="Number"
|
||||
class="form-control"
|
||||
placeholder="Number"
|
||||
bind:value={newPort.number}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-outline-secondary"
|
||||
on:click={() => addPort()}
|
||||
>
|
||||
<Fa icon={faPlus} />
|
||||
</button>
|
||||
</div>
|
||||
<div class="input-group mb-3">
|
||||
<span class="input-group-text">Link</span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="Clickable link on device card"
|
||||
aria-label="Link"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="url"
|
||||
bind:value={device.link}
|
||||
/>
|
||||
</div>
|
||||
<div class="input-group mb-1">
|
||||
<span class="input-group-text">Wake Cron<sup>(1)</sup></span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="Automatically wake device with cron"
|
||||
aria-label="Wake Cron"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="text"
|
||||
bind:value={device.wake_cron}
|
||||
/>
|
||||
<div class="input-group-text form-switch">
|
||||
<label class="form-check-label" for="wake-cron-enabled">Enable</label>
|
||||
<input
|
||||
id="wake-cron-enabled"
|
||||
class="form-check-input mt-0 ms-1"
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
aria-label="Enable/Disable wake cron"
|
||||
bind:checked={device.wake_cron_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="input-group mb-1">
|
||||
<span class="input-group-text">Shutdown Cron<sup>(1)</sup></span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="Automatically shutdown device with cron"
|
||||
aria-label="Shutdown Cron"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="text"
|
||||
bind:value={device.shutdown_cron}
|
||||
/>
|
||||
<div class="input-group-text form-switch">
|
||||
<label class="form-check-label" for="wake-shutdown-enabled">Enable</label>
|
||||
<input
|
||||
id="wake-shutdown-enabled"
|
||||
class="form-check-input mt-0 ms-1"
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
aria-label="Enable/Disable wake cron"
|
||||
bind:checked={device.shutdown_cron_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="input-group mb-3">
|
||||
<span class="input-group-text">Shutdown Cmd<sup>(2)</sup></span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="Command to shutdown device"
|
||||
aria-label="Shutdown Cmd"
|
||||
aria-describedby="addon-wrapping"
|
||||
type="text"
|
||||
bind:value={device.shutdown_cmd}
|
||||
/>
|
||||
</div>
|
||||
<div class="input-group mb-3">
|
||||
<span class="input-group-text">Password<sup>(3)</sup></span>
|
||||
<input
|
||||
class="form-control"
|
||||
placeholder="BIOS password for wol"
|
||||
aria-label="IP"
|
||||
aria-describedby="addon-wrapping"
|
||||
type={passwordType}
|
||||
value={device.password}
|
||||
maxlength="6"
|
||||
on:input={onPasswordInput}
|
||||
/>
|
||||
<button
|
||||
class="btn btn-outline-secondary"
|
||||
type="button"
|
||||
on:click={() => (passwordShow = !passwordShow)}
|
||||
>
|
||||
<Fa icon={passwordShow ? faEyeSlash : faEye} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-secondary"
|
||||
class:btn-success={button.state === 'success' ? true : false}
|
||||
class:btn-warning={button.state === 'waiting' ? true : false}
|
||||
class:btn-danger={button.state === 'failed' ? true : false}
|
||||
disabled={button.state !== 'none' ? true : false}
|
||||
>
|
||||
{#if button.state === 'none'}
|
||||
{mode === 'add' ? 'Add device' : 'Save device'}
|
||||
{:else if button.state === 'success'}
|
||||
{mode === 'add' ? 'Added successfully' : 'Saved successfully'}
|
||||
{:else if button.state === 'waiting'}
|
||||
Waiting
|
||||
{:else if button.state === 'failed'}
|
||||
Failed: {button.error}
|
||||
{/if}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="col-md-6 d-flex align-items-start flex-column">
|
||||
<div class="callout callout-info mb-auto">
|
||||
<h5>Optional:</h5>
|
||||
<p class="m-0">
|
||||
(1) Learn more about the correct syntax for cron on
|
||||
<a href="https://en.wikipedia.org/wiki/Cron" target="_blank" rel="noreferrer"
|
||||
>wikipedia</a
|
||||
>
|
||||
or refer to the
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
href="https://pkg.go.dev/github.com/robfig/cron">package documentation</a
|
||||
>
|
||||
</p>
|
||||
<p class="m-0">
|
||||
(2) Shell command to be executed. "net rpc", "sshpass" and "curl" are available.
|
||||
e.g.:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
Windows: <code>net rpc shutdown -I 192.168.1.13 -U "user%password"</code>
|
||||
</li>
|
||||
<li>
|
||||
Linux: <code
|
||||
>sshpass -p your_password ssh -o "StrictHostKeyChecking=no"
|
||||
user@hostname "sudo poweroff"</code
|
||||
>
|
||||
</li>
|
||||
</ul>
|
||||
<p class="m-0">
|
||||
(3) Some network cards have the option to set a password for magic packets, also
|
||||
called "SecureON". Password can only be 0, 4 or 6 characters in length.
|
||||
</p>
|
||||
</div>
|
||||
{#if mode === 'edit'}
|
||||
<div class="text-end mt-3 align-self-end">
|
||||
<button
|
||||
class="btn btn-danger"
|
||||
on:click={() => deleteDevice()}
|
||||
on:keydown={() => deleteDevice()}
|
||||
>
|
||||
{#if deleteButton.state === 'none'}
|
||||
Delete device
|
||||
{:else if deleteButton.state === 'waiting'}
|
||||
Waiting
|
||||
{:else if deleteButton.state === 'failed'}
|
||||
Failed: {deleteButton.error}
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -1,215 +0,0 @@
|
||||
<script>
|
||||
import { dev } from '$app/environment';
|
||||
import { pocketbase, authorizedStore, settings_public } from '@stores/pocketbase';
|
||||
|
||||
let username;
|
||||
let password;
|
||||
let passwordConfirm;
|
||||
let isAdmin;
|
||||
let callout = {
|
||||
hidden: true,
|
||||
level: 'danger',
|
||||
title: '',
|
||||
msg: ''
|
||||
};
|
||||
|
||||
$: if ($settings_public.setup_completed === false) {
|
||||
callout.title = '';
|
||||
callout.msg = 'No admin account has been set up. Please create one.';
|
||||
callout.level = 'info';
|
||||
callout.hidden = false;
|
||||
}
|
||||
|
||||
async function login() {
|
||||
if (isAdmin) {
|
||||
$pocketbase.admins
|
||||
.authWithPassword(username, password)
|
||||
.then(() => {
|
||||
authorizedStore.set(true);
|
||||
})
|
||||
.catch((err) => {
|
||||
authorizedStore.set(false);
|
||||
callout.level = 'danger';
|
||||
callout.title = err.status;
|
||||
callout.msg = err.message;
|
||||
callout.hidden = false;
|
||||
});
|
||||
} else {
|
||||
$pocketbase
|
||||
.collection('users')
|
||||
.authWithPassword(username, password)
|
||||
.then(() => {
|
||||
authorizedStore.set(true);
|
||||
})
|
||||
.catch((err) => {
|
||||
authorizedStore.set(false);
|
||||
callout.level = 'danger';
|
||||
callout.title = err.status;
|
||||
callout.msg = err.message;
|
||||
callout.hidden = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function register() {
|
||||
if (password !== passwordConfirm) {
|
||||
callout.level = 'danger';
|
||||
callout.title = "Passwords don't match";
|
||||
callout.msg = 'Please try again';
|
||||
callout.hidden = false;
|
||||
return;
|
||||
} else {
|
||||
callout.hidden = true;
|
||||
}
|
||||
$pocketbase.admins
|
||||
.create({
|
||||
email: username,
|
||||
password: password,
|
||||
passwordConfirm: passwordConfirm
|
||||
})
|
||||
.then(() => {
|
||||
$pocketbase.admins
|
||||
.authWithPassword(username, password)
|
||||
.then(() => {
|
||||
authorizedStore.set(true);
|
||||
})
|
||||
.catch((err) => {
|
||||
return err;
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
authorizedStore.set(false);
|
||||
callout.level = 'danger';
|
||||
callout.title = err.status;
|
||||
callout.msg = err.message;
|
||||
callout.hidden = false;
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="container text-dark-emphasis">
|
||||
<div class="row justify-content-center align-items-center">
|
||||
<div class="col text-center p-3 p-md-5">
|
||||
<img
|
||||
src={$settings_public.favicon !== ''
|
||||
? `${dev ? $pocketbase.baseUrl : ''}/api/files/settings_public/${
|
||||
$settings_public.id
|
||||
}/${$settings_public.favicon}`
|
||||
: '/gopher.svg'}
|
||||
alt={$settings_public.website_title ? $settings_public.website_title : 'UpSnap'}
|
||||
class="logo pe-none user-select-none"
|
||||
/>
|
||||
<h2 class="text-dark-emphasis fw-bold text-center mt-3">
|
||||
{$settings_public.setup_completed === true ? 'Login' : 'Register'}
|
||||
</h2>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row justify-content-center align-items-center p-2">
|
||||
<div class="col-md-6 col-lg-5 p-4 login rounded-5 shadow-sm">
|
||||
<div class="callout callout-{callout.level} mt-0" class:d-none={callout.hidden}>
|
||||
{#if callout.title !== ''}
|
||||
<h5>{callout.title}</h5>
|
||||
{/if}
|
||||
{#if callout.msg !== ''}
|
||||
<p class="m-0">{callout.msg}</p>
|
||||
{/if}
|
||||
</div>
|
||||
{#if $settings_public.setup_completed === true}
|
||||
<form class="w-100" on:submit|preventDefault={login}>
|
||||
<div class="mb-3">
|
||||
<label for="username" class="form-label">Username or email</label>
|
||||
<input
|
||||
type="text"
|
||||
class="form-control"
|
||||
id="username"
|
||||
placeholder="user@example.com"
|
||||
bind:value={username}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
class="form-control"
|
||||
id="password"
|
||||
placeholder="secret-password"
|
||||
bind:value={password}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="form-check form-switch mb-3">
|
||||
<input
|
||||
class="form-check-input"
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
id="flexSwitchCheckChecked"
|
||||
bind:checked={isAdmin}
|
||||
/>
|
||||
<label class="form-check-label" for="flexSwitchCheckChecked"
|
||||
>Admin login</label
|
||||
>
|
||||
</div>
|
||||
<button class="btn btn-secondary w-100" type="submit">Login</button>
|
||||
</form>
|
||||
<p class="text-center m-0 mt-3">
|
||||
<!-- hacky way of linking a non existing route in svelte -->
|
||||
<a href="/_/" rel="external" class="text-muted cursor-pointer">Manage users</a>
|
||||
</p>
|
||||
{:else}
|
||||
<form class="w-100" on:submit|preventDefault={register}>
|
||||
<div class="mb-3">
|
||||
<label for="username" class="form-label">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
class="form-control"
|
||||
id="username"
|
||||
placeholder="user@example.com"
|
||||
bind:value={username}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label"
|
||||
>Password (min. 10 characters)</label
|
||||
>
|
||||
<input
|
||||
type="password"
|
||||
class="form-control"
|
||||
id="password"
|
||||
placeholder="secret-password"
|
||||
minlength="10"
|
||||
bind:value={password}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="passwordConfirm" class="form-label">Password confirm</label>
|
||||
<input
|
||||
type="password"
|
||||
class="form-control"
|
||||
id="passwordConfirm"
|
||||
placeholder="secret-password"
|
||||
minlength="10"
|
||||
bind:value={passwordConfirm}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button class="btn btn-secondary w-100" type="submit">Create and login</button>
|
||||
</form>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.logo {
|
||||
width: 40%;
|
||||
min-width: 50px;
|
||||
max-width: 200px;
|
||||
}
|
||||
|
||||
.cursor-pointer {
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
@@ -1,143 +0,0 @@
|
||||
<script>
|
||||
import { dev } from '$app/environment';
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import { theme } from '@stores/theme';
|
||||
import { pocketbase, authorizedStore, settings_public } from '@stores/pocketbase';
|
||||
import Fa from 'svelte-fa/src/fa.svelte';
|
||||
import {
|
||||
faSun,
|
||||
faMoon,
|
||||
faCircleHalfStroke,
|
||||
faBrush,
|
||||
faRightFromBracket
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
let userInfo = {
|
||||
usernameOrEmail: '',
|
||||
role: ''
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
if ($pocketbase.authStore.baseModel?.collectionName === 'users') {
|
||||
userInfo.role = 'user';
|
||||
} else {
|
||||
userInfo.role = 'admin';
|
||||
}
|
||||
if ($pocketbase.authStore.baseModel?.username) {
|
||||
userInfo.usernameOrEmail = $pocketbase.authStore.baseModel.username;
|
||||
} else {
|
||||
userInfo.usernameOrEmail = $pocketbase.authStore.baseModel.email;
|
||||
}
|
||||
});
|
||||
|
||||
async function logout() {
|
||||
$pocketbase.authStore.clear();
|
||||
authorizedStore.set(false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<nav class="navbar navbar-expand-sm pt-0">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand" href="/">
|
||||
<img
|
||||
src={$settings_public.favicon !== ''
|
||||
? `${dev ? $pocketbase.baseUrl : ''}/api/files/settings_public/${
|
||||
$settings_public.id
|
||||
}/${$settings_public.favicon}`
|
||||
: '/gopher.svg'}
|
||||
alt={$settings_public.website_title ? $settings_public.website_title : 'UpSnap'}
|
||||
width="45"
|
||||
height="45"
|
||||
class:me-2={$settings_public.website_title !== ''}
|
||||
/>{$settings_public.website_title ? $settings_public.website_title : ''}
|
||||
</a>
|
||||
<button
|
||||
class="navbar-toggler border-0"
|
||||
type="button"
|
||||
data-bs-toggle="collapse"
|
||||
data-bs-target="#navbarSupportedContent"
|
||||
aria-controls="navbarSupportedContent"
|
||||
aria-expanded="false"
|
||||
aria-label="Toggle navigation"
|
||||
>
|
||||
<span class="navbar-toggler-icon" />
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navbarSupportedContent">
|
||||
<ul class="navbar-nav">
|
||||
{#if userInfo.role !== 'user'}
|
||||
<li class="nav-item">
|
||||
<a
|
||||
class="nav-link"
|
||||
class:active={$page.url.pathname === '/' ? true : false}
|
||||
href="/">Home</a
|
||||
>
|
||||
</li>
|
||||
<li class="nav-item me-3">
|
||||
<a
|
||||
class="nav-link"
|
||||
class:active={$page.url.pathname === '/settings/' ? true : false}
|
||||
href="/settings/">Settings</a
|
||||
>
|
||||
</li>
|
||||
{/if}
|
||||
<li class="nav-item dropdown">
|
||||
<div
|
||||
class="nav-link dropdown-toggle"
|
||||
role="button"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
>
|
||||
<Fa icon={faBrush} class="me-2" />
|
||||
Theme
|
||||
</div>
|
||||
<ul class="dropdown-menu border-0 p-1 shadow-sm mb-2">
|
||||
<li>
|
||||
<div
|
||||
class="dropdown-item"
|
||||
class:active={$theme === 'light'}
|
||||
on:click={() => ($theme = 'light')}
|
||||
on:keydown={() => ($theme = 'light')}
|
||||
>
|
||||
<Fa icon={faSun} class="me-2" />
|
||||
Light
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div
|
||||
class="dropdown-item"
|
||||
class:active={$theme === 'dark'}
|
||||
on:click={() => ($theme = 'dark')}
|
||||
on:keydown={() => ($theme = 'dark')}
|
||||
>
|
||||
<Fa icon={faMoon} class="me-2" />
|
||||
Dark
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div
|
||||
class="dropdown-item"
|
||||
class:active={$theme === 'auto'}
|
||||
on:click={() => ($theme = 'auto')}
|
||||
on:keydown={() => ($theme = 'auto')}
|
||||
>
|
||||
<Fa icon={faCircleHalfStroke} class="me-2" />
|
||||
Auto
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="ms-auto d-flex">
|
||||
<button
|
||||
class="text-dark-emphasis nav-link active border-0"
|
||||
data-toggle="tooltip"
|
||||
title="Logged in as {userInfo.role} "{userInfo.usernameOrEmail}""
|
||||
on:click={() => logout()}
|
||||
>
|
||||
<Fa icon={faRightFromBracket} class="me-2" />Logout ({userInfo.usernameOrEmail})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
@@ -1,10 +0,0 @@
|
||||
<script>
|
||||
import { fly } from 'svelte/transition';
|
||||
export let url;
|
||||
</script>
|
||||
|
||||
{#key url}
|
||||
<div in:fly={{ y: 50, duration: 300 }}>
|
||||
<slot />
|
||||
</div>
|
||||
{/key}
|
||||
@@ -1,16 +0,0 @@
|
||||
<script>
|
||||
import { pocketbase } from '@stores/pocketbase';
|
||||
|
||||
let isUser = false;
|
||||
$: isUser = $pocketbase.authStore.baseModel?.collectionName === 'users';
|
||||
</script>
|
||||
|
||||
{#if isUser}
|
||||
<div class="row justify-content-center align-items-center">
|
||||
<div class="col-auto">
|
||||
<div class="callout callout-danger m-0">
|
||||
Logged in as read only user. To make changes, please log in as admin.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,144 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
|
||||
import DeviceCardNic from './DeviceCardNic.svelte';
|
||||
import Fa from 'svelte-fa';
|
||||
import {
|
||||
faBed,
|
||||
faCircleArrowDown,
|
||||
faCircleArrowUp,
|
||||
faLock,
|
||||
faPen,
|
||||
faRotateLeft
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { scale } from 'svelte/transition';
|
||||
import { formatDistance, parseISO } from 'date-fns';
|
||||
import toast from 'svelte-french-toast';
|
||||
import type { Device } from '$lib/types/device';
|
||||
|
||||
export let device: Device;
|
||||
|
||||
let moreButtons = [
|
||||
{
|
||||
text: 'Edit',
|
||||
icon: faPen,
|
||||
onClick: () => goto(`/device/${device.id}`),
|
||||
requires: $pocketbase.authStore.isAdmin || $permission.update?.includes(device.id)
|
||||
},
|
||||
{
|
||||
text: 'Sleep',
|
||||
icon: faBed,
|
||||
onClick: () => sleep(),
|
||||
requires:
|
||||
($pocketbase.authStore.isAdmin || $permission.power?.includes(device.id)) &&
|
||||
device.status === 'online' &&
|
||||
device.sol_enabled
|
||||
},
|
||||
{
|
||||
text: 'Reboot',
|
||||
icon: faRotateLeft,
|
||||
onClick: () => reboot(),
|
||||
requires:
|
||||
($pocketbase.authStore.isAdmin || $permission.power?.includes(device.id)) &&
|
||||
device.status === 'online' &&
|
||||
device.shutdown_cmd !== ''
|
||||
}
|
||||
];
|
||||
|
||||
// update device status change
|
||||
let now = Date.now();
|
||||
let interval: number;
|
||||
$: {
|
||||
clearInterval(interval);
|
||||
interval = setInterval(() => {
|
||||
now = Date.now();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function sleep() {
|
||||
fetch(`${backendUrl}api/upsnap/sleep/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function reboot() {
|
||||
fetch(`${backendUrl}api/upsnap/reboot/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="card bg-base-300 shadow-md rounded-3xl" transition:scale={{ delay: 0, duration: 200 }}>
|
||||
<div class="card-body p-6">
|
||||
{#if device.link.toString() !== ''}
|
||||
<a href={device.link.toString()} target="_blank">
|
||||
<h1 class="card-title link">{device.name}</h1>
|
||||
</a>
|
||||
{:else}
|
||||
<h1 class="card-title">{device.name}</h1>
|
||||
{/if}
|
||||
<ul class="menu bg-base-200 rounded-box">
|
||||
<!-- TODO: change to nic array once backend supports it -->
|
||||
<DeviceCardNic {device} />
|
||||
</ul>
|
||||
{#if device.wake_cron_enabled || device.shutdown_cron_enabled || device.password}
|
||||
<div class="flex flex-row flex-wrap gap-2">
|
||||
{#if device.wake_cron_enabled}
|
||||
<div class="tooltip" data-tip="Wake cron">
|
||||
<span class="badge badge-success gap-1 p-3"
|
||||
><Fa icon={faCircleArrowUp} />{device.wake_cron}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.shutdown_cron_enabled}
|
||||
<div class="tooltip" data-tip="Shutdown cron">
|
||||
<span class="badge badge-error gap-1 p-3"
|
||||
><Fa icon={faCircleArrowDown} />{device.shutdown_cron}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.password}
|
||||
<div class="tooltip" data-tip="Wake password">
|
||||
<span class="badge gap-1 p-3"><Fa icon={faLock} />Password</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="card-actions mt-auto items-center">
|
||||
<span class="tooltip" data-tip="Last status change: {device.updated}">
|
||||
{formatDistance(parseISO(device.updated), now, {
|
||||
includeSeconds: true,
|
||||
addSuffix: true
|
||||
})}
|
||||
</span>
|
||||
{#if moreButtons.filter((btn) => btn.requires).length > 0}
|
||||
<div class="dropdown dropdown-top dropdown-end bg-base-300 ms-auto">
|
||||
<label tabindex="-1" class="btn btn-sm m-1" for="more-{device.id}">More</label>
|
||||
<ul
|
||||
id="more-{device.id}"
|
||||
tabindex="-1"
|
||||
class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-fit"
|
||||
>
|
||||
{#each moreButtons as btn}
|
||||
{#if btn.requires}
|
||||
<li>
|
||||
<button on:click={btn.onClick}>
|
||||
<Fa icon={btn.icon} />{btn.text}
|
||||
</button>
|
||||
</li>
|
||||
{/if}
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,147 @@
|
||||
<script lang="ts">
|
||||
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faCircle, faPowerOff } from '@fortawesome/free-solid-svg-icons';
|
||||
import toast from 'svelte-french-toast';
|
||||
import type { Device } from '$lib/types/device';
|
||||
|
||||
export let device: Device;
|
||||
|
||||
let hoverText = '';
|
||||
let disabled = false;
|
||||
let timeout = 120;
|
||||
var interval: number;
|
||||
|
||||
$: if (device.status === 'pending' && !interval) {
|
||||
countdown(Date.parse(device.updated));
|
||||
}
|
||||
$: minutes = Math.floor(timeout / 60);
|
||||
$: seconds = timeout % 60;
|
||||
$: if (device.status === 'pending' || device.status === '') {
|
||||
disabled = true;
|
||||
hoverText = 'Pending';
|
||||
} else if (device.status === 'online') {
|
||||
if (device.shutdown_cmd === '') {
|
||||
disabled = true;
|
||||
hoverText = 'No shutdown command set';
|
||||
} else if (!$pocketbase.authStore.isAdmin && !$permission.power?.includes(device.id)) {
|
||||
disabled = true;
|
||||
hoverText = 'No permission to shut down this device';
|
||||
} else {
|
||||
disabled = false;
|
||||
hoverText = 'Shut down';
|
||||
}
|
||||
} else if (device.status === 'offline') {
|
||||
if (!$pocketbase.authStore.isAdmin && !$permission.power?.includes(device.id)) {
|
||||
disabled = true;
|
||||
hoverText = 'No permission to power on this device';
|
||||
} else {
|
||||
disabled = false;
|
||||
hoverText = 'Power on';
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: change wake and shutdown to nic based routes, not device based
|
||||
function wake() {
|
||||
fetch(`${backendUrl}api/upsnap/wake/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
})
|
||||
.then(async (data) => {
|
||||
const dev = (await data.json()) as Device;
|
||||
countdown(Date.parse(dev.updated));
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
fetch(`${backendUrl}api/upsnap/shutdown/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
})
|
||||
.then(async (data) => {
|
||||
const dev = (await data.json()) as Device;
|
||||
countdown(Date.parse(dev.updated));
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function countdown(updated: number) {
|
||||
timeout = 120;
|
||||
const end = updated + 2 * 60 * 1000;
|
||||
interval = setInterval(() => {
|
||||
timeout = Math.round((end - Date.now()) / 1000);
|
||||
if (timeout <= 0 || device.status !== 'pending') {
|
||||
clearInterval(interval);
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function handleClick() {
|
||||
if (device.status === 'offline') {
|
||||
wake();
|
||||
} else if (device.status === 'online') {
|
||||
shutdown();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<li class="tooltip" class:disabled data-tip={hoverText}>
|
||||
<div
|
||||
class="flex items-start p-2 gap-4"
|
||||
on:click={disabled ? null : handleClick}
|
||||
on:keydown={disabled ? null : handleClick}
|
||||
role="none"
|
||||
>
|
||||
{#if device.status === 'offline'}
|
||||
<button class="btn btn-error flex-shrink"><Fa icon={faPowerOff} /></button>
|
||||
{:else if device.status === 'online'}
|
||||
<button
|
||||
class="btn btn-success flex-shrink"
|
||||
class:cursor-not-allowed={device.shutdown_cmd === ''}><Fa icon={faPowerOff} /></button
|
||||
>
|
||||
{:else if device.status === 'pending'}
|
||||
<button class="btn btn-warning flex-shrink">
|
||||
<span class="countdown font-mono">
|
||||
<span style="--value:{minutes};" />:
|
||||
<span style="--value:{seconds};" />
|
||||
</span>
|
||||
</button>
|
||||
{:else}
|
||||
<button class="btn btn-warning flex-shrink">
|
||||
<span class="loading loading-ring loading-sm" />
|
||||
</button>
|
||||
{/if}
|
||||
<div class="grow">
|
||||
<div class="text-lg font-bold leading-4">{device.ip}</div>
|
||||
<div>{device.mac}</div>
|
||||
<div class="flex flex-wrap gap-x-4 gap-y-0">
|
||||
{#if device?.expand?.ports}
|
||||
{#each device?.expand?.ports.sort((a, b) => a.number - b.number) as port}
|
||||
<span class="flex items-center gap-1 break-all">
|
||||
{#if port.status}
|
||||
<Fa icon={faCircle} class="text-success" />
|
||||
{port.name} ({port.number})
|
||||
{:else}
|
||||
<Fa icon={faCircle} class="text-error" />
|
||||
{port.name} ({port.number})
|
||||
{/if}
|
||||
</span>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<style>
|
||||
:global(.menu li.disabled) {
|
||||
color: inherit;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,605 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { pocketbase, permission } from '$lib/stores/pocketbase';
|
||||
import DeviceFormPort from '$lib/components/DeviceFormPort.svelte';
|
||||
import toast from 'svelte-french-toast';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faSave, faTrash, faX } from '@fortawesome/free-solid-svg-icons';
|
||||
import type { Device, Port, Group } from '$lib/types/device';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
export let device: Device;
|
||||
|
||||
let deleteModal: HTMLDialogElement;
|
||||
let deviceGroups = [] as Group[];
|
||||
let newGroup = '';
|
||||
|
||||
onMount(async () => {
|
||||
await getGroups();
|
||||
});
|
||||
|
||||
async function save() {
|
||||
// create/update all ports
|
||||
let portIds: string[] = [];
|
||||
await Promise.all(
|
||||
device.expand.ports.map(async (port) => {
|
||||
if (port.id === undefined) {
|
||||
const data = await createPort(port as Port);
|
||||
if (data === undefined) return;
|
||||
portIds = [...portIds, data.id];
|
||||
} else {
|
||||
const data = await updatePort(port as Port);
|
||||
if (data === undefined) return;
|
||||
portIds = [...portIds, data.id];
|
||||
}
|
||||
})
|
||||
);
|
||||
device.ports = portIds;
|
||||
device.id ? updateDevice(device) : createDevice(device);
|
||||
}
|
||||
|
||||
async function updateDevice(device: Device) {
|
||||
$pocketbase
|
||||
.collection('devices')
|
||||
.update(device.id, device)
|
||||
.then(() => {
|
||||
toast.success(`Updated ${device.name}`);
|
||||
goto('/');
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
async function createDevice(device: Device) {
|
||||
device.created_by = $pocketbase.authStore.isAdmin ? '' : $pocketbase.authStore.model?.id ?? '';
|
||||
$pocketbase
|
||||
.collection('devices')
|
||||
.create(device)
|
||||
.then(() => {
|
||||
toast.success(`Created ${device.name}`);
|
||||
goto('/');
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
async function createPort(port: Port): Promise<Port | undefined> {
|
||||
let newport: Port | undefined;
|
||||
await $pocketbase
|
||||
.collection('ports')
|
||||
.create(port)
|
||||
.then((data) => {
|
||||
newport = data as Port;
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
|
||||
newport = undefined;
|
||||
});
|
||||
return newport;
|
||||
}
|
||||
|
||||
async function updatePort(port: Port): Promise<Port | undefined> {
|
||||
let newport: Port | undefined;
|
||||
await $pocketbase
|
||||
.collection('ports')
|
||||
.update(port.id, port)
|
||||
.then((data) => {
|
||||
newport = data as Port;
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
|
||||
newport = undefined;
|
||||
});
|
||||
return newport;
|
||||
}
|
||||
|
||||
function deleteDevice() {
|
||||
$pocketbase
|
||||
.collection('devices')
|
||||
.delete(device.id)
|
||||
.then(() => {
|
||||
toast.success(`Deleted ${device.name}`);
|
||||
goto('/');
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function createEmptyPort() {
|
||||
if (device === undefined) return;
|
||||
device.expand.ports = [...device.expand.ports, { name: '', number: 1 } as Port];
|
||||
}
|
||||
|
||||
async function getGroups() {
|
||||
$pocketbase
|
||||
.collection('device_groups')
|
||||
.getFullList()
|
||||
.then((res) => {
|
||||
deviceGroups = res as Group[];
|
||||
});
|
||||
}
|
||||
|
||||
function addGroup() {
|
||||
if (!newGroup) return;
|
||||
$pocketbase
|
||||
.collection('device_groups')
|
||||
.create({
|
||||
name: newGroup
|
||||
})
|
||||
.then((res) => {
|
||||
deviceGroups = [...deviceGroups, res as Group];
|
||||
toast.success(`Created group ${newGroup}`);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function deleteGroup(group: Group) {
|
||||
const i = device.groups.indexOf(group.id);
|
||||
if (i !== -1) {
|
||||
device.groups.splice(i, 1);
|
||||
device.groups = device.groups;
|
||||
}
|
||||
$pocketbase
|
||||
.collection('device_groups')
|
||||
.delete(group.id)
|
||||
.then(async () => {
|
||||
await getGroups();
|
||||
toast.success(`Deleted group ${group.name}`);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function toggleGroup(id: string) {
|
||||
const i = device.groups.indexOf(id);
|
||||
if (i !== -1) {
|
||||
device.groups.splice(i, 1);
|
||||
device.groups = device.groups;
|
||||
} else {
|
||||
device.groups = [...device.groups, id];
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<form on:submit|preventDefault={save}>
|
||||
<div class="card w-full bg-base-300 shadow-xl">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">General</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
|
||||
<div class="form-control w-full max-w-xs">
|
||||
<label class="label" for="device-name">
|
||||
<div class="label-text">
|
||||
<span>Name</span>
|
||||
<span class="text-error">*</span>
|
||||
</div>
|
||||
</label>
|
||||
<input
|
||||
id="device-name"
|
||||
type="text"
|
||||
placeholder="Device name"
|
||||
class="input w-full max-w-xs"
|
||||
bind:value={device.name}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="form-control w-full max-w-xs">
|
||||
<label class="label" for="device-ip">
|
||||
<div class="label-text">
|
||||
<span>IP</span>
|
||||
<span class="text-error">*</span>
|
||||
</div>
|
||||
</label>
|
||||
<input
|
||||
id="device-ip"
|
||||
type="text"
|
||||
placeholder="192.168.0.5"
|
||||
class="input w-full max-w-xs"
|
||||
bind:value={device.ip}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="form-control w-full max-w-xs">
|
||||
<label class="label" for="device-mac">
|
||||
<div class="label-text">
|
||||
<span>Mac</span>
|
||||
<span class="text-error">*</span>
|
||||
</div>
|
||||
</label>
|
||||
<input
|
||||
id="device-mac"
|
||||
type="text"
|
||||
placeholder="aa:bb:cc:dd:ee:ff"
|
||||
class="input w-full max-w-xs"
|
||||
bind:value={device.mac}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="form-control w-full max-w-xs">
|
||||
<label class="label" for="device-netmask">
|
||||
<div class="label-text">
|
||||
<span>Netmask</span>
|
||||
<span class="text-error">*</span>
|
||||
</div>
|
||||
</label>
|
||||
<input
|
||||
id="device-netmask"
|
||||
type="text"
|
||||
placeholder="255.255.255.0"
|
||||
class="input w-full max-w-xs"
|
||||
bind:value={device.netmask}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<span class="badge text-error self-center">* required field</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Ports</h2>
|
||||
<p class="my-2">UpSnap can also check if given ports are open. You can define them below.</p>
|
||||
<div class="form-control w-full">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
<!-- eslint-disable-next-line @typescript-eslint/no-unused-vars -->
|
||||
{#each device.expand.ports as _, index}
|
||||
<DeviceFormPort bind:device {index} />
|
||||
{/each}
|
||||
</div>
|
||||
<button
|
||||
class="btn btn-wide btn-primary mt-4"
|
||||
on:click={() => createEmptyPort()}
|
||||
type="button">Add new port</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Link</h2>
|
||||
<p class="my-2">
|
||||
Makes your device name a clickable link, perfect for linking a dashboard for example.
|
||||
</p>
|
||||
<div class="form-control w-full">
|
||||
<input
|
||||
type="url"
|
||||
placeholder="https:// ..."
|
||||
class="input w-full max-w-xs"
|
||||
bind:value={device.link}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Wake</h2>
|
||||
<p class="my-2">
|
||||
You can power this device using a scheduled cron job. If you are not familiar with cron, you
|
||||
can read about it <a class="link" href="https://en.wikipedia.org/wiki/Cron" target="_blank"
|
||||
>here</a
|
||||
>
|
||||
or refer to the
|
||||
<a class="link" href="https://pkg.go.dev/github.com/robfig/cron/v3" target="_blank"
|
||||
>package documentation</a
|
||||
>
|
||||
for more information.
|
||||
</p>
|
||||
<div class="form-control flex flex-row flex-wrap gap-4">
|
||||
<div>
|
||||
<label class="label" for="wake-cron">
|
||||
<span class="label-text"
|
||||
>Wake cron
|
||||
{#if device.wake_cron_enabled}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="wake-cron"
|
||||
type="text"
|
||||
placeholder="M H DoM M DoW"
|
||||
class="input w-80"
|
||||
bind:value={device.wake_cron}
|
||||
disabled={!device.wake_cron_enabled}
|
||||
required={device.wake_cron_enabled}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col">
|
||||
<label class="label cursor-pointer" for="wake-cron-enable">
|
||||
<span class="label-text">Enable wake cron</span>
|
||||
</label>
|
||||
<input
|
||||
id="wake-cron-enable"
|
||||
type="checkbox"
|
||||
class="toggle toggle-success"
|
||||
bind:checked={device.wake_cron_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Sleep-On-LAN</h2>
|
||||
<p class="mt-2">
|
||||
You can put computers to sleep using the <a
|
||||
class="link"
|
||||
href="https://github.com/SR-G/sleep-on-lan"
|
||||
target="_blank">Sleep-On-LAN</a
|
||||
>
|
||||
tool. Sleep-On-LAN (SOL) is an external tool/daemon that operates on the PCs you want to put
|
||||
to sleep, providing a REST endpoint. For instructions on setting up Sleep-On-LAN, please refer
|
||||
to the
|
||||
<a href="https://github.com/SR-G/sleep-on-lan#usage" class="link" target="_blank">Usage</a> section.
|
||||
</p>
|
||||
<p>
|
||||
SOL is confiugred to send requests over HTTP instead of UDP to enable authorization and make
|
||||
requests more reliable.
|
||||
</p>
|
||||
<p class="font-bold">
|
||||
Therefore, please ensure that you include <span class="badge">HTTP:<YOURPORT></span>
|
||||
in the <span class="badge">Listeners</span> section of the
|
||||
<a href="https://github.com/SR-G/sleep-on-lan#configuration" class="link" target="_blank"
|
||||
>SOL configuration</a
|
||||
>.
|
||||
</p>
|
||||
<div class="flex flex-row flex-wrap gap-4 items-end mt-4">
|
||||
<div>
|
||||
<div class="form-control flex flex-row flex-wrap gap-4">
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<input
|
||||
id="sol-enable"
|
||||
type="checkbox"
|
||||
class="toggle toggle-success"
|
||||
bind:checked={device.sol_enabled}
|
||||
/>
|
||||
<label class="label cursor-pointer" for="sol-enable">
|
||||
<span class="label-text">Enable Sleep-On-LAN</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control flex flex-col">
|
||||
<label class="label" for="sol-port">
|
||||
<span class="label-text"
|
||||
>SOL Port
|
||||
{#if device.sol_enabled}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="sol-port"
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
placeholder="Default: 8009"
|
||||
class="input w-80"
|
||||
bind:value={device.sol_port}
|
||||
disabled={!device.sol_enabled}
|
||||
required={device.sol_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if device.sol_enabled}
|
||||
<div>
|
||||
<div class="form-control flex flex-row flex-wrap gap-4">
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<input
|
||||
id="sol-auth"
|
||||
type="checkbox"
|
||||
class="toggle toggle-success"
|
||||
bind:checked={device.sol_auth}
|
||||
/>
|
||||
<label class="label cursor-pointer" for="sol-auth">
|
||||
<span class="label-text">Authorization</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control flex flex-col">
|
||||
<label class="label" for="sol-user">
|
||||
<span class="label-text"
|
||||
>SOL User
|
||||
{#if device.sol_auth}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="sol-user"
|
||||
type="text"
|
||||
placeholder="username"
|
||||
class="input w-80"
|
||||
bind:value={device.sol_user}
|
||||
disabled={!device.sol_auth}
|
||||
required={device.sol_auth}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control flex flex-col">
|
||||
<label class="label" for="sol-password">
|
||||
<span class="label-text"
|
||||
>SOL Password
|
||||
{#if device.sol_auth}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="sol-password"
|
||||
type="password"
|
||||
placeholder="password"
|
||||
class="input w-80"
|
||||
bind:value={device.sol_password}
|
||||
disabled={!device.sol_auth}
|
||||
required={device.sol_auth}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Shutdown</h2>
|
||||
<p class="my-2">
|
||||
This <strong>shell command</strong> will run inside your container (if you use docker) or on
|
||||
your host (if you use the binary). To verify that works you can run the command inside the
|
||||
container or on your host shell first. Common commands are
|
||||
<span class="badge">net rpc</span> for windows, <span class="badge">sshpass</span> for linux
|
||||
or
|
||||
<span class="badge">curl</span> in general to make web requests.
|
||||
</p>
|
||||
<p class="my-2 font-bold">Examples:</p>
|
||||
<div class="mockup-code text-sm max-w-fit">
|
||||
<pre data-prefix="#"><code>Shutdown remote windows machine:</code></pre>
|
||||
<pre data-prefix="$" class="text-warning"><code
|
||||
>net rpc shutdown -I 192.168.1.13 -U "user%password"</code
|
||||
></pre>
|
||||
</div>
|
||||
<div class="mockup-code text-sm max-w-fit">
|
||||
<pre data-prefix="#"><code>Shutdown remote linux machine:</code></pre>
|
||||
<pre data-prefix="$" class="text-warning"><code
|
||||
>sshpass -p password ssh -o "StrictHostKeyChecking=no" user@192.168.1.13 "sudo poweroff"</code
|
||||
></pre>
|
||||
</div>
|
||||
<div class="form-control w-full">
|
||||
<label class="label cursor-pointer" for="shutdown-cmd">
|
||||
<span class="label-text">Shutdown command</span>
|
||||
</label>
|
||||
<input
|
||||
id="shutdown-cmd"
|
||||
type="text"
|
||||
placeholder="$:"
|
||||
class="input w-full max-w-xs mb-2"
|
||||
bind:value={device.shutdown_cmd}
|
||||
/>
|
||||
</div>
|
||||
<p class="my-2">
|
||||
Just like setting a cron to wake the device, you can also schedule a cron job to shut down
|
||||
this device.
|
||||
</p>
|
||||
<div class="form-control flex flex-row flex-wrap gap-4">
|
||||
<div>
|
||||
<label class="label" for="shutdown-cron">
|
||||
<span class="label-text"
|
||||
>Shutdown cron
|
||||
{#if device.shutdown_cron_enabled}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="shutdown-cron"
|
||||
type="text"
|
||||
placeholder="M H DoM M DoW"
|
||||
class="input w-80"
|
||||
bind:value={device.shutdown_cron}
|
||||
disabled={!device.shutdown_cron_enabled}
|
||||
required={device.shutdown_cron_enabled}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col">
|
||||
<label class="label cursor-pointer" for="shutdown-cron-enable">
|
||||
<span class="label-text">Enable shutdown cron</span>
|
||||
</label>
|
||||
<input
|
||||
id="shutdown-cron-enable"
|
||||
type="checkbox"
|
||||
class="toggle toggle-success"
|
||||
bind:checked={device.shutdown_cron_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Password</h2>
|
||||
<p class="my-2">
|
||||
Some network cards have the option to set a password for magic packets, also called <span
|
||||
class="badge">SecureON</span
|
||||
>. Password can only be 0, 4 or 6 characters in length.
|
||||
</p>
|
||||
<div class="form-control w-full">
|
||||
<input
|
||||
type="password"
|
||||
placeholder="123456"
|
||||
class="input w-full max-w-xs"
|
||||
maxlength="6"
|
||||
bind:value={device.password}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Groups</h2>
|
||||
<p class="my-2">
|
||||
You can add devices to a group to have them sorted by group on the dashboard.
|
||||
</p>
|
||||
<div class="flex flex-row flex-wrap gap-2">
|
||||
{#each deviceGroups as group}
|
||||
<div class="join">
|
||||
<div class=" tooltip" data-tip="Delete">
|
||||
<button
|
||||
class="join-item btn btn-error"
|
||||
type="button"
|
||||
on:click={() => deleteGroup(group)}><Fa icon={faX} /></button
|
||||
>
|
||||
</div>
|
||||
<div
|
||||
class="btn bg-base-100 hover:bg-base-200 join-item"
|
||||
on:click={() => toggleGroup(group.id)}
|
||||
role="none"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="checkbox checked:checkbox-primary"
|
||||
checked={device.groups.indexOf(group.id) !== -1}
|
||||
/>
|
||||
{group.name}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="join">
|
||||
<input
|
||||
class="input input-bordered join-item"
|
||||
placeholder="e.g. 'Basement' or 'Office'"
|
||||
type="text"
|
||||
bind:value={newGroup}
|
||||
/>
|
||||
<button class="btn btn-primary join-item" type="button" on:click={() => addGroup()}
|
||||
>Create</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-actions mt-6 justify-end gap-4">
|
||||
{#if $pocketbase.authStore.isAdmin || $permission.delete?.includes(device.id)}
|
||||
<button class="btn btn-error" type="button" on:click={() => deleteModal.showModal()}
|
||||
><Fa icon={faTrash} />Delete</button
|
||||
>
|
||||
<dialog class="modal" bind:this={deleteModal}>
|
||||
<form method="dialog" class="modal-box">
|
||||
<h3 class="font-bold text-lg">Confirm delete</h3>
|
||||
<p class="py-4">Are you sure you want to delete <strong>{device.name}</strong>?</p>
|
||||
<div class="modal-action">
|
||||
<button class="btn">Cancle</button>
|
||||
<button class="btn btn-error" on:click={() => deleteDevice()}>Delete</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
{/if}
|
||||
<button class="btn btn-success" type="submit"><Fa icon={faSave} />Save</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,71 @@
|
||||
<script lang="ts">
|
||||
import { pocketbase } from '$lib/stores/pocketbase';
|
||||
import { scale } from 'svelte/transition';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faTrash } from '@fortawesome/free-solid-svg-icons';
|
||||
import toast from 'svelte-french-toast';
|
||||
import type { Device, Port } from '$lib/types/device';
|
||||
import type { Record } from 'pocketbase';
|
||||
|
||||
export let device: Device;
|
||||
export let index: number;
|
||||
|
||||
function deletePort(port: Port | Record) {
|
||||
if (port.id !== undefined) {
|
||||
$pocketbase
|
||||
.collection('ports')
|
||||
.delete(port.id)
|
||||
.then(() => {
|
||||
device.ports = device.ports.filter((id) => id !== device.ports[index]);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
device.expand.ports = device.expand.ports.filter((p) => p !== device.expand.ports[index]);
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if device.expand.ports[index]}
|
||||
<div class="card bg-base-100 shadow-sm" transition:scale={{ delay: 0, duration: 200 }}>
|
||||
<div class="card-body p-3">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div>
|
||||
<label class="label p-0" for="port-name-{index}">
|
||||
<span class="label-text">Name</span>
|
||||
</label>
|
||||
<input
|
||||
id="port-name-{index}"
|
||||
type="text"
|
||||
placeholder="ssh"
|
||||
class="input input-sm input-bordered w-full"
|
||||
required
|
||||
bind:value={device.expand.ports[index].name}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label p-0" for="port-number-{index}">
|
||||
<span class="label-text">Number</span>
|
||||
</label>
|
||||
<input
|
||||
id="port-number-{index}"
|
||||
type="number"
|
||||
placeholder="22"
|
||||
min="1"
|
||||
max="65535"
|
||||
class="input input-sm input-bordered w-full"
|
||||
required
|
||||
bind:value={device.expand.ports[index].number}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-actions justify-end">
|
||||
<button
|
||||
class="btn btn-xs btn-outline btn-error"
|
||||
on:click={() => deletePort(device.expand.ports[index])}
|
||||
type="button"><Fa icon={faTrash} />Delete</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,235 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/stores';
|
||||
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
|
||||
import { settingsPub } from '$lib/stores/settings';
|
||||
import Fa from 'svelte-fa';
|
||||
import {
|
||||
faCog,
|
||||
faHome,
|
||||
faPlus,
|
||||
faSwatchbook,
|
||||
faChevronDown,
|
||||
faCheck,
|
||||
faUsersGear,
|
||||
faUserGear,
|
||||
faDoorOpen
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { themeChange } from 'theme-change';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let availableThemes = [
|
||||
'light',
|
||||
'dark',
|
||||
'cupcake',
|
||||
'bumblebee',
|
||||
'emerald',
|
||||
'corporate',
|
||||
'synthwave',
|
||||
'retro',
|
||||
'cyberpunk',
|
||||
'valentine',
|
||||
'halloween',
|
||||
'garden',
|
||||
'forest',
|
||||
'aqua',
|
||||
'lofi',
|
||||
'pastel',
|
||||
'fantasy',
|
||||
'wireframe',
|
||||
'black',
|
||||
'luxury',
|
||||
'dracula',
|
||||
'cmyk',
|
||||
'autumn',
|
||||
'business',
|
||||
'acid',
|
||||
'lemonade',
|
||||
'night',
|
||||
'coffee',
|
||||
'winter'
|
||||
];
|
||||
let activeTheme: string | null = '';
|
||||
let avatar = $pocketbase.authStore.model?.avatar;
|
||||
|
||||
onMount(() => {
|
||||
themeChange(false);
|
||||
activeTheme = document.documentElement.getAttribute('data-theme');
|
||||
|
||||
$pocketbase.authStore.onChange(() => {
|
||||
avatar = $pocketbase.authStore.model?.avatar;
|
||||
});
|
||||
});
|
||||
|
||||
async function logout() {
|
||||
await $pocketbase.collection('devices').unsubscribe('*');
|
||||
await $pocketbase.collection('ports').unsubscribe('*');
|
||||
await $pocketbase.collection('permissions').unsubscribe('*');
|
||||
$pocketbase.authStore.clear();
|
||||
goto('/login', { invalidateAll: true });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="navbar bg-base-100">
|
||||
<div class="justify-start">
|
||||
<div class="dropdown">
|
||||
<label tabindex="-1" class="btn btn-ghost lg:hidden" for="mobile-menu">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
><path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M4 6h16M4 12h8m-8 6h16"
|
||||
/></svg
|
||||
>
|
||||
</label>
|
||||
<ul
|
||||
id="mobile-menu"
|
||||
tabindex="-1"
|
||||
class="menu dropdown-content mt-3 z-[1] p-2 gap-1 shadow bg-base-300 rounded-box w-52"
|
||||
>
|
||||
{#if $settingsPub?.website_title}
|
||||
<div class="menu-title">
|
||||
{$settingsPub?.website_title}
|
||||
</div>
|
||||
{/if}
|
||||
<li>
|
||||
<a href="/" class="px-4 py-2" class:active={$page.url.pathname === '/'}
|
||||
><Fa icon={faHome} />Home</a
|
||||
>
|
||||
</li>
|
||||
{#if $pocketbase.authStore.isAdmin}
|
||||
<li>
|
||||
<a
|
||||
href="/users"
|
||||
class="px-4 py-2"
|
||||
class:active={$page.url.pathname.startsWith('/users')}
|
||||
><Fa icon={faUsersGear} />Users</a
|
||||
>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
href="/settings/"
|
||||
class="px-4 py-2"
|
||||
class:active={$page.url.pathname.startsWith('/settings')}
|
||||
><Fa icon={faCog} />Settings</a
|
||||
>
|
||||
</li>
|
||||
{/if}
|
||||
</ul>
|
||||
</div>
|
||||
<a class="btn btn-ghost normal-case text-xl px-2" href="/">
|
||||
<img
|
||||
src={$settingsPub?.id && $settingsPub?.favicon
|
||||
? `${backendUrl}api/files/settings_public/${$settingsPub?.id}/${$settingsPub?.favicon}`
|
||||
: '/gopher.svg'}
|
||||
alt={$settingsPub?.website_title ? $settingsPub?.website_title : 'UpSnap'}
|
||||
width="45"
|
||||
height="45"
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
<div class="hidden lg:flex">
|
||||
{#if $settingsPub?.website_title}
|
||||
<span class="px-2">{$settingsPub?.website_title}</span>
|
||||
{/if}
|
||||
<ul class="menu menu-horizontal px-1 gap-1">
|
||||
<li>
|
||||
<a href="/" class="p-2" class:active={$page.url.pathname === '/'}
|
||||
><Fa icon={faHome} />Home</a
|
||||
>
|
||||
</li>
|
||||
{#if $pocketbase.authStore.isAdmin}
|
||||
<li>
|
||||
<a href="/users" class="p-2" class:active={$page.url.pathname.startsWith('/users')}
|
||||
><Fa icon={faUsersGear} />Users</a
|
||||
>
|
||||
</li>
|
||||
<li>
|
||||
<a href="/settings/" class="p-2" class:active={$page.url.pathname.startsWith('/settings')}
|
||||
><Fa icon={faCog} />Settings</a
|
||||
>
|
||||
</li>
|
||||
{/if}
|
||||
</ul>
|
||||
</div>
|
||||
<div class="dropdown md:dropdown-end">
|
||||
<div tabindex="-1" class="btn normal-case btn-ghost">
|
||||
<Fa icon={faSwatchbook} />
|
||||
<span class="hidden font-normal md:inline">Theme</span>
|
||||
<Fa icon={faChevronDown} />
|
||||
</div>
|
||||
<div
|
||||
class="dropdown-content bg-base-200 text-base-content rounded-box h-fit max-h-96 w-56 overflow-y-auto shadow mt-3 z-[1]"
|
||||
>
|
||||
<div class="grid grid-cols-1 gap-3 p-3" tabindex="-1">
|
||||
{#each availableThemes as theme}
|
||||
<button
|
||||
class="outline-base-content overflow-hidden rounded-lg text-left"
|
||||
data-set-theme={theme}
|
||||
on:click={() => (activeTheme = theme)}
|
||||
on:keydown={() => (activeTheme = theme)}
|
||||
>
|
||||
<div
|
||||
data-theme={theme}
|
||||
class="bg-base-100 text-base-content w-full cursor-pointer font-sans"
|
||||
>
|
||||
<div class="grid grid-cols-5 grid-rows-3">
|
||||
<div class="col-span-5 row-span-3 row-start-1 flex items-center gap-2 px-4 py-3">
|
||||
<Fa icon={faCheck} class={activeTheme === theme ? 'visible' : 'invisible'} />
|
||||
<div class="flex-grow text-sm">{theme}</div>
|
||||
<div class="flex h-full flex-shrink-0 flex-wrap gap-1">
|
||||
<div class="bg-primary w-2 rounded" />
|
||||
<div class="bg-secondary w-2 rounded" />
|
||||
<div class="bg-accent w-2 rounded" />
|
||||
<div class="bg-neutral w-2 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="justify-end ms-auto">
|
||||
{#if $pocketbase.authStore?.model !== null}
|
||||
{#if $pocketbase.authStore.isAdmin || $permission.create}
|
||||
<a class="btn btn-success me-4" href="/device/new">
|
||||
<Fa icon={faPlus} />
|
||||
New
|
||||
</a>
|
||||
{/if}
|
||||
<div class="dropdown dropdown-end">
|
||||
<label tabindex="-1" class="btn btn-ghost btn-circle avatar" for="avatar">
|
||||
<div class="w-10 rounded-full" id="avatar">
|
||||
<img src="{backendUrl}_/images/avatars/avatar{avatar}.svg" alt="Avatar {avatar}" />
|
||||
</div>
|
||||
</label>
|
||||
<ul
|
||||
tabindex="-1"
|
||||
class="menu dropdown-content mt-3 z-[1] p-2 shadow bg-base-300 rounded-box"
|
||||
>
|
||||
<li class="menu-title">
|
||||
{$pocketbase.authStore.isAdmin
|
||||
? $pocketbase.authStore.model.email
|
||||
: $pocketbase.authStore.model.username}
|
||||
</li>
|
||||
<li>
|
||||
<a href="/account"><Fa icon={faUserGear} />Edit account</a>
|
||||
</li>
|
||||
<li>
|
||||
<div on:click={async () => logout()} on:keydown={async () => logout()} role="none">
|
||||
<Fa icon={faDoorOpen} />Logout
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,267 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { pocketbase, backendUrl } from '$lib/stores/pocketbase';
|
||||
import { settingsPriv } from '$lib/stores/settings';
|
||||
import PageLoading from '$lib/components/PageLoading.svelte';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faMagnifyingGlass, faPlus, faX } from '@fortawesome/free-solid-svg-icons';
|
||||
import toast from 'svelte-french-toast';
|
||||
import type { SettingsPrivate } from '$lib/types/settings';
|
||||
import type { ScanResponse, ScannedDevice } from '$lib/types/scan';
|
||||
import type { Device } from '$lib/types/device';
|
||||
|
||||
let scanRange = '';
|
||||
let scanRunning = false;
|
||||
let scanResponse: ScanResponse = {
|
||||
netmask: '',
|
||||
devices: []
|
||||
};
|
||||
let addAllCheckbox = true;
|
||||
let replaceNetmaskCheckbox = false;
|
||||
let replaceNetmask = '';
|
||||
|
||||
onMount(() => {
|
||||
if (!$settingsPriv) {
|
||||
$pocketbase
|
||||
.collection('settings_private')
|
||||
.getFirstListItem('')
|
||||
.then((res) => {
|
||||
settingsPriv.set(res as SettingsPrivate);
|
||||
scanRange = $settingsPriv.scan_range;
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
} else {
|
||||
scanRange = $settingsPriv.scan_range;
|
||||
}
|
||||
});
|
||||
|
||||
function saveSettings() {
|
||||
$pocketbase
|
||||
.collection('settings_private')
|
||||
.update($settingsPriv.id, {
|
||||
scan_range: scanRange
|
||||
})
|
||||
.then((res) => {
|
||||
settingsPriv.set(res as SettingsPrivate);
|
||||
toast.success('Scan range saved');
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function scan() {
|
||||
scanRunning = true;
|
||||
fetch(`${backendUrl}api/upsnap/scan`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
})
|
||||
.then(async (resp) => {
|
||||
if (resp.ok) {
|
||||
return resp.json();
|
||||
} else {
|
||||
return Promise.reject(await resp.json());
|
||||
}
|
||||
})
|
||||
.then((data) => {
|
||||
scanResponse = data as ScanResponse;
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err);
|
||||
})
|
||||
.finally(() => (scanRunning = false));
|
||||
}
|
||||
|
||||
async function createDevice(device: ScannedDevice): Promise<Device> {
|
||||
if (replaceNetmaskCheckbox) {
|
||||
device.netmask = replaceNetmask;
|
||||
} else {
|
||||
device.netmask = scanResponse.netmask;
|
||||
}
|
||||
return $pocketbase.collection('devices').create(device);
|
||||
}
|
||||
|
||||
async function addSingle(device: ScannedDevice) {
|
||||
await createDevice(device)
|
||||
.then(() => {
|
||||
toast.success(`Added ${device.name}`);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
async function addAll() {
|
||||
let count = 0;
|
||||
await Promise.all(
|
||||
scanResponse.devices.map(async (dev) => {
|
||||
if (!addAllCheckbox && dev.name === 'Unknown') return;
|
||||
await createDevice(dev)
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
})
|
||||
.then(() => {
|
||||
count += 1;
|
||||
});
|
||||
})
|
||||
);
|
||||
toast.success(`Added ${count} devices`);
|
||||
goto('/');
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if $settingsPriv}
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Network scan</h2>
|
||||
<p class="my-2">
|
||||
Automatically scan your network for devices. For this to work, you need to run UpSnap as
|
||||
root/admin and have nmap installed and available in your $PATH (For docker users, thats
|
||||
already the case and you don't need to do anything). Scanning might take some seconds.
|
||||
</p>
|
||||
<div class="flex flex-row flex-wrap gap-4 items-end">
|
||||
<form on:submit|preventDefault={saveSettings}>
|
||||
<label class="label" for="scan-range">
|
||||
<span class="label-text">IP range</span>
|
||||
</label>
|
||||
<div class="join">
|
||||
<input
|
||||
id="scan-range"
|
||||
class="input input-bordered join-item"
|
||||
type="text"
|
||||
placeholder="192.168.1.0/24"
|
||||
bind:value={scanRange}
|
||||
/>
|
||||
<button class="btn btn-primary join-item" type="submit">Save</button>
|
||||
</div>
|
||||
</form>
|
||||
<div>
|
||||
<div>
|
||||
{#if !$settingsPriv.scan_range}
|
||||
<button class="btn btn-error" disabled>
|
||||
<Fa icon={faX} /> No scan range
|
||||
</button>
|
||||
{:else if scanRange !== $settingsPriv.scan_range}
|
||||
<button class="btn btn-error" disabled>
|
||||
<Fa icon={faX} /> Unsaved changes
|
||||
</button>
|
||||
{:else if scanRunning}
|
||||
<button class="btn no-animation">
|
||||
<span class="loading loading-spinner" />
|
||||
Scan running
|
||||
</button>
|
||||
{:else}
|
||||
<button class="btn btn-success" on:click={() => scan()}>
|
||||
<Fa icon={faMagnifyingGlass} /> Scan
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if scanResponse.devices?.length > 0}
|
||||
{#each scanResponse.devices.sort( (a, b) => a.ip.localeCompare( b.ip, undefined, { numeric: true } ) ) as device, index}
|
||||
<div class="collapse collapse-arrow bg-base-200">
|
||||
<input type="radio" name="scanned-devices" checked={index === 0} />
|
||||
<div class="collapse-title font-bold">
|
||||
{device.name} <span class="badge">{device.ip}</span>
|
||||
</div>
|
||||
<div class="collapse-content">
|
||||
<div class="flex flex-row flex-wrap gap-4">
|
||||
<div>
|
||||
<strong>IP:</strong><br />
|
||||
{device.ip}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Mac:</strong><br />
|
||||
{device.mac}
|
||||
</div>
|
||||
<div>
|
||||
<strong>Mac vendor:</strong><br />
|
||||
{device.mac_vendor}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<strong>Netmask:</strong><br />
|
||||
{scanResponse.netmask}
|
||||
</div>
|
||||
<div class="ms-auto">
|
||||
<button
|
||||
class="btn btn-sm btn-success"
|
||||
on:click={(e) => {
|
||||
addSingle(device);
|
||||
e.currentTarget.disabled = true;
|
||||
}}><Fa icon={faPlus} />Add</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
<h2 class="card-title mt-4">Add all devices</h2>
|
||||
<div class="form-control max-w-fit">
|
||||
<label class="label cursor-pointer">
|
||||
<input type="checkbox" class="checkbox" bind:checked={replaceNetmaskCheckbox} />
|
||||
<span class="label-text ms-2">Replace netmask for all devices?</span>
|
||||
</label>
|
||||
</div>
|
||||
{#if replaceNetmaskCheckbox}
|
||||
<div class="form-control max-w-fit">
|
||||
<label class="label cursor-pointer" for="replaceNetmaskInput">
|
||||
<span class="label-text ms-2">New netmask</span>
|
||||
</label>
|
||||
<input
|
||||
id="replaceNetmaskInput"
|
||||
class="input input-bordered"
|
||||
type="text"
|
||||
placeholder="255.255.0.0"
|
||||
bind:value={replaceNetmask}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{#if scanResponse.devices.find((dev) => dev.name === 'Unknown')}
|
||||
<div class="form-control max-w-fit">
|
||||
<label class="label cursor-pointer">
|
||||
<input type="checkbox" class="checkbox" bind:checked={addAllCheckbox} />
|
||||
<span class="label-text ms-2">Include devices where name is "Unknown"</span>
|
||||
</label>
|
||||
{#if addAllCheckbox}
|
||||
<button
|
||||
class="btn btn-success"
|
||||
on:click={() => addAll()}
|
||||
disabled={scanResponse.devices.length === 0}
|
||||
>
|
||||
<Fa icon={faPlus} /> Add all ({scanResponse.devices.length})
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
class="btn btn-success"
|
||||
on:click={() => addAll()}
|
||||
disabled={scanResponse.devices.filter((dev) => dev.name !== 'Unknown').length === 0}
|
||||
>
|
||||
<Fa icon={faPlus} /> Add all ({scanResponse.devices.filter(
|
||||
(dev) => dev.name !== 'Unknown'
|
||||
).length})
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="form-control max-w-fit">
|
||||
<button
|
||||
class="btn btn-success"
|
||||
on:click={() => addAll()}
|
||||
disabled={scanResponse.devices.length === 0}
|
||||
>
|
||||
<Fa icon={faPlus} /> Add all ({scanResponse.devices.length})
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<PageLoading />
|
||||
{/if}
|
||||
@@ -0,0 +1,3 @@
|
||||
<div class="container max-w-lg mx-auto text-center">
|
||||
<span class="loading loading-dots loading-lg" />
|
||||
</div>
|
||||
@@ -0,0 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { fly } from 'svelte/transition';
|
||||
export let url: URL;
|
||||
</script>
|
||||
|
||||
{#key url}
|
||||
<div in:fly={{ y: 50, duration: 300 }}>
|
||||
<slot />
|
||||
</div>
|
||||
{/key}
|
||||
@@ -0,0 +1,7 @@
|
||||
export function toggleVisibility(el: HTMLInputElement) {
|
||||
if (el.type === 'password') {
|
||||
el.type = 'text';
|
||||
} else {
|
||||
el.type = 'password';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import PocketBase from 'pocketbase';
|
||||
import type { Permission } from '$lib/types/permission';
|
||||
|
||||
// set backend url based on environment
|
||||
export const backendUrl = import.meta.env.DEV ? 'http://127.0.0.1:8090/' : '/';
|
||||
|
||||
// connect to backend
|
||||
const pb = new PocketBase(backendUrl);
|
||||
pb.autoCancellation(false);
|
||||
|
||||
// export stores
|
||||
export const pocketbase = writable(pb);
|
||||
export const permission = writable({} as Permission);
|
||||
@@ -0,0 +1,5 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import type { SettingsPublic, SettingsPrivate } from '$lib/types/settings';
|
||||
|
||||
export const settingsPub = writable<SettingsPublic>();
|
||||
export const settingsPriv = writable<SettingsPrivate>();
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Record } from 'pocketbase';
|
||||
|
||||
export type Device = Record & {
|
||||
name: string;
|
||||
ip: string;
|
||||
mac: string;
|
||||
netmask: string;
|
||||
status: 'pending' | 'online' | 'offline' | '';
|
||||
ports: string[];
|
||||
link: URL;
|
||||
wake_cron: string;
|
||||
wake_cron_enabled: boolean;
|
||||
shutdown_cron: string;
|
||||
shutdown_cron_enabled: boolean;
|
||||
shutdown_cmd: string;
|
||||
password: string;
|
||||
groups: string[];
|
||||
expand: {
|
||||
ports: Port[];
|
||||
groups: Group[];
|
||||
};
|
||||
created_by: string;
|
||||
sol_enabled: boolean;
|
||||
sol_auth: boolean;
|
||||
sol_user: string;
|
||||
sol_passwort: string;
|
||||
sol_port: number;
|
||||
};
|
||||
|
||||
export type Port = Record & {
|
||||
name: string;
|
||||
number: number;
|
||||
};
|
||||
|
||||
export type Group = Record & {
|
||||
name: string;
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Record } from 'pocketbase';
|
||||
|
||||
export type Permission = Record & {
|
||||
user: string;
|
||||
create: boolean;
|
||||
read: string[];
|
||||
update: string[];
|
||||
delete: string[];
|
||||
power: string[];
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
export type ScannedDevice = {
|
||||
name: string;
|
||||
ip: string;
|
||||
mac: string;
|
||||
mac_vendor: string;
|
||||
netmask: string;
|
||||
status: 'pending' | 'online' | 'offline' | '';
|
||||
};
|
||||
|
||||
export type ScanResponse = {
|
||||
netmask: string;
|
||||
devices: ScannedDevice[];
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Record } from 'pocketbase';
|
||||
|
||||
export type SettingsPublic = Record & {
|
||||
collectionId: string;
|
||||
favicon: string;
|
||||
setup_completed: boolean;
|
||||
website_title: string;
|
||||
};
|
||||
|
||||
export type SettingsPrivate = Record & {
|
||||
interval: number;
|
||||
lazy_ping: boolean;
|
||||
scan_range: string;
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Record } from 'pocketbase';
|
||||
|
||||
export type User = Record & {
|
||||
username: string;
|
||||
email: string;
|
||||
avatar: number;
|
||||
};
|
||||
@@ -1,140 +1,125 @@
|
||||
<script>
|
||||
import { dev } from '$app/environment';
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import Navbar from '@components/Navbar.svelte';
|
||||
import Login from '@components/Login.svelte';
|
||||
import Transition from '@components/Transition.svelte';
|
||||
import { theme } from '@stores/theme';
|
||||
import {
|
||||
pocketbase,
|
||||
authorizedStore,
|
||||
devices,
|
||||
settings_private,
|
||||
settings_public
|
||||
} from '@stores/pocketbase';
|
||||
<script lang="ts">
|
||||
import '../app.css';
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/stores';
|
||||
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
|
||||
import { settingsPub } from '$lib/stores/settings';
|
||||
import Navbar from '$lib/components/Navbar.svelte';
|
||||
import Transition from '$lib/components/Transition.svelte';
|
||||
import toast, { Toaster, type ToastOptions } from 'svelte-french-toast';
|
||||
import type { SettingsPublic } from '$lib/types/settings';
|
||||
import type { Permission } from '$lib/types/permission';
|
||||
|
||||
let favicon;
|
||||
let preferesDark;
|
||||
let isAuth = false;
|
||||
const toastOptions: ToastOptions = {
|
||||
duration: 5000
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
// import bootstrap js
|
||||
import('bootstrap/js/dist/dropdown');
|
||||
import('bootstrap/js/dist/collapse');
|
||||
onMount(async () => {
|
||||
$pocketbase.authStore.onChange(() => {
|
||||
// load user permissions
|
||||
if ($pocketbase.authStore.model?.collectionName === 'users') {
|
||||
$pocketbase
|
||||
.collection('permissions')
|
||||
.getFirstListItem(`user.id = '${$pocketbase.authStore.model.id}'`)
|
||||
.then((data) => {
|
||||
permission.set(data as Permission);
|
||||
})
|
||||
.catch(() => {
|
||||
return;
|
||||
});
|
||||
|
||||
// set dark mode
|
||||
preferesDark = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
preferesDark.addEventListener('change', (e) => {
|
||||
if ($theme === 'auto') {
|
||||
document.documentElement.setAttribute(
|
||||
'data-bs-theme',
|
||||
e.matches ? 'dark' : 'light'
|
||||
);
|
||||
}
|
||||
});
|
||||
$pocketbase.collection('permissions').subscribe('*', (event) => {
|
||||
permission.set(event.record as Permission);
|
||||
toast.success('Your permissions have been updated');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
theme.subscribe((t) => {
|
||||
localStorage.setItem('theme', t);
|
||||
if (t === 'auto') {
|
||||
t = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
document.documentElement.setAttribute('data-bs-theme', t);
|
||||
});
|
||||
// set settingsPub store on load
|
||||
if (!$settingsPub) {
|
||||
const res = await $pocketbase.collection('settings_public').getFirstListItem('');
|
||||
settingsPub.set(res as SettingsPublic);
|
||||
}
|
||||
|
||||
authorizedStore.subscribe((state) => {
|
||||
isAuth = state;
|
||||
});
|
||||
// redirect to welcome page if setup is not completed
|
||||
if (!$settingsPub.setup_completed && $page.url.pathname !== '/welcome') {
|
||||
goto('/welcome');
|
||||
return;
|
||||
}
|
||||
|
||||
// load public settings and subscribe to changes and change favicon
|
||||
const settingsPublicRes = await $pocketbase.collection('settings_public').getList(1, 1);
|
||||
settings_public.set(settingsPublicRes.items[0]);
|
||||
updateSettingsPublic();
|
||||
$pocketbase.collection('settings_public').subscribe('*', function (e) {
|
||||
settings_public.set(e.record);
|
||||
updateSettingsPublic();
|
||||
});
|
||||
// load auth from localstorage
|
||||
const pbCookie = localStorage.getItem('pocketbase_auth');
|
||||
if (!pbCookie) {
|
||||
goto('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
// load auth from localstorage
|
||||
const pbCookie = localStorage.getItem('pocketbase_auth');
|
||||
if (pbCookie) {
|
||||
$pocketbase.authStore.loadFromCookie('pb_auth=' + pbCookie);
|
||||
$pocketbase.authStore.loadFromCookie('pb_auth=' + pbCookie);
|
||||
if (!$pocketbase.authStore.isValid) {
|
||||
goto('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
// try to refresh auth token if valid
|
||||
if ($pocketbase.authStore.isValid) {
|
||||
if ($pocketbase.authStore.model?.collectionName === 'users') {
|
||||
await $pocketbase.collection('users').authRefresh();
|
||||
} else {
|
||||
await $pocketbase.admins.authRefresh();
|
||||
}
|
||||
}
|
||||
authorizedStore.set($pocketbase.authStore.isValid);
|
||||
}
|
||||
});
|
||||
// only refresh token if valid less than 1 day
|
||||
const jwt = parseJwt($pocketbase.authStore.token);
|
||||
if (jwt.exp > Date.now() / 1000 + 60 * 60 * 24) {
|
||||
return;
|
||||
}
|
||||
|
||||
function updateSettingsPublic() {
|
||||
favicon.href =
|
||||
$settings_public.favicon === ''
|
||||
? '/gopher.svg'
|
||||
: `${dev ? $pocketbase.baseUrl : ''}/api/files/settings_public/${
|
||||
$settings_public.id
|
||||
}/${$settings_public.favicon}`;
|
||||
document.title =
|
||||
$settings_public.website_title === '' ? 'UpSnap' : $settings_public.website_title;
|
||||
}
|
||||
if ($pocketbase.authStore.model?.collectionName === 'users') {
|
||||
await $pocketbase
|
||||
.collection('users')
|
||||
.authRefresh()
|
||||
.catch(() => {
|
||||
goto('/login');
|
||||
});
|
||||
} else {
|
||||
await $pocketbase.admins.authRefresh().catch(() => {
|
||||
goto('/login');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
async function getSettingsPrivateAndDevices() {
|
||||
if ($pocketbase.authStore.model?.collectionName !== 'users') {
|
||||
const settingsPrivateRes = await $pocketbase
|
||||
.collection('settings_private')
|
||||
.getList(1, 1);
|
||||
settings_private.set(settingsPrivateRes.items[0]);
|
||||
}
|
||||
function parseJwt(token: string) {
|
||||
var base64Url = token.split('.')[1];
|
||||
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
||||
var jsonPayload = decodeURIComponent(
|
||||
window
|
||||
.atob(base64)
|
||||
.split('')
|
||||
.map(function (c) {
|
||||
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
|
||||
})
|
||||
.join('')
|
||||
);
|
||||
|
||||
let tempDevices = {};
|
||||
const devicesRes = await $pocketbase.collection('devices').getFullList(200, {
|
||||
sort: 'name',
|
||||
expand: 'ports'
|
||||
});
|
||||
devicesRes.forEach((device) => {
|
||||
tempDevices[device.id] = device;
|
||||
});
|
||||
devices.set(tempDevices);
|
||||
}
|
||||
|
||||
$: if (isAuth) {
|
||||
getSettingsPrivateAndDevices();
|
||||
}
|
||||
return JSON.parse(jsonPayload);
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<link rel="shortcut icon" href="/gopher.svg" bind:this={favicon} />
|
||||
<script>
|
||||
if (document) {
|
||||
preferesDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
let t = localStorage.getItem('theme');
|
||||
if (!t) {
|
||||
localStorage.setItem('theme', 'auto');
|
||||
t = preferesDark;
|
||||
} else if (t === 'auto') {
|
||||
t = preferesDark;
|
||||
}
|
||||
document.documentElement.setAttribute('data-bs-theme', t);
|
||||
}
|
||||
</script>
|
||||
<link
|
||||
rel="shortcut icon"
|
||||
href={$settingsPub?.id && $settingsPub?.favicon
|
||||
? `${backendUrl}api/files/settings_public/${$settingsPub?.id}/${$settingsPub?.favicon}`
|
||||
: '/gopher.svg'}
|
||||
/>
|
||||
{#if $settingsPub === undefined}
|
||||
<title>UpSnap</title>
|
||||
{:else}
|
||||
<title>{$settingsPub.website_title === '' ? 'UpSnap' : $settingsPub.website_title}</title>
|
||||
{/if}
|
||||
</svelte:head>
|
||||
|
||||
{#if isAuth}
|
||||
<Navbar />
|
||||
<Transition url={$page.url}>
|
||||
<slot />
|
||||
</Transition>
|
||||
{:else}
|
||||
<Login />
|
||||
{#if $pocketbase.authStore.isValid}
|
||||
<Navbar />
|
||||
{/if}
|
||||
|
||||
<style lang="scss" global>
|
||||
@import '../scss/main.scss';
|
||||
</style>
|
||||
<Toaster position="bottom-center" {toastOptions} />
|
||||
|
||||
<Transition url={$page.url}>
|
||||
<div class="container mx-auto p-2 mb-4">
|
||||
<slot />
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
@@ -1,63 +1,191 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
import DeviceCard from '@components/DeviceCard.svelte';
|
||||
import { pocketbase, devices } from '@stores/pocketbase';
|
||||
import { sortDevices } from '../sorts';
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { pocketbase, permission } from '$lib/stores/pocketbase';
|
||||
import DeviceCard from '$lib/components/DeviceCard.svelte';
|
||||
import PageLoading from '$lib/components/PageLoading.svelte';
|
||||
import toast from 'svelte-french-toast';
|
||||
import Fa from 'svelte-fa';
|
||||
import {
|
||||
faChevronCircleLeft,
|
||||
faChevronCircleRight,
|
||||
faPlus
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { browser } from '$app/environment';
|
||||
import type { Device } from '$lib/types/device';
|
||||
|
||||
onMount(async () => {
|
||||
// subscribe to database events
|
||||
$pocketbase.collection('devices').subscribe('*', async (e) => {
|
||||
if (e.action === 'create') {
|
||||
$devices[e.record.id] = e.record;
|
||||
} else if (e.action === 'update') {
|
||||
const device = await $pocketbase.collection('devices').getOne(e.record.id, {
|
||||
expand: 'ports'
|
||||
});
|
||||
$devices[device.id] = device;
|
||||
} else if (e.action === 'delete') {
|
||||
delete $devices[e.record.id];
|
||||
}
|
||||
});
|
||||
$pocketbase.collection('ports').subscribe('*', async (e) => {
|
||||
if (e.action === 'update') {
|
||||
const device = Object.values($devices).find((dev) =>
|
||||
dev.ports.includes(e.record.id)
|
||||
);
|
||||
if (!device) {
|
||||
return;
|
||||
}
|
||||
let loading = true;
|
||||
let devices = [] as Device[];
|
||||
let devicesWithGroup: {
|
||||
[key: string]: Device[];
|
||||
};
|
||||
let devicesWithoutGroups = [] as Device[];
|
||||
let orderBy: 'name' | 'ip';
|
||||
let orderExpanded = false;
|
||||
let orderByGroups: boolean;
|
||||
const gridClass =
|
||||
'grid grid-flow-row-dense grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4';
|
||||
|
||||
// replace device.expand.ports with updated record
|
||||
const portIdx = device.expand.ports.findIndex((port) => port.id === e.record.id);
|
||||
$devices[device.id].expand.ports[portIdx] = e.record;
|
||||
}
|
||||
});
|
||||
});
|
||||
$: {
|
||||
devicesWithoutGroups = [];
|
||||
devicesWithoutGroups = devices.filter((dev) => dev.groups.length === 0);
|
||||
}
|
||||
|
||||
// update device date
|
||||
let now = Date.now();
|
||||
let interval;
|
||||
$: {
|
||||
clearInterval(interval);
|
||||
interval = setInterval(() => {
|
||||
now = Date.now();
|
||||
}, 1000);
|
||||
}
|
||||
$: {
|
||||
devicesWithGroup = {};
|
||||
devices.forEach((dev) => {
|
||||
dev?.expand?.groups?.forEach((group) => {
|
||||
if (!devicesWithGroup[group.name]) {
|
||||
devicesWithGroup[group.name] = [];
|
||||
}
|
||||
devicesWithGroup[group.name] = [...devicesWithGroup[group.name], dev];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
$: if (browser && orderBy !== undefined) {
|
||||
localStorage.setItem('orderBy', orderBy);
|
||||
}
|
||||
$: if (browser && orderByGroups !== undefined) {
|
||||
localStorage.setItem('orderByGroups', orderByGroups.toString());
|
||||
}
|
||||
|
||||
function getAllDevices() {
|
||||
$pocketbase
|
||||
.collection('devices')
|
||||
.getFullList(1000, { sort: 'name', expand: 'ports,groups' })
|
||||
.then((resp) => {
|
||||
devices = resp as Device[];
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
})
|
||||
.finally(() => {
|
||||
loading = false;
|
||||
});
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
// get soring from local storage
|
||||
const lsO = localStorage.getItem('orderBy');
|
||||
if (lsO === 'name' || lsO === 'ip') {
|
||||
orderBy = lsO;
|
||||
} else {
|
||||
orderBy = 'name';
|
||||
}
|
||||
if (localStorage.getItem('orderByGroups') === null) {
|
||||
orderByGroups = true;
|
||||
} else {
|
||||
orderByGroups = localStorage.getItem('orderByGroups') === 'true' ? true : false;
|
||||
}
|
||||
|
||||
// get collections and subscribe to changes
|
||||
getAllDevices();
|
||||
|
||||
$pocketbase.collection('devices').subscribe('*', () => {
|
||||
getAllDevices();
|
||||
});
|
||||
|
||||
$pocketbase.collection('ports').subscribe('*', () => {
|
||||
getAllDevices();
|
||||
});
|
||||
|
||||
$pocketbase.collection('permissions').subscribe('*', () => {
|
||||
getAllDevices();
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="container text-body-emphasis mb-4">
|
||||
{#if Object.keys($devices).length > 0}
|
||||
<div class="row">
|
||||
{#each Object.values($devices).sort(sortDevices) as device}
|
||||
<DeviceCard {device} {now} />
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="text-center">
|
||||
<h4 class="text-muted">No devices</h4>
|
||||
<p>
|
||||
<a class="text-muted" href="/settings">Go to settings to add devices...</a>
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if loading}
|
||||
<PageLoading />
|
||||
{:else if devices.length > 0}
|
||||
<div class="flex justify-end">
|
||||
<div class="join mb-4">
|
||||
{#if orderExpanded}
|
||||
<div class="join-item">
|
||||
<div class="join">
|
||||
<button
|
||||
class="join-item btn"
|
||||
type="button"
|
||||
on:click={() => (orderByGroups = !orderByGroups)}
|
||||
>Groups
|
||||
<input
|
||||
type="checkbox"
|
||||
class="checkbox checked:checkbox-primary"
|
||||
checked={orderByGroups}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
class="join-item btn"
|
||||
type="radio"
|
||||
name="order"
|
||||
aria-label="Name"
|
||||
bind:group={orderBy}
|
||||
value="name"
|
||||
/>
|
||||
<input
|
||||
class="join-item btn"
|
||||
type="radio"
|
||||
name="order"
|
||||
aria-label="IP"
|
||||
bind:group={orderBy}
|
||||
value="ip"
|
||||
/>
|
||||
{/if}
|
||||
<div class="tooltip" data-tip="Order">
|
||||
<button class="join-item btn" on:click={() => (orderExpanded = !orderExpanded)}>
|
||||
{#if orderExpanded}
|
||||
<Fa icon={faChevronCircleRight} size="lg" />
|
||||
{:else}
|
||||
<Fa icon={faChevronCircleLeft} size="lg" />
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if orderByGroups}
|
||||
<div class="space-y-6">
|
||||
{#if devicesWithoutGroups.length > 0}
|
||||
<div class={gridClass}>
|
||||
{#each devicesWithoutGroups.sort( (a, b) => a[orderBy].localeCompare( b[orderBy], undefined, { numeric: true, sensitivity: 'base' } ) ) as device}
|
||||
<DeviceCard {device} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if Object.keys(devicesWithGroup).length > 0}
|
||||
{#each Object.keys(devicesWithGroup).sort( (a, b) => a.localeCompare( b, undefined, { numeric: true, sensitivity: 'base' } ) ) as group}
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold mb-3">{group}</h1>
|
||||
<div class={gridClass}>
|
||||
{#each devicesWithGroup[group].sort( (a, b) => a[orderBy].localeCompare( b[orderBy], undefined, { numeric: true, sensitivity: 'base' } ) ) as device}
|
||||
<DeviceCard {device} />
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div class={gridClass}>
|
||||
{#each devices.sort( (a, b) => a[orderBy].localeCompare( b[orderBy], undefined, { numeric: true, sensitivity: 'base' } ) ) as device}
|
||||
<DeviceCard {device} />
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="container text-center">
|
||||
<p>No devices here.</p>
|
||||
{#if $pocketbase.authStore.isAdmin || $permission.create}
|
||||
<p>
|
||||
<a href="/device/new" class="btn btn-ghost"
|
||||
><Fa icon={faPlus} class="ms-2" />Add your first device
|
||||
</a>
|
||||
</p>
|
||||
{:else}
|
||||
<p>
|
||||
Please ask the admin to grant you permissions to existing devices or to create new ones.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { pocketbase, backendUrl } from '$lib/stores/pocketbase';
|
||||
import toast from 'svelte-french-toast';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faSave } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
let newAvatar: number;
|
||||
let newPassword = {
|
||||
old: '',
|
||||
password: '',
|
||||
confirm: ''
|
||||
};
|
||||
$: adminBody = JSON.stringify({
|
||||
password: newPassword.password,
|
||||
passwordConfirm: newPassword.confirm
|
||||
});
|
||||
$: userBody = JSON.stringify({
|
||||
oldPassword: newPassword.old,
|
||||
password: newPassword.password,
|
||||
passwordConfirm: newPassword.confirm
|
||||
});
|
||||
|
||||
function changeAvatar() {
|
||||
if ($pocketbase.authStore.isAdmin) {
|
||||
if (!$pocketbase.authStore.model?.id) return;
|
||||
$pocketbase.admins
|
||||
.update($pocketbase.authStore.model.id, { avatar: newAvatar })
|
||||
.then(() => {
|
||||
toast.success('Avatar saved');
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
} else {
|
||||
if (!$pocketbase.authStore.model?.id) return;
|
||||
$pocketbase
|
||||
.collection('users')
|
||||
.update($pocketbase.authStore.model.id, { avatar: newAvatar })
|
||||
.then(() => {
|
||||
toast.success('Avatar saved');
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function changePassword() {
|
||||
fetch(
|
||||
`${backendUrl}api/${$pocketbase.authStore.isAdmin ? 'admins' : `collections/users/records`}/${
|
||||
$pocketbase.authStore.model?.id
|
||||
}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: $pocketbase.authStore.isAdmin ? adminBody : userBody
|
||||
}
|
||||
)
|
||||
.then(async (data) => {
|
||||
if (data.ok) {
|
||||
toast.success('Password changed. Please login again.');
|
||||
$pocketbase.authStore.clear();
|
||||
goto('/login');
|
||||
} else {
|
||||
const j = await data.json();
|
||||
if (j?.data?.password?.message) {
|
||||
toast.error(j?.data?.password?.message);
|
||||
} else if (j?.data?.passwordConfirm?.message) {
|
||||
toast.error("Passwords don't match");
|
||||
} else if (j.data?.oldPassword?.message) {
|
||||
toast.error(j.data.oldPassword.message);
|
||||
} else {
|
||||
toast.error(j.message || data.statusText);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1 class="text-3xl font-bold mb-8">Account</h1>
|
||||
<div class="card w-full bg-base-300 shadow-xl">
|
||||
<div class="card-body">
|
||||
<div class="flex flex-row gap-4 items-center">
|
||||
<div class="avatar">
|
||||
<div class="w-16 rounded-full">
|
||||
<!-- svelte static build will fail, because the image gets served from pocketbase
|
||||
and is not a local static file -->
|
||||
{#if $pocketbase.authStore.model?.id}
|
||||
<img
|
||||
src="{backendUrl}_/images/avatars/avatar{newAvatar ??
|
||||
$pocketbase.authStore.model?.avatar}.svg"
|
||||
alt="Avatar {newAvatar ?? $pocketbase.authStore.model?.avatar}"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="card-title">
|
||||
{$pocketbase.authStore.isAdmin
|
||||
? $pocketbase.authStore.model?.email
|
||||
: $pocketbase.authStore.model?.username}
|
||||
</h2>
|
||||
<h3>{$pocketbase.authStore.isAdmin ? 'Admin' : 'User'}</h3>
|
||||
</div>
|
||||
</div>
|
||||
<h2 class="card-title mt-4">Avatar</h2>
|
||||
<form on:submit|preventDefault={changeAvatar}>
|
||||
<div class="flex flex-row flex-wrap gap-4">
|
||||
{#each [...Array(10).keys()] as i}
|
||||
<div class="avatar btn btn-ghost btn-circle">
|
||||
<div
|
||||
class="w-11 rounded-full"
|
||||
class:ring={newAvatar !== undefined
|
||||
? i === newAvatar
|
||||
: i === $pocketbase.authStore.model?.avatar}
|
||||
class:ring-primary={newAvatar !== undefined
|
||||
? i === newAvatar
|
||||
: i === $pocketbase.authStore.model?.avatar}
|
||||
class:ring-offset-base-100={newAvatar !== undefined
|
||||
? i === newAvatar
|
||||
: i === $pocketbase.authStore.model?.avatar}
|
||||
class:ring-offset-2={newAvatar !== undefined
|
||||
? i === newAvatar
|
||||
: i === $pocketbase.authStore.model?.avatar}
|
||||
on:click={() => (newAvatar = i)}
|
||||
role="none"
|
||||
>
|
||||
<!-- svelte static build will fail, because the image gets served from pocketbase
|
||||
and is not a local static file -->
|
||||
{#if $pocketbase.authStore.model?.id}
|
||||
<img src="{backendUrl}_/images/avatars/avatar{i}.svg" alt="Avatar {i}" />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success mt-2"><Fa icon={faSave} />Save</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Change password</h2>
|
||||
<p>After the password has been changed, you will need to log in again.</p>
|
||||
<form on:submit|preventDefault={changePassword}>
|
||||
<div class="form-control w-full max-w-xs">
|
||||
{#if !$pocketbase.authStore.isAdmin}
|
||||
<label class="label" for="password-old">
|
||||
<span class="label-text">Old password</span>
|
||||
</label>
|
||||
<input
|
||||
id="password-old"
|
||||
type="password"
|
||||
placeholder="Old password"
|
||||
class="input input-bordered w-full max-w-xs"
|
||||
minlength="5"
|
||||
maxlength="72"
|
||||
bind:value={newPassword.old}
|
||||
required
|
||||
/>
|
||||
{/if}
|
||||
<label class="label" for="password-new">
|
||||
<span class="label-text">New password</span>
|
||||
</label>
|
||||
<input
|
||||
id="password-new"
|
||||
type="password"
|
||||
placeholder="New password"
|
||||
class="input input-bordered w-full max-w-xs"
|
||||
minlength={$pocketbase.authStore.isAdmin ? 10 : 5}
|
||||
maxlength="72"
|
||||
bind:value={newPassword.password}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="form-control w-full max-w-xs">
|
||||
<label class="label" for="password-confirm">
|
||||
<span class="label-text">Confirm password</span>
|
||||
</label>
|
||||
<input
|
||||
id="password-confirm"
|
||||
type="password"
|
||||
placeholder="New password"
|
||||
class="input input-bordered w-full max-w-xs"
|
||||
minlength={$pocketbase.authStore.isAdmin ? 10 : 5}
|
||||
maxlength="72"
|
||||
bind:value={newPassword.confirm}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-success mt-2"><Fa icon={faSave} />Save</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||