Compare commits

...

168 Commits

Author SHA1 Message Date
Maxi Quoß cce6823f25 feat: optional non-root docker user #207 2023-09-10 22:45:56 +02:00
seriousm4x f5f9378dd6 bump go build version to >= 1.21.1 2023-09-10 10:44:18 +02:00
seriousm4x 21d2025c8d npm-dep: update eslint, eslint-plugin-svelte 2023-09-10 10:43:20 +02:00
seriousm4x 44b5194214 go-dep: update pocketbase 0.18.3 2023-09-10 10:41:41 +02:00
dependabot[bot] e3cf66945e npm-dep: bump daisyui from 3.6.6 to 3.7.3 in /frontend
Bumps [daisyui](https://github.com/saadeghi/daisyui) from 3.6.6 to 3.7.3.
- [Changelog](https://github.com/saadeghi/daisyui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/saadeghi/daisyui/compare/v3.6.6...v3.7.3)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-07 09:39:06 +00:00
dependabot[bot] 630a77bba9 npm-dep: bump @typescript-eslint/eslint-plugin in /frontend
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 6.5.0 to 6.6.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.6.0/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-06 09:33:36 +00:00
dependabot[bot] 6e8bb4a48c npm-dep: bump @sveltejs/kit from 1.24.0 to 1.24.1 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.24.0 to 1.24.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.24.1/packages/kit)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-06 09:30:35 +00:00
dependabot[bot] c1bbdcb9c3 npm-dep: bump pocketbase from 0.17.3 to 0.18.0 in /frontend
Bumps [pocketbase](https://github.com/pocketbase/js-sdk) from 0.17.3 to 0.18.0.
- [Release notes](https://github.com/pocketbase/js-sdk/releases)
- [Changelog](https://github.com/pocketbase/js-sdk/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pocketbase/js-sdk/compare/v0.17.3...v0.18.0)

---
updated-dependencies:
- dependency-name: pocketbase
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-06 09:29:32 +00:00
dependabot[bot] b4ea1af7e9 npm-dep: bump @typescript-eslint/parser from 6.5.0 to 6.6.0 in /frontend
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 6.5.0 to 6.6.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.6.0/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-06 09:29:13 +00:00
dependabot[bot] 32e02a7ff1 go-dep: bump github.com/pocketbase/pocketbase in /backend
Bumps [github.com/pocketbase/pocketbase](https://github.com/pocketbase/pocketbase) from 0.18.0 to 0.18.1.
- [Release notes](https://github.com/pocketbase/pocketbase/releases)
- [Changelog](https://github.com/pocketbase/pocketbase/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pocketbase/pocketbase/compare/v0.18.0...v0.18.1)

---
updated-dependencies:
- dependency-name: github.com/pocketbase/pocketbase
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-06 09:28:54 +00:00
dependabot[bot] 9962bae913 npm-dep: bump daisyui from 3.6.5 to 3.6.6 in /frontend
Bumps [daisyui](https://github.com/saadeghi/daisyui) from 3.6.5 to 3.6.6.
- [Changelog](https://github.com/saadeghi/daisyui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/saadeghi/daisyui/compare/v3.6.5...v3.6.6)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-06 09:27:59 +00:00
dependabot[bot] 253b368622 npm-dep: bump daisyui from 3.6.4 to 3.6.5 in /frontend
Bumps [daisyui](https://github.com/saadeghi/daisyui) from 3.6.4 to 3.6.5.
- [Changelog](https://github.com/saadeghi/daisyui/blob/master/CHANGELOG.md)
- [Commits](https://github.com/saadeghi/daisyui/compare/v3.6.4...v3.6.5)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-05 10:04:15 +00:00
dependabot[bot] a3ee9ec884 gh-action: bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [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/v3...v4)

---
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-09-05 09:58:24 +00:00
dependabot[bot] ad8f53051a go-dep: bump github.com/pocketbase/pocketbase in /backend
Bumps [github.com/pocketbase/pocketbase](https://github.com/pocketbase/pocketbase) from 0.17.7 to 0.18.0.
- [Release notes](https://github.com/pocketbase/pocketbase/releases)
- [Changelog](https://github.com/pocketbase/pocketbase/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pocketbase/pocketbase/compare/v0.17.7...v0.18.0)

---
updated-dependencies:
- dependency-name: github.com/pocketbase/pocketbase
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-05 09:38:38 +00:00
seriousm4x 3a294726a8 feat: use native pocketbase isAdmin helper 2023-09-02 21:24:13 +02:00
seriousm4x b8a990f078 npm-dep: pnpm update 2023-09-02 21:07:23 +02:00
seriousm4x 085936a018 add workflow_dispatch 2023-09-02 20:50:34 +02:00
seriousm4x 488619f9fe Auto merge minor patches 2023-09-02 16:28:23 +02:00
dependabot[bot] b45a0dca3c npm-dep: bump svelte-check from 3.5.0 to 3.5.1 in /frontend
Bumps [svelte-check](https://github.com/sveltejs/language-tools) from 3.5.0 to 3.5.1.
- [Release notes](https://github.com/sveltejs/language-tools/releases)
- [Commits](https://github.com/sveltejs/language-tools/compare/svelte-check-3.5.0...svelte-check-3.5.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-30 09:29:58 +00:00
dependabot[bot] 5ed24e8e40 npm-dep: bump prettier from 3.0.2 to 3.0.3 in /frontend
Bumps [prettier](https://github.com/prettier/prettier) from 3.0.2 to 3.0.3.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.0.2...3.0.3)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-30 09:27:20 +00:00
dependabot[bot] 811d91b6f4 npm-dep: bump postcss from 8.4.28 to 8.4.29 in /frontend
Bumps [postcss](https://github.com/postcss/postcss) from 8.4.28 to 8.4.29.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.4.28...8.4.29)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-30 09:26:20 +00:00
dependabot[bot] fc95133c6b go-dep: bump github.com/pocketbase/pocketbase in /backend
Bumps [github.com/pocketbase/pocketbase](https://github.com/pocketbase/pocketbase) from 0.17.6 to 0.17.7.
- [Release notes](https://github.com/pocketbase/pocketbase/releases)
- [Changelog](https://github.com/pocketbase/pocketbase/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pocketbase/pocketbase/compare/v0.17.6...v0.17.7)

---
updated-dependencies:
- dependency-name: github.com/pocketbase/pocketbase
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-28 09:35:23 +00:00
dependabot[bot] 8514ea379f go-dep: bump github.com/pocketbase/pocketbase in /backend
Bumps [github.com/pocketbase/pocketbase](https://github.com/pocketbase/pocketbase) from 0.17.5 to 0.17.6.
- [Release notes](https://github.com/pocketbase/pocketbase/releases)
- [Changelog](https://github.com/pocketbase/pocketbase/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pocketbase/pocketbase/compare/v0.17.5...v0.17.6)

---
updated-dependencies:
- dependency-name: github.com/pocketbase/pocketbase
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-22 09:41:37 +00:00
dependabot[bot] 8102da5a7e npm-dep: bump @typescript-eslint/eslint-plugin in /frontend
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 6.4.0 to 6.4.1.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.4.1/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-22 09:40:44 +00:00
Maxi Quoß 5e6d7761aa run codeberg sync on tag push 2023-08-22 00:52:26 +02:00
Maxi Quoß 60837d2dd7 fix: remove btn margin 2023-08-21 20:21:06 +02:00
Maxi Quoß 59f1bf3f9c fix: re-add forgotten oidc login #103 2023-08-21 20:17:54 +02:00
Maxi Quoß 448dcbd16c fix: put more buttons into array 2023-08-21 17:35:16 +02:00
dependabot[bot] 88d8a4b952 npm-dep: bump tslib from 2.6.1 to 2.6.2 in /frontend
Bumps [tslib](https://github.com/Microsoft/tslib) from 2.6.1 to 2.6.2.
- [Release notes](https://github.com/Microsoft/tslib/releases)
- [Commits](https://github.com/Microsoft/tslib/compare/v2.6.1...v2.6.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-21 09:44:39 +00:00
seriousm4x d7b4ef75de remove tailing dots on toast messages 2023-08-19 00:23:07 +02:00
seriousm4x 84deb379e7 fix: break device name line on small screens 2023-08-19 00:17:37 +02:00
seriousm4x 109f374269 feat: network scan: replace netmask for all devices #169 2023-08-18 14:19:08 +02:00
seriousm4x a2d09762b3 fix: let svelte know the type of PUBLIC_VERSION 2023-08-18 13:53:18 +02:00
seriousm4x f83babb494 include .env 2023-08-18 13:51:31 +02:00
Maxi Quoß 36878ee42b fix: account dropdown items could overflow 2023-08-18 11:01:44 +02:00
dependabot[bot] c6e8eee77d go-dep: bump github.com/pocketbase/dbx from 1.10.0 to 1.10.1 in /backend
Bumps [github.com/pocketbase/dbx](https://github.com/pocketbase/dbx) from 1.10.0 to 1.10.1.
- [Release notes](https://github.com/pocketbase/dbx/releases)
- [Commits](https://github.com/pocketbase/dbx/compare/v1.10.0...v1.10.1)

---
updated-dependencies:
- dependency-name: github.com/pocketbase/dbx
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-17 09:48:33 +00:00
dependabot[bot] e098b0ba5d npm-dep: bump postcss from 8.4.27 to 8.4.28 in /frontend
Bumps [postcss](https://github.com/postcss/postcss) from 8.4.27 to 8.4.28.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.4.27...8.4.28)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-16 17:06:08 +00:00
Maxi Quoß 46c7870be4 auto publish new releases 2023-08-16 19:05:38 +02:00
Maxi Quoß a5cf8d718c fix: title too long for mobile layout, close #168 2023-08-16 19:04:35 +02:00
Maxi Quoß 79c048319d remove redundant 2023-08-16 12:23:53 +02:00
Maxi Quoß 4830f43bab upgrade docker-compose to version 4 2023-08-16 12:17:59 +02:00
dependabot[bot] 3b6f6abb1c npm-dep: bump prettier from 3.0.1 to 3.0.2 in /frontend
Bumps [prettier](https://github.com/prettier/prettier) from 3.0.1 to 3.0.2.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.0.1...3.0.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-16 09:13:20 +00:00
seriousm4x 15a5663934 fix: clear authstore if setup not completed 2023-08-16 11:02:13 +02:00
seriousm4x 834c42ba75 fix: frontend version var 2023-08-16 10:56:22 +02:00
seriousm4x d7b18c8513 fix: only stop cron if cron is running 2023-08-16 10:55:53 +02:00
seriousm4x c335903233 fix: only show sleep when device is online 2023-08-16 09:59:41 +02:00
seriousm4x d57520c66d feat: add reboot button, #108 2023-08-16 09:49:36 +02:00
seriousm4x 8d2e3a5ade Update .goreleaser.yaml 2023-08-16 02:32:13 +02:00
seriousm4x 733d6d519f feat: gracefully stop cron on terminate 2023-08-16 01:57:27 +02:00
seriousm4x 05686bf271 fix: ping port cause device stuck on pending 2023-08-16 01:28:13 +02:00
seriousm4x a237fba8c7 fix: broken nic timer (again) 2023-08-16 00:56:01 +02:00
seriousm4x b8fdb4202f feat: only refresh jwt if valid less than 1 day 2023-08-15 18:17:06 +02:00
seriousm4x 7b5dddfc06 fix: make sol port non-required 2023-08-15 18:15:46 +02:00
seriousm4x f8186ba015 feat: add sleep-on-lan support, #24 #78 #108 #162 2023-08-15 17:44:59 +02:00
seriousm4x b2f2dfdcf9 Merge pull request #163 from seriousm4x/dependabot/npm_and_yarn/frontend/typescript-eslint/eslint-plugin-6.4.0
npm-dep: bump @typescript-eslint/eslint-plugin from 6.3.0 to 6.4.0 in /frontend
2023-08-15 14:51:24 +02:00
dependabot[bot] 5270661bb5 npm-dep: bump @typescript-eslint/eslint-plugin in /frontend
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 6.3.0 to 6.4.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.4.0/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-15 12:50:54 +00:00
seriousm4x 67ea231f39 Merge pull request #164 from seriousm4x/dependabot/npm_and_yarn/frontend/typescript-eslint/parser-6.4.0
npm-dep: bump @typescript-eslint/parser from 6.3.0 to 6.4.0 in /frontend
2023-08-15 14:48:57 +02:00
Maxi Quoß 58d497eab1 try avoid loop variable capture 2023-08-15 14:30:33 +02:00
seriousm4x e52d7f44b2 fix: properly reset nic timer 2023-08-15 14:26:25 +02:00
dependabot[bot] 6982184ab6 go-dep: bump github.com/pocketbase/pocketbase in /backend
Bumps [github.com/pocketbase/pocketbase](https://github.com/pocketbase/pocketbase) from 0.17.4 to 0.17.5.
- [Release notes](https://github.com/pocketbase/pocketbase/releases)
- [Changelog](https://github.com/pocketbase/pocketbase/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pocketbase/pocketbase/compare/v0.17.4...v0.17.5)

---
updated-dependencies:
- dependency-name: github.com/pocketbase/pocketbase
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-15 10:04:04 +00:00
dependabot[bot] 4009a5c3e1 npm-dep: bump @typescript-eslint/parser from 6.3.0 to 6.4.0 in /frontend
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 6.3.0 to 6.4.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.4.0/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-15 09:37:45 +00:00
seriousm4x a55152250b reset timeout 2023-08-14 20:39:39 +02:00
seriousm4x bccbb9420c fix: simplify nic click logic 2023-08-14 17:48:10 +02:00
seriousm4x d3478026c2 fix no records shown with multiple users 2023-08-14 17:17:08 +02:00
seriousm4x 3fe17d1156 add buttons to toggle permissions 2023-08-14 17:09:42 +02:00
seriousm4x 2dab56e19e pnpm format 2023-08-14 16:15:50 +02:00
seriousm4x d9b14adc8d add lazy ping option 2023-08-14 16:10:55 +02:00
seriousm4x c1dbde574a fix nic tooltip 2023-08-14 15:24:34 +02:00
Maxi Quoß a39bf0e2f4 fix logic error 2023-08-14 11:44:47 +02:00
dependabot[bot] 37c25bb383 npm-dep: bump @sveltejs/kit from 1.22.5 to 1.22.6 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.22.5 to 1.22.6.
- [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.22.6/packages/kit)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-14 09:40:09 +00:00
dependabot[bot] e866b008ee npm-dep: bump autoprefixer from 10.4.14 to 10.4.15 in /frontend
Bumps [autoprefixer](https://github.com/postcss/autoprefixer) from 10.4.14 to 10.4.15.
- [Release notes](https://github.com/postcss/autoprefixer/releases)
- [Changelog](https://github.com/postcss/autoprefixer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/autoprefixer/compare/10.4.14...10.4.15)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-14 09:38:59 +00:00
seriousm4x 904b167c8e use pnpm for build 2023-08-14 02:49:48 +02:00
seriousm4x f9e8438297 update readme and screenshots 2023-08-14 02:44:30 +02:00
seriousm4x 390d077644 fix home spacing, fix create dev as admin 2023-08-14 02:16:46 +02:00
seriousm4x 2a90457e29 order by groups if localstorage unset 2023-08-14 01:48:48 +02:00
seriousm4x 9481fd10af better gap spacing 2023-08-14 01:12:37 +02:00
seriousm4x d5ecbadbcc fix order by when groups activated 2023-08-14 01:01:23 +02:00
seriousm4x 8155a9a19f remove dark theme overwrite 2023-08-14 00:53:11 +02:00
seriousm4x a79c1bf028 port ports by number 2023-08-14 00:52:42 +02:00
seriousm4x af021aefa7 show correct avatar for other users 2023-08-14 00:44:47 +02:00
seriousm4x 2d6cf95647 fix avatar update 2023-08-14 00:40:36 +02:00
seriousm4x 541e8b3d8b rename workflow 2023-08-14 00:14:13 +02:00
seriousm4x 77a73a91be add required field 2023-08-14 00:09:34 +02:00
seriousm4x 81cc067b3d actually fix build 2023-08-14 00:01:29 +02:00
seriousm4x cd94895b93 fix build 2023-08-13 23:53:15 +02:00
seriousm4x 311684f05f rename permissions to users, add create new user 2023-08-13 23:17:53 +02:00
seriousm4x 870d2dcc49 improve /login and /welcome 2023-08-13 20:00:13 +02:00
seriousm4x 2cc191336b improve navbar menus 2023-08-13 19:36:17 +02:00
seriousm4x a4c7fd4e39 use form for scan range 2023-08-13 19:26:23 +02:00
seriousm4x 6794091617 add account page 2023-08-13 19:19:22 +02:00
seriousm4x 24aec5e1de define possible device.status values 2023-08-13 19:19:12 +02:00
seriousm4x ef5329f8f7 remove prettier plugin-search-dir 2023-08-12 21:56:34 +02:00
seriousm4x e61a7f9464 npm-dep: update all 2023-08-12 21:53:38 +02:00
seriousm4x 4a80618320 cleanup merge errors 2023-08-12 21:11:02 +02:00
dependabot[bot] da6c822a9c go-dep: bump github.com/pocketbase/pocketbase in /backend
Bumps [github.com/pocketbase/pocketbase](https://github.com/pocketbase/pocketbase) from 0.17.0 to 0.17.4.
- [Release notes](https://github.com/pocketbase/pocketbase/releases)
- [Changelog](https://github.com/pocketbase/pocketbase/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pocketbase/pocketbase/compare/v0.17.0...v0.17.4)

---
updated-dependencies:
- dependency-name: github.com/pocketbase/pocketbase
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 19:09:39 +00:00
dependabot[bot] b6a2b085d9 npm-dep: bump @sveltejs/kit from 1.22.4 to 1.22.5 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.22.4 to 1.22.5.
- [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.22.5/packages/kit)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:56 +02:00
dependabot[bot] e49f2d08b0 npm-dep: bump vite from 4.4.8 to 4.4.9 in /frontend
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.4.8 to 4.4.9.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.4.9/packages/vite)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:55 +02:00
dependabot[bot] 15d52e4c76 npm-dep: bump @fortawesome/free-solid-svg-icons in /frontend
Bumps [@fortawesome/free-solid-svg-icons](https://github.com/FortAwesome/Font-Awesome) from 6.4.0 to 6.4.2.
- [Release notes](https://github.com/FortAwesome/Font-Awesome/releases)
- [Changelog](https://github.com/FortAwesome/Font-Awesome/blob/6.x/CHANGELOG.md)
- [Commits](https://github.com/FortAwesome/Font-Awesome/compare/6.4.0...6.4.2)

---
updated-dependencies:
- dependency-name: "@fortawesome/free-solid-svg-icons"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:52 +02:00
dependabot[bot] 323f6794e1 npm-dep: bump sass from 1.64.1 to 1.64.2 in /frontend
Bumps [sass](https://github.com/sass/dart-sass) from 1.64.1 to 1.64.2.
- [Release notes](https://github.com/sass/dart-sass/releases)
- [Changelog](https://github.com/sass/dart-sass/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sass/dart-sass/compare/1.64.1...1.64.2)

---
updated-dependencies:
- dependency-name: sass
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:44 +02:00
dependabot[bot] ae19470f0f npm-dep: bump @sveltejs/kit from 1.22.3 to 1.22.4 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.22.3 to 1.22.4.
- [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.22.4/packages/kit)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:41 +02:00
dependabot[bot] d53ee6836b npm-dep: bump vite from 4.4.7 to 4.4.8 in /frontend
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.4.7 to 4.4.8.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.4.8/packages/vite)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:36 +02:00
dependabot[bot] 569d2650ea npm-dep: bump svelte from 4.1.1 to 4.1.2 in /frontend
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 4.1.1 to 4.1.2.
- [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.1.2/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-08-12 21:05:32 +02:00
dependabot[bot] 6d7441473a npm-dep: bump @sveltejs/adapter-static from 2.0.2 to 2.0.3 in /frontend
Bumps [@sveltejs/adapter-static](https://github.com/sveltejs/kit/tree/HEAD/packages/adapter-static) from 2.0.2 to 2.0.3.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/master/packages/adapter-static/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/adapter-static@2.0.3/packages/adapter-static)

---
updated-dependencies:
- dependency-name: "@sveltejs/adapter-static"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:29 +02:00
dependabot[bot] d8cb3ec00a npm-dep: bump bootstrap from 5.3.0 to 5.3.1 in /frontend
Bumps [bootstrap](https://github.com/twbs/bootstrap) from 5.3.0 to 5.3.1.
- [Release notes](https://github.com/twbs/bootstrap/releases)
- [Commits](https://github.com/twbs/bootstrap/compare/v5.3.0...v5.3.1)

---
updated-dependencies:
- dependency-name: bootstrap
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:27 +02:00
dependabot[bot] acee769474 npm-dep: bump vite from 4.4.6 to 4.4.7 in /frontend
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.4.6 to 4.4.7.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.4.7/packages/vite)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:24 +02:00
dependabot[bot] da5a1dae04 npm-dep: bump sass from 1.64.0 to 1.64.1 in /frontend
Bumps [sass](https://github.com/sass/dart-sass) from 1.64.0 to 1.64.1.
- [Release notes](https://github.com/sass/dart-sass/releases)
- [Changelog](https://github.com/sass/dart-sass/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sass/dart-sass/compare/1.64.0...1.64.1)

---
updated-dependencies:
- dependency-name: sass
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-12 21:05:20 +02:00
seriousm4x ab13daef40 better mobile view 2023-08-12 21:05:18 +02:00
seriousm4x e5e710f1b9 multiple fixes 2023-08-12 21:05:17 +02:00
seriousm4x 054f9ef643 match dark theme with cupcake 2023-08-12 21:05:17 +02:00
seriousm4x 67d957c109 add permission page, close #75 2023-08-12 21:05:17 +02:00
seriousm4x 9d2871eae9 improve theme colors 2023-08-12 21:05:17 +02:00
seriousm4x d801f7c2da npm-dep: update all 2023-08-12 21:05:16 +02:00
seriousm4x 768be7ce15 update web ui to match backend permissions #75 2023-08-12 21:05:14 +02:00
seriousm4x 6fc02ce46d add user permissions to backend #75 2023-08-12 21:05:14 +02:00
seriousm4x 00a098b7c8 make port fields required 2023-08-12 21:05:14 +02:00
seriousm4x 5e417f6220 better admin check 2023-08-12 21:05:14 +02:00
seriousm4x 4b36131a8c required form fields and margin 2023-08-12 21:05:14 +02:00
seriousm4x 7e8b570f1c added toast notifications 2023-08-12 21:05:12 +02:00
seriousm4x 1cc232e6c6 improve group buttons 2023-08-12 21:05:10 +02:00
seriousm4x 97d0aab2f5 change default dark theme 2023-08-12 21:05:10 +02:00
seriousm4x 318f76f439 add dashboard order 2023-08-12 21:05:10 +02:00
seriousm4x eee83b5cb8 add empty permissions route 2023-08-12 21:05:10 +02:00
seriousm4x 54191b76e5 several button improvements 2023-08-12 21:05:10 +02:00
seriousm4x 550bf74438 adjust nav padding 2023-08-12 21:05:09 +02:00
seriousm4x 89bb99e78c fix save icon 2023-08-12 21:05:09 +02:00
seriousm4x 413a2a8f30 add theming 2023-08-12 21:05:09 +02:00
seriousm4x ac15e39ae1 delete forgotten device store things 2023-08-12 21:05:09 +02:00
seriousm4x 1602136eeb settings: add icon, change color 2023-08-12 21:05:09 +02:00
seriousm4x b04029abf9 ux improvements for network scan 2023-08-12 21:05:09 +02:00
seriousm4x adf2936ab8 add network scan 2023-08-12 21:05:09 +02:00
seriousm4x 94111846f4 ux improvements 2023-08-12 21:05:09 +02:00
seriousm4x 6099b67d4b show countdown for wake/shutdown 2023-08-12 21:05:09 +02:00
seriousm4x 19e3c63fa7 various small changes 2023-08-12 21:05:08 +02:00
seriousm4x 90baf0aef8 improve home loading, remove $devices store 2023-08-12 21:05:08 +02:00
seriousm4x 3ffd3c6a41 simplify fetch on edit page 2023-08-12 21:05:08 +02:00
seriousm4x 18046b6db6 reuse device form, simplify realtime updates 2023-08-12 21:05:07 +02:00
seriousm4x 5b112d81ad go-dep: update all 2023-08-12 21:05:05 +02:00
seriousm4x 689b96bf11 npm-dep: update all 2023-08-12 21:05:02 +02:00
seriousm4x da63e134d6 add settings page 2023-08-12 21:04:58 +02:00
Maxi Quoß 1c06774617 no hover if no shutdown:_cmd, move required fields 2023-08-12 21:04:58 +02:00
Maxi Quoß 522f5916b1 add spacing between sections 2023-08-12 21:04:58 +02:00
seriousm4x 39b2cc62eb improve ts 2023-08-12 21:04:58 +02:00
seriousm4x da3f424019 add page transitions 2023-08-12 21:04:58 +02:00
seriousm4x a875613b76 finish device edit, fix navbar 2023-08-12 21:04:58 +02:00
seriousm4x de2d86f752 cleanup 2023-08-12 21:04:56 +02:00
seriousm4x ef69268736 more changes to device settings 2023-08-12 21:04:54 +02:00
seriousm4x deac242e74 add multiple nics to device card 2023-08-12 21:04:50 +02:00
seriousm4x 90eccbc5b5 add home grid and adjust nav 2023-08-12 21:04:50 +02:00
seriousm4x 4d682e073f first commit for tailwind rewrite
- uses daisyUI
- signup, login and logout is done (need some more testing)
2023-08-12 21:04:47 +02:00
dependabot[bot] 0dbf7033f4 npm-dep: bump @sveltejs/kit from 1.22.4 to 1.22.5 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.22.4 to 1.22.5.
- [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.22.5/packages/kit)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-11 09:23:18 +00:00
dependabot[bot] 024f749aa4 npm-dep: bump vite from 4.4.8 to 4.4.9 in /frontend
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.4.8 to 4.4.9.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.4.9/packages/vite)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-08 09:28:59 +00:00
dependabot[bot] 1977a255bf npm-dep: bump @fortawesome/free-solid-svg-icons in /frontend
Bumps [@fortawesome/free-solid-svg-icons](https://github.com/FortAwesome/Font-Awesome) from 6.4.0 to 6.4.2.
- [Release notes](https://github.com/FortAwesome/Font-Awesome/releases)
- [Changelog](https://github.com/FortAwesome/Font-Awesome/blob/6.x/CHANGELOG.md)
- [Commits](https://github.com/FortAwesome/Font-Awesome/compare/6.4.0...6.4.2)

---
updated-dependencies:
- dependency-name: "@fortawesome/free-solid-svg-icons"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-03 09:36:44 +00:00
dependabot[bot] 53ded6888e npm-dep: bump sass from 1.64.1 to 1.64.2 in /frontend
Bumps [sass](https://github.com/sass/dart-sass) from 1.64.1 to 1.64.2.
- [Release notes](https://github.com/sass/dart-sass/releases)
- [Changelog](https://github.com/sass/dart-sass/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sass/dart-sass/compare/1.64.1...1.64.2)

---
updated-dependencies:
- dependency-name: sass
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-02 09:38:15 +00:00
dependabot[bot] 2b8e2669d0 npm-dep: bump @sveltejs/kit from 1.22.3 to 1.22.4 in /frontend
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 1.22.3 to 1.22.4.
- [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.22.4/packages/kit)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-02 09:37:39 +00:00
dependabot[bot] 29a45afd81 npm-dep: bump vite from 4.4.7 to 4.4.8 in /frontend
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.4.7 to 4.4.8.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.4.8/packages/vite)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-02 09:36:30 +00:00
dependabot[bot] e13504ec6c npm-dep: bump svelte from 4.1.1 to 4.1.2 in /frontend
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 4.1.1 to 4.1.2.
- [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.1.2/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-08-01 10:08:18 +00:00
dependabot[bot] f5231ecd3d npm-dep: bump @sveltejs/adapter-static from 2.0.2 to 2.0.3 in /frontend
Bumps [@sveltejs/adapter-static](https://github.com/sveltejs/kit/tree/HEAD/packages/adapter-static) from 2.0.2 to 2.0.3.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/master/packages/adapter-static/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/adapter-static@2.0.3/packages/adapter-static)

---
updated-dependencies:
- dependency-name: "@sveltejs/adapter-static"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-28 09:34:18 +00:00
dependabot[bot] 7615a26d3f npm-dep: bump bootstrap from 5.3.0 to 5.3.1 in /frontend
Bumps [bootstrap](https://github.com/twbs/bootstrap) from 5.3.0 to 5.3.1.
- [Release notes](https://github.com/twbs/bootstrap/releases)
- [Commits](https://github.com/twbs/bootstrap/compare/v5.3.0...v5.3.1)

---
updated-dependencies:
- dependency-name: bootstrap
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-26 09:55:11 +00:00
dependabot[bot] af03b54b3b npm-dep: bump vite from 4.4.6 to 4.4.7 in /frontend
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.4.6 to 4.4.7.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.4.7/packages/vite)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-25 09:13:51 +00:00
dependabot[bot] 43a4485926 npm-dep: bump sass from 1.64.0 to 1.64.1 in /frontend
Bumps [sass](https://github.com/sass/dart-sass) from 1.64.0 to 1.64.1.
- [Release notes](https://github.com/sass/dart-sass/releases)
- [Changelog](https://github.com/sass/dart-sass/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sass/dart-sass/compare/1.64.0...1.64.1)

---
updated-dependencies:
- dependency-name: sass
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-24 09:38:23 +00:00
seriousm4x 977a923936 add other commits to changelog 2023-07-21 20:20:11 +02:00
dependabot[bot] 95f134eb27 npm-dep: bump eslint-plugin-svelte from 2.32.3 to 2.32.4 in /frontend
Bumps [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte) from 2.32.3 to 2.32.4.
- [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.3...v2.32.4)

---
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-21 18:05:31 +00:00
seriousm4x cb14a87783 npm-dep: update 2023-07-21 20:03:52 +02:00
seriousm4x 9fdfc8ad0b error check all database writes (debug for #135) 2023-07-21 20:02:11 +02:00
dependabot[bot] 04a4299930 npm-dep: bump svelte from 4.1.0 to 4.1.1 in /frontend
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 4.1.0 to 4.1.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.1.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-07-21 10:01:58 +00:00
dependabot[bot] ad6c2afbc2 npm-dep: bump eslint-plugin-svelte from 2.32.2 to 2.32.3 in /frontend
Bumps [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte) from 2.32.2 to 2.32.3.
- [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.2...v2.32.3)

---
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-20 09:18:29 +00:00
seriousm4x bc1d8c8e6f nicer changelogs 2023-07-20 01:37:38 +02:00
seriousm4x d1f3d38835 no more auto merge commits 2023-07-20 01:37:25 +02:00
110 changed files with 5523 additions and 10062 deletions
+2
View File
@@ -2,6 +2,8 @@
.gitignore
.dockerignore
Dockerfile
Dockerfile.dev
data
README.md
frontend/.svelte-kit
+7 -1
View File
@@ -6,13 +6,19 @@ updates:
schedule:
interval: daily
open-pull-requests-limit: 10
commit-message:
prefix: go-dep
- package-ecosystem: npm
directory: "/frontend"
schedule:
interval: daily
open-pull-requests-limit: 10
commit-message:
prefix: npm-dep
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
open-pull-requests-limit: 10
commit-message:
prefix: gh-action
+3 -1
View File
@@ -3,12 +3,14 @@ name: Mirror Sync
on:
push:
branches: ["master"]
tags:
- '*'
workflow_dispatch:
jobs:
codeberg:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: pixta-dev/repository-mirroring-action@v1
+5 -3
View File
@@ -1,5 +1,7 @@
name: Dependabot auto-merge
on: pull_request
on:
pull_request:
workflow_dispatch:
permissions:
contents: write
@@ -16,8 +18,8 @@ jobs:
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"
if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} || ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}}
run: gh pr merge --auto --rebase "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
@@ -1,9 +1,9 @@
name: v3 build
name: release
on:
push:
tags:
- "3.*.*"
- "*.*.*"
workflow_dispatch:
jobs:
@@ -12,7 +12,7 @@ jobs:
steps:
# pull code
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0
@@ -25,15 +25,16 @@ jobs:
# build sveltekit frontend
- name: Build frontend
run: |
npm --prefix=./frontend i
UPSNAP_VERSION=${GITHUB_REF##*/} npm --prefix=./frontend run build
npm i -g pnpm
pnpm --prefix=./frontend i
PUBLIC_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
cp -r ./frontend/build/* ./backend/pb_public/
# setup go
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: ">=1.20"
go-version: ">=1.21.1"
# build
- name: Run GoReleaser
@@ -52,7 +53,7 @@ jobs:
steps:
# pull code
- name: Check Out Repo
uses: actions/checkout@v3
uses: actions/checkout@v4
# image tags
- name: Docker meta
+2 -1
View File
@@ -100,7 +100,7 @@ web_modules/
.yarn-integrity
# dotenv environment variable files
.env
#.env
.env.development.local
.env.test.local
.env.production.local
@@ -193,6 +193,7 @@ package
# End of https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
build
data
backend/pb_data
backend/pb_public/*
+24
View File
@@ -0,0 +1,24 @@
FROM node:alpine as node
WORKDIR /app
COPY frontend/ .
RUN npm i -g pnpm &&\
pnpm i &&\
pnpm run build
FROM golang:alpine as go
WORKDIR /app
COPY backend/ .
COPY --from=node /app/build ./pb_public
ENV CGO_ENABLED=0
RUN go build -o upsnap main.go &&\
chmod +x upsnap
FROM alpine:3
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
rm -rf /var/cache/apk/*
WORKDIR /app
COPY --from=go /app/upsnap upsnap
HEALTHCHECK --interval=10s \
CMD curl -fs "http://localhost:8090/api/health" || exit 1
ENTRYPOINT ["./upsnap", "serve", "--http=0.0.0.0:8090"]
+23 -38
View File
@@ -4,33 +4,36 @@
<div align="center" width="100%">
<h2>UpSnap</h2>
<p>A simple wake on lan web app written with SvelteKit, Go, PocketBase and nmap.</p>
<p>A simple wake on lan web app written with SvelteKit, Go and PocketBase.</p>
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/upsnap" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/downloads/seriousm4x/upsnap/total" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/go-mod/go-version/seriousm4x/UpSnap?filename=backend/go.mod" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/v/release/seriousm4x/upsnap?display_name=tag" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/deploy.yml/badge.svg?event=push" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/release.yml/badge.svg?event=push" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
</div>
## ✨ Features
- Dashboard to wake up devices with one click
- Set timed wake and shutdown events via cron
- Add custom ports to devices which will be pinged
- Discover devices by scanning network
- User/Password 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
- 🚀 One-Click Device Wake-Up Dashboard
- ⏰ Timed Events via Cron for Automation
- 🔌 Ping Any Port You Choose
- 🔍 Discover Devices with Network Scanning (nmap required)
- 👤 Secured User Management
- 🎨 29 Themes
- 🐳 [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7, arm/v6
- 🏠 Self-Hostable, No Cloud Bullshit!
## 📸 Screenshots
| Dark | Light |
| ------------------------------ | ------------------------------- |
| ![](/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) |
| Dark | Light |
| --------------------------------- | ---------------------------------- |
| ![](/assets/home-dark.webp) | ![](/assets/home-light.webp) |
| ![](/assets/account-dark.webp) | ![](/assets/account-light.webp) |
| ![](/assets/new-manual-dark.webp) | ![](/assets/new-manual-light.webp) |
| ![](/assets/new-scan-dark.webp) | ![](/assets/new-scan-light.webp) |
| ![](/assets/settings-dark.webp) | ![](/assets/settings-light.webp) |
| ![](/assets/users-dark.webp) | ![](/assets/users-light.webp) |
## 🚀 Run the binary
@@ -38,7 +41,7 @@ Just download the latest binary from the [release page](https://github.com/serio
For more options check `./upsnap --help` or visit [PocketBase documentation](https://pocketbase.io/docs).
If you need network discovery, make sure to have `nmap` installed and run upsnap as root/admin.
If you want to use network discovery, make sure to have `nmap` installed and run UpSnap as root/admin.
## 🐳 Run in docker
@@ -49,8 +52,8 @@ 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
test: curl -fs "http://localhost:5000/api/health" || exit 1
interval: 10s
```
And if you need additional packages inside the container, do this:
@@ -71,27 +74,9 @@ upsnap.example.com {
}
```
## 🔒 Authorisation
## 🔒 User permissions
**Since version 3.1 authorisation is enabled by default.**
User management is done through the PocketBase webinterface at [http://localhost:8090/\_/](http://localhost:8090/_/). This is mainly for internal use, such as within a home or corporate network. For external use please see below.
- To manage users, click the "Collections" icon on the left and select "users".
- To manage admins, click the "Settings" icon on the left and select "Admin".
Api permissions listed by user role:
| Api | Unauthorized | Users | Admins |
| ---------------- | ------------ | ----- | ------ |
| List/Search Rule | ❌ | ✅ | ✅ |
| View Rule | ❌ | ✅ | ✅ |
| Create Rule | ❌ | ❌ | ✅ |
| Delete Rule | ❌ | ❌ | ✅ |
| Manage Rule | ❌ | ❌ | ✅ |
| Wake devices | ❌ | ✅ | ✅ |
| Shutdown devices | ❌ | ✅ | ✅ |
| Scan network | ❌ | ❌ | ✅ |
UpSnap offers unique access for each user, per device. While admins have all permissions, they can assign specific rights to users such as displaying/hiding a device, accessing device editing, deleting and powering devices on/off.
## 🌍 Exposing to the open web
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 326 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 324 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
for i in *.png; do
magick -quality 100 "$i" "$(basename "$i" .png)".webp
rm "$i"
done
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 690 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 696 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+21 -2
View File
@@ -1,5 +1,5 @@
release:
# draft: true
#draft: true
prerelease: auto
before:
hooks:
@@ -9,7 +9,7 @@ builds:
env:
- CGO_ENABLED=0
ldflags:
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Version }}
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Tag }}
goos:
- linux
- windows
@@ -33,4 +33,23 @@ checksum:
snapshot:
name_template: "{{ .Version }}"
changelog:
use: github
sort: asc
groups:
- title: Features
regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
order: 0
- title: "Bug fixes"
regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$'
order: 1
- title: "Go dependencies"
regexp: '^.*?go-dep(\([[:word:]]+\))??!?:.+$'
order: 2
- title: "Npm dependencies"
regexp: '^.*?npm-dep(\([[:word:]]+\))??!?:.+$'
order: 3
- title: "Github Actions"
regexp: '^.*?gh-action(\([[:word:]]+\))??!?:.+$'
order: 4
- title: Others
order: 999
+88 -40
View File
@@ -8,11 +8,14 @@ import (
"github.com/seriousm4x/upsnap/networking"
)
var Devices []*models.Record
var PingRunning bool = false
var WakeShutdownRunning bool = false
var CronPing *cron.Cron
var CronWakeShutdown *cron.Cron
func RunPing(app *pocketbase.PocketBase) {
PingRunning = true
settingsPrivateRecords, err := app.Dao().FindRecordsByExpr("settings_private")
if err != nil {
logger.Error.Println(err)
@@ -21,51 +24,66 @@ func RunPing(app *pocketbase.PocketBase) {
// init cronjob
CronPing = cron.New()
CronPing.AddFunc(settingsPrivateRecords[0].GetString("interval"), func() {
// skip cron if no realtime clients connected
// skip cron if no realtime clients connected and lazy_ping is turned on
realtimeClients := len(app.SubscriptionsBroker().Clients())
if realtimeClients == 0 {
if realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping") {
return
}
devices, err := app.Dao().FindRecordsByExpr("devices")
if err != nil {
logger.Error.Println(err)
return
}
// expand ports field
expandFetchFunc := func(c *models.Collection, ids []string) ([]*models.Record, error) {
return app.Dao().FindRecordsByIds(c.Id, ids, nil)
}
merr := app.Dao().ExpandRecords(Devices, []string{"ports"}, expandFetchFunc)
merr := app.Dao().ExpandRecords(devices, []string{"ports"}, expandFetchFunc)
if len(merr) > 0 {
return
}
for _, device := range Devices {
// ping
go func(device *models.Record) {
oldStatus := device.Get("status")
newStatus := networking.PingDevice(device)
if newStatus {
if oldStatus == "offline" || oldStatus == "" {
device.Set("status", "online")
app.Dao().SaveRecord(device)
for _, device := range devices {
// ping device
go func(d *models.Record) {
status := d.GetString("status")
if status == "pending" {
return
}
if networking.PingDevice(d) {
if status == "online" {
return
}
d.Set("status", "online")
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
} else {
if oldStatus == "online" || oldStatus == "" {
device.Set("status", "offline")
app.Dao().SaveRecord(device)
if status == "offline" {
return
}
d.Set("status", "offline")
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}
}(device)
// scan ports
go func(device *models.Record) {
ports, err := app.Dao().FindRecordsByIds("ports", device.GetStringSlice("ports"))
// ping ports
go func(d *models.Record) {
ports, err := app.Dao().FindRecordsByIds("ports", d.GetStringSlice("ports"))
if err != nil {
logger.Error.Println(err)
}
for _, port := range ports {
isUp := networking.CheckPort(device.GetString("ip"), port.GetString("number"))
isUp := networking.CheckPort(d.GetString("ip"), port.GetString("number"))
if isUp != port.GetBool("status") {
port.Set("status", isUp)
app.Dao().SaveRecord(port)
device.RefreshUpdated()
app.Dao().SaveRecord(device)
if err := app.Dao().SaveRecord(port); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}
}
}(device)
@@ -75,56 +93,86 @@ func RunPing(app *pocketbase.PocketBase) {
}
func RunWakeShutdown(app *pocketbase.PocketBase) {
WakeShutdownRunning = true
CronWakeShutdown = cron.New()
for _, device := range Devices {
wake_cron := device.GetString("wake_cron")
wake_cron_enabled := device.GetBool("wake_cron_enabled")
shutdown_cron := device.GetString("shutdown_cron")
shutdown_cron_enabled := device.GetBool("shutdown_cron_enabled")
devices, err := app.Dao().FindRecordsByExpr("devices")
if err != nil {
logger.Error.Println(err)
return
}
for _, device := range devices {
dev := device
wake_cron := dev.GetString("wake_cron")
wake_cron_enabled := dev.GetBool("wake_cron_enabled")
shutdown_cron := dev.GetString("shutdown_cron")
shutdown_cron_enabled := dev.GetBool("shutdown_cron_enabled")
if wake_cron_enabled && wake_cron != "" {
// avoid using last element
// https://github.com/robfig/cron/issues/115
go func(d *models.Record) {
_, err := CronWakeShutdown.AddFunc(wake_cron, func() {
d.Set("status", "pending")
app.Dao().SaveRecord(d)
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
if err := networking.WakeDevice(d); err != nil {
logger.Error.Println(err)
d.Set("status", "offline")
app.Dao().SaveRecord(d)
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
} else {
d.Set("status", "online")
app.Dao().SaveRecord(d)
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}
})
if err != nil {
logger.Error.Println(err)
}
}(device)
}(dev)
}
if shutdown_cron_enabled && shutdown_cron != "" {
// avoid using last element
// https://github.com/robfig/cron/issues/115
go func(d *models.Record) {
_, err := CronWakeShutdown.AddFunc(shutdown_cron, func() {
d.Set("status", "pending")
app.Dao().SaveRecord(d)
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
if err := networking.ShutdownDevice(d); err != nil {
logger.Error.Println(err)
d.Set("status", "online")
app.Dao().SaveRecord(d)
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
} else {
d.Set("status", "offline")
app.Dao().SaveRecord(d)
if err := app.Dao().SaveRecord(d); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}
})
if err != nil {
logger.Error.Println(err)
}
}(device)
}(dev)
}
}
CronWakeShutdown.Run()
}
func StopAll() {
if PingRunning {
logger.Info.Println("stopping ping cronjob")
ctx := CronPing.Stop()
<-ctx.Done()
}
if WakeShutdownRunning {
logger.Info.Println("stopping wake/shutdown cronjob")
ctx := CronWakeShutdown.Stop()
<-ctx.Done()
}
}
+46 -44
View File
@@ -1,12 +1,14 @@
module github.com/seriousm4x/upsnap
go 1.19
go 1.21
toolchain go1.21.1
require (
github.com/labstack/echo/v5 v5.0.0-20220201181537-ed2888cfa198
github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
github.com/pocketbase/dbx v1.10.0
github.com/pocketbase/pocketbase v0.16.10
github.com/pocketbase/dbx v1.10.1
github.com/pocketbase/pocketbase v0.18.3
github.com/prometheus-community/pro-bing v0.3.0
github.com/robfig/cron/v3 v3.0.1
)
@@ -14,28 +16,28 @@ require (
require (
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.303 // indirect
github.com/aws/aws-sdk-go-v2 v1.19.0 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.10 // indirect
github.com/aws/aws-sdk-go-v2/config v1.18.28 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.13.27 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.5 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.72 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.35 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.29 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.36 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.27 // 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.30 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.29 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.14.4 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.37.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.12.13 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.13 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.19.3 // indirect
github.com/aws/smithy-go v1.13.5 // indirect
github.com/aws/aws-sdk-go v1.45.6 // indirect
github.com/aws/aws-sdk-go-v2 v1.21.0 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.13 // indirect
github.com/aws/aws-sdk-go-v2/config v1.18.39 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.13.37 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.11 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.83 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.41 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.35 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.42 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.1.4 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.14 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.36 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.35 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.15.4 // indirect
github.com/aws/aws-sdk-go-v2/service/s3 v1.38.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.13.6 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.15.6 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.21.5 // indirect
github.com/aws/smithy-go v1.14.2 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/domodwyer/mailyak/v3 v3.6.0 // indirect
github.com/domodwyer/mailyak/v3 v3.6.2 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
@@ -44,7 +46,7 @@ require (
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/google/uuid v1.3.1 // indirect
github.com/google/wire v0.5.0 // indirect
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
@@ -56,7 +58,7 @@ require (
github.com/mattn/go-sqlite3 v1.14.17 // indirect
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
github.com/mdlayher/packet v1.1.2 // indirect
github.com/mdlayher/socket v0.4.1 // indirect
github.com/mdlayher/socket v0.5.0 // indirect
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/spf13/cast v1.5.1 // indirect
@@ -65,32 +67,32 @@ require (
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.opencensus.io v0.24.0 // indirect
gocloud.dev v0.32.0 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/image v0.9.0 // indirect
gocloud.dev v0.34.0 // indirect
golang.org/x/crypto v0.13.0 // indirect
golang.org/x/image v0.12.0 // indirect
golang.org/x/mod v0.12.0 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/oauth2 v0.10.0 // indirect
golang.org/x/net v0.15.0 // indirect
golang.org/x/oauth2 v0.12.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/sys v0.10.0 // indirect
golang.org/x/term v0.10.0 // indirect
golang.org/x/text v0.11.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/term v0.12.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/tools v0.11.0 // indirect
golang.org/x/tools v0.13.0 // indirect
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
google.golang.org/api v0.132.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753 // indirect
google.golang.org/grpc v1.56.2 // indirect
google.golang.org/api v0.139.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d // indirect
google.golang.org/grpc v1.58.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
lukechampine.com/uint128 v1.3.0 // indirect
modernc.org/cc/v3 v3.41.0 // indirect
modernc.org/ccgo/v3 v3.16.14 // indirect
modernc.org/ccgo/v3 v3.16.15 // indirect
modernc.org/libc v1.24.1 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.6.0 // indirect
modernc.org/memory v1.7.1 // indirect
modernc.org/opt v0.1.3 // indirect
modernc.org/sqlite v1.24.0 // indirect
modernc.org/strutil v1.1.3 // indirect
modernc.org/sqlite v1.25.0 // indirect
modernc.org/strutil v1.2.0 // indirect
modernc.org/token v1.1.0 // indirect
)
+128 -3138
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,33 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.Name = "device_groups"
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.Name = "groups"
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,140 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models"
)
func init() {
m.Register(func(db dbx.Builder) error {
jsonData := `{
"id": "7emu7fnnwuim2ua",
"created": "2023-08-10 21:19:39.520Z",
"updated": "2023-08-10 21:19:39.520Z",
"name": "permissions",
"type": "base",
"system": false,
"schema": [
{
"system": false,
"id": "tzxtuykz",
"name": "user",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "27do0wbcuyfmbmx",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": 1,
"displayFields": []
}
},
{
"system": false,
"id": "nd1ekexz",
"name": "create",
"type": "bool",
"required": false,
"unique": false,
"options": {}
},
{
"system": false,
"id": "z79gcpy3",
"name": "read",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": [
"name"
]
}
},
{
"system": false,
"id": "t7wwbk2c",
"name": "update",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": [
"name"
]
}
},
{
"system": false,
"id": "b4u0gqa7",
"name": "delete",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": [
"name"
]
}
},
{
"system": false,
"id": "nyeqt3fn",
"name": "power",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "z5lghx2r3tm45n1",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": null,
"displayFields": []
}
}
],
"indexes": [
"CREATE UNIQUE INDEX ` + "`" + `idx_2GIk1Fo` + "`" + ` ON ` + "`" + `permissions` + "`" + ` (` + "`" + `user` + "`" + `)"
],
"listRule": "@request.auth.id = user.id",
"viewRule": "@request.auth.id = user.id",
"createRule": null,
"updateRule": null,
"deleteRule": "@request.auth.id = user.id",
"options": {}
}`
collection := &models.Collection{}
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
return err
}
return daos.New(db).SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("7emu7fnnwuim2ua")
if err != nil {
return err
}
return dao.DeleteCollection(collection)
})
}
@@ -0,0 +1,77 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.ViewRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.CreateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.update.id")
collection.DeleteRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && id ?= @collection.permissions.delete.id")
// add
new_created_by := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "naciykac",
"name": "created_by",
"type": "relation",
"required": false,
"unique": false,
"options": {
"collectionId": "27do0wbcuyfmbmx",
"cascadeDelete": false,
"minSelect": null,
"maxSelect": 1,
"displayFields": [
"username"
]
}
}`), new_created_by)
collection.Schema.AddField(new_created_by)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
// remove
collection.Schema.RemoveField("naciykac")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,42 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
collection.DeleteRule = types.Pointer("@request.auth.id = @collection.permissions.user.id && @collection.permissions.create = true")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,75 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("qqvyfrex")
// add
new_status := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "qmiatdwa",
"name": "status",
"type": "select",
"required": false,
"unique": false,
"options": {
"maxSelect": 1,
"values": [
"pending",
"online",
"offline"
]
}
}`), new_status)
collection.Schema.AddField(new_status)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add
del_status := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "qqvyfrex",
"name": "status",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), del_status)
collection.Schema.AddField(del_status)
// remove
collection.Schema.RemoveField("qmiatdwa")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,68 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id = id")
collection.ViewRule = types.Pointer("@request.auth.id = id")
collection.UpdateRule = types.Pointer("@request.auth.id = id")
collection.DeleteRule = types.Pointer("@request.auth.id = id")
// add
new_avatar := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "i1qnezoa",
"name": "avatar",
"type": "number",
"required": false,
"unique": false,
"options": {
"min": 0,
"max": 9
}
}`), new_avatar)
collection.Schema.AddField(new_avatar)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
// remove
collection.Schema.RemoveField("i1qnezoa")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,48 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// add
new_lazy_ping := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "yjyq5pvg",
"name": "lazy_ping",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_lazy_ping)
collection.Schema.AddField(new_lazy_ping)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("yjyq5pvg")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,42 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
collection.DeleteRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("djqp3uxrac2ores")
if err != nil {
return err
}
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,50 @@
package migrations
import (
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/tools/types"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.ViewRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.read.id")
collection.CreateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && @collection.permissions.create = true")
collection.UpdateRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.update.id")
collection.DeleteRule = types.Pointer("@request.auth.id ?= @collection.permissions.user.id && id ?= @collection.permissions.delete.id")
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
collection.ListRule = nil
collection.ViewRule = nil
collection.CreateRule = nil
collection.UpdateRule = nil
collection.DeleteRule = nil
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,123 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// add
new_sol_enabled := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "ueieydw5",
"name": "sol_enabled",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_sol_enabled)
collection.Schema.AddField(new_sol_enabled)
// add
new_sol_auth := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "yfszwhpw",
"name": "sol_auth",
"type": "bool",
"required": false,
"unique": false,
"options": {}
}`), new_sol_auth)
collection.Schema.AddField(new_sol_auth)
// add
new_sol_user := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "dbcmnrmp",
"name": "sol_user",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), new_sol_user)
collection.Schema.AddField(new_sol_user)
// add
new_sol_password := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "hvz8stfy",
"name": "sol_password",
"type": "text",
"required": false,
"unique": false,
"options": {
"min": null,
"max": null,
"pattern": ""
}
}`), new_sol_password)
collection.Schema.AddField(new_sol_password)
// add
new_sol_port := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "6kfqheid",
"name": "sol_port",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), new_sol_port)
collection.Schema.AddField(new_sol_port)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// remove
collection.Schema.RemoveField("ueieydw5")
// remove
collection.Schema.RemoveField("yfszwhpw")
// remove
collection.Schema.RemoveField("dbcmnrmp")
// remove
collection.Schema.RemoveField("hvz8stfy")
// remove
collection.Schema.RemoveField("6kfqheid")
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,64 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
// update
edit_number := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "8nwuncgg",
"name": "number",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), edit_number)
collection.Schema.AddField(edit_number)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
if err != nil {
return err
}
// update
edit_number := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "8nwuncgg",
"name": "number",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": null,
"max": 65535
}
}`), edit_number)
collection.Schema.AddField(edit_number)
return dao.SaveCollection(collection)
})
}
@@ -0,0 +1,64 @@
package migrations
import (
"encoding/json"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/daos"
m "github.com/pocketbase/pocketbase/migrations"
"github.com/pocketbase/pocketbase/models/schema"
)
func init() {
m.Register(func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update
edit_sol_port := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "6kfqheid",
"name": "sol_port",
"type": "number",
"required": false,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), edit_sol_port)
collection.Schema.AddField(edit_sol_port)
return dao.SaveCollection(collection)
}, func(db dbx.Builder) error {
dao := daos.New(db);
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
if err != nil {
return err
}
// update
edit_sol_port := &schema.SchemaField{}
json.Unmarshal([]byte(`{
"system": false,
"id": "6kfqheid",
"name": "sol_port",
"type": "number",
"required": true,
"unique": false,
"options": {
"min": 1,
"max": 65535
}
}`), edit_sol_port)
collection.Schema.AddField(edit_sol_port)
return dao.SaveCollection(collection)
})
}
+9 -2
View File
@@ -2,6 +2,7 @@ package networking
import (
"net"
"runtime"
"time"
"github.com/pocketbase/pocketbase/models"
@@ -16,8 +17,14 @@ func PingDevice(device *models.Record) bool {
return false
}
pinger.Count = 1
pinger.Timeout = 500 * 1000000 // 500ms
pinger.SetPrivileged(true)
pinger.Timeout = 500 * time.Millisecond
// windows needs privileged permissions.
// If you have issues on linux, see here: https://github.com/prometheus-community/pro-bing#linux
if runtime.GOOS == "windows" {
pinger.SetPrivileged(true)
}
err = pinger.Run()
if err != nil {
logger.Error.Println(err)
+1 -1
View File
@@ -35,7 +35,7 @@ func ShutdownDevice(device *models.Record) error {
return fmt.Errorf("%s", stderr.String())
}
// check state every second for 2 min
// check state every seconds for 2 min
start := time.Now()
for {
time.Sleep(1 * time.Second)
+52
View File
@@ -0,0 +1,52 @@
package networking
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"github.com/pocketbase/pocketbase/models"
"github.com/seriousm4x/upsnap/logger"
)
type SolResponse struct {
Message string `json:"message"`
}
func SleepDevice(device *models.Record) (SolResponse, error) {
logger.Info.Println("sleep triggered for", device.GetString("name"))
var solResp SolResponse
var url string
if device.GetBool("sol_auth") {
url = fmt.Sprintf("http://%s:%s@%s:%d/sleep?format=JSON",
device.GetString("sol_user"), device.GetString("sol_password"), device.GetString("ip"), device.GetInt("sol_port"))
} else {
url = fmt.Sprintf("http://%s:%d/sleep?format=JSON", device.GetString("ip"), device.GetInt("sol_port"))
}
resp, err := http.Get(url)
if err != nil {
return solResp, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, err := io.ReadAll(resp.Body)
if err != nil {
return solResp, err
}
var solResp SolResponse
if err := json.Unmarshal(body, &solResp); err != nil {
return solResp, err
}
return solResp, errors.New("status code was not 200")
}
return solResp, nil
}
+1 -1
View File
@@ -15,7 +15,7 @@ func WakeDevice(device *models.Record) error {
return err
}
// check state every second for 2 min
// check state every seconds for 2 min
start := time.Now()
for {
time.Sleep(1 * time.Second)
+77 -14
View File
@@ -7,6 +7,7 @@ import (
"os/exec"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
@@ -20,16 +21,74 @@ func HandlerWake(c echo.Context) error {
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
go func(*models.Record) {
record.Set("status", "pending")
App.Dao().SaveRecord(record)
if err := networking.WakeDevice(record); err != nil {
record.Set("status", "pending")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
go func(r *models.Record) {
if err := networking.WakeDevice(r); err != nil {
logger.Error.Println(err)
record.Set("status", "offline")
r.Set("status", "offline")
} else {
record.Set("status", "online")
r.Set("status", "online")
}
if err := App.Dao().SaveRecord(r); err != nil {
logger.Error.Println("Failed to save record:", err)
}
}(record)
return c.JSON(http.StatusOK, record)
}
func HandlerSleep(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
resp, err := networking.SleepDevice(record)
if err != nil {
logger.Error.Println(err)
record.Set("status", "online")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
return apis.NewBadRequestError(resp.Message, nil)
}
record.Set("status", "offline")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
return c.JSON(http.StatusOK, nil)
}
func HandlerReboot(c echo.Context) error {
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
record.Set("status", "pending")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
go func(r *models.Record) {
if err := networking.ShutdownDevice(r); err != nil {
logger.Error.Println(err)
r.Set("status", "online")
} else {
time.Sleep(15 * time.Second) // some devices might not respond to ping but are still shutting down
if err := networking.WakeDevice(r); err != nil {
logger.Error.Println(err)
r.Set("status", "offline")
} else {
r.Set("status", "online")
}
}
if err := App.Dao().SaveRecord(r); err != nil {
logger.Error.Println("Failed to save record:", err)
}
App.Dao().SaveRecord(record)
}(record)
return c.JSON(http.StatusOK, record)
}
@@ -39,16 +98,20 @@ func HandlerShutdown(c echo.Context) error {
if err != nil {
return apis.NewNotFoundError("The device does not exist.", err)
}
go func(*models.Record) {
record.Set("status", "pending")
App.Dao().SaveRecord(record)
if err := networking.ShutdownDevice(record); err != nil {
record.Set("status", "pending")
if err := App.Dao().SaveRecord(record); err != nil {
logger.Error.Println("Failed to save record:", err)
}
go func(r *models.Record) {
if err := networking.ShutdownDevice(r); err != nil {
logger.Error.Println(err)
record.Set("status", "online")
r.Set("status", "online")
} else {
record.Set("status", "offline")
r.Set("status", "offline")
}
if err := App.Dao().SaveRecord(r); err != nil {
logger.Error.Println("Failed to save record:", err)
}
App.Dao().SaveRecord(record)
}(record)
return c.JSON(http.StatusOK, record)
}
+36
View File
@@ -0,0 +1,36 @@
package pb
import (
"fmt"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/models"
)
func RequireUpSnapPermission() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
admin, _ := c.Get(apis.ContextAdminKey).(*models.Admin)
if admin != nil {
return next(c)
}
user, _ := c.Get(apis.ContextAuthRecordKey).(*models.Record)
if user == nil {
return apis.NewUnauthorizedError("The request requires admin or record authorization token to be set.", nil)
}
deviceId := c.PathParam("id")
// find record where user has device with power permission
res, err := App.Dao().FindFirstRecordByFilter("permissions",
fmt.Sprintf("user.id = '%s' && power.id ?= '%s'", user.Id, deviceId))
if res == nil || err != nil {
return apis.NewForbiddenError("You are not allowed to perform this request.", nil)
}
return next(c)
}
}
}
+52 -40
View File
@@ -1,6 +1,7 @@
package pb
import (
"fmt"
"io/fs"
"net/http"
"os"
@@ -25,38 +26,54 @@ func StartPocketBase(distDirFS fs.FS) {
App.RootCmd.Version = Version
// auto migrate db
migratecmd.MustRegister(App, App.RootCmd, &migratecmd.Options{
migratecmd.MustRegister(App, App.RootCmd, migratecmd.Config{
Automigrate: true,
})
// event hooks
App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
// set static website path
e.Router.GET("/*", apis.StaticDirectoryHandler(distDirFS, true))
// add wake route to api
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/wake/:id",
Handler: HandlerWake,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
apis.RequireAdminOrRecordAuth("users"),
RequireUpSnapPermission(),
},
})
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/sleep/:id",
Handler: HandlerSleep,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
RequireUpSnapPermission(),
},
})
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/reboot/:id",
Handler: HandlerReboot,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
RequireUpSnapPermission(),
},
})
// add shutdown route to api
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/shutdown/:id",
Handler: HandlerShutdown,
Middlewares: []echo.MiddlewareFunc{
apis.ActivityLogger(App),
apis.RequireAdminOrRecordAuth("users"),
RequireUpSnapPermission(),
},
})
// add network scan route to api
e.Router.AddRoute(echo.Route{
Method: http.MethodGet,
Path: "/api/upsnap/scan",
@@ -67,34 +84,27 @@ func StartPocketBase(distDirFS fs.FS) {
},
})
// import environment and set settings
if err := importSettings(); err != nil {
return err
}
// reset device states and run ping cronjob
if err := resetDeviceStates(); err != nil {
return err
}
// run cronjobs
go cronjobs.RunPing(App)
go cronjobs.RunWakeShutdown(App)
// restart ping cronjobs or wake/shutdown cronjobs on model update
// add event hook before starting server.
// using this outside App.OnBeforeServe() would not work
App.OnModelAfterUpdate().Add(func(e *core.ModelEvent) error {
App.OnModelAfterUpdate("settings_private", "devices").Add(func(e *core.ModelEvent) error {
if e.Model.TableName() == "settings_private" {
for _, job := range cronjobs.CronPing.Entries() {
cronjobs.CronPing.Remove(job.ID)
}
go cronjobs.RunPing(App)
} else if e.Model.TableName() == "devices" {
if err := refreshDeviceList(); err != nil {
logger.Error.Println(err)
return err
}
for _, job := range cronjobs.CronWakeShutdown.Entries() {
cronjobs.CronWakeShutdown.Remove(job.ID)
}
@@ -105,17 +115,33 @@ func StartPocketBase(distDirFS fs.FS) {
return nil
})
// refresh the device list on database events
App.OnModelAfterCreate().Add(func(e *core.ModelEvent) error {
if e.Model.TableName() == "_admins" {
if err := setSetupCompleted(); err != nil {
logger.Error.Println(err)
return err
}
} else {
if err := refreshDeviceList(); err != nil {
return nil
} else if e.Model.TableName() == "devices" {
// when a device is created, give the user all rights to the device he just created
deviceRec := e.Model.(*models.Record)
userId := deviceRec.GetString("created_by")
var permissionRec *models.Record
permissionRec, err := App.Dao().FindFirstRecordByFilter("permissions",
fmt.Sprintf("user.id = '%s'", userId))
if err != nil && err.Error() != "sql: no rows in result set" {
logger.Error.Println(err)
return err
} else if permissionRec != nil {
permissionRec.Set("read", append(permissionRec.GetStringSlice("read"), deviceRec.Id))
permissionRec.Set("update", append(permissionRec.GetStringSlice("update"), deviceRec.Id))
permissionRec.Set("delete", append(permissionRec.GetStringSlice("delete"), deviceRec.Id))
permissionRec.Set("power", append(permissionRec.GetStringSlice("power"), deviceRec.Id))
if err := App.Dao().SaveRecord(permissionRec); err != nil {
logger.Error.Println(err)
return err
}
}
}
return nil
@@ -126,23 +152,21 @@ func StartPocketBase(distDirFS fs.FS) {
logger.Error.Println(err)
return err
}
} else {
if err := refreshDeviceList(); err != nil {
logger.Error.Println(err)
return err
}
}
return nil
})
// start pocketbase
App.OnTerminate().Add(func(e *core.TerminateEvent) error {
cronjobs.StopAll()
return nil
})
if err := App.Start(); err != nil {
logger.Error.Fatalln(err)
}
}
func importSettings() error {
// get first settingsPrivate record
settingsPrivateRecords, err := App.Dao().FindRecordsByExpr("settings_private")
if err != nil {
return err
@@ -156,7 +180,6 @@ func importSettings() error {
settingsPrivate = settingsPrivateRecords[0]
}
// get first settingsPublic record
settingsPublicRecords, err := App.Dao().FindRecordsByExpr("settings_public")
if err != nil {
return err
@@ -182,18 +205,15 @@ func importSettings() error {
interval = os.Getenv("UPSNAP_INTERVAL")
}
// set private settings
settingsPrivate.Set("interval", interval)
if scanRange := os.Getenv("UPSNAP_SCAN_RANGE"); scanRange != "" {
settingsPrivate.Set("scan_range", scanRange)
}
// set public settings
if websiteTitle := os.Getenv("UPSNAP_WEBSITE_TITLE"); websiteTitle != "" {
settingsPublic.Set("website_title", websiteTitle)
}
// save records
if err := App.Dao().SaveRecord(settingsPrivate); err != nil {
return err
}
@@ -215,20 +235,12 @@ func resetDeviceStates() error {
return err
}
for _, device := range devices {
device.Set("status", "offline")
if err := App.Dao().SaveRecord(device); err != nil {
d := device
d.Set("status", "offline")
if err := App.Dao().SaveRecord(d); err != nil {
return err
}
}
cronjobs.Devices = devices
return nil
}
func refreshDeviceList() error {
var err error
if cronjobs.Devices, err = App.Dao().FindRecordsByExpr("devices"); err != nil {
return err
}
return nil
}
+29
View File
@@ -0,0 +1,29 @@
version: "3"
services:
upsnap:
container_name: upsnap
build:
dockerfile: Dockerfile.dev
network_mode: host
restart: unless-stopped
volumes:
- ./data:/app/pb_data
# # To use a non-root user, create the mountpoint first before starting
# # the container (mkdir data) so that it has the right permissions.
# user: 1000:1000
# environment:
# - TZ=Europe/Berlin # Set container timezone for cron schedules
# - UPSNAP_INTERVAL=@every 10s # Sets the interval in which the devices are pinged
# - UPSNAP_SCAN_RANGE=192.168.1.0/24 # Scan range is used for device discovery on local network
# - UPSNAP_WEBSITE_TITLE=Custom name # Custom website title
# # dns is used for name resolution during network scan
# dns:
# - 192.18.0.1
# - 192.18.0.2
# # you can change the listen ip:port inside the container like this:
# entrypoint: /bin/sh -c "./upsnap serve --http 0.0.0.0:5000"
# healthcheck:
# test: curl -fs "http://localhost:5000/api/health" || exit 1
# interval: 10s
# # or install custom packages for shutdown
# entrypoint: /bin/sh -c "apk update && apk add --no-cache <YOUR_PACKAGE> && rm -rf /var/cache/apk/* && ./upsnap serve --http 0.0.0.0:8090"
+25 -23
View File
@@ -1,25 +1,27 @@
version: "3"
services:
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"
upsnap:
container_name: upsnap
image: ghcr.io/seriousm4x/upsnap:4
network_mode: host
restart: unless-stopped
volumes:
- ./data:/app/pb_data
# # To use a non-root user, create the mountpoint first (mkdir data) so that it has the right permission.
# user: 1000:1000
# environment:
# - TZ=Europe/Berlin # Set container timezone for cron schedules
# - UPSNAP_INTERVAL=@every 10s # Sets the interval in which the devices are pinged
# - UPSNAP_SCAN_RANGE=192.168.1.0/24 # Scan range is used for device discovery on local network
# - UPSNAP_WEBSITE_TITLE=Custom name # Custom website title
# # 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"
+1
View File
@@ -0,0 +1 @@
PUBLIC_VERSION=""
+1 -2
View File
@@ -4,11 +4,10 @@ node_modules
/.svelte-kit
/package
.env
.env.\*
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock
+28 -21
View File
@@ -1,23 +1,30 @@
module.exports = {
root: true,
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
},
env: {
browser: true,
es2017: true,
node: true
}
root: true,
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:svelte/recommended',
'prettier'
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
extraFileExtensions: ['.svelte']
},
env: {
browser: true,
es2017: true,
node: true
},
overrides: [
{
files: ['*.svelte'],
parser: 'svelte-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser'
}
}
]
};
+9
View File
@@ -0,0 +1,9 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
+1
View File
@@ -0,0 +1 @@
_
+2 -2
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
cd frontend && npx lint-staged
+1
View File
@@ -1 +1,2 @@
engine-strict=true
resolution-mode=highest
+6 -6
View File
@@ -1,8 +1,8 @@
{
"useTabs": false,
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "none",
"semi": true,
"printWidth": 100
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}
-3960
View File
File diff suppressed because it is too large Load Diff
+47 -42
View File
@@ -1,44 +1,49 @@
{
"name": "frontend",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "cd .. && husky install frontend/.husky",
"lint": "prettier --ignore-path ../.gitignore --check --plugin-search-dir=. . && eslint --fix .",
"format": "prettier --ignore-path ../.gitignore --write --plugin-search-dir=. ."
},
"devDependencies": {
"@sveltejs/adapter-static": "^2.0.2",
"@sveltejs/kit": "^1.22.3",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-svelte": "^2.32.2",
"husky": "^8.0.3",
"lint-staged": "^13.2.3",
"prettier": "^2.8.8",
"prettier-plugin-svelte": "^2.10.1",
"svelte": "^4.1.0",
"svelte-preprocess": "^5.0.4",
"typescript": "^5.1.6",
"vite": "^4.4.4"
},
"type": "module",
"dependencies": {
"@fortawesome/free-solid-svg-icons": "^6.4.0",
"@popperjs/core": "^2.11.8",
"bootstrap": "5.3.0",
"date-fns": "^2.30.0",
"pocketbase": "^0.15.3",
"sass": "^1.63.6",
"svelte-fa": "^3.0.4"
},
"lint-staged": {
"*.{js,svelte}": "eslint --fix --ignore-path ../.gitignore .",
"*.{js,css,md,svelte,scss}": "prettier --write --ignore-path ../.gitignore --plugin-search-dir=. ."
}
"name": "upsnap-frontend",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "eslint --fix --cache --ignore-path ../.gitignore .",
"format": "prettier --write --cache --cache-strategy content --ignore-path ../.gitignore .",
"prepare": "cd .. && husky install frontend/.husky"
},
"devDependencies": {
"@sveltejs/adapter-static": "^2.0.3",
"@sveltejs/kit": "^1.24.1",
"@typescript-eslint/eslint-plugin": "^6.6.0",
"@typescript-eslint/parser": "^6.6.0",
"autoprefixer": "^10.4.15",
"daisyui": "^3.7.3",
"eslint": "^8.49.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-svelte": "^2.33.1",
"husky": "^8.0.3",
"postcss": "^8.4.29",
"prettier": "^3.0.3",
"prettier-plugin-svelte": "^3.0.3",
"svelte": "^4.2.0",
"svelte-check": "^3.5.1",
"tailwindcss": "^3.3.3",
"tslib": "^2.6.2",
"typescript": "^5.2.2",
"vite": "^4.4.9"
},
"type": "module",
"lint-staged": {
"*.{js,svelte}": "eslint --fix --cache --ignore-path ../.gitignore .",
"*.{js,css,md,svelte,scss}": "prettier --write --cache --cache-strategy content --ignore-path ../.gitignore ."
},
"dependencies": {
"@fortawesome/free-solid-svg-icons": "^6.4.2",
"date-fns": "^2.30.0",
"pocketbase": "^0.18.0",
"svelte-fa": "^3.0.4",
"svelte-french-toast": "^1.2.0",
"theme-change": "^2.5.0"
}
}
+745 -738
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
};
+3
View File
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+12
View File
@@ -0,0 +1,12 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface Platform {}
}
}
export {};
+28 -10
View File
@@ -1,12 +1,30 @@
<!DOCTYPE html>
<html lang="en" class="h-100">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
<script>
const darkTheme = 'dark';
const lightTheme = 'cupcake';
const preferesDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = localStorage.getItem('theme')
? localStorage.getItem('theme')
: preferesDark
? darkTheme
: lightTheme;
document.documentElement.setAttribute('data-theme', theme);
<body data-sveltekit-preload-data="hover" class="h-100">
<div style="display: contents">%sveltekit.body%</div>
</body>
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', ({ matches }) => {
matches
? document.documentElement.setAttribute('data-theme', darkTheme)
: document.documentElement.setAttribute('data-theme', lightTheme);
});
</script>
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
-163
View File
@@ -1,163 +0,0 @@
<script>
import { dev } from '$app/environment';
import { parseISO, formatDistance } from 'date-fns';
import { pocketbase } from '@stores/pocketbase';
import Fa from 'svelte-fa/src/fa.svelte';
import {
faPowerOff,
faEllipsisVertical,
faCircle,
faCircleUp,
faCircleDown,
faLock
} from '@fortawesome/free-solid-svg-icons';
import { sortPorts } from '../sorts';
export let device;
export let now;
function shutdown() {
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/shutdown/${device.id}`, {
headers: {
Authorization: $pocketbase.authStore.baseToken
}
});
}
function wake() {
fetch(`${dev ? 'http://localhost:8090' : ''}/api/upsnap/wake/${device.id}`, {
headers: {
Authorization: $pocketbase.authStore.baseToken
}
});
}
</script>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 g-4">
<div
class="card border-0 rounded-5 px-3 py-2 shadow-sm"
class:offline={device.status == 'offline' ? true : false}
class:online={device.status == 'online' ? true : false}
class:pending={device.status == 'pending' ? true : false}
>
<div class="card-body">
<div class="row">
<div class="col-auto me-auto">
{#if device.status === 'offline'}
<span
class="text-danger"
role="none"
on:click={() => wake()}
on:keydown={() => wake()}
>
<div>
<Fa icon={faPowerOff} class="fs-4 power-hover" />
</div>
</span>
{:else if device.status === 'online'}
{#if device.shutdown_cmd !== ''}
<span
class="text-success"
role="none"
on:click={() => shutdown()}
on:keydown={() => shutdown()}
>
<div>
<Fa icon={faPowerOff} class="fs-4 power-hover" />
</div>
</span>
{:else}
<span class="text-success">
<div>
<Fa icon={faPowerOff} class="fs-4" />
</div>
</span>
{/if}
{:else if device.status === 'pending'}
<div
class="spinner-border text-warning"
style="width: 23px;height: 23px;"
role="status"
>
<span class="visually-hidden">Loading...</span>
</div>
{/if}
</div>
<div class="col-auto fs-5">
<a
href="/device/{device.id}"
class="text-reset text-center ellipsis power-hover"
>
<Fa icon={faEllipsisVertical} />
</a>
</div>
</div>
{#if device.link}
<p class="m-0 fw-bold fs-5 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 text-body-emphasis">{device.name}</p>
{/if}
<p class="text-muted mb-2">{device.ip}</p>
{#if device?.expand?.ports}
<div class="mb-2">
{#each device.expand.ports.sort(sortPorts) as port}
<p class="m-0">
<Fa
icon={faCircle}
class="me-1 {port.status ? 'port-up' : 'port-down'}"
/>{port.name}
<span class="text-muted">({port.number})</span>
</p>
{/each}
</div>
{/if}
{#if device.wake_cron !== ''}
<span
class="badge rounded-pill {device.wake_cron_enabled
? 'text-bg-success'
: 'text-bg-danger'}"
data-toggle="tooltip"
title="Wake cron {device.wake_cron_enabled ? 'enabled' : 'disabled'}"
>
<Fa icon={faCircleUp} class="me-1" />
{device.wake_cron}
</span>
{/if}
{#if device.shutdown_cron !== ''}
<span
class="badge rounded-pill {device.shutdown_cron_enabled
? 'text-bg-success'
: 'text-bg-danger'}"
data-toggle="tooltip"
title="Shutdown cron {device.shutdown_cron_enabled ? 'enabled' : 'disabled'}"
>
<Fa icon={faCircleDown} class="me-1" />
{device.shutdown_cron}
</span>
{/if}
{#if device.password !== ''}
<span
class="badge rounded-pill text-bg-secondary"
data-toggle="tooltip"
title="Wake password set"
>
<Fa icon={faLock} class="mx-1" />
</span>
{/if}
<p
class="text-muted m-0"
data-toggle="tooltip"
title="Last status change: {device.updated}"
>
{formatDistance(parseISO(device.updated), now, {
includeSeconds: true,
addSuffix: true
})}
</p>
</div>
</div>
</div>
-418
View File
@@ -1,418 +0,0 @@
<script>
import { goto } from '$app/navigation';
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';
export let device;
export let mode;
let timeout;
let button = {
state: 'none',
error: ''
};
let deleteButton = {
state: 'none',
error: ''
};
let newPort = {
name: '',
number: null
};
let passwordShow = false;
$: passwordType = passwordShow ? 'text' : 'password';
async function addOrUpdateDevice() {
button.state = 'waiting';
try {
// validate password length
if (
device.password.length != 0 &&
device.password.length != 4 &&
device.password.length != 6
) {
throw 'Password must be 0, 4 or 6 characters long';
}
// add ports not in db
for (let i = 0; i < device.expand.ports.length; i++) {
const port = device.expand.ports[i];
if (!port.id) {
const result = await $pocketbase.collection('ports').create(port);
device.ports = [...device.ports, result.id];
} else {
await $pocketbase.collection('ports').update(port.id, port);
}
}
// create or update device
if (mode === 'add') {
await $pocketbase.collection('devices').create(device);
} else {
await $pocketbase.collection('devices').update(device.id, device);
}
// show button with timeout
clearTimeout(timeout);
timeout = setTimeout(() => {
button.state = 'none';
}, 3000);
button.state = 'success';
} catch (error) {
clearTimeout(timeout);
setTimeout(() => {
button.error = '';
button.state = 'none';
}, 3000);
button.error = error;
button.state = 'failed';
}
}
async function deleteDevice() {
deleteButton.state = 'waiting';
try {
await $pocketbase.collection('devices').delete(device.id);
device.ports.forEach(async (port) => {
await $pocketbase.collection('ports').delete(port);
});
delete $devices[device.id];
goto('/');
} catch (error) {
clearTimeout(timeout);
timeout = setTimeout(() => {
deleteButton.error = '';
deleteButton.state = 'none';
}, 3000);
deleteButton.error = error;
deleteButton.state = 'failed';
}
}
async function deletePort(idx) {
// delete port from db if it has an id
// ports with id exist in db, ports without id are not created yet
const port = device.expand.ports[idx];
if (port.id) {
await $pocketbase.collection('ports').delete(port.id);
const i = device.ports.indexOf(port.id);
if (i !== -1) {
device.ports.splice(i, 1);
device.ports = device.ports;
}
}
device.expand.ports.splice(idx, 1);
device.expand.ports = device.expand.ports;
}
function addPort() {
device.expand.ports = [...device.expand.ports, JSON.parse(JSON.stringify(newPort))];
newPort.name = '';
newPort.number = null;
}
function onPasswordInput(event) {
device.password = event.target.value;
}
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 text-body-emphasis">{mode === 'add' ? 'Add new device' : device.name}</h3>
<div class="row">
<div class="col-md-6">
<form on:submit|preventDefault={addOrUpdateDevice}>
<h5>Required:</h5>
<div class="input-group mb-1">
<span class="input-group-text">Name</span>
<input
class="form-control"
placeholder="Office Pc"
aria-label="Name"
aria-describedby="addon-wrapping"
type="text"
required
bind:value={device.name}
/>
</div>
<div class="input-group mb-1">
<span class="input-group-text">IP</span>
<input
class="form-control"
placeholder="192.168.1.34"
aria-label="IP"
aria-describedby="addon-wrapping"
type="text"
required
bind:value={device.ip}
/>
</div>
<div class="input-group mb-1">
<span class="input-group-text">MAC</span>
<input
class="form-control"
placeholder="aa:bb:cc:dd:ee:ff"
aria-label="MAC"
aria-describedby="addon-wrapping"
type="text"
required
bind:value={device.mac}
/>
</div>
<div class="input-group">
<span class="input-group-text">Netmask</span>
<input
class="form-control"
placeholder="Most likely 255.255.255.0 or 255.255.0.0"
aria-label="Netmask"
aria-describedby="addon-wrapping"
type="text"
required
bind:value={device.netmask}
/>
</div>
<h5 class="mt-4">Optional:</h5>
{#if device?.expand?.ports}
{#each device.expand.ports as port, idx}
<div class="input-group mb-1">
<span class="input-group-text">Port</span>
<input
type="text"
aria-label="Name"
class="form-control"
placeholder="Name"
bind:value={port.name}
/>
<input
type="number"
min="0"
max="65535"
aria-label="Number"
class="form-control"
placeholder="Number"
bind:value={port.number}
/>
<button
type="button"
class="btn btn-outline-secondary"
on:click={() => deletePort(idx)}
>
<Fa icon={faTrashCan} />
</button>
</div>
{/each}
{/if}
<div class="input-group mb-1">
<span class="input-group-text">Port</span>
<input
type="text"
aria-label="Name"
class="form-control"
placeholder="Name"
bind:value={newPort.name}
/>
<input
type="number"
min="0"
max="65535"
aria-label="Number"
class="form-control"
placeholder="Number"
bind:value={newPort.number}
/>
<button
type="button"
class="btn btn-outline-secondary"
on:click={() => addPort()}
>
<Fa icon={faPlus} />
</button>
</div>
<div class="input-group mb-1">
<span class="input-group-text">Link</span>
<input
class="form-control"
placeholder="Clickable link on device card"
aria-label="Link"
aria-describedby="addon-wrapping"
type="url"
bind:value={device.link}
/>
</div>
<div class="input-group mb-1">
<span class="input-group-text">Wake Cron<sup>(1)</sup></span>
<input
class="form-control"
placeholder="Automatically wake device with cron"
aria-label="Wake Cron"
aria-describedby="addon-wrapping"
type="text"
bind:value={device.wake_cron}
/>
<div class="input-group-text form-switch">
<label class="form-check-label" for="wake-cron-enabled">Enable</label>
<input
id="wake-cron-enabled"
class="form-check-input mt-0 ms-1"
type="checkbox"
role="switch"
aria-label="Enable/Disable wake cron"
bind:checked={device.wake_cron_enabled}
/>
</div>
</div>
<div class="input-group mb-1">
<span class="input-group-text">Shutdown Cron<sup>(1)</sup></span>
<input
class="form-control"
placeholder="Automatically shutdown device with cron"
aria-label="Shutdown Cron"
aria-describedby="addon-wrapping"
type="text"
bind:value={device.shutdown_cron}
/>
<div class="input-group-text form-switch">
<label class="form-check-label" for="wake-shutdown-enabled">Enable</label>
<input
id="wake-shutdown-enabled"
class="form-check-input mt-0 ms-1"
type="checkbox"
role="switch"
aria-label="Enable/Disable wake cron"
bind:checked={device.shutdown_cron_enabled}
/>
</div>
</div>
<div class="input-group mb-1">
<span class="input-group-text">Shutdown Cmd<sup>(2)</sup></span>
<input
class="form-control"
placeholder="Command to shutdown device"
aria-label="Shutdown Cmd"
aria-describedby="addon-wrapping"
type="text"
bind:value={device.shutdown_cmd}
/>
</div>
<div class="input-group mb-3">
<span class="input-group-text">Password<sup>(3)</sup></span>
<input
class="form-control"
placeholder="BIOS password for wol"
aria-label="IP"
aria-describedby="addon-wrapping"
type={passwordType}
value={device.password}
maxlength="6"
on:input={onPasswordInput}
/>
<button
class="btn btn-outline-secondary"
type="button"
on:click={() => (passwordShow = !passwordShow)}
>
<Fa icon={passwordShow ? faEyeSlash : faEye} />
</button>
</div>
{#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"
class:btn-success={button.state === 'success' ? true : false}
class:btn-warning={button.state === 'waiting' ? true : false}
class:btn-danger={button.state === 'failed' ? true : false}
disabled={button.state !== 'none' ? true : false}
>
{#if button.state === 'none'}
{mode === 'add' ? 'Add device' : 'Save device'}
{:else if button.state === 'success'}
{mode === 'add' ? 'Added successfully' : 'Saved successfully'}
{:else if button.state === 'waiting'}
Waiting
{:else if button.state === 'failed'}
Failed: {button.error}
{/if}
</button>
</form>
</div>
<div class="col-md-6 d-flex align-items-start flex-column">
<div class="callout callout-info mb-auto">
<h5>Optional:</h5>
<p class="m-0">
(1) Learn more about the correct syntax for cron on
<a href="https://en.wikipedia.org/wiki/Cron" target="_blank" rel="noreferrer"
>wikipedia</a
>
or refer to the
<a
target="_blank"
rel="noreferrer"
href="https://pkg.go.dev/github.com/robfig/cron">package documentation</a
>
</p>
<p class="m-0">
(2) Shell command to be executed. "net rpc", "sshpass" and "curl" are available.
e.g.:
</p>
<ul>
<li>
Windows: <code>net rpc shutdown -I 192.168.1.13 -U "user%password"</code>
</li>
<li>
Linux: <code
>sshpass -p your_password ssh -o "StrictHostKeyChecking=no"
user@hostname "sudo poweroff"</code
>
</li>
</ul>
<p class="m-0">
(3) Some network cards have the option to set a password for magic packets, also
called "SecureON". Password can only be 0, 4 or 6 characters in length.
</p>
</div>
{#if mode === 'edit'}
<div class="text-end mt-3 align-self-end">
<button
class="btn btn-danger"
on:click={() => deleteDevice()}
on:keydown={() => deleteDevice()}
>
{#if deleteButton.state === 'none'}
Delete device
{:else if deleteButton.state === 'waiting'}
Waiting
{:else if deleteButton.state === 'failed'}
Failed: {deleteButton.error}
{/if}
</button>
</div>
{/if}
</div>
</div>
</section>
-237
View File
@@ -1,237 +0,0 @@
<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>
-146
View File
@@ -1,146 +0,0 @@
<script>
import { dev } from '$app/environment';
import { onMount } from 'svelte';
import { page } from '$app/stores';
import { theme } from '@stores/theme';
import { pocketbase, authorizedStore, settings_public } from '@stores/pocketbase';
import Fa from 'svelte-fa/src/fa.svelte';
import {
faSun,
faMoon,
faCircleHalfStroke,
faBrush,
faRightFromBracket
} from '@fortawesome/free-solid-svg-icons';
let userInfo = {
usernameOrEmail: '',
role: ''
};
onMount(async () => {
if ($pocketbase.authStore.baseModel?.collectionName === 'users') {
userInfo.role = 'user';
} else {
userInfo.role = 'admin';
}
if ($pocketbase.authStore.baseModel?.username) {
userInfo.usernameOrEmail = $pocketbase.authStore.baseModel.username;
} else {
userInfo.usernameOrEmail = $pocketbase.authStore.baseModel.email;
}
});
async function logout() {
$pocketbase.authStore.clear();
authorizedStore.set(false);
}
</script>
<nav class="navbar navbar-expand-sm pt-0">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<img
src={$settings_public.favicon !== ''
? `${dev ? $pocketbase.baseUrl : ''}/api/files/settings_public/${
$settings_public.id
}/${$settings_public.favicon}`
: '/gopher.svg'}
alt={$settings_public.website_title ? $settings_public.website_title : 'UpSnap'}
width="45"
height="45"
class:me-2={$settings_public.website_title !== ''}
/>{$settings_public.website_title ? $settings_public.website_title : ''}
</a>
<button
class="navbar-toggler border-0"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon" />
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav">
{#if userInfo.role !== 'user'}
<li class="nav-item">
<a
class="nav-link"
class:active={$page.url.pathname === '/' ? true : false}
href="/">Home</a
>
</li>
<li class="nav-item me-3">
<a
class="nav-link"
class:active={$page.url.pathname === '/settings/' ? true : false}
href="/settings/">Settings</a
>
</li>
{/if}
<li class="nav-item dropdown">
<div
class="nav-link dropdown-toggle"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<Fa icon={faBrush} class="me-2" />
Theme
</div>
<ul class="dropdown-menu border-0 p-1 shadow-sm mb-2">
<li>
<div
class="dropdown-item"
class:active={$theme === 'light'}
role="none"
on:click={() => ($theme = 'light')}
on:keydown={() => ($theme = 'light')}
>
<Fa icon={faSun} class="me-2" />
Light
</div>
</li>
<li>
<div
class="dropdown-item"
class:active={$theme === 'dark'}
role="none"
on:click={() => ($theme = 'dark')}
on:keydown={() => ($theme = 'dark')}
>
<Fa icon={faMoon} class="me-2" />
Dark
</div>
</li>
<li>
<div
class="dropdown-item"
class:active={$theme === 'auto'}
role="none"
on:click={() => ($theme = 'auto')}
on:keydown={() => ($theme = 'auto')}
>
<Fa icon={faCircleHalfStroke} class="me-2" />
Auto
</div>
</li>
</ul>
</li>
</ul>
<div class="ms-auto d-flex">
<button
class="text-dark-emphasis nav-link active border-0"
data-toggle="tooltip"
title="Logged in as {userInfo.role} &quot;{userInfo.usernameOrEmail}&quot;"
on:click={() => logout()}
>
<Fa icon={faRightFromBracket} class="me-2" />Logout ({userInfo.usernameOrEmail})
</button>
</div>
</div>
</div>
</nav>
-10
View File
@@ -1,10 +0,0 @@
<script>
import { fly } from 'svelte/transition';
export let url;
</script>
{#key url}
<div in:fly={{ y: 50, duration: 300 }}>
<slot />
</div>
{/key}
@@ -1,16 +0,0 @@
<script>
import { pocketbase } from '@stores/pocketbase';
let isUser = false;
$: isUser = $pocketbase.authStore.baseModel?.collectionName === 'users';
</script>
{#if isUser}
<div class="row justify-content-center align-items-center">
<div class="col-auto">
<div class="callout callout-danger m-0">
Logged in as read only user. To make changes, please log in as admin.
</div>
</div>
</div>
{/if}
@@ -0,0 +1,144 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
import DeviceCardNic from './DeviceCardNic.svelte';
import Fa from 'svelte-fa';
import {
faBed,
faCircleArrowDown,
faCircleArrowUp,
faLock,
faPen,
faRotateLeft
} from '@fortawesome/free-solid-svg-icons';
import { scale } from 'svelte/transition';
import { formatDistance, parseISO } from 'date-fns';
import toast from 'svelte-french-toast';
import type { Device } from '$lib/types/device';
export let device: Device;
let moreButtons = [
{
text: 'Edit',
icon: faPen,
onClick: () => goto(`/device/${device.id}`),
requires: $pocketbase.authStore.isAdmin || $permission.update?.includes(device.id)
},
{
text: 'Sleep',
icon: faBed,
onClick: () => sleep(),
requires:
($pocketbase.authStore.isAdmin || $permission.power?.includes(device.id)) &&
device.status === 'online' &&
device.sol_enabled
},
{
text: 'Reboot',
icon: faRotateLeft,
onClick: () => reboot(),
requires:
($pocketbase.authStore.isAdmin || $permission.power?.includes(device.id)) &&
device.status === 'online' &&
device.shutdown_cmd !== ''
}
];
// update device status change
let now = Date.now();
let interval: number;
$: {
clearInterval(interval);
interval = setInterval(() => {
now = Date.now();
}, 1000);
}
function sleep() {
fetch(`${backendUrl}api/upsnap/sleep/${device.id}`, {
headers: {
Authorization: $pocketbase.authStore.token
}
}).catch((err) => {
toast.error(err.message);
});
}
function reboot() {
fetch(`${backendUrl}api/upsnap/reboot/${device.id}`, {
headers: {
Authorization: $pocketbase.authStore.token
}
}).catch((err) => {
toast.error(err.message);
});
}
</script>
<div class="card bg-base-300 shadow-md rounded-3xl" transition:scale={{ delay: 0, duration: 200 }}>
<div class="card-body p-6">
{#if device.link.toString() !== ''}
<a href={device.link.toString()} target="_blank">
<h1 class="card-title link">{device.name}</h1>
</a>
{:else}
<h1 class="card-title">{device.name}</h1>
{/if}
<ul class="menu bg-base-200 rounded-box">
<!-- TODO: change to nic array once backend supports it -->
<DeviceCardNic {device} />
</ul>
{#if device.wake_cron_enabled || device.shutdown_cron_enabled || device.password}
<div class="flex flex-row flex-wrap gap-2">
{#if device.wake_cron_enabled}
<div class="tooltip" data-tip="Wake cron">
<span class="badge badge-success gap-1 p-3"
><Fa icon={faCircleArrowUp} />{device.wake_cron}</span
>
</div>
{/if}
{#if device.shutdown_cron_enabled}
<div class="tooltip" data-tip="Shutdown cron">
<span class="badge badge-error gap-1 p-3"
><Fa icon={faCircleArrowDown} />{device.shutdown_cron}</span
>
</div>
{/if}
{#if device.password}
<div class="tooltip" data-tip="Wake password">
<span class="badge gap-1 p-3"><Fa icon={faLock} />Password</span>
</div>
{/if}
</div>
{/if}
<div class="card-actions mt-auto items-center">
<span class="tooltip" data-tip="Last status change: {device.updated}">
{formatDistance(parseISO(device.updated), now, {
includeSeconds: true,
addSuffix: true
})}
</span>
{#if moreButtons.filter((btn) => btn.requires).length > 0}
<div class="dropdown dropdown-top dropdown-end bg-base-300 ms-auto">
<label tabindex="-1" class="btn btn-sm m-1" for="more-{device.id}">More</label>
<ul
id="more-{device.id}"
tabindex="-1"
class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-fit"
>
{#each moreButtons as btn}
{#if btn.requires}
<li>
<button on:click={btn.onClick}>
<Fa icon={btn.icon} />{btn.text}
</button>
</li>
{/if}
{/each}
</ul>
</div>
{/if}
</div>
</div>
</div>
@@ -0,0 +1,147 @@
<script lang="ts">
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
import Fa from 'svelte-fa';
import { faCircle, faPowerOff } from '@fortawesome/free-solid-svg-icons';
import toast from 'svelte-french-toast';
import type { Device } from '$lib/types/device';
export let device: Device;
let hoverText = '';
let disabled = false;
let timeout = 120;
var interval: number;
$: if (device.status === 'pending' && !interval) {
countdown(Date.parse(device.updated));
}
$: minutes = Math.floor(timeout / 60);
$: seconds = timeout % 60;
$: if (device.status === 'pending' || device.status === '') {
disabled = true;
hoverText = 'Pending';
} else if (device.status === 'online') {
if (device.shutdown_cmd === '') {
disabled = true;
hoverText = 'No shutdown command set';
} else if (!$pocketbase.authStore.isAdmin && !$permission.power?.includes(device.id)) {
disabled = true;
hoverText = 'No permission to shut down this device';
} else {
disabled = false;
hoverText = 'Shut down';
}
} else if (device.status === 'offline') {
if (!$pocketbase.authStore.isAdmin && !$permission.power?.includes(device.id)) {
disabled = true;
hoverText = 'No permission to power on this device';
} else {
disabled = false;
hoverText = 'Power on';
}
}
// TODO: change wake and shutdown to nic based routes, not device based
function wake() {
fetch(`${backendUrl}api/upsnap/wake/${device.id}`, {
headers: {
Authorization: $pocketbase.authStore.token
}
})
.then(async (data) => {
const dev = (await data.json()) as Device;
countdown(Date.parse(dev.updated));
})
.catch((err) => {
toast.error(err.message);
});
}
function shutdown() {
fetch(`${backendUrl}api/upsnap/shutdown/${device.id}`, {
headers: {
Authorization: $pocketbase.authStore.token
}
})
.then(async (data) => {
const dev = (await data.json()) as Device;
countdown(Date.parse(dev.updated));
})
.catch((err) => {
toast.error(err.message);
});
}
function countdown(updated: number) {
timeout = 120;
const end = updated + 2 * 60 * 1000;
interval = setInterval(() => {
timeout = Math.round((end - Date.now()) / 1000);
if (timeout <= 0 || device.status !== 'pending') {
clearInterval(interval);
}
}, 1000);
}
function handleClick() {
if (device.status === 'offline') {
wake();
} else if (device.status === 'online') {
shutdown();
}
}
</script>
<li class="tooltip" class:disabled data-tip={hoverText}>
<div
class="flex items-start p-2 gap-4"
on:click={disabled ? null : handleClick}
on:keydown={disabled ? null : handleClick}
role="none"
>
{#if device.status === 'offline'}
<button class="btn btn-error flex-shrink"><Fa icon={faPowerOff} /></button>
{:else if device.status === 'online'}
<button
class="btn btn-success flex-shrink"
class:cursor-not-allowed={device.shutdown_cmd === ''}><Fa icon={faPowerOff} /></button
>
{:else if device.status === 'pending'}
<button class="btn btn-warning flex-shrink">
<span class="countdown font-mono">
<span style="--value:{minutes};" />:
<span style="--value:{seconds};" />
</span>
</button>
{:else}
<button class="btn btn-warning flex-shrink">
<span class="loading loading-ring loading-sm" />
</button>
{/if}
<div class="grow">
<div class="text-lg font-bold leading-4">{device.ip}</div>
<div>{device.mac}</div>
<div class="flex flex-wrap gap-x-4 gap-y-0">
{#if device?.expand?.ports}
{#each device?.expand?.ports.sort((a, b) => a.number - b.number) as port}
<span class="flex items-center gap-1 break-all">
{#if port.status}
<Fa icon={faCircle} class="text-success" />
{port.name} ({port.number})
{:else}
<Fa icon={faCircle} class="text-error" />
{port.name} ({port.number})
{/if}
</span>
{/each}
{/if}
</div>
</div>
</div>
</li>
<style>
:global(.menu li.disabled) {
color: inherit;
}
</style>
@@ -0,0 +1,605 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { pocketbase, permission } from '$lib/stores/pocketbase';
import DeviceFormPort from '$lib/components/DeviceFormPort.svelte';
import toast from 'svelte-french-toast';
import Fa from 'svelte-fa';
import { faSave, faTrash, faX } from '@fortawesome/free-solid-svg-icons';
import type { Device, Port, Group } from '$lib/types/device';
import { onMount } from 'svelte';
export let device: Device;
let deleteModal: HTMLDialogElement;
let deviceGroups = [] as Group[];
let newGroup = '';
onMount(async () => {
await getGroups();
});
async function save() {
// create/update all ports
let portIds: string[] = [];
await Promise.all(
device.expand.ports.map(async (port) => {
if (port.id === undefined) {
const data = await createPort(port as Port);
if (data === undefined) return;
portIds = [...portIds, data.id];
} else {
const data = await updatePort(port as Port);
if (data === undefined) return;
portIds = [...portIds, data.id];
}
})
);
device.ports = portIds;
device.id ? updateDevice(device) : createDevice(device);
}
async function updateDevice(device: Device) {
$pocketbase
.collection('devices')
.update(device.id, device)
.then(() => {
toast.success(`Updated ${device.name}`);
goto('/');
})
.catch((err) => {
toast.error(err.message);
});
}
async function createDevice(device: Device) {
device.created_by = $pocketbase.authStore.isAdmin ? '' : $pocketbase.authStore.model?.id ?? '';
$pocketbase
.collection('devices')
.create(device)
.then(() => {
toast.success(`Created ${device.name}`);
goto('/');
})
.catch((err) => {
toast.error(err.message);
});
}
async function createPort(port: Port): Promise<Port | undefined> {
let newport: Port | undefined;
await $pocketbase
.collection('ports')
.create(port)
.then((data) => {
newport = data as Port;
})
.catch((err) => {
toast.error(err.message);
newport = undefined;
});
return newport;
}
async function updatePort(port: Port): Promise<Port | undefined> {
let newport: Port | undefined;
await $pocketbase
.collection('ports')
.update(port.id, port)
.then((data) => {
newport = data as Port;
})
.catch((err) => {
toast.error(err.message);
newport = undefined;
});
return newport;
}
function deleteDevice() {
$pocketbase
.collection('devices')
.delete(device.id)
.then(() => {
toast.success(`Deleted ${device.name}`);
goto('/');
})
.catch((err) => {
toast.error(err.message);
});
}
function createEmptyPort() {
if (device === undefined) return;
device.expand.ports = [...device.expand.ports, { name: '', number: 1 } as Port];
}
async function getGroups() {
$pocketbase
.collection('device_groups')
.getFullList()
.then((res) => {
deviceGroups = res as Group[];
});
}
function addGroup() {
if (!newGroup) return;
$pocketbase
.collection('device_groups')
.create({
name: newGroup
})
.then((res) => {
deviceGroups = [...deviceGroups, res as Group];
toast.success(`Created group ${newGroup}`);
})
.catch((err) => {
toast.error(err.message);
});
}
function deleteGroup(group: Group) {
const i = device.groups.indexOf(group.id);
if (i !== -1) {
device.groups.splice(i, 1);
device.groups = device.groups;
}
$pocketbase
.collection('device_groups')
.delete(group.id)
.then(async () => {
await getGroups();
toast.success(`Deleted group ${group.name}`);
})
.catch((err) => {
toast.error(err.message);
});
}
function toggleGroup(id: string) {
const i = device.groups.indexOf(id);
if (i !== -1) {
device.groups.splice(i, 1);
device.groups = device.groups;
} else {
device.groups = [...device.groups, id];
}
}
</script>
<form on:submit|preventDefault={save}>
<div class="card w-full bg-base-300 shadow-xl">
<div class="card-body">
<h2 class="card-title">General</h2>
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
<div class="form-control w-full max-w-xs">
<label class="label" for="device-name">
<div class="label-text">
<span>Name</span>
<span class="text-error">*</span>
</div>
</label>
<input
id="device-name"
type="text"
placeholder="Device name"
class="input w-full max-w-xs"
bind:value={device.name}
required
/>
</div>
<div class="form-control w-full max-w-xs">
<label class="label" for="device-ip">
<div class="label-text">
<span>IP</span>
<span class="text-error">*</span>
</div>
</label>
<input
id="device-ip"
type="text"
placeholder="192.168.0.5"
class="input w-full max-w-xs"
bind:value={device.ip}
required
/>
</div>
<div class="form-control w-full max-w-xs">
<label class="label" for="device-mac">
<div class="label-text">
<span>Mac</span>
<span class="text-error">*</span>
</div>
</label>
<input
id="device-mac"
type="text"
placeholder="aa:bb:cc:dd:ee:ff"
class="input w-full max-w-xs"
bind:value={device.mac}
required
/>
</div>
<div class="form-control w-full max-w-xs">
<label class="label" for="device-netmask">
<div class="label-text">
<span>Netmask</span>
<span class="text-error">*</span>
</div>
</label>
<input
id="device-netmask"
type="text"
placeholder="255.255.255.0"
class="input w-full max-w-xs"
bind:value={device.netmask}
required
/>
</div>
<span class="badge text-error self-center">* required field</span>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Ports</h2>
<p class="my-2">UpSnap can also check if given ports are open. You can define them below.</p>
<div class="form-control w-full">
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
<!-- eslint-disable-next-line @typescript-eslint/no-unused-vars -->
{#each device.expand.ports as _, index}
<DeviceFormPort bind:device {index} />
{/each}
</div>
<button
class="btn btn-wide btn-primary mt-4"
on:click={() => createEmptyPort()}
type="button">Add new port</button
>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Link</h2>
<p class="my-2">
Makes your device name a clickable link, perfect for linking a dashboard for example.
</p>
<div class="form-control w-full">
<input
type="url"
placeholder="https:// ..."
class="input w-full max-w-xs"
bind:value={device.link}
/>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Wake</h2>
<p class="my-2">
You can power this device using a scheduled cron job. If you are not familiar with cron, you
can read about it <a class="link" href="https://en.wikipedia.org/wiki/Cron" target="_blank"
>here</a
>
or refer to the
<a class="link" href="https://pkg.go.dev/github.com/robfig/cron/v3" target="_blank"
>package documentation</a
>
for more information.
</p>
<div class="form-control flex flex-row flex-wrap gap-4">
<div>
<label class="label" for="wake-cron">
<span class="label-text"
>Wake cron
{#if device.wake_cron_enabled}
<span class="text-error">*</span>
{/if}
</span>
</label>
<input
id="wake-cron"
type="text"
placeholder="M H DoM M DoW"
class="input w-80"
bind:value={device.wake_cron}
disabled={!device.wake_cron_enabled}
required={device.wake_cron_enabled}
/>
</div>
<div class="flex flex-col">
<label class="label cursor-pointer" for="wake-cron-enable">
<span class="label-text">Enable wake cron</span>
</label>
<input
id="wake-cron-enable"
type="checkbox"
class="toggle toggle-success"
bind:checked={device.wake_cron_enabled}
/>
</div>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Sleep-On-LAN</h2>
<p class="mt-2">
You can put computers to sleep using the <a
class="link"
href="https://github.com/SR-G/sleep-on-lan"
target="_blank">Sleep-On-LAN</a
>
tool. Sleep-On-LAN (SOL) is an external tool/daemon that operates on the PCs you want to put
to sleep, providing a REST endpoint. For instructions on setting up Sleep-On-LAN, please refer
to the
<a href="https://github.com/SR-G/sleep-on-lan#usage" class="link" target="_blank">Usage</a> section.
</p>
<p>
SOL is confiugred to send requests over HTTP instead of UDP to enable authorization and make
requests more reliable.
</p>
<p class="font-bold">
Therefore, please ensure that you include <span class="badge">HTTP:&lt;YOURPORT&gt;</span>
in the <span class="badge">Listeners</span> section of the
<a href="https://github.com/SR-G/sleep-on-lan#configuration" class="link" target="_blank"
>SOL configuration</a
>.
</p>
<div class="flex flex-row flex-wrap gap-4 items-end mt-4">
<div>
<div class="form-control flex flex-row flex-wrap gap-4">
<div class="flex flex-row gap-2 items-center">
<input
id="sol-enable"
type="checkbox"
class="toggle toggle-success"
bind:checked={device.sol_enabled}
/>
<label class="label cursor-pointer" for="sol-enable">
<span class="label-text">Enable Sleep-On-LAN</span>
</label>
</div>
</div>
<div class="form-control flex flex-col">
<label class="label" for="sol-port">
<span class="label-text"
>SOL Port
{#if device.sol_enabled}
<span class="text-error">*</span>
{/if}
</span>
</label>
<input
id="sol-port"
type="number"
min="1"
max="65535"
placeholder="Default: 8009"
class="input w-80"
bind:value={device.sol_port}
disabled={!device.sol_enabled}
required={device.sol_enabled}
/>
</div>
</div>
{#if device.sol_enabled}
<div>
<div class="form-control flex flex-row flex-wrap gap-4">
<div class="flex flex-row gap-2 items-center">
<input
id="sol-auth"
type="checkbox"
class="toggle toggle-success"
bind:checked={device.sol_auth}
/>
<label class="label cursor-pointer" for="sol-auth">
<span class="label-text">Authorization</span>
</label>
</div>
</div>
<div class="form-control flex flex-col">
<label class="label" for="sol-user">
<span class="label-text"
>SOL User
{#if device.sol_auth}
<span class="text-error">*</span>
{/if}
</span>
</label>
<input
id="sol-user"
type="text"
placeholder="username"
class="input w-80"
bind:value={device.sol_user}
disabled={!device.sol_auth}
required={device.sol_auth}
/>
</div>
</div>
<div class="form-control flex flex-col">
<label class="label" for="sol-password">
<span class="label-text"
>SOL Password
{#if device.sol_auth}
<span class="text-error">*</span>
{/if}
</span>
</label>
<input
id="sol-password"
type="password"
placeholder="password"
class="input w-80"
bind:value={device.sol_password}
disabled={!device.sol_auth}
required={device.sol_auth}
/>
</div>
{/if}
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Shutdown</h2>
<p class="my-2">
This <strong>shell command</strong> will run inside your container (if you use docker) or on
your host (if you use the binary). To verify that works you can run the command inside the
container or on your host shell first. Common commands are
<span class="badge">net rpc</span> for windows, <span class="badge">sshpass</span> for linux
or
<span class="badge">curl</span> in general to make web requests.
</p>
<p class="my-2 font-bold">Examples:</p>
<div class="mockup-code text-sm max-w-fit">
<pre data-prefix="#"><code>Shutdown remote windows machine:</code></pre>
<pre data-prefix="$" class="text-warning"><code
>net rpc shutdown -I 192.168.1.13 -U "user%password"</code
></pre>
</div>
<div class="mockup-code text-sm max-w-fit">
<pre data-prefix="#"><code>Shutdown remote linux machine:</code></pre>
<pre data-prefix="$" class="text-warning"><code
>sshpass -p password ssh -o "StrictHostKeyChecking=no" user@192.168.1.13 "sudo poweroff"</code
></pre>
</div>
<div class="form-control w-full">
<label class="label cursor-pointer" for="shutdown-cmd">
<span class="label-text">Shutdown command</span>
</label>
<input
id="shutdown-cmd"
type="text"
placeholder="$:"
class="input w-full max-w-xs mb-2"
bind:value={device.shutdown_cmd}
/>
</div>
<p class="my-2">
Just like setting a cron to wake the device, you can also schedule a cron job to shut down
this device.
</p>
<div class="form-control flex flex-row flex-wrap gap-4">
<div>
<label class="label" for="shutdown-cron">
<span class="label-text"
>Shutdown cron
{#if device.shutdown_cron_enabled}
<span class="text-error">*</span>
{/if}
</span>
</label>
<input
id="shutdown-cron"
type="text"
placeholder="M H DoM M DoW"
class="input w-80"
bind:value={device.shutdown_cron}
disabled={!device.shutdown_cron_enabled}
required={device.shutdown_cron_enabled}
/>
</div>
<div class="flex flex-col">
<label class="label cursor-pointer" for="shutdown-cron-enable">
<span class="label-text">Enable shutdown cron</span>
</label>
<input
id="shutdown-cron-enable"
type="checkbox"
class="toggle toggle-success"
bind:checked={device.shutdown_cron_enabled}
/>
</div>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Password</h2>
<p class="my-2">
Some network cards have the option to set a password for magic packets, also called <span
class="badge">SecureON</span
>. Password can only be 0, 4 or 6 characters in length.
</p>
<div class="form-control w-full">
<input
type="password"
placeholder="123456"
class="input w-full max-w-xs"
maxlength="6"
bind:value={device.password}
/>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Groups</h2>
<p class="my-2">
You can add devices to a group to have them sorted by group on the dashboard.
</p>
<div class="flex flex-row flex-wrap gap-2">
{#each deviceGroups as group}
<div class="join">
<div class=" tooltip" data-tip="Delete">
<button
class="join-item btn btn-error"
type="button"
on:click={() => deleteGroup(group)}><Fa icon={faX} /></button
>
</div>
<div
class="btn bg-base-100 hover:bg-base-200 join-item"
on:click={() => toggleGroup(group.id)}
role="none"
>
<input
type="checkbox"
class="checkbox checked:checkbox-primary"
checked={device.groups.indexOf(group.id) !== -1}
/>
{group.name}
</div>
</div>
{/each}
</div>
<div class="join">
<input
class="input input-bordered join-item"
placeholder="e.g. 'Basement' or 'Office'"
type="text"
bind:value={newGroup}
/>
<button class="btn btn-primary join-item" type="button" on:click={() => addGroup()}
>Create</button
>
</div>
</div>
</div>
<div class="card-actions mt-6 justify-end gap-4">
{#if $pocketbase.authStore.isAdmin || $permission.delete?.includes(device.id)}
<button class="btn btn-error" type="button" on:click={() => deleteModal.showModal()}
><Fa icon={faTrash} />Delete</button
>
<dialog class="modal" bind:this={deleteModal}>
<form method="dialog" class="modal-box">
<h3 class="font-bold text-lg">Confirm delete</h3>
<p class="py-4">Are you sure you want to delete <strong>{device.name}</strong>?</p>
<div class="modal-action">
<button class="btn">Cancle</button>
<button class="btn btn-error" on:click={() => deleteDevice()}>Delete</button>
</div>
</form>
</dialog>
{/if}
<button class="btn btn-success" type="submit"><Fa icon={faSave} />Save</button>
</div>
</form>
@@ -0,0 +1,71 @@
<script lang="ts">
import { pocketbase } from '$lib/stores/pocketbase';
import { scale } from 'svelte/transition';
import Fa from 'svelte-fa';
import { faTrash } from '@fortawesome/free-solid-svg-icons';
import toast from 'svelte-french-toast';
import type { Device, Port } from '$lib/types/device';
import type { Record } from 'pocketbase';
export let device: Device;
export let index: number;
function deletePort(port: Port | Record) {
if (port.id !== undefined) {
$pocketbase
.collection('ports')
.delete(port.id)
.then(() => {
device.ports = device.ports.filter((id) => id !== device.ports[index]);
})
.catch((err) => {
toast.error(err.message);
});
}
device.expand.ports = device.expand.ports.filter((p) => p !== device.expand.ports[index]);
}
</script>
{#if device.expand.ports[index]}
<div class="card bg-base-100 shadow-sm" transition:scale={{ delay: 0, duration: 200 }}>
<div class="card-body p-3">
<div class="flex flex-row gap-2">
<div>
<label class="label p-0" for="port-name-{index}">
<span class="label-text">Name</span>
</label>
<input
id="port-name-{index}"
type="text"
placeholder="ssh"
class="input input-sm input-bordered w-full"
required
bind:value={device.expand.ports[index].name}
/>
</div>
<div>
<label class="label p-0" for="port-number-{index}">
<span class="label-text">Number</span>
</label>
<input
id="port-number-{index}"
type="number"
placeholder="22"
min="1"
max="65535"
class="input input-sm input-bordered w-full"
required
bind:value={device.expand.ports[index].number}
/>
</div>
</div>
<div class="card-actions justify-end">
<button
class="btn btn-xs btn-outline btn-error"
on:click={() => deletePort(device.expand.ports[index])}
type="button"><Fa icon={faTrash} />Delete</button
>
</div>
</div>
</div>
{/if}
+235
View File
@@ -0,0 +1,235 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
import { settingsPub } from '$lib/stores/settings';
import Fa from 'svelte-fa';
import {
faCog,
faHome,
faPlus,
faSwatchbook,
faChevronDown,
faCheck,
faUsersGear,
faUserGear,
faDoorOpen
} from '@fortawesome/free-solid-svg-icons';
import { themeChange } from 'theme-change';
import { onMount } from 'svelte';
let availableThemes = [
'light',
'dark',
'cupcake',
'bumblebee',
'emerald',
'corporate',
'synthwave',
'retro',
'cyberpunk',
'valentine',
'halloween',
'garden',
'forest',
'aqua',
'lofi',
'pastel',
'fantasy',
'wireframe',
'black',
'luxury',
'dracula',
'cmyk',
'autumn',
'business',
'acid',
'lemonade',
'night',
'coffee',
'winter'
];
let activeTheme: string | null = '';
let avatar = $pocketbase.authStore.model?.avatar;
onMount(() => {
themeChange(false);
activeTheme = document.documentElement.getAttribute('data-theme');
$pocketbase.authStore.onChange(() => {
avatar = $pocketbase.authStore.model?.avatar;
});
});
async function logout() {
await $pocketbase.collection('devices').unsubscribe('*');
await $pocketbase.collection('ports').unsubscribe('*');
await $pocketbase.collection('permissions').unsubscribe('*');
$pocketbase.authStore.clear();
goto('/login', { invalidateAll: true });
}
</script>
<div class="navbar bg-base-100">
<div class="justify-start">
<div class="dropdown">
<label tabindex="-1" class="btn btn-ghost lg:hidden" for="mobile-menu">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
><path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 6h16M4 12h8m-8 6h16"
/></svg
>
</label>
<ul
id="mobile-menu"
tabindex="-1"
class="menu dropdown-content mt-3 z-[1] p-2 gap-1 shadow bg-base-300 rounded-box w-52"
>
{#if $settingsPub?.website_title}
<div class="menu-title">
{$settingsPub?.website_title}
</div>
{/if}
<li>
<a href="/" class="px-4 py-2" class:active={$page.url.pathname === '/'}
><Fa icon={faHome} />Home</a
>
</li>
{#if $pocketbase.authStore.isAdmin}
<li>
<a
href="/users"
class="px-4 py-2"
class:active={$page.url.pathname.startsWith('/users')}
><Fa icon={faUsersGear} />Users</a
>
</li>
<li>
<a
href="/settings/"
class="px-4 py-2"
class:active={$page.url.pathname.startsWith('/settings')}
><Fa icon={faCog} />Settings</a
>
</li>
{/if}
</ul>
</div>
<a class="btn btn-ghost normal-case text-xl px-2" href="/">
<img
src={$settingsPub?.id && $settingsPub?.favicon
? `${backendUrl}api/files/settings_public/${$settingsPub?.id}/${$settingsPub?.favicon}`
: '/gopher.svg'}
alt={$settingsPub?.website_title ? $settingsPub?.website_title : 'UpSnap'}
width="45"
height="45"
/>
</a>
</div>
<div class="hidden lg:flex">
{#if $settingsPub?.website_title}
<span class="px-2">{$settingsPub?.website_title}</span>
{/if}
<ul class="menu menu-horizontal px-1 gap-1">
<li>
<a href="/" class="p-2" class:active={$page.url.pathname === '/'}
><Fa icon={faHome} />Home</a
>
</li>
{#if $pocketbase.authStore.isAdmin}
<li>
<a href="/users" class="p-2" class:active={$page.url.pathname.startsWith('/users')}
><Fa icon={faUsersGear} />Users</a
>
</li>
<li>
<a href="/settings/" class="p-2" class:active={$page.url.pathname.startsWith('/settings')}
><Fa icon={faCog} />Settings</a
>
</li>
{/if}
</ul>
</div>
<div class="dropdown md:dropdown-end">
<div tabindex="-1" class="btn normal-case btn-ghost">
<Fa icon={faSwatchbook} />
<span class="hidden font-normal md:inline">Theme</span>
<Fa icon={faChevronDown} />
</div>
<div
class="dropdown-content bg-base-200 text-base-content rounded-box h-fit max-h-96 w-56 overflow-y-auto shadow mt-3 z-[1]"
>
<div class="grid grid-cols-1 gap-3 p-3" tabindex="-1">
{#each availableThemes as theme}
<button
class="outline-base-content overflow-hidden rounded-lg text-left"
data-set-theme={theme}
on:click={() => (activeTheme = theme)}
on:keydown={() => (activeTheme = theme)}
>
<div
data-theme={theme}
class="bg-base-100 text-base-content w-full cursor-pointer font-sans"
>
<div class="grid grid-cols-5 grid-rows-3">
<div class="col-span-5 row-span-3 row-start-1 flex items-center gap-2 px-4 py-3">
<Fa icon={faCheck} class={activeTheme === theme ? 'visible' : 'invisible'} />
<div class="flex-grow text-sm">{theme}</div>
<div class="flex h-full flex-shrink-0 flex-wrap gap-1">
<div class="bg-primary w-2 rounded" />
<div class="bg-secondary w-2 rounded" />
<div class="bg-accent w-2 rounded" />
<div class="bg-neutral w-2 rounded" />
</div>
</div>
</div>
</div>
</button>
{/each}
</div>
</div>
</div>
<div class="justify-end ms-auto">
{#if $pocketbase.authStore?.model !== null}
{#if $pocketbase.authStore.isAdmin || $permission.create}
<a class="btn btn-success me-4" href="/device/new">
<Fa icon={faPlus} />
New
</a>
{/if}
<div class="dropdown dropdown-end">
<label tabindex="-1" class="btn btn-ghost btn-circle avatar" for="avatar">
<div class="w-10 rounded-full" id="avatar">
<img src="{backendUrl}_/images/avatars/avatar{avatar}.svg" alt="Avatar {avatar}" />
</div>
</label>
<ul
tabindex="-1"
class="menu dropdown-content mt-3 z-[1] p-2 shadow bg-base-300 rounded-box"
>
<li class="menu-title">
{$pocketbase.authStore.isAdmin
? $pocketbase.authStore.model.email
: $pocketbase.authStore.model.username}
</li>
<li>
<a href="/account"><Fa icon={faUserGear} />Edit account</a>
</li>
<li>
<div on:click={async () => logout()} on:keydown={async () => logout()} role="none">
<Fa icon={faDoorOpen} />Logout
</div>
</li>
</ul>
</div>
{/if}
</div>
</div>
@@ -0,0 +1,267 @@
<script lang="ts">
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { pocketbase, backendUrl } from '$lib/stores/pocketbase';
import { settingsPriv } from '$lib/stores/settings';
import PageLoading from '$lib/components/PageLoading.svelte';
import Fa from 'svelte-fa';
import { faMagnifyingGlass, faPlus, faX } from '@fortawesome/free-solid-svg-icons';
import toast from 'svelte-french-toast';
import type { SettingsPrivate } from '$lib/types/settings';
import type { ScanResponse, ScannedDevice } from '$lib/types/scan';
import type { Device } from '$lib/types/device';
let scanRange = '';
let scanRunning = false;
let scanResponse: ScanResponse = {
netmask: '',
devices: []
};
let addAllCheckbox = true;
let replaceNetmaskCheckbox = false;
let replaceNetmask = '';
onMount(() => {
if (!$settingsPriv) {
$pocketbase
.collection('settings_private')
.getFirstListItem('')
.then((res) => {
settingsPriv.set(res as SettingsPrivate);
scanRange = $settingsPriv.scan_range;
})
.catch((err) => {
toast.error(err.message);
});
} else {
scanRange = $settingsPriv.scan_range;
}
});
function saveSettings() {
$pocketbase
.collection('settings_private')
.update($settingsPriv.id, {
scan_range: scanRange
})
.then((res) => {
settingsPriv.set(res as SettingsPrivate);
toast.success('Scan range saved');
})
.catch((err) => {
toast.error(err.message);
});
}
function scan() {
scanRunning = true;
fetch(`${backendUrl}api/upsnap/scan`, {
headers: {
Authorization: $pocketbase.authStore.token
}
})
.then(async (resp) => {
if (resp.ok) {
return resp.json();
} else {
return Promise.reject(await resp.json());
}
})
.then((data) => {
scanResponse = data as ScanResponse;
})
.catch((err) => {
toast.error(err);
})
.finally(() => (scanRunning = false));
}
async function createDevice(device: ScannedDevice): Promise<Device> {
if (replaceNetmaskCheckbox) {
device.netmask = replaceNetmask;
} else {
device.netmask = scanResponse.netmask;
}
return $pocketbase.collection('devices').create(device);
}
async function addSingle(device: ScannedDevice) {
await createDevice(device)
.then(() => {
toast.success(`Added ${device.name}`);
})
.catch((err) => {
toast.error(err.message);
});
}
async function addAll() {
let count = 0;
await Promise.all(
scanResponse.devices.map(async (dev) => {
if (!addAllCheckbox && dev.name === 'Unknown') return;
await createDevice(dev)
.catch((err) => {
toast.error(err.message);
})
.then(() => {
count += 1;
});
})
);
toast.success(`Added ${count} devices`);
goto('/');
}
</script>
{#if $settingsPriv}
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Network scan</h2>
<p class="my-2">
Automatically scan your network for devices. For this to work, you need to run UpSnap as
root/admin and have nmap installed and available in your $PATH (For docker users, thats
already the case and you don't need to do anything). Scanning might take some seconds.
</p>
<div class="flex flex-row flex-wrap gap-4 items-end">
<form on:submit|preventDefault={saveSettings}>
<label class="label" for="scan-range">
<span class="label-text">IP range</span>
</label>
<div class="join">
<input
id="scan-range"
class="input input-bordered join-item"
type="text"
placeholder="192.168.1.0/24"
bind:value={scanRange}
/>
<button class="btn btn-primary join-item" type="submit">Save</button>
</div>
</form>
<div>
<div>
{#if !$settingsPriv.scan_range}
<button class="btn btn-error" disabled>
<Fa icon={faX} /> No scan range
</button>
{:else if scanRange !== $settingsPriv.scan_range}
<button class="btn btn-error" disabled>
<Fa icon={faX} /> Unsaved changes
</button>
{:else if scanRunning}
<button class="btn no-animation">
<span class="loading loading-spinner" />
Scan running
</button>
{:else}
<button class="btn btn-success" on:click={() => scan()}>
<Fa icon={faMagnifyingGlass} /> Scan
</button>
{/if}
</div>
</div>
</div>
{#if scanResponse.devices?.length > 0}
{#each scanResponse.devices.sort( (a, b) => a.ip.localeCompare( b.ip, undefined, { numeric: true } ) ) as device, index}
<div class="collapse collapse-arrow bg-base-200">
<input type="radio" name="scanned-devices" checked={index === 0} />
<div class="collapse-title font-bold">
{device.name} <span class="badge">{device.ip}</span>
</div>
<div class="collapse-content">
<div class="flex flex-row flex-wrap gap-4">
<div>
<strong>IP:</strong><br />
{device.ip}
</div>
<div>
<strong>Mac:</strong><br />
{device.mac}
</div>
<div>
<strong>Mac vendor:</strong><br />
{device.mac_vendor}
</div>
<div>
<strong>Netmask:</strong><br />
{scanResponse.netmask}
</div>
<div class="ms-auto">
<button
class="btn btn-sm btn-success"
on:click={(e) => {
addSingle(device);
e.currentTarget.disabled = true;
}}><Fa icon={faPlus} />Add</button
>
</div>
</div>
</div>
</div>
{/each}
<h2 class="card-title mt-4">Add all devices</h2>
<div class="form-control max-w-fit">
<label class="label cursor-pointer">
<input type="checkbox" class="checkbox" bind:checked={replaceNetmaskCheckbox} />
<span class="label-text ms-2">Replace netmask for all devices?</span>
</label>
</div>
{#if replaceNetmaskCheckbox}
<div class="form-control max-w-fit">
<label class="label cursor-pointer" for="replaceNetmaskInput">
<span class="label-text ms-2">New netmask</span>
</label>
<input
id="replaceNetmaskInput"
class="input input-bordered"
type="text"
placeholder="255.255.0.0"
bind:value={replaceNetmask}
/>
</div>
{/if}
{#if scanResponse.devices.find((dev) => dev.name === 'Unknown')}
<div class="form-control max-w-fit">
<label class="label cursor-pointer">
<input type="checkbox" class="checkbox" bind:checked={addAllCheckbox} />
<span class="label-text ms-2">Include devices where name is "Unknown"</span>
</label>
{#if addAllCheckbox}
<button
class="btn btn-success"
on:click={() => addAll()}
disabled={scanResponse.devices.length === 0}
>
<Fa icon={faPlus} /> Add all ({scanResponse.devices.length})
</button>
{:else}
<button
class="btn btn-success"
on:click={() => addAll()}
disabled={scanResponse.devices.filter((dev) => dev.name !== 'Unknown').length === 0}
>
<Fa icon={faPlus} /> Add all ({scanResponse.devices.filter(
(dev) => dev.name !== 'Unknown'
).length})
</button>
{/if}
</div>
{:else}
<div class="form-control max-w-fit">
<button
class="btn btn-success"
on:click={() => addAll()}
disabled={scanResponse.devices.length === 0}
>
<Fa icon={faPlus} /> Add all ({scanResponse.devices.length})
</button>
</div>
{/if}
{/if}
</div>
</div>
{:else}
<PageLoading />
{/if}
@@ -0,0 +1,3 @@
<div class="container max-w-lg mx-auto text-center">
<span class="loading loading-dots loading-lg" />
</div>
@@ -0,0 +1,10 @@
<script lang="ts">
import { fly } from 'svelte/transition';
export let url: URL;
</script>
{#key url}
<div in:fly={{ y: 50, duration: 300 }}>
<slot />
</div>
{/key}
+7
View File
@@ -0,0 +1,7 @@
export function toggleVisibility(el: HTMLInputElement) {
if (el.type === 'password') {
el.type = 'text';
} else {
el.type = 'password';
}
}
+14
View File
@@ -0,0 +1,14 @@
import { writable } from 'svelte/store';
import PocketBase from 'pocketbase';
import type { Permission } from '$lib/types/permission';
// set backend url based on environment
export const backendUrl = import.meta.env.DEV ? 'http://127.0.0.1:8090/' : '/';
// connect to backend
const pb = new PocketBase(backendUrl);
pb.autoCancellation(false);
// export stores
export const pocketbase = writable(pb);
export const permission = writable({} as Permission);
+5
View File
@@ -0,0 +1,5 @@
import { writable } from 'svelte/store';
import type { SettingsPublic, SettingsPrivate } from '$lib/types/settings';
export const settingsPub = writable<SettingsPublic>();
export const settingsPriv = writable<SettingsPrivate>();
+37
View File
@@ -0,0 +1,37 @@
import type { Record } from 'pocketbase';
export type Device = Record & {
name: string;
ip: string;
mac: string;
netmask: string;
status: 'pending' | 'online' | 'offline' | '';
ports: string[];
link: URL;
wake_cron: string;
wake_cron_enabled: boolean;
shutdown_cron: string;
shutdown_cron_enabled: boolean;
shutdown_cmd: string;
password: string;
groups: string[];
expand: {
ports: Port[];
groups: Group[];
};
created_by: string;
sol_enabled: boolean;
sol_auth: boolean;
sol_user: string;
sol_passwort: string;
sol_port: number;
};
export type Port = Record & {
name: string;
number: number;
};
export type Group = Record & {
name: string;
};
+10
View File
@@ -0,0 +1,10 @@
import type { Record } from 'pocketbase';
export type Permission = Record & {
user: string;
create: boolean;
read: string[];
update: string[];
delete: string[];
power: string[];
};
+13
View File
@@ -0,0 +1,13 @@
export type ScannedDevice = {
name: string;
ip: string;
mac: string;
mac_vendor: string;
netmask: string;
status: 'pending' | 'online' | 'offline' | '';
};
export type ScanResponse = {
netmask: string;
devices: ScannedDevice[];
};
+14
View File
@@ -0,0 +1,14 @@
import type { Record } from 'pocketbase';
export type SettingsPublic = Record & {
collectionId: string;
favicon: string;
setup_completed: boolean;
website_title: string;
};
export type SettingsPrivate = Record & {
interval: number;
lazy_ping: boolean;
scan_range: string;
};
+7
View File
@@ -0,0 +1,7 @@
import type { Record } from 'pocketbase';
export type User = Record & {
username: string;
email: string;
avatar: number;
};
+107 -130
View File
@@ -1,148 +1,125 @@
<script>
import { dev } from '$app/environment';
import { onMount } from 'svelte';
import { page } from '$app/stores';
import Navbar from '@components/Navbar.svelte';
import Login from '@components/Login.svelte';
import Transition from '@components/Transition.svelte';
import { theme } from '@stores/theme';
import {
pocketbase,
authorizedStore,
devices,
groups,
settings_private,
settings_public
} from '@stores/pocketbase';
<script lang="ts">
import '../app.css';
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { pocketbase, backendUrl, permission } from '$lib/stores/pocketbase';
import { settingsPub } from '$lib/stores/settings';
import Navbar from '$lib/components/Navbar.svelte';
import Transition from '$lib/components/Transition.svelte';
import toast, { Toaster, type ToastOptions } from 'svelte-french-toast';
import type { SettingsPublic } from '$lib/types/settings';
import type { Permission } from '$lib/types/permission';
let favicon;
let preferesDark;
let isAuth = false;
const toastOptions: ToastOptions = {
duration: 5000
};
onMount(async () => {
// import bootstrap js
import('bootstrap/js/dist/dropdown');
import('bootstrap/js/dist/collapse');
onMount(async () => {
$pocketbase.authStore.onChange(() => {
// load user permissions
if ($pocketbase.authStore.model?.collectionName === 'users') {
$pocketbase
.collection('permissions')
.getFirstListItem(`user.id = '${$pocketbase.authStore.model.id}'`)
.then((data) => {
permission.set(data as Permission);
})
.catch(() => {
return;
});
// set dark mode
preferesDark = window.matchMedia('(prefers-color-scheme: dark)');
preferesDark.addEventListener('change', (e) => {
if ($theme === 'auto') {
document.documentElement.setAttribute(
'data-bs-theme',
e.matches ? 'dark' : 'light'
);
}
});
$pocketbase.collection('permissions').subscribe('*', (event) => {
permission.set(event.record as Permission);
toast.success('Your permissions have been updated');
});
}
});
theme.subscribe((t) => {
localStorage.setItem('theme', t);
if (t === 'auto') {
t = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
document.documentElement.setAttribute('data-bs-theme', t);
});
// set settingsPub store on load
if (!$settingsPub) {
const res = await $pocketbase.collection('settings_public').getFirstListItem('');
settingsPub.set(res as SettingsPublic);
}
authorizedStore.subscribe((state) => {
isAuth = state;
});
// redirect to welcome page if setup is not completed
if (!$settingsPub.setup_completed && $page.url.pathname !== '/welcome') {
goto('/welcome');
return;
}
// load public settings and subscribe to changes and change favicon
const settingsPublicRes = await $pocketbase.collection('settings_public').getList(1, 1);
settings_public.set(settingsPublicRes.items[0]);
updateSettingsPublic();
$pocketbase.collection('settings_public').subscribe('*', function (e) {
settings_public.set(e.record);
updateSettingsPublic();
});
// load auth from localstorage
const pbCookie = localStorage.getItem('pocketbase_auth');
if (!pbCookie) {
goto('/login');
return;
}
// load auth from localstorage
const pbCookie = localStorage.getItem('pocketbase_auth');
if (pbCookie) {
$pocketbase.authStore.loadFromCookie('pb_auth=' + pbCookie);
$pocketbase.authStore.loadFromCookie('pb_auth=' + pbCookie);
if (!$pocketbase.authStore.isValid) {
goto('/login');
return;
}
// try to refresh auth token if valid
if ($pocketbase.authStore.isValid) {
if ($pocketbase.authStore.model?.collectionName === 'users') {
await $pocketbase.collection('users').authRefresh();
} else {
await $pocketbase.admins.authRefresh();
}
}
authorizedStore.set($pocketbase.authStore.isValid);
}
});
// only refresh token if valid less than 1 day
const jwt = parseJwt($pocketbase.authStore.token);
if (jwt.exp > Date.now() / 1000 + 60 * 60 * 24) {
return;
}
function updateSettingsPublic() {
favicon.href =
$settings_public.favicon === ''
? '/gopher.svg'
: `${dev ? $pocketbase.baseUrl : ''}/api/files/settings_public/${
$settings_public.id
}/${$settings_public.favicon}`;
document.title =
$settings_public.website_title === '' ? 'UpSnap' : $settings_public.website_title;
}
if ($pocketbase.authStore.model?.collectionName === 'users') {
await $pocketbase
.collection('users')
.authRefresh()
.catch(() => {
goto('/login');
});
} else {
await $pocketbase.admins.authRefresh().catch(() => {
goto('/login');
});
}
});
async function getSettingsPrivateAndDevices() {
if ($pocketbase.authStore.model?.collectionName !== 'users') {
const settingsPrivateRes = await $pocketbase
.collection('settings_private')
.getList(1, 1);
settings_private.set(settingsPrivateRes.items[0]);
}
function parseJwt(token: string) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(
window
.atob(base64)
.split('')
.map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
})
.join('')
);
// 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();
}
return JSON.parse(jsonPayload);
}
</script>
<svelte:head>
<link rel="shortcut icon" href="/gopher.svg" bind:this={favicon} />
<script>
if (document) {
preferesDark = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
let t = localStorage.getItem('theme');
if (!t) {
localStorage.setItem('theme', 'auto');
t = preferesDark;
} else if (t === 'auto') {
t = preferesDark;
}
document.documentElement.setAttribute('data-bs-theme', t);
}
</script>
<link
rel="shortcut icon"
href={$settingsPub?.id && $settingsPub?.favicon
? `${backendUrl}api/files/settings_public/${$settingsPub?.id}/${$settingsPub?.favicon}`
: '/gopher.svg'}
/>
{#if $settingsPub === undefined}
<title>UpSnap</title>
{:else}
<title>{$settingsPub.website_title === '' ? 'UpSnap' : $settingsPub.website_title}</title>
{/if}
</svelte:head>
{#if isAuth}
<Navbar />
<Transition url={$page.url}>
<slot />
</Transition>
{:else}
<Login />
{#if $pocketbase.authStore.isValid}
<Navbar />
{/if}
<style lang="scss" global>
@import '../scss/main.scss';
</style>
<Toaster position="bottom-center" {toastOptions} />
<Transition url={$page.url}>
<div class="container mx-auto p-2 mb-4">
<slot />
</div>
</Transition>
+184 -88
View File
@@ -1,95 +1,191 @@
<script>
import { onMount } from 'svelte';
import DeviceCard from '@components/DeviceCard.svelte';
import { pocketbase, devices } from '@stores/pocketbase';
import { sortDevices, sortGroups } from '../sorts';
<script lang="ts">
import { onMount } from 'svelte';
import { pocketbase, permission } from '$lib/stores/pocketbase';
import DeviceCard from '$lib/components/DeviceCard.svelte';
import PageLoading from '$lib/components/PageLoading.svelte';
import toast from 'svelte-french-toast';
import Fa from 'svelte-fa';
import {
faChevronCircleLeft,
faChevronCircleRight,
faPlus
} from '@fortawesome/free-solid-svg-icons';
import { browser } from '$app/environment';
import type { Device } from '$lib/types/device';
onMount(async () => {
// subscribe to database events
$pocketbase.collection('devices').subscribe('*', async (e) => {
if (e.action === 'create') {
$devices[e.record.id] = e.record;
} else if (e.action === 'update') {
const device = await $pocketbase.collection('devices').getOne(e.record.id, {
expand: 'ports,groups'
});
$devices[device.id] = device;
} else if (e.action === 'delete') {
delete $devices[e.record.id];
}
});
$pocketbase.collection('ports').subscribe('*', async (e) => {
if (e.action === 'update') {
const device = Object.values($devices).find((dev) =>
dev.ports.includes(e.record.id)
);
if (!device) {
return;
}
let loading = true;
let devices = [] as Device[];
let devicesWithGroup: {
[key: string]: Device[];
};
let devicesWithoutGroups = [] as Device[];
let orderBy: 'name' | 'ip';
let orderExpanded = false;
let orderByGroups: boolean;
const gridClass =
'grid grid-flow-row-dense grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4';
// replace device.expand.ports with updated record
const portIdx = device.expand.ports.findIndex((port) => port.id === e.record.id);
$devices[device.id].expand.ports[portIdx] = e.record;
}
});
});
$: {
devicesWithoutGroups = [];
devicesWithoutGroups = devices.filter((dev) => dev.groups.length === 0);
}
let devicesWithoutGroups = [];
let devicesWithGroup = {};
$: {
devicesWithGroup = {};
devices.forEach((dev) => {
dev?.expand?.groups?.forEach((group) => {
if (!devicesWithGroup[group.name]) {
devicesWithGroup[group.name] = [];
}
devicesWithGroup[group.name] = [...devicesWithGroup[group.name], dev];
});
});
}
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];
});
});
});
$: if (browser && orderBy !== undefined) {
localStorage.setItem('orderBy', orderBy);
}
$: if (browser && orderByGroups !== undefined) {
localStorage.setItem('orderByGroups', orderByGroups.toString());
}
// update device date
let now = Date.now();
let interval;
$: {
clearInterval(interval);
interval = setInterval(() => {
now = Date.now();
}, 1000);
}
function getAllDevices() {
$pocketbase
.collection('devices')
.getFullList(1000, { sort: 'name', expand: 'ports,groups' })
.then((resp) => {
devices = resp as Device[];
})
.catch((err) => {
toast.error(err.message);
})
.finally(() => {
loading = false;
});
}
onMount(() => {
// get soring from local storage
const lsO = localStorage.getItem('orderBy');
if (lsO === 'name' || lsO === 'ip') {
orderBy = lsO;
} else {
orderBy = 'name';
}
if (localStorage.getItem('orderByGroups') === null) {
orderByGroups = true;
} else {
orderByGroups = localStorage.getItem('orderByGroups') === 'true' ? true : false;
}
// get collections and subscribe to changes
getAllDevices();
$pocketbase.collection('devices').subscribe('*', () => {
getAllDevices();
});
$pocketbase.collection('ports').subscribe('*', () => {
getAllDevices();
});
$pocketbase.collection('permissions').subscribe('*', () => {
getAllDevices();
});
});
</script>
<div class="container text-body-emphasis mb-4">
{#if Object.keys($devices).length > 0}
{#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>
<p>
<a class="text-muted" href="/settings">Go to settings to add devices...</a>
</p>
</div>
{/if}
</div>
{#if loading}
<PageLoading />
{:else if devices.length > 0}
<div class="flex justify-end">
<div class="join mb-4">
{#if orderExpanded}
<div class="join-item">
<div class="join">
<button
class="join-item btn"
type="button"
on:click={() => (orderByGroups = !orderByGroups)}
>Groups
<input
type="checkbox"
class="checkbox checked:checkbox-primary"
checked={orderByGroups}
/>
</button>
</div>
</div>
<input
class="join-item btn"
type="radio"
name="order"
aria-label="Name"
bind:group={orderBy}
value="name"
/>
<input
class="join-item btn"
type="radio"
name="order"
aria-label="IP"
bind:group={orderBy}
value="ip"
/>
{/if}
<div class="tooltip" data-tip="Order">
<button class="join-item btn" on:click={() => (orderExpanded = !orderExpanded)}>
{#if orderExpanded}
<Fa icon={faChevronCircleRight} size="lg" />
{:else}
<Fa icon={faChevronCircleLeft} size="lg" />
{/if}
</button>
</div>
</div>
</div>
{#if orderByGroups}
<div class="space-y-6">
{#if devicesWithoutGroups.length > 0}
<div class={gridClass}>
{#each devicesWithoutGroups.sort( (a, b) => a[orderBy].localeCompare( b[orderBy], undefined, { numeric: true, sensitivity: 'base' } ) ) as device}
<DeviceCard {device} />
{/each}
</div>
{/if}
{#if Object.keys(devicesWithGroup).length > 0}
{#each Object.keys(devicesWithGroup).sort( (a, b) => a.localeCompare( b, undefined, { numeric: true, sensitivity: 'base' } ) ) as group}
<div>
<h1 class="text-2xl font-bold mb-3">{group}</h1>
<div class={gridClass}>
{#each devicesWithGroup[group].sort( (a, b) => a[orderBy].localeCompare( b[orderBy], undefined, { numeric: true, sensitivity: 'base' } ) ) as device}
<DeviceCard {device} />
{/each}
</div>
</div>
{/each}
{/if}
</div>
{:else}
<div class={gridClass}>
{#each devices.sort( (a, b) => a[orderBy].localeCompare( b[orderBy], undefined, { numeric: true, sensitivity: 'base' } ) ) as device}
<DeviceCard {device} />
{/each}
</div>
{/if}
{:else}
<div class="container text-center">
<p>No devices here.</p>
{#if $pocketbase.authStore.isAdmin || $permission.create}
<p>
<a href="/device/new" class="btn btn-ghost"
><Fa icon={faPlus} class="ms-2" />Add your first device
</a>
</p>
{:else}
<p>
Please ask the admin to grant you permissions to existing devices or to create new ones.
</p>
{/if}
</div>
{/if}
+201
View File
@@ -0,0 +1,201 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { pocketbase, backendUrl } from '$lib/stores/pocketbase';
import toast from 'svelte-french-toast';
import Fa from 'svelte-fa';
import { faSave } from '@fortawesome/free-solid-svg-icons';
let newAvatar: number;
let newPassword = {
old: '',
password: '',
confirm: ''
};
$: adminBody = JSON.stringify({
password: newPassword.password,
passwordConfirm: newPassword.confirm
});
$: userBody = JSON.stringify({
oldPassword: newPassword.old,
password: newPassword.password,
passwordConfirm: newPassword.confirm
});
function changeAvatar() {
if ($pocketbase.authStore.isAdmin) {
if (!$pocketbase.authStore.model?.id) return;
$pocketbase.admins
.update($pocketbase.authStore.model.id, { avatar: newAvatar })
.then(() => {
toast.success('Avatar saved');
})
.catch((err) => {
toast.error(err.message);
});
} else {
if (!$pocketbase.authStore.model?.id) return;
$pocketbase
.collection('users')
.update($pocketbase.authStore.model.id, { avatar: newAvatar })
.then(() => {
toast.success('Avatar saved');
})
.catch((err) => {
toast.error(err.message);
});
}
}
function changePassword() {
fetch(
`${backendUrl}api/${$pocketbase.authStore.isAdmin ? 'admins' : `collections/users/records`}/${
$pocketbase.authStore.model?.id
}`,
{
method: 'PATCH',
headers: {
Authorization: $pocketbase.authStore.token,
'Content-Type': 'application/json'
},
body: $pocketbase.authStore.isAdmin ? adminBody : userBody
}
)
.then(async (data) => {
if (data.ok) {
toast.success('Password changed. Please login again.');
$pocketbase.authStore.clear();
goto('/login');
} else {
const j = await data.json();
if (j?.data?.password?.message) {
toast.error(j?.data?.password?.message);
} else if (j?.data?.passwordConfirm?.message) {
toast.error("Passwords don't match");
} else if (j.data?.oldPassword?.message) {
toast.error(j.data.oldPassword.message);
} else {
toast.error(j.message || data.statusText);
}
}
})
.catch((err) => {
toast.error(err.message);
});
}
</script>
<h1 class="text-3xl font-bold mb-8">Account</h1>
<div class="card w-full bg-base-300 shadow-xl">
<div class="card-body">
<div class="flex flex-row gap-4 items-center">
<div class="avatar">
<div class="w-16 rounded-full">
<!-- svelte static build will fail, because the image gets served from pocketbase
and is not a local static file -->
{#if $pocketbase.authStore.model?.id}
<img
src="{backendUrl}_/images/avatars/avatar{newAvatar ??
$pocketbase.authStore.model?.avatar}.svg"
alt="Avatar {newAvatar ?? $pocketbase.authStore.model?.avatar}"
/>
{/if}
</div>
</div>
<div>
<h2 class="card-title">
{$pocketbase.authStore.isAdmin
? $pocketbase.authStore.model?.email
: $pocketbase.authStore.model?.username}
</h2>
<h3>{$pocketbase.authStore.isAdmin ? 'Admin' : 'User'}</h3>
</div>
</div>
<h2 class="card-title mt-4">Avatar</h2>
<form on:submit|preventDefault={changeAvatar}>
<div class="flex flex-row flex-wrap gap-4">
{#each [...Array(10).keys()] as i}
<div class="avatar btn btn-ghost btn-circle">
<div
class="w-11 rounded-full"
class:ring={newAvatar !== undefined
? i === newAvatar
: i === $pocketbase.authStore.model?.avatar}
class:ring-primary={newAvatar !== undefined
? i === newAvatar
: i === $pocketbase.authStore.model?.avatar}
class:ring-offset-base-100={newAvatar !== undefined
? i === newAvatar
: i === $pocketbase.authStore.model?.avatar}
class:ring-offset-2={newAvatar !== undefined
? i === newAvatar
: i === $pocketbase.authStore.model?.avatar}
on:click={() => (newAvatar = i)}
role="none"
>
<!-- svelte static build will fail, because the image gets served from pocketbase
and is not a local static file -->
{#if $pocketbase.authStore.model?.id}
<img src="{backendUrl}_/images/avatars/avatar{i}.svg" alt="Avatar {i}" />
{/if}
</div>
</div>
{/each}
</div>
<button type="submit" class="btn btn-success mt-2"><Fa icon={faSave} />Save</button>
</form>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Change password</h2>
<p>After the password has been changed, you will need to log in again.</p>
<form on:submit|preventDefault={changePassword}>
<div class="form-control w-full max-w-xs">
{#if !$pocketbase.authStore.isAdmin}
<label class="label" for="password-old">
<span class="label-text">Old password</span>
</label>
<input
id="password-old"
type="password"
placeholder="Old password"
class="input input-bordered w-full max-w-xs"
minlength="5"
maxlength="72"
bind:value={newPassword.old}
required
/>
{/if}
<label class="label" for="password-new">
<span class="label-text">New password</span>
</label>
<input
id="password-new"
type="password"
placeholder="New password"
class="input input-bordered w-full max-w-xs"
minlength={$pocketbase.authStore.isAdmin ? 10 : 5}
maxlength="72"
bind:value={newPassword.password}
required
/>
</div>
<div class="form-control w-full max-w-xs">
<label class="label" for="password-confirm">
<span class="label-text">Confirm password</span>
</label>
<input
id="password-confirm"
type="password"
placeholder="New password"
class="input input-bordered w-full max-w-xs"
minlength={$pocketbase.authStore.isAdmin ? 10 : 5}
maxlength="72"
bind:value={newPassword.confirm}
required
/>
</div>
<button type="submit" class="btn btn-success mt-2"><Fa icon={faSave} />Save</button>
</form>
</div>
</div>
-4
View File
@@ -1,4 +0,0 @@
/** @type {import('./$types').PageLoad} */
export function load({ params }) {
return { params };
}
+41 -18
View File
@@ -1,22 +1,45 @@
<script>
import { devices } from '@stores/pocketbase';
import DeviceForm from '@components/DeviceForm.svelte';
import UnauthorizedMsg from '@components/UnauthorizedMsg.svelte';
<script lang="ts">
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { pocketbase, permission } from '$lib/stores/pocketbase';
import PageLoading from '$lib/components/PageLoading.svelte';
import DeviceForm from '$lib/components/DeviceForm.svelte';
import toast from 'svelte-french-toast';
import type { Device, Port } from '$lib/types/device';
export let data;
let device;
$: if (Object.hasOwn($permission, 'update')) {
if (!$pocketbase.authStore.isAdmin && !$permission.update.includes($page.params.id)) {
toast(`You don't have permission to visit ${$page.url.pathname}`, {
icon: '⛔'
});
goto('/');
}
}
$: {
device = $devices[data.params.id];
if (device && !device?.expand?.ports) {
device.expand.ports = [];
}
}
async function getDevice(): Promise<Device> {
const resp = await $pocketbase
.collection('devices')
.getOne($page.params.id, { expand: 'ports,groups' });
let device = resp as Device;
if (!device.expand) device.expand = {};
if (!device.expand.ports) {
device.expand.ports = [] as Port[];
}
return resp as Device;
}
</script>
{#if device}
<div class="container">
<UnauthorizedMsg />
<DeviceForm bind:device mode="edit" />
</div>
{/if}
{#await getDevice()}
<PageLoading />
{:then device}
<h1 class="text-3xl font-bold mb-8 sm:break-all">{device.name}</h1>
<DeviceForm {device} />
{:catch err}
<div class="container max-w-lg mx-auto">
{err}
</div>
{/await}
@@ -0,0 +1,65 @@
<script lang="ts">
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import DeviceForm from '$lib/components/DeviceForm.svelte';
import NetworkScan from '$lib/components/NetworkScan.svelte';
import { pocketbase, permission } from '$lib/stores/pocketbase';
import { faBinoculars, faWrench } from '@fortawesome/free-solid-svg-icons';
import Fa from 'svelte-fa';
import toast from 'svelte-french-toast';
import type { Device, Port } from '$lib/types/device';
let device: Device = {
expand: {
ports: [] as Port[]
},
groups: [] as string[]
} as Device;
$: if (Object.hasOwn($permission, 'create')) {
if (!$pocketbase.authStore.isAdmin && !$permission.create) {
toast(`You don't have permission to visit ${$page.url.pathname}`, {
icon: '⛔'
});
goto('/');
}
}
let tabs = [
{
name: 'manual',
icon: faWrench,
show: true
},
{
name: 'network scan',
icon: faBinoculars,
show: $pocketbase.authStore.isAdmin
}
];
let activeTab = 'manual';
</script>
<h1 class="text-3xl font-bold mb-8">New device</h1>
<div class="flex justify-center mb-6">
<ul class="menu menu-horizontal bg-base-300 rounded-box gap-1">
{#each tabs as tab}
{#if tab.show}
<li>
<button
class="capitalize"
class:active={activeTab === tab.name}
on:click={() => (activeTab = tab.name)}
>{tab.name} <Fa icon={tab.icon} class="ms-2" /></button
>
</li>
{/if}
{/each}
</ul>
</div>
{#if activeTab === 'manual'}
<DeviceForm {device} />
{:else}
<NetworkScan />
{/if}
+126
View File
@@ -0,0 +1,126 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { pocketbase } from '$lib/stores/pocketbase';
import { settingsPub } from '$lib/stores/settings';
import Fa from 'svelte-fa';
import { faLockOpen, faEye, faQuestionCircle } from '@fortawesome/free-solid-svg-icons';
import { toggleVisibility } from '$lib/helpers/forms';
import toast from 'svelte-french-toast';
import { onMount } from 'svelte';
let inputPassword: HTMLInputElement;
let form = {
email: '',
password: ''
};
onMount(() => {
if ($pocketbase.authStore.isValid) {
goto('/');
}
});
function tryAdminThenUser() {
$pocketbase.admins
.authWithPassword(form.email, form.password)
.then(() => {
goto('/');
})
.catch(() => {
$pocketbase
.collection('users')
.authWithPassword(form.email, form.password)
.then(() => {
goto('/');
})
.catch((err) => {
toast.error(err.message);
});
});
}
function loginOIDC() {
$pocketbase
.collection('users')
.authWithOAuth2({ provider: 'oidc' })
.then(() => {
goto('/');
})
.catch((err) => {
console.log(err);
toast.error(err.message);
});
}
</script>
<div class="mt-10 flex items-center justify-center">
<div class="card bg-base-300 shadow-xl w-full max-w-lg">
<div class="card-body">
{#if $settingsPub?.website_title}
<h1 class="text-xl text-center font-bold">{$settingsPub?.website_title}</h1>
{/if}
<div class="flex flex-row gap-4">
<figure class="w-16"><img src="/gopher.svg" alt="Gopher" /></figure>
<h2 class="card-title">Welcome</h2>
</div>
<form class="form-control w-full" on:submit|preventDefault={tryAdminThenUser}>
<label class="label" for="email">
<span class="label-text">Email or Username:</span>
</label>
<input
id="email"
type="text"
class="input input-bordered w-full"
required
bind:value={form.email}
/>
<label class="label" for="password">
<span class="label-text">Password:</span>
</label>
<label class="relative block">
<div
class="absolute top-1/2 -translate-y-1/2 right-4 cursor-pointer"
role="none"
on:click={() => toggleVisibility(inputPassword)}
on:keydown={() => toggleVisibility(inputPassword)}
>
<Fa icon={faEye} />
</div>
<input
id="password"
type="password"
class="input input-bordered w-full"
maxlength="72"
required
bind:value={form.password}
bind:this={inputPassword}
/>
</label>
<div class="card-actions mt-4">
<div class="dropdown">
<label tabindex="-1" class="btn btn-neutral" for="other-providers">Other</label>
<ul
id="other-providers"
tabindex="-1"
class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-56"
>
<li class="menu-title flex flex-row gap-2 items-center">
Other Auth Providers <a
href="https://github.com/seriousm4x/UpSnap/wiki/Auth-providers"
target="_blank"><Fa icon={faQuestionCircle} /></a
>
</li>
<li>
<button type="button" on:click={loginOIDC}>OIDC 1</button>
</li>
</ul>
</div>
<button class="btn btn-primary ms-auto" type="submit"
>Login <Fa icon={faLockOpen} /></button
>
</div>
</form>
</div>
</div>
</div>
+188 -469
View File
@@ -1,478 +1,197 @@
<script>
import { dev } from '$app/environment';
import {
pocketbase,
settings_private,
settings_public,
devices,
groups
} from '@stores/pocketbase';
import UnauthorizedMsg from '@components/UnauthorizedMsg.svelte';
import DeviceForm from '@components/DeviceForm.svelte';
import Fa from 'svelte-fa/src/fa.svelte';
import { faPlus, faXmark } from '@fortawesome/free-solid-svg-icons';
<script lang="ts">
import { goto } from '$app/navigation';
import { settingsPub, settingsPriv } from '$lib/stores/settings';
import { pocketbase, backendUrl } from '$lib/stores/pocketbase';
import PageLoading from '$lib/components/PageLoading.svelte';
import toast from 'svelte-french-toast';
import Fa from 'svelte-fa';
import { faSave } from '@fortawesome/free-solid-svg-icons';
import { onMount } from 'svelte';
import { page } from '$app/stores';
import { PUBLIC_VERSION } from '$env/static/public';
import type { SettingsPublic, SettingsPrivate } from '$lib/types/settings';
let version = import.meta.env.UPSNAP_VERSION;
let settingsPubClone: SettingsPublic | undefined;
let settingsPrivClone: SettingsPrivate | undefined;
let faviconPreview: HTMLImageElement;
let faviconInputElement: HTMLInputElement;
let iconFiles = [];
let iconPreview;
let timeout;
let buttons = {
settings: {
state: 'none',
error: ''
},
scan: {
state: 'none',
error: ''
},
addAllDevices: {
state: 'none',
error: ''
}
};
let newDevice = {
name: '',
ip: '',
mac: '',
netmask: '255.255.255.0',
expand: {
ports: []
},
ports: [],
link: '',
wake_cron: '',
wake_cron_enabled: false,
shutdown_cron: '',
shutdown_cron_enabled: false,
shutdown_cmd: '',
password: '',
groups: []
};
let newGroup = '';
let scannedDevices = {};
onMount(() => {
if (!$pocketbase.authStore.isAdmin) {
toast(`You don't have permission to visit ${$page.url.pathname}`, {
icon: '⛔'
});
goto('/');
return;
}
$: 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';
}
settingsPub.subscribe((settings) => {
settingsPubClone = settings;
});
settingsPriv.subscribe((settings) => {
settingsPrivClone = settings;
});
async function saveSettings() {
buttons.settings.state = 'waiting';
try {
// update settings private
if ($settings_private.interval === '') {
$settings_private.interval = '@every 3s';
}
await $pocketbase
.collection('settings_private')
.update($settings_private.id, $settings_private);
if (!$settingsPriv) {
$pocketbase
.collection('settings_private')
.getFirstListItem('')
.then((res) => {
settingsPriv.set(res as SettingsPrivate);
});
}
});
// 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);
function resetFavicon() {
if (settingsPubClone === undefined) return;
settingsPubClone.favicon = '';
faviconInputElement.value = '';
faviconPreview.src = '/gopher.svg';
}
//set button
clearTimeout(timeout);
timeout = setTimeout(() => {
buttons.settings.state = 'none';
}, 3000);
buttons.settings.state = 'success';
} catch (error) {
clearTimeout(timeout);
timeout = setTimeout(() => {
buttons.settings.error = '';
buttons.settings.state = 'none';
}, 3000);
buttons.settings.error = error;
buttons.settings.state = 'failed';
}
}
async function save() {
if (
settingsPubClone === undefined ||
settingsPrivClone === undefined ||
faviconInputElement === undefined
)
return;
async function scanDevices() {
buttons.scan.state = 'waiting';
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`, {
headers: {
Authorization: $pocketbase.authStore.baseToken
}
})
.then((res) => res.json())
.then((data) => {
if (data.message) {
clearTimeout(timeout);
timeout = setTimeout(() => {
buttons.scan.error = '';
buttons.scan.state = 'none';
}, 3000);
buttons.scan.error = data.message;
buttons.scan.state = 'failed';
} else {
scannedDevices = data;
clearTimeout(timeout);
timeout = setTimeout(() => {
buttons.scan.state = 'none';
}, 3000);
buttons.scan.state = 'success';
}
})
.catch((error) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
buttons.scan.error = '';
buttons.scan.state = 'none';
}, 3000);
buttons.scan.error = error;
buttons.scan.state = 'failed';
});
}
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 addDevice(device) {
await $pocketbase.collection('devices').create(device);
}
async function addGroup() {
const res = await $pocketbase.collection('groups').create({
name: newGroup
});
$groups = [...$groups, res];
newGroup = '';
}
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;
}
}
if (faviconInputElement.files !== null && faviconInputElement.files?.length > 0) {
let form = new FormData();
form.append('favicon', faviconInputElement.files[0]);
const res = await $pocketbase.collection('settings_public').update(settingsPubClone.id, form);
settingsPub.set(res as SettingsPublic);
}
await $pocketbase
.collection('settings_public')
.update(settingsPubClone.id, settingsPubClone)
.then((res) => {
settingsPub.set(res as SettingsPublic);
})
.catch((err) => {
toast.error(err.message);
});
await $pocketbase
.collection('settings_private')
.update(settingsPrivClone.id, settingsPrivClone)
.then((res) => {
toast.success('Saved settings');
settingsPriv.set(res as SettingsPrivate);
goto('/');
})
.catch((err) => {
toast.error(err.message);
});
}
</script>
<div class="container">
<UnauthorizedMsg />
<section class="m-0 mt-4 p-4 shadow-sm">
<form on:submit|preventDefault={saveSettings}>
<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>
<input
class="form-control"
placeholder="e.g. '@every 5s' or '@every 1m'"
aria-label="Interval"
aria-describedby="addon-wrapping"
type="text"
bind:value={$settings_private.interval}
/>
</div>
<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
type="text"
class="form-control"
placeholder="e.g. 'UpSnap'"
aria-label="Website title"
aria-describedby="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">
<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
<a
href="https://en.wikipedia.org/wiki/Cron"
target="_blank"
rel="noreferrer">wikipedia</a
>
or refer to the
<a
target="_blank"
rel="noreferrer"
href="https://pkg.go.dev/github.com/robfig/cron"
>package documentation</a
>
</p>
<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>
<button
type="submit"
class="btn btn-secondary"
class:btn-success={buttons.settings.state === 'success' ? true : false}
class:btn-warning={buttons.settings.state === 'waiting' ? true : false}
class:btn-danger={buttons.settings.state === 'failed' ? true : false}
disabled={buttons.settings.state !== 'none' ? true : false}
>
{#if buttons.settings.state === 'none'}
Save
{:else if buttons.settings.state === 'success'}
Saved
{:else if buttons.settings.state === 'waiting'}
Waiting
{:else if buttons.settings.state === 'failed'}
Failed: {buttons.settings.error}
{/if}
</button>
</form>
</section>
<DeviceForm bind:device={newDevice} mode="add" />
<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">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">
<span class="input-group-text" id="ip-range">IP range</span>
<input
type="text"
class="form-control"
placeholder="e.g. '192.168.1.0/24'"
aria-label="ip-range"
aria-describedby="ip-range"
bind:value={$settings_private.scan_range}
/>
</div>
<button
type="submit"
class="btn btn-secondary"
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_private.scan_range === '' ||
buttons.scan.state !== 'none'
? true
: false}
>
{#if buttons.scan.state === 'none'}
Scan
{:else if buttons.scan.state === 'success'}
Scanned
{:else if buttons.scan.state === 'waiting'}
Scan running (might take some seconds)
{:else if buttons.scan.state === 'failed'}
Failed: {buttons.scan.error}
{/if}
</button>
</form>
</div>
<div class="col-md-6">
<div class="callout callout-info mb-0">
<p class="m-0">
For network scan to work, you need to run UpSnap as root/admin and have nmap
installed and available in your $PATH. (For docker users, thats already the
case and you don't need to do anything.)
</p>
</div>
</div>
</div>
{#if scannedDevices.devices}
<div class="mt-3">
<div class="row align-items-center my-1">
<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-lg-3">
{device.name}
</div>
<div class="col-lg-2">
{device.ip}
</div>
<div class="col-lg-2">
{device.mac}
</div>
<div class="col-lg-2">
{device.mac_vendor}
</div>
<div class="col-lg-2">
{scannedDevices.netmask}
</div>
<div class="col-lg-1">
<button
class="btn btn-sm btn-secondary py-0"
on:click={async (e) => {
e.target.disabled = true;
device.netmask = scannedDevices.netmask;
await addDevice(device);
}}
on:keydown={async (e) => {
e.target.disabled = true;
device.netmask = scannedDevices.netmask;
await addDevice(device);
}}
>
Add <Fa icon={faPlus} />
</button>
</div>
</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>
<p class="m-0 my-4 p-4 text-center text-muted">
{#if version !== undefined}
UpSnap version: <a
href="https://github.com/seriousm4x/UpSnap/releases/tag/{version}"
class="text-reset">{version}</a
>
{:else}
UpSnap version: (untracked)
{/if}
</p>
</div>
<style lang="scss">
.icon-preview {
height: 130px;
}
</style>
{#if settingsPubClone === undefined || settingsPrivClone === undefined}
<PageLoading />
{:else}
<h1 class="text-3xl font-bold mb-8">Settings</h1>
<form on:submit|preventDefault={save}>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Ping interval</h2>
<p class="mt-2">
Sets the interval in which the devices are pinged. Leave blank to use default value of <span
class="badge">@every 3s</span
>.
</p>
<p>
Learn more about the correct syntax for cron on
<a target="_blank" class="link" href="https://en.wikipedia.org/wiki/Cron">Wikipedia</a>
or refer to the
<a target="_blank" class="link" href="https://pkg.go.dev/github.com/robfig/cron/v3"
>package documentation</a
>.
</p>
<div class="form-control w-full mt-2">
<input
type="text"
placeholder="e.g. '@every 5s' or '@every 1m'"
class="input w-full max-w-xs"
bind:value={settingsPrivClone.interval}
/>
</div>
<h2 class="card-title mt-2">Lazy ping</h2>
<p class="mt-2">
When lazy ping is turned on, UpSnap will only ping devices if there is an active user
visiting the website. If it's turned off, UpSnap will always ping devices.
</p>
<div class="form-control w-fit">
<label class="label cursor-pointer gap-2">
<input
type="checkbox"
class="checkbox checkbox-primary"
bind:checked={settingsPrivClone.lazy_ping}
/>
<span class="label-text">Enable</span>
</label>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Website title</h2>
<p class="my-2">Sets the title of the website and in the browser tab.</p>
<div class="form-control w-full">
<input
type="text"
placeholder="e.g. 'UpSnap'"
class="input w-full max-w-xs"
bind:value={settingsPubClone.website_title}
/>
</div>
</div>
</div>
<div class="card w-full bg-base-300 shadow-xl mt-6">
<div class="card-body">
<h2 class="card-title">Icon</h2>
<p class="my-2">
Set a custom favicon. Supported file types are
<span class="badge">.ico</span>, <span class="badge">.png</span>,
<span class="badge">.svg</span>, <span class="badge">.gif</span> and
<span class="badge">.jpg/.jpeg</span>.
</p>
<div>
<img
class="h-36"
src={$settingsPub.favicon !== ''
? `${backendUrl}api/files/settings_public/${$settingsPub.id}/${$settingsPub.favicon}`
: '/gopher.svg'}
alt="Favicon preview"
bind:this={faviconPreview}
/>
</div>
<div class="form-control w-full max-w-md flex flex-row gap-4">
<input
type="file"
class="file-input w-full max-w-xs"
accept=".ico,.png,.svg,.gif,.jpg,.jpeg"
bind:this={faviconInputElement}
/>
<button
class="btn btn-outline btn-error"
on:click={() => resetFavicon()}
on:keydown={() => resetFavicon()}>Reset</button
>
</div>
</div>
</div>
<div class="card-actions justify-end mt-6">
<button class="btn btn-success" type="submit"><Fa icon={faSave} />Save</button>
</div>
</form>
<div class="container mx-auto text-center mt-6">
{#if PUBLIC_VERSION === ''}
UpSnap version: (untracked)
{:else}
UpSnap version: <a
href="https://github.com/seriousm4x/UpSnap/releases/tag/{PUBLIC_VERSION}"
class="link">{PUBLIC_VERSION}</a
>
{/if}
</div>
{/if}

Some files were not shown because too many files have changed in this diff Show More