Compare commits

...

108 Commits

Author SHA1 Message Date
seriousm4x 47c03527d0 update go dependencies 2023-07-03 20:03:12 +02:00
seriousm4x 92a4657459 update dependencies 2023-07-03 20:02:20 +02:00
seriousm4x 6d0d4a8adc Merge pull request #106 from seriousm4x/dependabot/npm_and_yarn/frontend/eslint-8.44.0
Bump eslint from 8.43.0 to 8.44.0 in /frontend
2023-07-03 19:55:31 +02:00
dependabot[bot] a395b3ed60 Bump eslint from 8.43.0 to 8.44.0 in /frontend
Bumps [eslint](https://github.com/eslint/eslint) from 8.43.0 to 8.44.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.43.0...v8.44.0)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-03 09:18:47 +00:00
github-actions[bot] 8830222e10 Merge pull request #107 from seriousm4x/dependabot/npm_and_yarn/frontend/eslint-plugin-svelte-2.32.2
Bump eslint-plugin-svelte from 2.32.1 to 2.32.2 in /frontend
2023-07-03 09:17:56 +00:00
dependabot[bot] ffc4e92f96 Bump eslint-plugin-svelte from 2.32.1 to 2.32.2 in /frontend
Bumps [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte) from 2.32.1 to 2.32.2.
- [Release notes](https://github.com/sveltejs/eslint-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/eslint-plugin-svelte/compare/v2.32.1...v2.32.2)

---
updated-dependencies:
- dependency-name: eslint-plugin-svelte
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-03 09:17:30 +00:00
seriousm4x 5674e5681e huge change 2023-07-01 21:58:06 +02:00
seriousm4x ba03d9e490 add star history chart 2023-07-01 21:55:17 +02:00
seriousm4x eb54cb9403 adjust column width #105 2023-07-01 20:34:38 +02:00
seriousm4x debd82a288 add mac vendor to scan table 2023-07-01 19:27:29 +02:00
seriousm4x 319817983e only allow user registrations from oauth, not user/password #103 2023-07-01 17:48:33 +02:00
seriousm4x a31f704274 add oidc user auth #103 2023-07-01 14:27:56 +02:00
seriousm4x c3eb2d869c netowrk scan: use reverse dns lookup for unknown devices #105 2023-07-01 12:35:41 +02:00
seriousm4x 49584c22a5 added "add all devices" button for network scan #104 2023-07-01 11:59:20 +02:00
seriousm4x 63bf2367c2 avoid device replication #97 2023-07-01 11:24:50 +02:00
github-actions[bot] b5200ec372 Merge pull request #102 from seriousm4x/dependabot/npm_and_yarn/frontend/eslint-plugin-svelte-2.32.1
Bump eslint-plugin-svelte from 2.32.0 to 2.32.1 in /frontend
2023-06-30 09:45:42 +00:00
dependabot[bot] 05d6aaf7d0 Bump eslint-plugin-svelte from 2.32.0 to 2.32.1 in /frontend
Bumps [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte) from 2.32.0 to 2.32.1.
- [Release notes](https://github.com/sveltejs/eslint-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/eslint-plugin-svelte/compare/v2.32.0...v2.32.1)

---
updated-dependencies:
- dependency-name: eslint-plugin-svelte
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-30 09:45:29 +00:00
seriousm4x 28b51f7b8d Merge pull request #99 from seriousm4x/dependabot/npm_and_yarn/frontend/eslint-plugin-svelte-2.32.0
Bump eslint-plugin-svelte from 2.31.1 to 2.32.0 in /frontend
2023-06-30 00:07:23 +02:00
dependabot[bot] 487b0d9689 Bump eslint-plugin-svelte from 2.31.1 to 2.32.0 in /frontend
Bumps [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte) from 2.31.1 to 2.32.0.
- [Release notes](https://github.com/sveltejs/eslint-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/eslint-plugin-svelte/compare/v2.31.1...v2.32.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-svelte
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-29 22:03:07 +00:00
github-actions[bot] 1daeef8c14 Merge pull request #100 from seriousm4x/dependabot/npm_and_yarn/frontend/svelte-4.0.1
Bump svelte from 4.0.0 to 4.0.1 in /frontend
2023-06-29 22:01:42 +00:00
dependabot[bot] a632eb2cc9 Bump svelte from 4.0.0 to 4.0.1 in /frontend
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 4.0.0 to 4.0.1.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/master/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@4.0.1/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-29 22:01:29 +00:00
github-actions[bot] 5a64dcf327 Merge pull request #98 from seriousm4x/dependabot/npm_and_yarn/frontend/typescript-5.1.6
Bump typescript from 5.1.5 to 5.1.6 in /frontend
2023-06-29 21:59:45 +00:00
dependabot[bot] 99997b75e9 Bump typescript from 5.1.5 to 5.1.6 in /frontend
Bumps [typescript](https://github.com/Microsoft/TypeScript) from 5.1.5 to 5.1.6.
- [Release notes](https://github.com/Microsoft/TypeScript/releases)
- [Commits](https://github.com/Microsoft/TypeScript/commits)

---
updated-dependencies:
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-29 21:59:31 +00:00
seriousm4x c75564fc98 Merge pull request #101 from seriousm4x/dependabot/npm_and_yarn/frontend/sveltejs/kit-1.21.0
Bump @sveltejs/kit from 1.20.5 to 1.21.0 in /frontend
2023-06-29 23:58:42 +02:00
Maxi Quoß 57e2d5c331 dependabot: auto-merge semver-patch updates 2023-06-29 23:57:37 +02:00
seriousm4x 8628e13e45 add device groups #97 2023-06-29 17:16:10 +02:00
dependabot[bot] d0f3b41558 Bump @sveltejs/kit from 1.20.5 to 1.21.0 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.20.5 to 1.21.0.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/master/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@1.21.0/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-29 09:34:21 +00:00
Maxi Quoß c37294dec0 update dependencies 2023-06-28 11:50:08 +02:00
Maxi Quoß 343be4249b update dependencies 2023-06-28 11:36:53 +02:00
seriousm4x 9a1c8b74f9 Merge pull request #84 from seriousm4x/dependabot/github_actions/actions/checkout-3
Bump actions/checkout from 2 to 3
2023-06-28 11:27:39 +02:00
seriousm4x 19d0cff28c Merge pull request #83 from seriousm4x/dependabot/github_actions/actions/setup-go-4
Bump actions/setup-go from 3 to 4
2023-06-28 11:27:28 +02:00
seriousm4x 29bf818a27 Merge pull request #82 from seriousm4x/dependabot/github_actions/docker/build-push-action-4
Bump docker/build-push-action from 3 to 4
2023-06-28 11:27:17 +02:00
dependabot[bot] 769db97654 Bump actions/checkout from 2 to 3
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-28 09:24:41 +00:00
dependabot[bot] 1df79f0699 Bump actions/setup-go from 3 to 4
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-28 09:24:37 +00:00
dependabot[bot] d81ffd8435 Bump docker/build-push-action from 3 to 4
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3 to 4.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-28 09:24:32 +00:00
seriousm4x ac85abcb13 Merge pull request #81 from gaby/dependabot
Add support for dependabot
2023-06-28 11:23:48 +02:00
Juan Calderon-Perez 613022453d Add support for dependabot 2023-06-27 21:09:44 -04:00
Maxi Quoß 45c0fbb462 higher contrast for titles 2023-06-01 15:18:58 +02:00
Maxi Quoß b011d88b3d workflow: codeberg remove cron 2023-06-01 14:56:21 +02:00
Maxi Quoß 2bc7bab5f7 remove v2 restore 2023-06-01 14:38:07 +02:00
Maxi Quoß 4eed2bf31b format 2023-06-01 14:37:10 +02:00
Maxi Quoß 326a7f359f update dependencies 2023-06-01 14:33:49 +02:00
Maxi Quoß cbbd0f301e workflow: add codeberg mirror 2023-06-01 13:18:27 +02:00
seriousm4x fdf125d071 fix wrong icon url for prod env, fix #70 2023-04-12 23:27:42 +02:00
seriousm4x 72e3d3d343 npm format 2023-04-07 22:04:39 +02:00
seriousm4x 3331b53d39 npm format 2023-04-07 22:01:15 +02:00
seriousm4x 1faae16e18 update dependencies
- fix sveltekit csrf issue
- pocketbase 0.14.3
2023-04-07 21:57:41 +02:00
seriousm4x 28cc52f6c1 Merge pull request #67 from seriousm4x/dependabot/npm_and_yarn/frontend/sveltejs/kit-1.15.1
Bump @sveltejs/kit from 1.12.0 to 1.15.1 in /frontend
2023-04-04 23:46:42 +02:00
dependabot[bot] 6a388229dd Bump @sveltejs/kit from 1.12.0 to 1.15.1 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.12.0 to 1.15.1.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/master/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@1.15.1/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-04 21:45:44 +00:00
Maxi Quoß 014e6785be readme: add armv6 to images 2023-03-26 11:37:25 +02:00
seriousm4x 2fed755948 readme: create admin on frontend 2023-03-23 20:54:35 +01:00
seriousm4x 9106d25b95 add armv6 support #64 2023-03-21 01:13:16 +01:00
Maxi Quoß 8e9ba1503c add package-lock again 2023-03-19 20:04:22 +01:00
Maxi Quoß 9e83416848 update dependencies 2023-03-19 19:58:13 +01:00
Maxi Quoß 054f60ee48 fix #63 2023-03-19 19:52:10 +01:00
Maxi Quoß 469d480988 fix devices would not load for normal users 2023-03-13 09:23:54 +01:00
Maxi Quoß 87bf05528c own func for setup completed, refreshDeviceList() now returns error 2023-03-10 11:05:41 +01:00
Maxi Quoß 93a72207cc show register form if setup not completed 2023-03-10 10:52:38 +01:00
Maxi Quoß df9f549d65 fix save record settingsPrivate 2023-03-10 02:38:17 +01:00
Maxi Quoß c43bcbd299 update callout and screenshots 2023-03-10 02:28:36 +01:00
Maxi Quoß 79a70b6053 set custom icon
- split settings collection into settings_private and settings_public
- add icon input to frontend
2023-03-10 02:11:56 +01:00
Maxi Quoß f061c7d00a update screenshots 2023-03-09 22:42:08 +01:00
Maxi Quoß 59bc936237 change import path for fa icons 2023-03-09 22:41:50 +01:00
Maxi Quoß 1b299aa3a3 add new gopher as project image 2023-03-08 21:02:22 +01:00
Maxi Quoß 327b47c2a1 apk add samba (not installed by samba-common-tools anymore), close #61 2023-03-07 20:33:20 +01:00
Maxi Quoß d7c4a922e2 fix scan not working #59 2023-03-07 10:03:21 +01:00
Maxi Quoß 8c4c402c2c refresh auth tokens to avoid expiration 2023-03-06 18:13:25 +01:00
Maxi Quoß 9351889337 minor changes 2023-03-05 16:20:06 +01:00
Maxi Quoß 327ac67e33 update screenshots 2023-03-05 15:39:46 +01:00
Maxi Quoß 2764ed6ac5 rel="external" fixes "not found" build error 2023-03-05 15:37:03 +01:00
Maxi Quoß c519084e78 message is prerendered and cant be changed at runtime 2023-03-05 08:40:24 +01:00
Maxi Quoß 0d9a743b09 authentification -> authorisation 2023-03-05 07:13:35 +01:00
Maxi Quoß 12689b19f9 update readme with auth #42 #55 2023-03-05 07:11:54 +01:00
Maxi Quoß 5ed25bb06b add custom welcome message 2023-03-05 06:32:38 +01:00
Maxi Quoß 94fabed6dd css and logic improvements 2023-03-05 05:54:34 +01:00
Maxi Quoß 5493df087b pnpm... 2023-03-05 02:46:34 +01:00
Maxi Quoß 8d479669f4 add authentification #42 #55
* from now on, upsnap always requires authentification (user or admin)
* users can view the dashboard and use wake/shutdown (read only)
* admins can do everything (add, modify and delete)
* make navbar collapse on small screens
2023-03-05 02:44:47 +01:00
Maxi Quoß 40f6bddff6 update dependencies 2023-03-04 11:54:47 +01:00
Maxi Quoß 9a6b3a0c07 remove log 2023-03-04 11:51:07 +01:00
Maxi Quoß a1de1638a9 fix navbar active background for settings 2023-03-04 11:48:40 +01:00
Maxi Quoß 5469a2b0aa add shdow to theme dropdown menu 2023-03-04 11:33:31 +01:00
Maxi Quoß a7f3edd5f7 update dependencies 2023-02-26 11:30:26 +01:00
Maxi Quoß 3aec978570 docker-compose: make port change more clear #54 2023-02-22 16:30:01 +01:00
Maxi Quoß 37f7df24c2 npm update 2023-02-17 01:25:37 +01:00
Maxi Quoß 9a90d59188 use go 1.20 2023-02-17 01:19:44 +01:00
Maxi Quoß 4148ef0952 go mod tidy 2023-02-17 01:18:43 +01:00
Maxi Quoß 49cda92036 update backend dependencies 2023-02-17 01:11:28 +01:00
Maxi Quoß 021555dc18 update frontend dependencies 2023-02-17 01:11:12 +01:00
Maxi Quoß 3b9decd572 add container_name, fix health whitespace 2023-02-11 22:54:19 +01:00
Maxi Quoß 9a1a816f25 change error messages 2023-02-11 22:49:23 +01:00
Maxi Quoß 8d43554e0e check if To4() == nil 2023-02-11 22:48:16 +01:00
Maxi Quoß b88f567d9f move healthcheck to dockerfile 2023-02-11 22:24:50 +01:00
Maxi Quoß cb168f2f47 remove magicpacket log 2023-02-11 22:24:23 +01:00
Maxi Quoß 376220c557 natural sort devices by name
meaning, 1-2-10 instead of 1-10-2
2023-02-11 22:08:39 +01:00
Maxi Quoß ef064e9335 shutdown: print stderr to log 2023-02-11 21:53:57 +01:00
Maxi Quoß 67870d8114 add go version badge 2023-02-09 01:12:54 +01:00
Maxi Quoß 7bd4712ddd get correct broadcast for netmask 0.0.0.0, #46 2023-02-09 00:40:04 +01:00
seriousm4x f3b740d092 Create FUNDING.yml 2023-02-05 00:52:25 +01:00
Maxi Quoß a721af02b4 add info about custom packages in container 2023-02-04 14:43:15 +01:00
seriousm4x b9aa9feb1d Update issue templates 2023-02-04 13:27:27 +01:00
seriousm4x 59770cf013 Update issue templates 2023-02-04 13:27:05 +01:00
seriousm4x 8b65cd69bc Update issue templates 2023-02-04 13:24:56 +01:00
seriousm4x 0f7026f3d0 Update issue templates 2023-02-04 13:22:49 +01:00
Maxi Quoß 66b41170e8 rename workflow 2023-02-01 20:20:53 +01:00
Maxi Quoß 27b1a10e86 goreleaser: -rm-dist has been deprecated 2023-02-01 17:56:59 +01:00
Maxi Quoß 482a9884a4 add some error logging 2023-02-01 17:51:34 +01:00
Maxi Quoß ed285f502e fix openssh not working, close #37 2023-02-01 17:06:59 +01:00
Maxi Quoß b6f76c55c9 replace go-ping/ping (deprecated) 2023-01-31 13:47:13 +01:00
60 changed files with 4670 additions and 4361 deletions
+2
View File
@@ -0,0 +1,2 @@
github: seriousm4x
ko_fi: seriousm4x
@@ -0,0 +1,17 @@
---
name: "⭐ Feature request"
about: Suggest an idea for this project
title: "[REQUEST]"
labels: ''
assignees: ''
---
**The problem you currently have with this project**
A clear and concise description of what the problem is.
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,41 @@
---
name: "\U0001F577️ Bug report"
about: Create a report to help the project improve
title: "[BUG]"
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Logs**
```
formatted logs here
```
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Host OS (and version)**
eg. Windows 10, Ubuntu 22.10, macOS 13
**Host Architecture**
e.g. amd64/arm64/arm7
**Brower (if relevant)**
e.g. Firefox 109.0.1
**Additional context**
Add any other context about the problem here.
+18
View File
@@ -0,0 +1,18 @@
version: 2
updates:
- package-ecosystem: gomod
directory: "/backend"
schedule:
interval: daily
open-pull-requests-limit: 10
- package-ecosystem: npm
directory: "/frontend"
schedule:
interval: daily
open-pull-requests-limit: 10
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
+17
View File
@@ -0,0 +1,17 @@
# Sync repo to the Codeberg mirror
name: Mirror Sync
on:
push:
branches: ["master"]
workflow_dispatch:
jobs:
codeberg:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: pixta-dev/repository-mirroring-action@v1
with:
target_repo_url: "git@codeberg.org:seriousm4x/UpSnap.git"
ssh_private_key: ${{ secrets.CODEBERG_SSH }}
@@ -0,0 +1,23 @@
name: Dependabot auto-merge
on: pull_request
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'}}
run: gh pr merge --auto --merge "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
+7 -7
View File
@@ -1,4 +1,4 @@
name: Deploy release
name: v3 build
on:
push:
@@ -26,14 +26,14 @@ jobs:
- name: Build frontend
run: |
npm --prefix=./frontend i
UPSNAP_VERSION=${GITHUB_REF##*/} npm --prefix=./frontend run build
UPSNAP_VERSION=${GITHUB_REF##*/} npm --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.19.5"
go-version: ">=1.20"
# build
- name: Run GoReleaser
@@ -41,7 +41,7 @@ jobs:
with:
distribution: goreleaser
version: latest
args: release --rm-dist
args: release --clean
workdir: backend
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -87,10 +87,10 @@ 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/v7
platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ${{ steps.meta.outputs.tags }}
+1
View File
@@ -199,3 +199,4 @@ backend/pb_public/*
!backend/pb_public/.gitkeep
dist/
vite.config.js.timestamp*
+3 -1
View File
@@ -12,8 +12,10 @@ RUN wget https://github.com/seriousm4x/UpSnap/releases/download/${VERSION}/UpSna
FROM alpine:3
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba-common-tools sshpass curl &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
rm -rf /var/cache/apk/*
WORKDIR /app
COPY --from=downloader /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"]
+64 -13
View File
@@ -1,31 +1,33 @@
<div align="center" width="100%">
<img src="frontend/static/favicon.png" width="128" />
<img src="frontend/static/gopher.svg" width="150" />
</div>
<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, PocketBase and nmap.</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/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
<h3><a href="https://github.com/seriousm4x/UpSnap/releases/tag/3.0.0">v3 is here! 🤩 Check it out</a></h3>
</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
- Dark/light or system prefered color scheme
- [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7
- 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 or OIDC 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
## 📸 Screenshots
| Dark | Light |
| ------------------------------ | ------------------------------- |
| ![](/assets/login_dark.png) | ![](/assets/login_light.png) |
| ![](/assets/home_dark.png) | ![](/assets/home_light.png) |
| ![](/assets/device_dark.png) | ![](/assets/device_light.png) |
| ![](/assets/settings_dark.png) | ![](/assets/settings_light.png) |
@@ -40,7 +42,24 @@ If you need network discovery, make sure to have `nmap` installed and run upsnap
## 🐳 Run in docker
Alternatively use the [docker-compose](docker-compose.yml) example. See the comments in the file for customization.
You can use the [docker-compose](docker-compose.yml) example. See the comments in the file for customization.
If you want to change the port, change the following (5000 in this case):
```yml
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
```
And if you need additional packages inside the container, do this:
```yml
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"
```
You can search for your needed package [here](https://pkgs.alpinelinux.org/packages).
### Reverse Proxy
@@ -52,6 +71,36 @@ upsnap.example.com {
}
```
## 🔒 Authorisation
**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 | ❌ | ❌ | ✅ |
## 🌍 Exposing to the open web
Although UpSnap has user authorisation, it is **not recommended to expose it to the open web** and make it accessible by everyone!
**Reason**: The shutdown device command is basically a command piped to #sh (root if you run docker). If anyone gains unauthorized access and can abuse this api route in any way, the attacker has access to a (root) shell on your local network.
**Recommended**: If you need access from outside your network, please use a vpn. Wireguard or OpenVPN is your way to go.
## 🔧 Help developing
Fork this branch and clone it.
@@ -64,8 +113,6 @@ go mod tidy
go run main.go serve
```
Log in to [http://localhost:8090/\_/](http://localhost:8090/_/), create an admin user and add some devices.
2. Start frontend
```sh
@@ -74,4 +121,8 @@ pnpm i
pnpm run dev
```
Open up [http://localhost:5173/](http://localhost:5173/)
Open up [http://localhost:5173/](http://localhost:5173/), create an admin user and add some devices.
## 🌟 Star History
[![Star History Chart](https://api.star-history.com/svg?repos=seriousm4x/UpSnap&type=Date)](https://star-history.com/#seriousm4x/UpSnap&Date)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 161 KiB

After

Width:  |  Height:  |  Size: 326 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

After

Width:  |  Height:  |  Size: 324 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 KiB

After

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 289 KiB

After

Width:  |  Height:  |  Size: 690 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 292 KiB

After

Width:  |  Height:  |  Size: 696 KiB

+1
View File
@@ -19,6 +19,7 @@ builds:
- arm64
- arm
goarm:
- 6
- 7
ignore:
- goos: windows
+2 -2
View File
@@ -13,14 +13,14 @@ var CronPing *cron.Cron
var CronWakeShutdown *cron.Cron
func RunPing(app *pocketbase.PocketBase) {
settingsRecords, err := app.Dao().FindRecordsByExpr("settings")
settingsPrivateRecords, err := app.Dao().FindRecordsByExpr("settings_private")
if err != nil {
logger.Error.Println(err)
}
// init cronjob
CronPing = cron.New()
CronPing.AddFunc(settingsRecords[0].GetString("interval"), func() {
CronPing.AddFunc(settingsPrivateRecords[0].GetString("interval"), func() {
// skip cron if no realtime clients connected
realtimeClients := len(app.SubscriptionsBroker().Clients())
if realtimeClients == 0 {
+56 -56
View File
@@ -3,94 +3,94 @@ module github.com/seriousm4x/upsnap
go 1.19
require (
github.com/go-ping/ping v1.1.0
github.com/labstack/echo/v5 v5.0.0-20220201181537-ed2888cfa198
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
github.com/pocketbase/dbx v1.9.0
github.com/pocketbase/pocketbase v0.12.0
github.com/pocketbase/dbx v1.10.0
github.com/pocketbase/pocketbase v0.16.7
github.com/prometheus-community/pro-bing v0.2.0
github.com/robfig/cron/v3 v3.0.1
)
require (
github.com/AlecAivazis/survey/v2 v2.3.6 // indirect
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/aws/aws-sdk-go v1.44.189 // indirect
github.com/aws/aws-sdk-go-v2 v1.17.3 // 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.294 // indirect
github.com/aws/aws-sdk-go-v2 v1.18.1 // 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.10 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.13.10 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.21 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.49 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.27 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.21 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.28 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.18 // indirect
github.com/aws/aws-sdk-go-v2/config v1.18.27 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.13.26 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.4 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.71 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.34 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.28 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.35 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.26 // 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.22 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.21 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.21 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.30.1 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.12.0 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.18.2 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.29 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.28 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.14.3 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.36.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.12.12 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.12 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.19.2 // indirect
github.com/aws/smithy-go v1.13.5 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/domodwyer/mailyak/v3 v3.3.4 // indirect
github.com/domodwyer/mailyak/v3 v3.6.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fatih/color v1.14.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.1 // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/ganigeorgiev/fexpr v0.3.0 // indirect
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
github.com/golang-jwt/jwt/v4 v4.4.3 // indirect
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.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/google/wire v0.5.0 // indirect
github.com/googleapis/gax-go/v2 v2.7.0 // indirect
github.com/googleapis/gax-go/v2 v2.11.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
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-sqlite3 v1.14.16 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
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.1 // indirect
github.com/mdlayher/socket v0.4.0 // indirect
github.com/mdlayher/packet v1.1.2 // indirect
github.com/mdlayher/socket v0.4.1 // 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.0 // indirect
github.com/spf13/cobra v1.6.1 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/cobra v1.7.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
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.28.0 // indirect
golang.org/x/crypto v0.5.0 // indirect
golang.org/x/image v0.3.0 // indirect
golang.org/x/mod v0.7.0 // indirect
golang.org/x/net v0.5.0 // indirect
golang.org/x/oauth2 v0.4.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.4.0 // indirect
golang.org/x/term v0.4.0 // indirect
golang.org/x/text v0.6.0 // indirect
gocloud.dev v0.30.0 // indirect
golang.org/x/crypto v0.10.0 // indirect
golang.org/x/image v0.8.0 // indirect
golang.org/x/mod v0.11.0 // indirect
golang.org/x/net v0.11.0 // indirect
golang.org/x/oauth2 v0.9.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sys v0.9.0 // indirect
golang.org/x/term v0.9.0 // indirect
golang.org/x/text v0.10.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.5.0 // indirect
golang.org/x/tools v0.10.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
google.golang.org/api v0.108.0 // indirect
google.golang.org/api v0.129.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20230127162408-596548ed4efa // indirect
google.golang.org/grpc v1.52.3 // indirect
google.golang.org/protobuf v1.28.1 // indirect
lukechampine.com/uint128 v1.2.0 // indirect
modernc.org/cc/v3 v3.40.0 // indirect
modernc.org/ccgo/v3 v3.16.13 // indirect
modernc.org/libc v1.22.2 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230629202037-9506855d4529 // indirect
google.golang.org/grpc v1.56.1 // indirect
google.golang.org/protobuf v1.31.0 // indirect
lukechampine.com/uint128 v1.3.0 // indirect
modernc.org/cc/v3 v3.41.0 // indirect
modernc.org/ccgo/v3 v3.16.14 // indirect
modernc.org/libc v1.24.1 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.6.0 // indirect
modernc.org/opt v0.1.3 // indirect
modernc.org/sqlite v1.20.3 // indirect
modernc.org/sqlite v1.23.1 // indirect
modernc.org/strutil v1.1.3 // indirect
modernc.org/token v1.1.0 // indirect
)
+839 -291
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,55 @@
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": "27do0wbcuyfmbmx",
"created": "2023-03-04 20:33:00.558Z",
"updated": "2023-03-04 20:33:00.558Z",
"name": "users",
"type": "auth",
"system": false,
"schema": [],
"listRule": null,
"viewRule": null,
"createRule": null,
"updateRule": null,
"deleteRule": null,
"options": {
"allowEmailAuth": true,
"allowOAuth2Auth": false,
"allowUsernameAuth": true,
"exceptEmailDomains": [],
"manageRule": null,
"minPasswordLength": 8,
"onlyEmailDomains": [],
"requireEmail": false
}
}`
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("27do0wbcuyfmbmx")
if err != nil {
return err
}
return dao.DeleteCollection(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.ViewRule = types.Pointer("@request.auth.id != \"\"")
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
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 = types.Pointer("")
collection.UpdateRule = types.Pointer("")
collection.DeleteRule = types.Pointer("")
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("cti4l8f4mz8df3r")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = types.Pointer("")
collection.UpdateRule = types.Pointer("")
collection.DeleteRule = types.Pointer("")
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("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = types.Pointer("")
collection.UpdateRule = types.Pointer("")
collection.DeleteRule = types.Pointer("")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,80 @@
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": "t1rajoyzl6691g3",
"created": "2023-03-09 22:17:29.463Z",
"updated": "2023-03-09 22:17:29.463Z",
"name": "settings_public",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "s1grje98",
"name": "website_title",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
},
{
"system": false,
"id": "tlzz87pj",
"name": "favicon",
"type": "file",
"required": false,
"unique": false,
"options": {
"maxSelect": 1,
"maxSize": 5242880,
"mimeTypes": [
"image/x-icon",
"image/png",
"image/svg+xml",
"image/gif",
"image/jpeg"
],
"thumbs": []
}
}
],
"listRule": "",
"viewRule": "",
"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("t1rajoyzl6691g3")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,65 @@
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("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.Name = "settings_private"
collection.ListRule = nil
collection.ViewRule = nil
// remove
collection.Schema.RemoveField("slrjkipw")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
collection.Name = "settings"
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
// add
del_website_title := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "slrjkipw",
"name": "website_title",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), del_website_title)
collection.Schema.AddField(del_website_title)
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("t1rajoyzl6691g3")
if err != nil {
return err
}
// add
new_setup_completed := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "vrxqcsnv",
"name": "setup_completed",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_setup_completed)
collection.Schema.AddField(new_setup_completed)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("t1rajoyzl6691g3")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("vrxqcsnv")
return dao.SaveCollection(collection)
})
}
@@ -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)
})
}
+26 -20
View File
@@ -1,7 +1,6 @@
package networking
import (
"encoding/binary"
"errors"
"fmt"
"net"
@@ -17,18 +16,10 @@ func SendMagicPacket(device *models.Record) error {
password := device.GetString("password")
// parse inputs
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return fmt.Errorf("error: invalid ip address")
}
parsedMac, err := net.ParseMAC(mac)
if err != nil {
return err
}
parsedNetmask := net.ParseIP(netmask)
if parsedNetmask == nil {
return fmt.Errorf("error: invalid netmask")
}
var bytePassword []byte
if len(password) == 0 || len(password) == 4 || len(password) == 6 {
bytePassword = []byte(password)
@@ -37,11 +28,7 @@ func SendMagicPacket(device *models.Record) error {
}
// get target addr
ipNet := &net.IPNet{
IP: parsedIP,
Mask: parsedNetmask.DefaultMask(),
}
broadcastIp, err := getBroadcastIp(ipNet)
broadcastIp, err := getBroadcastIp(ip, netmask)
if err != nil {
return err
}
@@ -64,11 +51,30 @@ func wakeUDP(addr string, target net.HardwareAddr, password []byte) error {
return c.WakePassword(addr, target, password)
}
func getBroadcastIp(n *net.IPNet) (net.IP, error) {
if n.IP.To4() == nil {
return net.IP{}, errors.New("does not support IPv6 addresses")
func getBroadcastIp(ipStr, maskStr string) (string, error) {
ip := net.ParseIP(ipStr)
if ip == nil {
return "", errors.New("ip not a valid ipv4 address")
}
ip := make(net.IP, len(n.IP.To4()))
binary.BigEndian.PutUint32(ip, binary.BigEndian.Uint32(n.IP.To4())|^binary.BigEndian.Uint32(net.IP(n.Mask).To4()))
return ip, nil
ip = ip.To4()
if ip == nil {
return "", errors.New("ip not a valid ipv4 address")
}
mask := net.ParseIP(maskStr)
if mask == nil {
return "", errors.New("subnet mask not a valid ipv4 address")
}
mask = mask.To4()
ip = ip.To4()
if ip == nil {
return "", errors.New("subnet mask not a valid ipv4 address")
}
broadcast := make(net.IP, 4)
for i := range ip {
broadcast[i] = ip[i] | ^mask[i]
}
return broadcast.String(), nil
}
+2 -2
View File
@@ -4,13 +4,13 @@ import (
"net"
"time"
"github.com/go-ping/ping"
"github.com/pocketbase/pocketbase/models"
probing "github.com/prometheus-community/pro-bing"
"github.com/seriousm4x/upsnap/logger"
)
func PingDevice(device *models.Record) bool {
pinger, err := ping.NewPinger(device.GetString("ip"))
pinger, err := probing.NewPinger(device.GetString("ip"))
if err != nil {
logger.Error.Println(err)
return false
+4 -1
View File
@@ -1,6 +1,7 @@
package networking
import (
"bytes"
"fmt"
"os/exec"
"runtime"
@@ -28,8 +29,10 @@ func ShutdownDevice(device *models.Record) error {
}
cmd := exec.Command(shell, shell_arg, shutdown_cmd)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return err
return fmt.Errorf("%s", stderr.String())
}
// check state every second for 2 min
+25 -9
View File
@@ -11,6 +11,7 @@ import (
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/logger"
"github.com/seriousm4x/upsnap/networking"
)
@@ -23,6 +24,7 @@ func HandlerWake(c echo.Context) error {
record.Set("status", "pending")
App.Dao().SaveRecord(record)
if err := networking.WakeDevice(record); err != nil {
logger.Error.Println(err)
record.Set("status", "offline")
} else {
record.Set("status", "online")
@@ -41,6 +43,7 @@ func HandlerShutdown(c echo.Context) error {
record.Set("status", "pending")
App.Dao().SaveRecord(record)
if err := networking.ShutdownDevice(record); err != nil {
logger.Error.Println(err)
record.Set("status", "online")
} else {
record.Set("status", "offline")
@@ -67,12 +70,12 @@ func HandlerScan(c echo.Context) error {
}
// check if scan range is valid
allSettings, err := App.Dao().FindRecordsByExpr("settings")
allPrivateSettings, err := App.Dao().FindRecordsByExpr("settings_private")
if err != nil {
return err
}
settings := allSettings[0]
scanRange := settings.GetString("scan_range")
settingsPrivate := allPrivateSettings[0]
scanRange := settingsPrivate.GetString("scan_range")
_, ipNet, err := net.ParseCIDR(scanRange)
if err != nil {
return apis.NewBadRequestError(err.Error(), nil)
@@ -92,9 +95,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
@@ -118,15 +122,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)
}
+94 -24
View File
@@ -2,7 +2,6 @@ package pb
import (
"io/fs"
"log"
"net/http"
"os"
@@ -42,6 +41,7 @@ func StartPocketBase(distDirFS fs.FS) {
Handler: HandlerWake,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
apis.RequireAdminOrRecordAuth("users"),
},
})
@@ -52,6 +52,7 @@ func StartPocketBase(distDirFS fs.FS) {
Handler: HandlerShutdown,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
apis.RequireAdminOrRecordAuth("users"),
},
})
@@ -62,6 +63,7 @@ func StartPocketBase(distDirFS fs.FS) {
Handler: HandlerScan,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
apis.RequireAdminAuth(),
},
})
@@ -83,13 +85,16 @@ func StartPocketBase(distDirFS fs.FS) {
// add event hook before starting server.
// using this outside App.OnBeforeServe() would not work
App.OnModelAfterUpdate().Add(func(e *core.ModelEvent) error {
if e.Model.TableName() == "settings" {
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" {
refreshDeviceList()
if err := refreshDeviceList(); err != nil {
logger.Error.Println(err)
return err
}
for _, job := range cronjobs.CronWakeShutdown.Entries() {
cronjobs.CronWakeShutdown.Remove(job.ID)
}
@@ -102,33 +107,67 @@ func StartPocketBase(distDirFS fs.FS) {
// refresh the device list on database events
App.OnModelAfterCreate().Add(func(e *core.ModelEvent) error {
refreshDeviceList()
if e.Model.TableName() == "_admins" {
if err := setSetupCompleted(); err != nil {
logger.Error.Println(err)
return err
}
} else {
if err := refreshDeviceList(); err != nil {
logger.Error.Println(err)
return err
}
}
return nil
})
App.OnModelAfterDelete().Add(func(e *core.ModelEvent) error {
refreshDeviceList()
if e.Model.TableName() == "_admins" {
if err := setSetupCompleted(); err != nil {
logger.Error.Println(err)
return err
}
} else {
if err := refreshDeviceList(); err != nil {
logger.Error.Println(err)
return err
}
}
return nil
})
// start pocketbase
if err := App.Start(); err != nil {
log.Fatal(err)
logger.Error.Fatalln(err)
}
}
func importSettings() error {
// get first settings record
settingsRecords, err := App.Dao().FindRecordsByExpr("settings")
// get first settingsPrivate record
settingsPrivateRecords, err := App.Dao().FindRecordsByExpr("settings_private")
if err != nil {
return err
}
settingsCollection, err := App.Dao().FindCollectionByNameOrId("settings")
settingsPrivateCollection, err := App.Dao().FindCollectionByNameOrId("settings_private")
if err != nil {
return err
}
settings := models.NewRecord(settingsCollection)
if len(settingsRecords) > 0 {
settings = settingsRecords[0]
settingsPrivate := models.NewRecord(settingsPrivateCollection)
if len(settingsPrivateRecords) > 0 {
settingsPrivate = settingsPrivateRecords[0]
}
// get first settingsPublic record
settingsPublicRecords, err := App.Dao().FindRecordsByExpr("settings_public")
if err != nil {
return err
}
settingsPublicCollection, err := App.Dao().FindCollectionByNameOrId("settings_public")
if err != nil {
return err
}
settingsPublic := models.NewRecord(settingsPublicCollection)
if len(settingsPublicRecords) > 0 {
settingsPublic = settingsPublicRecords[0]
}
// set ping interval settings. priority:
@@ -136,22 +175,33 @@ func importSettings() error {
// 2nd: database entry
// 3rd: default values
interval := "@every 3s"
if settings.GetString("interval") != "" {
interval = settings.GetString("interval")
if settingsPrivate.GetString("interval") != "" {
interval = settingsPrivate.GetString("interval")
}
if os.Getenv("UPSNAP_INTERVAL") != "" {
interval = os.Getenv("UPSNAP_INTERVAL")
}
// save settings to db
settings.Set("interval", interval)
// set private settings
settingsPrivate.Set("interval", interval)
if scanRange := os.Getenv("UPSNAP_SCAN_RANGE"); scanRange != "" {
settings.Set("scan_range", scanRange)
settingsPrivate.Set("scan_range", scanRange)
}
if scanRange := os.Getenv("UPSNAP_WEBSITE_TITLE"); scanRange != "" {
settings.Set("website_title", scanRange)
// set public settings
if websiteTitle := os.Getenv("UPSNAP_WEBSITE_TITLE"); websiteTitle != "" {
settingsPublic.Set("website_title", websiteTitle)
}
if err := App.Dao().SaveRecord(settings); err != nil {
// save records
if err := App.Dao().SaveRecord(settingsPrivate); err != nil {
return err
}
if err := App.Dao().SaveRecord(settingsPublic); err != nil {
return err
}
if err := setSetupCompleted(); err != nil {
logger.Error.Println(err)
return err
}
@@ -174,10 +224,30 @@ func resetDeviceStates() error {
return nil
}
func refreshDeviceList() {
func refreshDeviceList() error {
var err error
cronjobs.Devices, err = App.Dao().FindRecordsByExpr("devices")
if err != nil {
logger.Error.Println(err)
if cronjobs.Devices, err = App.Dao().FindRecordsByExpr("devices"); err != nil {
return err
}
return nil
}
func setSetupCompleted() error {
totalAdmins, err := App.Dao().TotalAdmins()
if err != nil {
return err
}
settingsPublicRecords, err := App.Dao().FindRecordsByExpr("settings_public")
if err != nil {
return err
}
if totalAdmins > 0 {
settingsPublicRecords[0].Set("setup_completed", true)
} else {
settingsPublicRecords[0].Set("setup_completed", false)
}
if err := App.Dao().SaveRecord(settingsPublicRecords[0]); err != nil {
return err
}
return nil
}
+23 -17
View File
@@ -1,19 +1,25 @@
version: "3"
services:
upsnap:
image: ghcr.io/seriousm4x/upsnap:3
network_mode: host
restart: unless-stopped
volumes:
- ./data:/app/pb_data
healthcheck:
test: wget --no-verbose --tries=1 --spider http://localhost:8090/api/health || exit 1
interval: 1m
timeout: 10s
retries: 3
# 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
# command: ["./upsnap", "serve", "--http", "0.0.0.0:8090"] # Uncomment this if you want to change the port for example
upsnap:
container_name: upsnap
image: ghcr.io/seriousm4x/upsnap:3
network_mode: host
restart: unless-stopped
volumes:
- ./data:/app/pb_data
# 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"
+11 -3
View File
@@ -1,8 +1,16 @@
module.exports = {
root: true,
extends: ['eslint:recommended', 'prettier'],
plugins: ['svelte3'],
overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }],
extends: ['plugin:svelte/recommended', 'prettier'],
parser: '@typescript-eslint/parser',
overrides: [
{
files: ['*.svelte'],
parser: 'svelte-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser'
}
}
],
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020
+898 -2971
View File
File diff suppressed because it is too large Load Diff
+21 -21
View File
@@ -11,31 +11,31 @@
"format": "prettier --ignore-path ../.gitignore --write --plugin-search-dir=. ."
},
"devDependencies": {
"@sveltejs/adapter-static": "^1.0.5",
"@sveltejs/kit": "^1.3.3",
"@typescript-eslint/eslint-plugin": "^5.49.0",
"@typescript-eslint/parser": "^5.49.0",
"eslint": "^8.33.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-svelte3": "^4.0.0",
"@sveltejs/adapter-static": "^2.0.2",
"@sveltejs/kit": "^1.21.0",
"@typescript-eslint/eslint-plugin": "^5.61.0",
"@typescript-eslint/parser": "^5.61.0",
"eslint": "^8.44.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-svelte": "^2.32.2",
"husky": "^8.0.3",
"lint-staged": "^13.1.0",
"prettier": "^2.8.3",
"prettier-plugin-svelte": "^2.9.0",
"svelte": "^3.55.1",
"svelte-preprocess": "^5.0.1",
"typescript": "^4.9.4",
"vite": "^4.0.4"
"lint-staged": "^13.2.3",
"prettier": "^2.8.8",
"prettier-plugin-svelte": "^2.10.1",
"svelte": "^4.0.2",
"svelte-preprocess": "^5.0.4",
"typescript": "^5.1.6",
"vite": "^4.3.9"
},
"type": "module",
"dependencies": {
"@fortawesome/free-solid-svg-icons": "^6.2.1",
"@popperjs/core": "^2.11.6",
"bootstrap": "5.3.0-alpha1",
"date-fns": "^2.29.3",
"pocketbase": "^0.10.1",
"sass": "^1.57.1",
"svelte-fa": "^3.0.3"
"@fortawesome/free-solid-svg-icons": "^6.4.0",
"@popperjs/core": "^2.11.8",
"bootstrap": "5.3.0",
"date-fns": "^2.30.0",
"pocketbase": "^0.15.2",
"sass": "^1.63.6",
"svelte-fa": "^3.0.4"
},
"lint-staged": {
"*.{js,svelte}": "eslint --fix --ignore-path ../.gitignore .",
+967 -693
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -2,10 +2,10 @@
<html lang="en" class="h-100">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover" class="h-100">
<div style="display: contents">%sveltekit.body%</div>
</body>
+23 -8
View File
@@ -1,6 +1,8 @@
<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,
@@ -9,18 +11,25 @@
faCircleDown,
faLock
} from '@fortawesome/free-solid-svg-icons';
import Fa from 'svelte-fa';
import { sortPorts } from '../sorts';
export let device;
export let now;
function shutdown() {
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/shutdown/${device.id}`);
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}`);
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/wake/${device.id}`, {
headers: {
Authorization: $pocketbase.authStore.baseToken
}
});
}
</script>
@@ -35,8 +44,13 @@
<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">
<span
class="text-danger"
role="none"
on:click={() => wake()}
on:keydown={() => wake()}
>
<div>
<Fa icon={faPowerOff} class="fs-4 power-hover" />
</div>
</span>
@@ -44,10 +58,11 @@
{#if device.shutdown_cmd !== ''}
<span
class="text-success"
role="none"
on:click={() => shutdown()}
on:keydown={() => shutdown()}
>
<div role="button">
<div>
<Fa icon={faPowerOff} class="fs-4 power-hover" />
</div>
</span>
@@ -78,13 +93,13 @@
</div>
</div>
{#if device.link}
<p class="m-0 fw-bold fs-5">
<p class="m-0 fw-bold fs-5 text-body-emphasis">
<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>
<p class="m-0 fw-bold fs-5 text-body-emphasis">{device.name}</p>
{/if}
<p class="text-muted mb-2">{device.ip}</p>
{#if device?.expand?.ports}
+35 -6
View File
@@ -1,8 +1,8 @@
<script>
import { goto } from '$app/navigation';
import { pocketbase, devices } from '@stores/pocketbase';
import { pocketbase, devices, groups } from '@stores/pocketbase';
import Fa from 'svelte-fa/src/fa.svelte';
import { faEye, faEyeSlash, faPlus, faTrashCan } from '@fortawesome/free-solid-svg-icons';
import Fa from 'svelte-fa';
export let device;
export let mode;
@@ -115,10 +115,20 @@
function onPasswordInput(event) {
device.password = event.target.value;
}
function toggleGroup(grpId) {
const i = device.groups.indexOf(grpId);
if (i !== -1) {
device.groups.splice(i, 1);
device.groups = device.groups;
} else {
device.groups = [...device.groups, grpId];
}
}
</script>
<section class="m-0 mt-4 p-4 shadow-sm">
<h3 class="mb-3">{mode === 'add' ? 'Add new device' : device.name}</h3>
<h3 class="mb-3 text-body-emphasis">{mode === 'add' ? 'Add new device' : device.name}</h3>
<div class="row">
<div class="col-md-6">
<form on:submit|preventDefault={addOrUpdateDevice}>
@@ -185,6 +195,7 @@
/>
<input
type="number"
min="0"
max="65535"
aria-label="Number"
class="form-control"
@@ -201,7 +212,7 @@
</div>
{/each}
{/if}
<div class="input-group mb-3">
<div class="input-group mb-1">
<span class="input-group-text">Port</span>
<input
type="text"
@@ -212,6 +223,7 @@
/>
<input
type="number"
min="0"
max="65535"
aria-label="Number"
class="form-control"
@@ -226,7 +238,7 @@
<Fa icon={faPlus} />
</button>
</div>
<div class="input-group mb-3">
<div class="input-group mb-1">
<span class="input-group-text">Link</span>
<input
class="form-control"
@@ -281,7 +293,7 @@
/>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group mb-1">
<span class="input-group-text">Shutdown Cmd<sup>(2)</sup></span>
<input
class="form-control"
@@ -312,6 +324,23 @@
<Fa icon={passwordShow ? faEyeSlash : faEye} />
</button>
</div>
{#if groups}
<h5 class="mt-4">Groups:</h5>
<div class="input-group mb-3">
{#each $groups as grp}
<span
class="badge rounded-pill fs-6 cursor-pointer me-2 {device?.groups?.includes(
grp.id
)
? 'text-bg-success'
: 'text-bg-secondary text-white-50'} "
role="none"
on:click={() => toggleGroup(grp.id)}
on:keydown={() => toggleGroup(grp.id)}>{grp.name}</span
>
{/each}
</div>
{/if}
<button
type="submit"
class="btn btn-secondary"
+237
View File
@@ -0,0 +1,237 @@
<script>
import { dev } from '$app/environment';
import { page } from '$app/stores';
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 loginUserPass() {
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 loginOIDC() {
$pocketbase
.collection('users')
.authWithOAuth2({ provider: 'oidc' })
.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={loginUserPass}>
<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="btn btn-outline-secondary btn-sm"
>Manage users</a
>
<button
class="btn btn-outline-secondary btn-sm"
data-toggle="tooltip"
title="You can setup OIDC at {$page.url.host}/_/#/settings/auth-providers"
on:click={() => loginOIDC()}
on:keydown={() => loginOIDC()}>Login with OIDC</button
>
</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;
}
</style>
+85 -40
View File
@@ -1,55 +1,87 @@
<script>
import { dev } from '$app/environment';
import { onMount } from 'svelte';
import { page } from '$app/stores';
import { theme } from '@stores/theme';
import { pocketbase, settings } from '@stores/pocketbase';
import { faSun, faMoon, faCircleHalfStroke, faBrush } from '@fortawesome/free-solid-svg-icons';
import Fa from 'svelte-fa';
import { onMount } from 'svelte';
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 () => {
$pocketbase.collection('settings').subscribe('*', function (e) {
settings.set(e.record);
document.title = $settings.website_title;
});
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>
<svelte:head>
{#if $settings.website_title !== ''}
<title>{$settings.website_title}</title>
{:else}
<title>UpSnap</title>
{/if}
</svelte:head>
<nav class="navbar navbar-expand">
<nav class="navbar navbar-expand-sm pt-0">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<img
src="/favicon.png"
alt="UpSnap"
width="30"
height="30"
class:me-2={$settings.website_title !== ''}
/>{$settings.website_title ? $settings.website_title : ''}
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>
<div class="collapse navbar-collapse" id="navbarNav">
<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">
<li class="nav-item">
<a
class="nav-link"
class:active={$page.url.pathname === '/' ? true : false}
href="/">Home</a
>
</li>
<li class="nav-item">
<a
class="nav-link"
class:active={$page.url.pathname === '/settings' ? true : false}
href="/settings">Settings</a
>
</li>
<li class="nav-item dropdown ms-3">
{#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"
@@ -59,11 +91,12 @@
<Fa icon={faBrush} class="me-2" />
Theme
</div>
<ul class="dropdown-menu border-0 p-1">
<ul class="dropdown-menu border-0 p-1 shadow-sm mb-2">
<li>
<div
class="dropdown-item"
class:active={$theme === 'light'}
role="none"
on:click={() => ($theme = 'light')}
on:keydown={() => ($theme = 'light')}
>
@@ -75,6 +108,7 @@
<div
class="dropdown-item"
class:active={$theme === 'dark'}
role="none"
on:click={() => ($theme = 'dark')}
on:keydown={() => ($theme = 'dark')}
>
@@ -86,6 +120,7 @@
<div
class="dropdown-item"
class:active={$theme === 'auto'}
role="none"
on:click={() => ($theme = 'auto')}
on:keydown={() => ($theme = 'auto')}
>
@@ -96,6 +131,16 @@
</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} &quot;{userInfo.usernameOrEmail}&quot;"
on:click={() => logout()}
>
<Fa icon={faRightFromBracket} class="me-2" />Logout ({userInfo.usernameOrEmail})
</button>
</div>
</div>
</div>
</nav>
@@ -0,0 +1,16 @@
<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}
+93 -23
View File
@@ -1,32 +1,28 @@
<script>
import { dev } from '$app/environment';
import { onMount } from 'svelte';
import { page } from '$app/stores';
import { theme } from '@stores/theme';
import Navbar from '@components/Navbar.svelte';
import Login from '@components/Login.svelte';
import Transition from '@components/Transition.svelte';
import { pocketbase, settings, devices } from '@stores/pocketbase';
import { theme } from '@stores/theme';
import {
pocketbase,
authorizedStore,
devices,
groups,
settings_private,
settings_public
} from '@stores/pocketbase';
let favicon;
let preferesDark;
let isAuth = false;
onMount(async () => {
let settingsRes = {};
settingsRes = await $pocketbase.collection('settings').getList(1, 1);
settings.set(settingsRes.items[0]);
let tempDevices = {};
const devicesRes = await $pocketbase.collection('devices').getFullList(200, {
sort: 'name',
expand: 'ports'
});
devicesRes.forEach((device) => {
tempDevices[device.id] = device;
});
devices.set(tempDevices);
});
onMount(() => {
// import bootstrap js
import('bootstrap/js/dist/dropdown');
import('bootstrap/js/dist/collapse');
// set dark mode
preferesDark = window.matchMedia('(prefers-color-scheme: dark)');
@@ -46,10 +42,81 @@
}
document.documentElement.setAttribute('data-bs-theme', t);
});
authorizedStore.subscribe((state) => {
isAuth = state;
});
// 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) {
$pocketbase.authStore.loadFromCookie('pb_auth=' + pbCookie);
// 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);
}
});
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;
}
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]);
}
// get all devices from pb and save in svelte store
let tempDevices = {};
const devicesRes = await $pocketbase.collection('devices').getFullList(-1, {
sort: 'name',
expand: 'ports,groups'
});
devicesRes.forEach((device) => {
tempDevices[device.id] = device;
});
devices.set(tempDevices);
// get all groups from pb and save in svelte store
const groupsRes = await $pocketbase.collection('groups').getFullList(-1, {
sort: 'name'
});
groups.set(groupsRes);
}
$: if (isAuth) {
getSettingsPrivateAndDevices();
}
</script>
<svelte:head>
<link rel="shortcut icon" href="/gopher.svg" bind:this={favicon} />
<script>
if (document) {
preferesDark = window.matchMedia('(prefers-color-scheme: dark)').matches
@@ -67,11 +134,14 @@
</script>
</svelte:head>
<Navbar />
<Transition url={$page.url}>
<slot />
</Transition>
{#if isAuth}
<Navbar />
<Transition url={$page.url}>
<slot />
</Transition>
{:else}
<Login />
{/if}
<style lang="scss" global>
@import '../scss/main.scss';
+39 -7
View File
@@ -2,7 +2,7 @@
import { onMount } from 'svelte';
import DeviceCard from '@components/DeviceCard.svelte';
import { pocketbase, devices } from '@stores/pocketbase';
import { sortDevices } from '../sorts';
import { sortDevices, sortGroups } from '../sorts';
onMount(async () => {
// subscribe to database events
@@ -11,7 +11,7 @@
$devices[e.record.id] = e.record;
} else if (e.action === 'update') {
const device = await $pocketbase.collection('devices').getOne(e.record.id, {
expand: 'ports'
expand: 'ports,groups'
});
$devices[device.id] = device;
} else if (e.action === 'delete') {
@@ -34,6 +34,27 @@
});
});
let devicesWithoutGroups = [];
let devicesWithGroup = {};
devices.subscribe((d) => {
// sort devices into their groups
devicesWithoutGroups = [];
devicesWithGroup = {};
Object.values(d).forEach((device) => {
if (device.groups.length === 0) {
devicesWithoutGroups = [...devicesWithoutGroups, device];
return;
}
device.expand.groups.forEach((grp) => {
if (!devicesWithGroup.hasOwnProperty(grp.name)) {
devicesWithGroup[grp.name] = [];
}
devicesWithGroup[grp.name] = [...devicesWithGroup[grp.name], device];
});
});
});
// update device date
let now = Date.now();
let interval;
@@ -47,11 +68,22 @@
<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>
{#if devicesWithoutGroups.length > 0}
<div class="row">
{#each devicesWithoutGroups.sort(sortDevices) as device}
<DeviceCard {device} {now} />
{/each}
</div>
{/if}
{#each Object.keys(devicesWithGroup).sort(sortGroups) as grp}
<h2 class="mt-4 mb-0">{grp}</h2>
<div class="row">
{#each devicesWithGroup[grp] as device}
<DeviceCard {device} {now} />
{/each}
</div>
{/each}
{:else}
<div class="text-center">
<h4 class="text-muted">No devices</h4>
+2 -1
View File
@@ -1,6 +1,7 @@
<script>
import { devices } from '@stores/pocketbase';
import DeviceForm from '@components/DeviceForm.svelte';
import UnauthorizedMsg from '@components/UnauthorizedMsg.svelte';
export let data;
let device;
@@ -11,11 +12,11 @@
device.expand.ports = [];
}
}
$:;
</script>
{#if device}
<div class="container">
<UnauthorizedMsg />
<DeviceForm bind:device mode="edit" />
</div>
{/if}
+218 -133
View File
@@ -1,24 +1,32 @@
<script>
import { dev } from '$app/environment';
import { pocketbase, settings, devices } from '@stores/pocketbase';
import {
pocketbase,
settings_private,
settings_public,
devices,
groups
} from '@stores/pocketbase';
import UnauthorizedMsg from '@components/UnauthorizedMsg.svelte';
import DeviceForm from '@components/DeviceForm.svelte';
import { faPlus } from '@fortawesome/free-solid-svg-icons';
import Fa from 'svelte-fa';
import Fa from 'svelte-fa/src/fa.svelte';
import { faPlus, faXmark } from '@fortawesome/free-solid-svg-icons';
let version = import.meta.env.UPSNAP_VERSION;
let files;
let iconFiles = [];
let iconPreview;
let timeout;
let buttons = {
settings: {
state: 'none',
error: ''
},
restore: {
scan: {
state: 'none',
error: ''
},
scan: {
addAllDevices: {
state: 'none',
error: ''
}
@@ -38,17 +46,46 @@
shutdown_cron: '',
shutdown_cron_enabled: false,
shutdown_cmd: '',
password: ''
password: '',
groups: []
};
let newGroup = '';
let scannedDevices = {};
$: if (iconPreview && iconFiles.length > 0) {
iconPreview.src = URL.createObjectURL(iconFiles[0]);
} else if (iconPreview && $settings_public.favicon !== '') {
iconPreview.src = `${dev ? $pocketbase.baseUrl : ''}/api/files/settings_public/${
$settings_public.id
}/${$settings_public.favicon}`;
} else if (iconPreview) {
iconPreview.src = '/gopher.svg';
}
async function saveSettings() {
buttons.settings.state = 'waiting';
try {
if ($settings.interval === '') {
$settings.interval = '@every 3s';
// update settings private
if ($settings_private.interval === '') {
$settings_private.interval = '@every 3s';
}
await $pocketbase.collection('settings').update($settings.id, $settings);
await $pocketbase
.collection('settings_private')
.update($settings_private.id, $settings_private);
// update settings public
if (iconFiles.length > 0) {
const formData = new FormData();
formData.append('favicon', iconFiles[0]);
await $pocketbase
.collection('settings_public')
.update($settings_public.id, formData);
}
await $pocketbase
.collection('settings_public')
.update($settings_public.id, $settings_public);
//set button
clearTimeout(timeout);
timeout = setTimeout(() => {
buttons.settings.state = 'none';
@@ -67,9 +104,24 @@
async function scanDevices() {
buttons.scan.state = 'waiting';
await $pocketbase.collection('settings').update($settings.id, $settings);
await $pocketbase
.collection('settings_private')
.update($settings_private.id, $settings_private)
.catch((err) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
buttons.scan.error = '';
buttons.scan.state = 'none';
}, 3000);
buttons.scan.error = err;
buttons.scan.state = 'failed';
});
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/scan`)
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/scan`, {
headers: {
Authorization: $pocketbase.authStore.baseToken
}
})
.then((res) => res.json())
.then((data) => {
if (data.message) {
@@ -100,87 +152,45 @@
});
}
async function addDevice(device) {
await $pocketbase.collection('devices').create(device);
$devices[device.id] = device;
async function addAllDevices() {
buttons.addAllDevices.state = 'waiting';
scannedDevices.devices.forEach(async (device) => {
device.netmask = scannedDevices.netmask;
await addDevice(device);
});
buttons.addAllDevices.state = 'success';
}
async function restoreV2Backup() {
buttons.restore.state = 'waiting';
async function addDevice(device) {
await $pocketbase.collection('devices').create(device);
}
try {
// delete all devices in pocketbase
let result = await $pocketbase.collection('devices').getFullList();
for (let index = 0; index < result.length; index++) {
$pocketbase.collection('devices').delete(result[index].id);
}
// delete all ports in pocketbase
result = await $pocketbase.collection('ports').getFullList();
for (let index = 0; index < result.length; index++) {
await $pocketbase.collection('ports').delete(result[index].id);
}
async function addGroup() {
const res = await $pocketbase.collection('groups').create({
name: newGroup
});
$groups = [...$groups, res];
newGroup = '';
}
let reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = async (e) => {
// parse uploaded file
let data = JSON.parse(e.target.result);
if (!Array.isArray(data)) {
return;
}
// loop devices
for (let index = 0; index < data.length; index++) {
const device = data[index];
// create ports
let thisDevicePorts = [];
for (let index = 0; index < device.ports.length; index++) {
const port = device.ports[index];
const record = await $pocketbase.collection('ports').create({
name: port.name,
number: port.number
});
thisDevicePorts.push(record.id);
}
// create device
await $pocketbase.collection('devices').create({
name: device.name,
ip: device.ip,
mac: device.mac,
netmask: device.netmask,
ports: thisDevicePorts,
link: device.link,
wake_cron: device.wake.cron,
wake_cron_enabled: device.wake.enabled,
shutdown_cron: device.shutdown.cron,
shutdown_cron_enabled: device.shutdown.cron.enabled,
shutdown_cmd: device.shutdown.command
});
}
};
setTimeout(() => {
buttons.restore.state = 'none';
}, 3000);
buttons.restore.state = 'success';
} catch (error) {
setTimeout(() => {
buttons.restore.error = '';
buttons.restore.state = 'none';
}, 3000);
buttons.restore.error = error;
buttons.restore.state = 'failed';
async function deleteGroup(id) {
await $pocketbase.collection('groups').delete(id);
const ids = $groups.map((grp) => grp.id);
const i = ids.indexOf(id);
if (i > -1) {
$groups.splice(i, 1);
$groups = $groups;
}
}
</script>
<div class="container">
<UnauthorizedMsg />
<section class="m-0 mt-4 p-4 shadow-sm">
<form on:submit|preventDefault={saveSettings}>
<h3 class="mb-3">Ping interval</h3>
<div class="row">
<div class="col-md-6">
<h3 class="mb-3 text-body-emphasis">Ping interval</h3>
<p>Sets the interval in which the devices are pinged.</p>
<div class="input-group mb-3">
<span class="input-group-text">Cron</span>
@@ -190,11 +200,11 @@
aria-label="Interval"
aria-describedby="addon-wrapping"
type="text"
bind:value={$settings.interval}
bind:value={$settings_private.interval}
/>
</div>
<h3 class="my-3">Website title</h3>
<p>Set the website title in the navbar.</p>
<h3 class="my-3 text-body-emphasis">Title</h3>
<p>Sets the title of the website and in the browser tab.</p>
<div class="input-group mb-3">
<span class="input-group-text" id="website-title">Title</span>
<input
@@ -203,13 +213,41 @@
placeholder="e.g. 'UpSnap'"
aria-label="Website title"
aria-describedby="website-title"
bind:value={$settings.website_title}
bind:value={$settings_public.website_title}
/>
</div>
<h3 class="my-3 text-body-emphasis">Icon</h3>
<img
src=""
alt=""
class="img-fluid icon-preview mb-3"
bind:this={iconPreview}
/>
<div class="mb-3">
<label for="iconInput" class="form-label">Set a custom favicon.</label>
<div class="input-group">
<input
class="form-control"
type="file"
id="iconInput"
accept=".ico,.png,.svg,.gif,.jpg,.jpeg"
bind:files={iconFiles}
/>
<button
type="button"
class="btn btn-outline-danger"
on:click={() => {
iconFiles = [];
$settings_public.favicon = '';
}}>Back to Gopher</button
>
</div>
</div>
</div>
<div class="col-md-6">
<div class="callout callout-info m-0">
<p class="m-0">
<h5>Ping interval:</h5>
<p>
Leave blank to use default value of <span class="fw-bold"
>"@every 3s"</span
>. Learn more about the correct syntax for cron on
@@ -226,6 +264,15 @@
>package documentation</a
>
</p>
<h5>Icon:</h5>
<p class="m-0">
Supported file types are
<span class="badge text-bg-secondary">.ico</span>,
<span class="badge text-bg-secondary">.png</span>,
<span class="badge text-bg-secondary">.svg</span>,
<span class="badge text-bg-secondary">.gif</span> and
<span class="badge text-bg-secondary">.jpg/.jpeg</span>.
</p>
</div>
</div>
</div>
@@ -253,7 +300,48 @@
<section class="m-0 my-4 p-4 shadow-sm">
<div class="row">
<div class="col-md-6">
<h3 class="mb-3">Network scan</h3>
<h3 class="mb-3 text-body-emphasis">Manage Groups</h3>
<p>
{#each $groups as grp}
<div class="badge rounded-pill fs-6 text-bg-secondary me-2">
{grp.name}
<span
class="px-1"
on:click={() => deleteGroup(grp.id)}
on:keydown={() => deleteGroup(grp.id)}
role="button"
tabindex="0"
>
<Fa icon={faXmark} />
</span>
</div>
{/each}
</p>
<div class="input-group mb-3">
<span class="input-group-text">Add new group</span>
<input
class="form-control"
placeholder="Name for your new group"
aria-label="New Group"
type="text"
bind:value={newGroup}
/>
<button
class="btn btn-outline-secondary"
type="button"
on:click={() => addGroup()}
on:keydown={() => addGroup()}
>
<Fa icon={faPlus} />
</button>
</div>
</div>
</div>
</section>
<section class="m-0 my-4 p-4 shadow-sm">
<div class="row">
<div class="col-md-6">
<h3 class="mb-3 text-body-emphasis">Network scan</h3>
<p>Set the network address to scan.</p>
<form on:submit|preventDefault={scanDevices}>
<div class="input-group mb-3">
@@ -264,7 +352,7 @@
placeholder="e.g. '192.168.1.0/24'"
aria-label="ip-range"
aria-describedby="ip-range"
bind:value={$settings.scan_range}
bind:value={$settings_private.scan_range}
/>
</div>
<button
@@ -273,7 +361,8 @@
class:btn-success={buttons.scan.state === 'success' ? true : false}
class:btn-warning={buttons.scan.state === 'waiting' ? true : false}
class:btn-danger={buttons.scan.state === 'failed' ? true : false}
disabled={$settings.scan_range === '' || buttons.scan.state !== 'none'
disabled={$settings_private.scan_range === '' ||
buttons.scan.state !== 'none'
? true
: false}
>
@@ -302,28 +391,32 @@
{#if scannedDevices.devices}
<div class="mt-3">
<div class="row align-items-center my-1">
<div class="col-md fw-bold">Name</div>
<div class="col-md fw-bold">IP</div>
<div class="col-md fw-bold">MAC</div>
<div class="col-md fw-bold">Netmask</div>
<div class="col-md fw-bold">Add</div>
<div class="col-lg-3 fw-bold">Name</div>
<div class="col-lg-2 fw-bold">IP</div>
<div class="col-lg-2 fw-bold">MAC</div>
<div class="col-lg-2 fw-bold">MAC Vendor</div>
<div class="col-lg-2 fw-bold">Netmask</div>
<div class="col-lg-1 fw-bold">Add</div>
</div>
{#each scannedDevices?.devices as device}
<hr class="my-1" />
<div class="row align-items-center my-1">
<div class="col-md">
<div class="col-lg-3">
{device.name}
</div>
<div class="col-md">
<div class="col-lg-2">
{device.ip}
</div>
<div class="col-md">
<div class="col-lg-2">
{device.mac}
</div>
<div class="col-md">
<div class="col-lg-2">
{device.mac_vendor}
</div>
<div class="col-lg-2">
{scannedDevices.netmask}
</div>
<div class="col-md">
<div class="col-lg-1">
<button
class="btn btn-sm btn-secondary py-0"
on:click={async (e) => {
@@ -343,43 +436,29 @@
</div>
{/each}
</div>
<button
class="btn btn-secondary mt-3"
class:btn-success={buttons.addAllDevices.state === 'success' ? true : false}
class:btn-warning={buttons.addAllDevices.state === 'waiting' ? true : false}
on:click={async (e) => {
e.target.disabled = true;
await addAllDevices();
}}
on:keydown={async (e) => {
e.target.disabled = true;
await addAllDevices();
}}
>
{#if buttons.addAllDevices.state === 'success'}
Added
{:else if buttons.addAllDevices.state === 'waiting'}
Adding all...
{:else}
Add all <Fa icon={faPlus} />
{/if}
</button>
{/if}
</section>
<section class="m-0 my-4 p-4 shadow-sm">
<h3 class="mb-3">Restore</h3>
<p>
If you had UpSnap &gt;=2.3.2 and &lt;3.0.0 running before, you can restore your devices
here.
</p>
<div class="callout callout-danger fw-bold">This will wipe the existing database!</div>
<input
class="form-control mb-3"
aria-label="Restore"
aria-describedby="Restore"
type="file"
accept=".json"
bind:files
/>
<button
type="button"
class="btn btn-secondary"
class:btn-success={buttons.restore.state === 'success' ? true : false}
class:btn-warning={buttons.restore.state === 'waiting' ? true : false}
class:btn-danger={buttons.restore.state === 'failed' ? true : false}
disabled={files ? false : true}
on:click={() => restoreV2Backup()}
>
{#if buttons.restore.state === 'none'}
Restore
{:else if buttons.restore.state === 'success'}
Restored
{:else if buttons.restore.state === 'waiting'}
Waiting
{:else if buttons.restore.state === 'failed'}
Failed: {buttons.restore.error}
{/if}
</button>
</section>
<p class="m-0 my-4 p-4 text-center text-muted">
{#if version !== undefined}
UpSnap version: <a
@@ -391,3 +470,9 @@
{/if}
</p>
</div>
<style lang="scss">
.icon-preview {
height: 130px;
}
</style>
+19 -2
View File
@@ -21,6 +21,10 @@ $grays: (
$body-bg-dark: $gray-1000;
$dropdown-link-active-bg: $gray-1000;
$dropdown-min-width: 0;
$form-check-input-checked-bg-color: $orange-300;
$form-check-input-checked-border-color: $orange-500;
$input-focus-border-color: $gray-500;
$input-focus-box-shadow: $gray-900;
// import rest
@import '../../node_modules/bootstrap/scss/maps';
@@ -41,6 +45,7 @@ $dropdown-min-width: 0;
@import '../../node_modules/bootstrap/scss/buttons';
@import '../../node_modules/bootstrap/scss/spinners';
@import '../../node_modules/bootstrap/scss/badge';
@import '../../node_modules/bootstrap/scss/transitions';
@import '../../node_modules/bootstrap/scss/utilities/api';
@@ -59,6 +64,12 @@ section {
}
}
.navbar-toggler {
&:focus {
box-shadow: none !important;
}
}
.btn {
border-radius: 0.5rem;
}
@@ -116,7 +127,8 @@ html[data-bs-theme='light'] {
}
section,
.card {
.card,
.login {
background: #ffffff;
}
}
@@ -128,7 +140,8 @@ html[data-bs-theme='dark'] {
}
section,
.card {
.card,
.login {
background: #25252b;
}
@@ -143,3 +156,7 @@ html[data-bs-theme='dark'] {
background-color: $gray-800;
}
}
.cursor-pointer {
cursor: pointer;
}
+11 -1
View File
@@ -1,5 +1,15 @@
export function sortDevices(a, b) {
return a.name > b.name;
return a.name.localeCompare(b.name, undefined, {
numeric: true,
sensitivity: 'base'
});
}
export function sortGroups(a, b) {
return a.localeCompare(b, undefined, {
numeric: true,
sensitivity: 'base'
});
}
export function sortPorts(a, b) {
+10 -7
View File
@@ -2,11 +2,7 @@ import { writable } from 'svelte/store';
import PocketBase from 'pocketbase';
// set backend url based on environment
let backend_url = '/';
let isDevMode = import.meta.env.DEV;
if (isDevMode) {
backend_url = 'http://127.0.0.1:8090';
}
let backend_url = import.meta.env.DEV ? 'http://127.0.0.1:8090' : '/';
// get default values for stores
const pb = new PocketBase(backend_url);
@@ -14,7 +10,14 @@ pb.autoCancellation(false);
// export stores
export const pocketbase = writable(pb);
export const settings = writable({
website_title: ''
export const settings_private = writable({
interal: '',
scan_range: ''
});
export const settings_public = writable({
website_title: '',
favicon: ''
});
export const devices = writable({});
export const groups = writable([]);
export const authorizedStore = writable(false);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.5 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 54 KiB

+1 -1
View File
@@ -17,7 +17,7 @@ const config = {
'@stores': path.resolve('./src/stores')
},
prerender: {
entries: ['/device/[id]']
entries: ['/device/[id]', '/settings', '/']
}
}
};