Compare commits
200 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2bc7bab5f7 | |||
| 4eed2bf31b | |||
| 326a7f359f | |||
| cbbd0f301e | |||
| fdf125d071 | |||
| 72e3d3d343 | |||
| 3331b53d39 | |||
| 1faae16e18 | |||
| 28cc52f6c1 | |||
| 6a388229dd | |||
| 014e6785be | |||
| 2fed755948 | |||
| 9106d25b95 | |||
| 8e9ba1503c | |||
| 9e83416848 | |||
| 054f60ee48 | |||
| 469d480988 | |||
| 87bf05528c | |||
| 93a72207cc | |||
| df9f549d65 | |||
| c43bcbd299 | |||
| 79a70b6053 | |||
| f061c7d00a | |||
| 59bc936237 | |||
| 1b299aa3a3 | |||
| 327b47c2a1 | |||
| d7c4a922e2 | |||
| 8c4c402c2c | |||
| 9351889337 | |||
| 327ac67e33 | |||
| 2764ed6ac5 | |||
| c519084e78 | |||
| 0d9a743b09 | |||
| 12689b19f9 | |||
| 5ed25bb06b | |||
| 94fabed6dd | |||
| 5493df087b | |||
| 8d479669f4 | |||
| 40f6bddff6 | |||
| 9a6b3a0c07 | |||
| a1de1638a9 | |||
| 5469a2b0aa | |||
| a7f3edd5f7 | |||
| 3aec978570 | |||
| 37f7df24c2 | |||
| 9a90d59188 | |||
| 4148ef0952 | |||
| 49cda92036 | |||
| 021555dc18 | |||
| 3b9decd572 | |||
| 9a1a816f25 | |||
| 8d43554e0e | |||
| b88f567d9f | |||
| cb168f2f47 | |||
| 376220c557 | |||
| ef064e9335 | |||
| 67870d8114 | |||
| 7bd4712ddd | |||
| f3b740d092 | |||
| a721af02b4 | |||
| b9aa9feb1d | |||
| 59770cf013 | |||
| 8b65cd69bc | |||
| 0f7026f3d0 | |||
| 66b41170e8 | |||
| 27b1a10e86 | |||
| 482a9884a4 | |||
| ed285f502e | |||
| b6f76c55c9 | |||
| 7bdb99c066 | |||
| e07755f3b9 | |||
| 9b7a7632e6 | |||
| 8c8671908c | |||
| 288baf0217 | |||
| 647dfe3e9e | |||
| b0452aa82d | |||
| b5258bbb03 | |||
| f77c2c0146 | |||
| b68bb20e06 | |||
| bb00b613e2 | |||
| 82cc4004c0 | |||
| e515ee2fae | |||
| 1039fc2a46 | |||
| cda3cba9ca | |||
| 737507faef | |||
| 4ff62b1a3f | |||
| 62cec056b9 | |||
| e78b66c920 | |||
| 3018394888 | |||
| 4c91967d6e | |||
| 3fc2031914 | |||
| 1de83d0e34 | |||
| 2cc9dde62a | |||
| 1f433dd40b | |||
| 969d1545b4 | |||
| 18ef9f81c8 | |||
| a182f7b041 | |||
| 752e61c1db | |||
| feff042a88 | |||
| b5fb030ddc | |||
| bab9648d53 | |||
| f477088404 | |||
| abe58fd87e | |||
| cc20206a7f | |||
| f60c938a65 | |||
| 6227ca2dc8 | |||
| b840a45efc | |||
| c59fae6a10 | |||
| 7e7caf3643 | |||
| 7943177b33 | |||
| 7c3808b8d5 | |||
| 2054f31ad4 | |||
| 6fefce8377 | |||
| 6f611114fb | |||
| 7286167586 | |||
| b1d4257013 | |||
| 7d005aa9d0 | |||
| 6aedb5b5d1 | |||
| 5cd333e2dc | |||
| 80b47012a8 | |||
| 8f76628e15 | |||
| 0ef4b4ac02 | |||
| 3d0ad679ee | |||
| 465407fbc2 | |||
| 81a581ff29 | |||
| abf8b8114f | |||
| b43cd7fe99 | |||
| d4fdeb8051 | |||
| fe973e2c87 | |||
| 988f182430 | |||
| dd5401b265 | |||
| f29c15c6fc | |||
| 953ecabfd6 | |||
| f025df8918 | |||
| cf71eb413a | |||
| 7dd4affa96 | |||
| 306e4015cc | |||
| 3dc2eaca6d | |||
| 2d7a5755ce | |||
| e39d626119 | |||
| a3b1413fbb | |||
| 4d21b0fc92 | |||
| 665c586d44 | |||
| 037f718a2e | |||
| d83f574396 | |||
| 6555ce3b38 | |||
| 24916af042 | |||
| fe273013a7 | |||
| f1a73e7bbe | |||
| a51157f0f3 | |||
| 3bddd8f521 | |||
| 9a4f29d63d | |||
| 1fe78aa50e | |||
| 58d41e660f | |||
| 49f3ff78b2 | |||
| c0b055ed1b | |||
| a7dd5ab74c | |||
| 2aabf0f0c5 | |||
| 87915b2dd3 | |||
| 375abd0c42 | |||
| f5a9a480d4 | |||
| ddbe52918c | |||
| ba806970a0 | |||
| 0d9f3ecb04 | |||
| 7c483d99c8 | |||
| 6b076b5009 | |||
| f8e1ede7cb | |||
| 4eecbe3cff | |||
| 78dd8e3b23 | |||
| 63d8e2c285 | |||
| 4571b46353 | |||
| 2d33ada47c | |||
| bc5c9497a1 | |||
| 6a472beaee | |||
| a34c419fd9 | |||
| 221cb86000 | |||
| d4aac95fcd | |||
| 0f0a0ac98b | |||
| 36cef610c3 | |||
| fdb19e5cfb | |||
| 705008898f | |||
| 2e251f309c | |||
| 21218ef91a | |||
| d08b8b3722 | |||
| e02ecbc639 | |||
| 42bb71a017 | |||
| 20a3ddea1a | |||
| 4906ce722b | |||
| f36be22e46 | |||
| b1e8eaf864 | |||
| 01afbd1919 | |||
| 97e0d94d24 | |||
| 35df2757fd | |||
| ccc53c5349 | |||
| 5f1a68ab36 | |||
| daff99510f | |||
| cff1705a9f | |||
| d15810d8b2 | |||
| 9e9fed767e | |||
| 58fedcec48 |
@@ -1,5 +1,12 @@
|
||||
.git
|
||||
node_modules
|
||||
/app/frontend/public/build
|
||||
/app/frontend/scripts
|
||||
**/db.sqlite3
|
||||
.gitignore
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
README.md
|
||||
|
||||
frontend/.svelte-kit
|
||||
frontend/node_modules
|
||||
frontend/build
|
||||
|
||||
backend/pb_data
|
||||
backend/pb_public
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
github: seriousm4x
|
||||
ko_fi: seriousm4x
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: "⭐ Feature request"
|
||||
about: Suggest an idea for this project
|
||||
title: "[REQUEST]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**The problem you currently have with this project**
|
||||
A clear and concise description of what the problem is.
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: "\U0001F577️ Bug report"
|
||||
about: Create a report to help the project improve
|
||||
title: "[BUG]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Logs**
|
||||
```
|
||||
formatted logs here
|
||||
```
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Host OS (and version)**
|
||||
eg. Windows 10, Ubuntu 22.10, macOS 13
|
||||
|
||||
**Host Architecture**
|
||||
e.g. amd64/arm64/arm7
|
||||
|
||||
**Brower (if relevant)**
|
||||
e.g. Firefox 109.0.1
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,19 @@
|
||||
# Sync repo to the Codeberg mirror
|
||||
name: Mirror Sync
|
||||
on:
|
||||
push:
|
||||
branches: ["master"]
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 */24 * * *"
|
||||
jobs:
|
||||
codeberg:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: pixta-dev/repository-mirroring-action@v1
|
||||
with:
|
||||
target_repo_url: "git@codeberg.org:seriousm4x/UpSnap.git"
|
||||
ssh_private_key: ${{ secrets.CODEBERG_SSH }}
|
||||
@@ -0,0 +1,98 @@
|
||||
name: v3 build
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "3.*.*"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# pull code
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# install latest node
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: latest
|
||||
|
||||
# build sveltekit frontend
|
||||
- name: Build frontend
|
||||
run: |
|
||||
npm --prefix=./frontend i
|
||||
UPSNAP_VERSION=${GITHUB_REF##*/} npm --prefix=./frontend run build
|
||||
cp -r ./frontend/build/* ./backend/pb_public/
|
||||
|
||||
# setup go
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: ">=1.20"
|
||||
|
||||
# build
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: latest
|
||||
args: release --clean
|
||||
workdir: backend
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
docker:
|
||||
needs: goreleaser
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# pull code
|
||||
- name: Check Out Repo
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# image tags
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/seriousm4x/UpSnap
|
||||
tags: |
|
||||
type=ref,event=tag
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
|
||||
# qemu
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
|
||||
# docker buildx
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
# ghcr.io login
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# build and push
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v6,linux/arm/v7
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
build-args: |
|
||||
VERSION=${{github.ref_name}}
|
||||
@@ -1,58 +0,0 @@
|
||||
name: CI to Docker Hub
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Check Out Repo
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Prepare tags
|
||||
id: prep
|
||||
run: |
|
||||
DOCKER_IMAGE=${{ secrets.DOCKER_HUB_USERNAME }}/upsnap
|
||||
VERSION=${GITHUB_REF#refs/tags/}
|
||||
TAGS="${DOCKER_IMAGE}:${VERSION},${DOCKER_IMAGE}:${VERSION:0:2},${DOCKER_IMAGE}:latest"
|
||||
echo ::set-output name=tags::${TAGS}
|
||||
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-${{ github.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-buildx-
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v1
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v2
|
||||
with:
|
||||
context: ./
|
||||
file: ./Dockerfile
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
push: true
|
||||
tags: ${{ steps.prep.outputs.tags }}
|
||||
cache-from: type=local,src=/tmp/.buildx-cache
|
||||
cache-to: type=local,dest=/tmp/.buildx-cache
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
@@ -1,287 +1,202 @@
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=go,visualstudiocode,svelte,node
|
||||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/windows,linux,macos,python,django
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=windows,linux,macos,python,django
|
||||
|
||||
### Django ###
|
||||
*.log
|
||||
*.pot
|
||||
*.pyc
|
||||
__pycache__/
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
media
|
||||
|
||||
# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
|
||||
# in your Git repository. Update and uncomment the following line accordingly.
|
||||
# <django-project-name>/staticfiles/
|
||||
|
||||
### Django.Python Stack ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
### Go ###
|
||||
# If you prefer the allow list template instead of the deny list, see community template:
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
pytestdebug.log
|
||||
# Go workspace file
|
||||
go.work
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
### Node ###
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Django stuff:
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
doc/_build/
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Environments
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
pythonenv*
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
|
||||
# profiling data
|
||||
.prof
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
|
||||
### Linux ###
|
||||
*~
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# KDE directory preferences
|
||||
.directory
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# Linux trash folder which might appear on any partition or disk
|
||||
.Trash-*
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# .nfs files are created when an open file is removed but is still being accessed
|
||||
.nfs*
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
### Node Patch ###
|
||||
# Serverless Webpack directories
|
||||
.webpack/
|
||||
|
||||
# Optional stylelint cache
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
# SvelteKit build / generate output
|
||||
.svelte-kit
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
### Svelte ###
|
||||
# gitignore template for the SvelteKit, frontend web component framework
|
||||
# website: https://kit.svelte.dev/
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
.svelte-kit/
|
||||
package
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
### VisualStudioCode ###
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# C extensions
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Distribution / packaging
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
### VisualStudioCode Patch ###
|
||||
# Ignore all local history of files
|
||||
.history
|
||||
.ionide
|
||||
|
||||
# Installer logs
|
||||
# End of https://www.toptal.com/developers/gitignore/api/go,visualstudiocode,svelte,node
|
||||
|
||||
# Unit test / coverage reports
|
||||
build
|
||||
|
||||
# Translations
|
||||
backend/pb_data
|
||||
backend/pb_public/*
|
||||
!backend/pb_public/.gitkeep
|
||||
|
||||
# Django stuff:
|
||||
|
||||
# Flask stuff:
|
||||
|
||||
# Scrapy stuff:
|
||||
|
||||
# Sphinx documentation
|
||||
|
||||
# PyBuilder
|
||||
|
||||
# Jupyter Notebook
|
||||
|
||||
# IPython
|
||||
|
||||
# pyenv
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
|
||||
# Celery stuff
|
||||
|
||||
# SageMath parsed files
|
||||
|
||||
# Environments
|
||||
|
||||
# Spyder project settings
|
||||
|
||||
# Rope project settings
|
||||
|
||||
# mkdocs documentation
|
||||
|
||||
# mypy
|
||||
|
||||
# Pyre type checker
|
||||
|
||||
# pytype static type analyzer
|
||||
|
||||
# profiling data
|
||||
|
||||
### Windows ###
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
Thumbs.db:encryptable
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/windows,linux,macos,python,django
|
||||
|
||||
.vscode
|
||||
staticfiles
|
||||
dist/
|
||||
vite.config.js.timestamp*
|
||||
|
||||
@@ -1,36 +1,21 @@
|
||||
FROM debian:bullseye-slim as base
|
||||
|
||||
FROM base as python-build
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
WORKDIR /python-build
|
||||
RUN apt-get update &&\
|
||||
apt-get install -y --no-install-recommends build-essential libffi-dev libssl-dev cargo python3 python3-dev python3-pip python3-venv default-libmysqlclient-dev libpq-dev &&\
|
||||
python3 -m venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
COPY app/backend/requirements.txt .
|
||||
RUN python3 -m pip install --no-cache-dir --upgrade pip wheel &&\
|
||||
pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
FROM node:17-bullseye-slim as node-build
|
||||
WORKDIR /node-build
|
||||
COPY app/frontend/package*.json ./
|
||||
COPY app/frontend/src ./src
|
||||
COPY app/frontend/public ./public
|
||||
COPY app/frontend/rollup.config.js ./
|
||||
|
||||
FROM base
|
||||
FROM alpine:3 as downloader
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
ARG TARGETVARIANT
|
||||
ARG VERSION
|
||||
ENV BUILDX_ARCH="${TARGETOS:-linux}_${TARGETARCH:-amd64}${TARGETVARIANT}"
|
||||
WORKDIR /app
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get update &&\
|
||||
apt-get install -y --no-install-recommends default-mysql-client nodejs npm iputils-ping nmap samba-common-bin openssh-client sshpass &&\
|
||||
apt-get clean &&\
|
||||
rm -rf /var/lib/{apt,dpkg,cache,log}/
|
||||
COPY --from=python-build /opt/venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
COPY --from=node-build /node-build ./frontend
|
||||
COPY app/backend ./backend
|
||||
COPY app/run.sh ./
|
||||
RUN wget https://github.com/seriousm4x/UpSnap/releases/download/${VERSION}/UpSnap_${VERSION}_${BUILDX_ARCH}.zip &&\
|
||||
unzip UpSnap_${VERSION}_${BUILDX_ARCH}.zip &&\
|
||||
rm -f UpSnap_${VERSION}_${BUILDX_ARCH}.zip &&\
|
||||
chmod +x upsnap
|
||||
|
||||
CMD ["./run.sh"]
|
||||
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=downloader /app/upsnap upsnap
|
||||
HEALTHCHECK --interval=10s \
|
||||
CMD curl -fs "http://localhost:8090/api/health" || exit 1
|
||||
ENTRYPOINT ["./upsnap", "serve", "--http=0.0.0.0:8090"]
|
||||
|
||||
@@ -1,43 +1,124 @@
|
||||
<div align="center" width="100%">
|
||||
<img src="app/frontend/public/favicon.png" width="128" />
|
||||
<img src="frontend/static/gopher.svg" width="150" />
|
||||
</div>
|
||||
|
||||
<div align="center" width="100%">
|
||||
<h2>UpSnap</h2>
|
||||
<p>A simple wake on lan app written with Svelte, Django, Django-Channels (websockets), Celery, Redis and nmap.</p>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/upsnap" /></a> <a target="_blank" href="https://hub.docker.com/r/seriousm4x/upsnap"><img src="https://img.shields.io/docker/pulls/seriousm4x/upsnap" /></a> <a target="_blank" href="https://hub.docker.com/r/seriousm4x/upsnap"><img src="https://img.shields.io/docker/v/seriousm4x/upsnap/latest?label=docker%20image%20ver." /></a> <a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
|
||||
<p>A simple wake on lan app written with SvelteKit, Go, PocketBase and nmap.</p>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/upsnap" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/downloads/seriousm4x/upsnap/total" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/go-mod/go-version/seriousm4x/UpSnap?filename=backend/go.mod" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/v/release/seriousm4x/upsnap?display_name=tag" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/deploy.yml/badge.svg?event=push" /></a>
|
||||
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
|
||||
</div>
|
||||
|
||||
## ✨ Features
|
||||
|
||||
* Dashboard to wake up devices with 1 click
|
||||
* Set timed wake and shutdown events via cron
|
||||
* Add custom ports to devices which will be scanned
|
||||
* Discover devices by scanning network
|
||||
* Notifications on status changes
|
||||
* Devices only get pinged when there are 1 or more visitors
|
||||
* Dark/light or system prefered color scheme
|
||||
* [Docker images](https://hub.docker.com/r/seriousm4x/upsnap) for amd64, arm64, arm/v7
|
||||
- Dashboard to wake up devices with one click
|
||||
- Set timed wake and shutdown events via cron
|
||||
- Add custom ports to devices which will be pinged
|
||||
- Discover devices by scanning network
|
||||
- User/Password protected login
|
||||
- Dark/light or system prefered color scheme
|
||||
- [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7, arm/v6
|
||||
|
||||
## 📸 Screenshots
|
||||
|
||||
| Dark | Light |
|
||||
| -------------------- | --------------------- |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
| Dark | Light |
|
||||
| ------------------------------ | ------------------------------- |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
## 🐳 Run your own instance
|
||||
## 🚀 Run the binary
|
||||
|
||||
There are 3 example docker-compose files to choose from. The simplest is [docker-compose-sqlite.yml](docker-compose-sqlite.yml).
|
||||
Just download the latest binary from the [release page](https://github.com/seriousm4x/UpSnap/releases) and run it `./upsnap serve --http=0.0.0.0:8090`.
|
||||
|
||||
The website will be available at [localhost:8000](http://localhost:8000). If you run it on a different pc, it will be `http://<your-ip>:8000`. You can change the port in the docker-compose file.
|
||||
For more options check `./upsnap --help` or visit [PocketBase documentation](https://pocketbase.io/docs).
|
||||
|
||||
### Databases
|
||||
If you need network discovery, make sure to have `nmap` installed and run upsnap as root/admin.
|
||||
|
||||
Upsnap supports 3 different databases. Postgres, MySQL and SQLite. If you already have an existing database you want to use, delete the database container from the compose file. Always make sure to set the correct database type environment variable, e.g. DB_TYPE=mysql
|
||||
## 🐳 Run in docker
|
||||
|
||||
## 📝 Other infos
|
||||
You can use the [docker-compose](docker-compose.yml) example. See the comments in the file for customization.
|
||||
|
||||
* The app container needs to run in host network mode to send the wakeonlan command on your local network. Therefore all other containers also need to run in host network mode. I don't like it but there is no way around.
|
||||
If you want to change the port, change the following (5000 in this case):
|
||||
|
||||
```yml
|
||||
entrypoint: /bin/sh -c "./upsnap serve --http 0.0.0.0:5000"
|
||||
healthcheck:
|
||||
test: curl -fs "http://localhost:5000/api/health" || exit 1
|
||||
interval: 10s
|
||||
```
|
||||
|
||||
And if you need additional packages inside the container, do this:
|
||||
|
||||
```yml
|
||||
entrypoint: /bin/sh -c "apk update && apk add --no-cache <YOUR_PACKAGE> && rm -rf /var/cache/apk/* && ./upsnap serve --http 0.0.0.0:8090"
|
||||
```
|
||||
|
||||
You can search for your needed package [here](https://pkgs.alpinelinux.org/packages).
|
||||
|
||||
### Reverse Proxy
|
||||
|
||||
**Caddy example**
|
||||
|
||||
```
|
||||
upsnap.example.com {
|
||||
reverse_proxy localhost:8090
|
||||
}
|
||||
```
|
||||
|
||||
## 🔒 Authorisation
|
||||
|
||||
**Since version 3.1 authorisation is enabled by default.**
|
||||
|
||||
User management is done through the PocketBase webinterface at [http://localhost:8090/\_/](http://localhost:8090/_/). This is mainly for internal use, such as within a home or corporate network. For external use please see below.
|
||||
|
||||
- To manage users, click the "Collections" icon on the left and select "users".
|
||||
- To manage admins, click the "Settings" icon on the left and select "Admin".
|
||||
|
||||
Api permissions listed by user role:
|
||||
|
||||
| Api | Unauthorized | Users | Admins |
|
||||
| ---------------- | ------------ | ----- | ------ |
|
||||
| List/Search Rule | ❌ | ✅ | ✅ |
|
||||
| View Rule | ❌ | ✅ | ✅ |
|
||||
| Create Rule | ❌ | ❌ | ✅ |
|
||||
| Delete Rule | ❌ | ❌ | ✅ |
|
||||
| Manage Rule | ❌ | ❌ | ✅ |
|
||||
| Wake devices | ❌ | ✅ | ✅ |
|
||||
| Shutdown devices | ❌ | ✅ | ✅ |
|
||||
| Scan network | ❌ | ❌ | ✅ |
|
||||
|
||||
## 🌍 Exposing to the open web
|
||||
|
||||
Although UpSnap has user authorisation, it is **not recommended to expose it to the open web** and make it accessible by everyone!
|
||||
|
||||
**Reason**: The shutdown device command is basically a command piped to #sh (root if you run docker). If anyone gains unauthorized access and can abuse this api route in any way, the attacker has access to a (root) shell on your local network.
|
||||
|
||||
**Recommended**: If you need access from outside your network, please use a vpn. Wireguard or OpenVPN is your way to go.
|
||||
|
||||
## 🔧 Help developing
|
||||
|
||||
Fork this branch and clone it.
|
||||
|
||||
1. Start backend
|
||||
|
||||
```sh
|
||||
cd backend
|
||||
go mod tidy
|
||||
go run main.go serve
|
||||
```
|
||||
|
||||
2. Start frontend
|
||||
|
||||
```sh
|
||||
cd frontend
|
||||
pnpm i
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
Open up [http://localhost:5173/](http://localhost:5173/), create an admin user and add some devices.
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
"""
|
||||
ASGI config for backend project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
|
||||
django_asgi_app = get_asgi_application()
|
||||
|
||||
from channels.auth import AuthMiddlewareStack
|
||||
from channels.routing import ProtocolTypeRouter, URLRouter
|
||||
from wol.routing import ws_urlpatterns
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
|
||||
|
||||
application = ProtocolTypeRouter({
|
||||
"http": django_asgi_app,
|
||||
"websocket": AuthMiddlewareStack(URLRouter(ws_urlpatterns))
|
||||
})
|
||||
@@ -1,9 +0,0 @@
|
||||
import os
|
||||
|
||||
from celery import Celery
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
|
||||
|
||||
app = Celery("dango_wol")
|
||||
app.config_from_object("django.conf:settings", namespace="CELERY")
|
||||
app.autodiscover_tasks()
|
||||
@@ -1,177 +0,0 @@
|
||||
"""
|
||||
Django settings for backend project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 4.0.2.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/4.0/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/4.0/ref/settings/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.management.utils import get_random_secret_key
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', get_random_secret_key())
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True'
|
||||
|
||||
ALLOWED_HOSTS = ["*"]
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'channels',
|
||||
'django_celery_beat',
|
||||
'wol'
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'whitenoise.middleware.WhiteNoiseMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'backend.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.debug',
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'backend.wsgi.application'
|
||||
WSGI_APPLICATION = 'backend.wsgi.application'
|
||||
ASGI_APPLICATION = 'backend.asgi.application'
|
||||
CELERY_BROKER_URL = f"redis://{os.getenv('REDIS_HOST', '127.0.0.1')}:{os.getenv('REDIS_PORT', 6379)}"
|
||||
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
|
||||
|
||||
if os.getenv("DB_TYPE") == "postgres":
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql_psycopg2",
|
||||
"NAME": os.getenv("DB_NAME", "upsnap"),
|
||||
"USER": os.getenv("DB_USER", "upsnap"),
|
||||
"PASSWORD": os.getenv("DB_PASSWORD", "upsnap"),
|
||||
"HOST": os.getenv("DB_HOST", "127.0.0.1"),
|
||||
"PORT": os.getenv("DB_PORT", 5432),
|
||||
"OPTIONS": {
|
||||
"connect_timeout": 30
|
||||
}
|
||||
}
|
||||
}
|
||||
elif os.getenv("DB_TYPE") == "mysql":
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.mysql",
|
||||
"NAME": os.getenv("DB_NAME", "upsnap"),
|
||||
"USER": os.getenv("DB_USER", "upsnap"),
|
||||
"PASSWORD": os.getenv("DB_PASSWORD", "upsnap"),
|
||||
"HOST": os.getenv("DB_HOST", "127.0.0.1"),
|
||||
"PORT": os.getenv("DB_PORT", 3306),
|
||||
"OPTIONS": {
|
||||
"connect_timeout": 30
|
||||
}
|
||||
}
|
||||
}
|
||||
elif os.getenv("DB_TYPE") == "sqlite":
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME" : "db.sqlite3",
|
||||
}
|
||||
}
|
||||
|
||||
CHANNEL_LAYERS = {
|
||||
"default": {
|
||||
"BACKEND": "channels_redis.core.RedisChannelLayer",
|
||||
"CONFIG": {
|
||||
"hosts": [(os.getenv("REDIS_HOST", "127.0.0.1"), os.getenv("REDIS_PORT", 6379))],
|
||||
"capacity": 1000,
|
||||
"expiry": 10
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/4.0/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = os.getenv("DJANGO_LANGUAGE_CODE", "en")
|
||||
|
||||
TIME_ZONE = os.getenv("DJANGO_TIME_ZONE", "UTC")
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/4.0/howto/static-files/
|
||||
|
||||
STATIC_URL = 'static/'
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
||||
VERSION = "v2.0.1"
|
||||
@@ -1,23 +0,0 @@
|
||||
"""backend URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/4.0/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.conf import settings
|
||||
from django.conf.urls.static import static
|
||||
from django.urls import path
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls)
|
||||
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
||||
@@ -1,16 +0,0 @@
|
||||
"""
|
||||
WSGI config for backend project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
@@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,11 +0,0 @@
|
||||
celery[redis]
|
||||
channels
|
||||
channels-redis
|
||||
django
|
||||
django-celery-beat
|
||||
gunicorn
|
||||
mysqlclient
|
||||
psycopg2-binary
|
||||
uvicorn[standard]
|
||||
wakeonlan
|
||||
whitenoise
|
||||
@@ -1,45 +0,0 @@
|
||||
import os
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django_celery_beat.models import IntervalSchedule, PeriodicTask
|
||||
|
||||
from wol.models import Settings, Websocket
|
||||
|
||||
# create superuser
|
||||
if os.getenv("DJANGO_SUPERUSER_USER") and os.getenv("DJANGO_SUPERUSER_PASSWORD"):
|
||||
if not User.objects.filter(username=os.getenv("DJANGO_SUPERUSER_USER")).exists():
|
||||
User.objects.create_superuser(os.getenv("DJANGO_SUPERUSER_USER"), password=os.getenv("DJANGO_SUPERUSER_PASSWORD"))
|
||||
else:
|
||||
print('Django user exists')
|
||||
|
||||
# reset visitors
|
||||
[i.delete() for i in Websocket.objects.all()]
|
||||
Websocket.objects.create(visitors=0)
|
||||
|
||||
# ping interval
|
||||
if os.environ.get("PING_INTERVAL"):
|
||||
if int(os.environ.get("PING_INTERVAL")) < 5:
|
||||
print("Ping interval lower than 5 seconds is not recommended. Please use an interval of 5 seconds or higher. Automatically set to 5 seconds.")
|
||||
ping_interval = 5
|
||||
else:
|
||||
ping_interval = int(os.environ.get("PING_INTERVAL"))
|
||||
else:
|
||||
ping_interval = 5
|
||||
Settings.objects.update_or_create(
|
||||
id=1,
|
||||
defaults={
|
||||
"interval": ping_interval
|
||||
}
|
||||
)
|
||||
|
||||
# register device ping task
|
||||
schedule, created = IntervalSchedule.objects.get_or_create(
|
||||
every=ping_interval,
|
||||
period=IntervalSchedule.SECONDS,
|
||||
)
|
||||
if created:
|
||||
PeriodicTask.objects.create(
|
||||
interval=schedule,
|
||||
name="Ping all devices",
|
||||
task="wol.tasks.ping_all_devices"
|
||||
)
|
||||
@@ -1,25 +0,0 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from wol.models import Device, Port, Settings
|
||||
|
||||
|
||||
class DeviceAdmin(admin.ModelAdmin):
|
||||
list_display = ["name", "ip", "mac", "netmask", "ports"]
|
||||
search_fields = ["name", "ip", "mac"]
|
||||
list_filter = ["name", "netmask"]
|
||||
|
||||
def ports(self, obj):
|
||||
return ", ".join([p.name for p in obj.port.all()])
|
||||
|
||||
class PortAdmin(admin.ModelAdmin):
|
||||
list_display = ["number", "name"]
|
||||
search_fields = ["number", "name"]
|
||||
list_filter = ["number", "name"]
|
||||
|
||||
class SettingsAdmin(admin.ModelAdmin):
|
||||
list_display = ["sort_by", "scan_address", "interval"]
|
||||
|
||||
|
||||
admin.site.register(Device, DeviceAdmin)
|
||||
admin.site.register(Port, PortAdmin)
|
||||
admin.site.register(Settings, SettingsAdmin)
|
||||
@@ -1,6 +0,0 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class WolConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'wol'
|
||||
@@ -1,12 +0,0 @@
|
||||
import ipaddress
|
||||
import wakeonlan
|
||||
import subprocess
|
||||
|
||||
|
||||
def wake(mac, ip, netmask):
|
||||
subnet = ipaddress.ip_network(
|
||||
f"{ip}/{netmask}", strict=False).broadcast_address
|
||||
wakeonlan.send_magic_packet(mac, ip_address=str(subnet))
|
||||
|
||||
def shutdown(command):
|
||||
subprocess.run(command, shell=True)
|
||||
@@ -1,320 +0,0 @@
|
||||
import ipaddress
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from channels.db import database_sync_to_async
|
||||
from channels.generic.websocket import AsyncWebsocketConsumer
|
||||
from django_celery_beat.models import (CrontabSchedule, IntervalSchedule,
|
||||
PeriodicTask)
|
||||
|
||||
from wol.commands import shutdown, wake
|
||||
from wol.models import Device, Port, Settings, Websocket
|
||||
|
||||
|
||||
class WSConsumer(AsyncWebsocketConsumer):
|
||||
async def connect(self):
|
||||
await self.channel_layer.group_add("wol", self.channel_name)
|
||||
await self.accept()
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "init",
|
||||
"message": {
|
||||
"devices": await self.get_all_devices(),
|
||||
"settings": await self.get_settings()
|
||||
}
|
||||
}))
|
||||
await self.add_visitor()
|
||||
await self.channel_layer.group_send(
|
||||
"wol", {
|
||||
"type": "send_group",
|
||||
"message": {
|
||||
"type": "visitor",
|
||||
"message": await self.get_visitors()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async def disconnect(self, _):
|
||||
await self.channel_layer.group_discard("wol", self.channel_name)
|
||||
await self.remove_visitor()
|
||||
await self.channel_layer.group_send(
|
||||
"wol", {
|
||||
"type": "send_group",
|
||||
"message": {
|
||||
"type": "visitor",
|
||||
"message": await self.get_visitors()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
async def receive(self, text_data=None):
|
||||
received = json.loads(text_data)
|
||||
if received["type"] == "wake":
|
||||
await self.wake_device(received["id"])
|
||||
await self.channel_layer.group_send(
|
||||
"wol", {
|
||||
"type": "send_group",
|
||||
"message": {
|
||||
"type": "pending",
|
||||
"message": received["id"]
|
||||
}
|
||||
}
|
||||
)
|
||||
elif received["type"] == "shutdown":
|
||||
await self.shutdown_device(received["id"])
|
||||
await self.channel_layer.group_send(
|
||||
"wol", {
|
||||
"type": "send_group",
|
||||
"message": {
|
||||
"type": "pending",
|
||||
"message": received["id"]
|
||||
}
|
||||
}
|
||||
)
|
||||
elif received["type"] == "delete_device":
|
||||
await self.delete_device(received["id"])
|
||||
await self.channel_layer.group_send(
|
||||
"wol", {
|
||||
"type": "send_group",
|
||||
"message": {
|
||||
"type": "delete",
|
||||
"message": received["id"]
|
||||
}
|
||||
}
|
||||
)
|
||||
elif received["type"] == "update_device":
|
||||
await self.update_device(received["data"])
|
||||
elif received["type"] == "update_port":
|
||||
await self.update_port(received["data"])
|
||||
elif received["type"] == "update_settings":
|
||||
await self.update_settings(received["data"])
|
||||
elif received["type"] == "scan_network":
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "scan_network",
|
||||
"message": await self.scan_network()
|
||||
}))
|
||||
elif received["type"] == "backup":
|
||||
await self.send(text_data=json.dumps({
|
||||
"type": "backup",
|
||||
"message": await self.get_all_devices()
|
||||
}))
|
||||
|
||||
async def send_group(self, event):
|
||||
await self.send(json.dumps(event["message"]))
|
||||
|
||||
@database_sync_to_async
|
||||
def add_visitor(self):
|
||||
visitor_count = Websocket.objects.first()
|
||||
visitor_count.visitors += 1
|
||||
visitor_count.save()
|
||||
|
||||
@database_sync_to_async
|
||||
def remove_visitor(self):
|
||||
visitor_count = Websocket.objects.first()
|
||||
visitor_count.visitors -= 1
|
||||
visitor_count.save()
|
||||
|
||||
@database_sync_to_async
|
||||
def get_visitors(self):
|
||||
return Websocket.objects.first().visitors
|
||||
|
||||
@database_sync_to_async
|
||||
def wake_device(self, id):
|
||||
dev = Device.objects.filter(id=id).first()
|
||||
wake(dev.mac, dev.ip, dev.netmask)
|
||||
|
||||
@database_sync_to_async
|
||||
def shutdown_device(self, id):
|
||||
dev = Device.objects.filter(id=id).first()
|
||||
shutdown(dev.shutdown_cmd)
|
||||
|
||||
@database_sync_to_async
|
||||
def get_all_devices(self):
|
||||
devices = Device.objects.all()
|
||||
d = []
|
||||
for dev in devices:
|
||||
data = {
|
||||
"id": dev.id,
|
||||
"name": dev.name,
|
||||
"ip": dev.ip,
|
||||
"mac": dev.mac,
|
||||
"netmask": dev.netmask,
|
||||
"ports": [],
|
||||
"wake": {
|
||||
"enabled": False,
|
||||
"cron": ""
|
||||
},
|
||||
"shutdown": {
|
||||
"enabled": False,
|
||||
"cron": "",
|
||||
"command": dev.shutdown_cmd
|
||||
}
|
||||
}
|
||||
for p in Port.objects.all().order_by("number"):
|
||||
data["ports"].append({
|
||||
"number": p.number,
|
||||
"name": p.name,
|
||||
"checked": False,
|
||||
"open": False
|
||||
})
|
||||
for action in ["wake", "shutdown"]:
|
||||
try:
|
||||
task = PeriodicTask.objects.filter(
|
||||
name=f"{data['name']}-{action}",
|
||||
task=f"wol.tasks.scheduled_{action}", crontab_id__isnull=False).get()
|
||||
if task:
|
||||
wake = CrontabSchedule.objects.get(id=task.crontab_id)
|
||||
data[action]["enabled"] = task.enabled
|
||||
data[action]["cron"] = " ".join(
|
||||
[wake.minute, wake.hour, wake.day_of_week, wake.day_of_month, wake.month_of_year])
|
||||
except PeriodicTask.DoesNotExist:
|
||||
pass
|
||||
d.append(data)
|
||||
return d
|
||||
|
||||
@database_sync_to_async
|
||||
def delete_device(self, id):
|
||||
dev = Device.objects.get(id=id)
|
||||
dev.delete()
|
||||
|
||||
@database_sync_to_async
|
||||
def update_device(self, data):
|
||||
obj, _ = Device.objects.update_or_create(
|
||||
mac=data["mac"],
|
||||
defaults={
|
||||
"name": data["name"],
|
||||
"ip": data["ip"],
|
||||
"netmask": data["netmask"],
|
||||
"shutdown_cmd": data["shutdown"]["command"] if data.get("shutdown") else ""
|
||||
}
|
||||
)
|
||||
if data.get("ports"):
|
||||
for port in data.get("ports"):
|
||||
if port["checked"]:
|
||||
p, _ = Port.objects.get_or_create(
|
||||
number=port["number"], name=port["name"])
|
||||
obj.port.add(p)
|
||||
else:
|
||||
p = Port.objects.filter(number=port["number"]).first()
|
||||
if p and p in obj.port.all():
|
||||
obj.port.remove(p)
|
||||
|
||||
for action in ["wake", "shutdown"]:
|
||||
if data.get(action):
|
||||
if data[action]["enabled"]:
|
||||
cron = data[action]["cron"].strip().split(" ")
|
||||
if not len(cron) == 5:
|
||||
return
|
||||
minute, hour, dom, month, dow = cron
|
||||
schedule, _ = CrontabSchedule.objects.get_or_create(
|
||||
minute=minute,
|
||||
hour=hour,
|
||||
day_of_week=dow,
|
||||
day_of_month=dom,
|
||||
month_of_year=month
|
||||
)
|
||||
PeriodicTask.objects.update_or_create(
|
||||
name=f"{data['name']}-{action}",
|
||||
defaults={
|
||||
"crontab": schedule,
|
||||
"task": f"wol.tasks.scheduled_{action}",
|
||||
"args": json.dumps([data["id"]]),
|
||||
"enabled": True
|
||||
}
|
||||
)
|
||||
else:
|
||||
for task in PeriodicTask.objects.filter(name=f"{data['name']}-{action}", task=f"wol.tasks.scheduled_{action}"):
|
||||
task.enabled = False
|
||||
task.save()
|
||||
|
||||
@database_sync_to_async
|
||||
def update_port(self, data):
|
||||
if data.get("name"):
|
||||
Port.objects.update_or_create(
|
||||
number=data["number"],
|
||||
defaults={
|
||||
"name": data["name"]
|
||||
}
|
||||
)
|
||||
else:
|
||||
Port.objects.filter(number=data["number"]).delete()
|
||||
|
||||
@database_sync_to_async
|
||||
def get_settings(self):
|
||||
conf = Settings.objects.get(id=1)
|
||||
data = {
|
||||
"discovery": conf.scan_address,
|
||||
"interval": conf.interval,
|
||||
"scan_network": [],
|
||||
"notifications": conf.notifications
|
||||
}
|
||||
return data
|
||||
|
||||
@database_sync_to_async
|
||||
def update_settings(self, data):
|
||||
if data["interval"] > 5:
|
||||
data["interval"] = 5
|
||||
Settings.objects.update_or_create(
|
||||
id=1,
|
||||
defaults={
|
||||
"scan_address": data["discovery"],
|
||||
"interval": data["interval"],
|
||||
"notifications": data["notifications"]
|
||||
}
|
||||
)
|
||||
schedule, _ = IntervalSchedule.objects.get_or_create(
|
||||
every=data["interval"],
|
||||
period=IntervalSchedule.SECONDS,
|
||||
)
|
||||
PeriodicTask.objects.update_or_create(
|
||||
task="wol.tasks.ping_all_devices",
|
||||
defaults={
|
||||
"interval": schedule
|
||||
}
|
||||
)
|
||||
|
||||
@database_sync_to_async
|
||||
def scan_network(self):
|
||||
data = []
|
||||
conf = Settings.objects.get(id=1)
|
||||
netmask = str(ipaddress.ip_network(conf.scan_address).netmask)
|
||||
|
||||
if not conf.scan_address:
|
||||
return
|
||||
|
||||
p = subprocess.Popen(
|
||||
["nmap", "-sP", conf.scan_address], stdout=subprocess.PIPE)
|
||||
out = p.communicate()[0].decode("utf-8")
|
||||
ip_line = "Nmap scan report for"
|
||||
mac_line = "MAC Address:"
|
||||
|
||||
for line in out.splitlines():
|
||||
if line.startswith(ip_line):
|
||||
line_splitted = line.split()
|
||||
if len(line_splitted) == 6:
|
||||
name = line_splitted[4]
|
||||
ip = line_splitted[5]
|
||||
ip = ip.replace("(", "")
|
||||
ip = ip.replace(")", "")
|
||||
else:
|
||||
name = "Unknown"
|
||||
ip = line_splitted[4]
|
||||
elif line.startswith(mac_line):
|
||||
line_splitted = line.split()
|
||||
mac = line_splitted[2]
|
||||
data.append({
|
||||
"name": name,
|
||||
"ip": ip,
|
||||
"netmask": netmask,
|
||||
"mac": mac,
|
||||
"ports": [],
|
||||
"wake": {
|
||||
"enabled": False,
|
||||
"cron": ""
|
||||
},
|
||||
"shutdown": {
|
||||
"enabled": False,
|
||||
"cron": "",
|
||||
"command": ""
|
||||
}
|
||||
})
|
||||
return data
|
||||
@@ -1,23 +0,0 @@
|
||||
# Generated by Django 3.1.3 on 2020-11-15 19:37
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Device',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.SlugField(max_length=100)),
|
||||
('ip', models.GenericIPAddressField()),
|
||||
('mac', models.SlugField(max_length=17)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.1.3 on 2020-11-15 19:43
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='device',
|
||||
name='mac',
|
||||
field=models.CharField(max_length=17),
|
||||
),
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.1.3 on 2020-11-15 22:50
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0002_auto_20201115_2043'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='device',
|
||||
name='status',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
@@ -1,17 +0,0 @@
|
||||
# Generated by Django 3.1.3 on 2020-11-16 02:50
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0003_device_status'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='device',
|
||||
name='status',
|
||||
),
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.1.5 on 2021-01-18 16:21
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0004_remove_device_status'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='device',
|
||||
name='netmask',
|
||||
field=models.CharField(default='255.255.255.0', max_length=15),
|
||||
),
|
||||
]
|
||||
@@ -1,20 +0,0 @@
|
||||
# Generated by Django 3.2.7 on 2021-09-22 20:02
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0005_device_netmask'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Websocket',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('visitors', models.PositiveSmallIntegerField(default=0)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.2.7 on 2021-09-23 16:17
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0006_websocket'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='device',
|
||||
name='scheduled_wake',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -1,23 +0,0 @@
|
||||
# Generated by Django 3.2.7 on 2021-09-27 16:17
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0007_device_scheduled_wake'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Settings',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('ping_interval', models.PositiveSmallIntegerField(default=5)),
|
||||
('enable_notifications', models.BooleanField(default=True)),
|
||||
('enable_console_logging', models.BooleanField(default=True)),
|
||||
('sort_by', models.SlugField(default='name')),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -1,17 +0,0 @@
|
||||
# Generated by Django 3.2.7 on 2021-09-27 19:05
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0008_settings'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='settings',
|
||||
name='ping_interval',
|
||||
),
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.2.7 on 2021-09-28 19:00
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0009_remove_settings_ping_interval'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='settings',
|
||||
name='enable_console_logging',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.2.7 on 2021-09-28 20:19
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0010_alter_settings_enable_console_logging'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='settings',
|
||||
name='scan_address',
|
||||
field=models.GenericIPAddressField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.2.7 on 2021-09-28 23:11
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0011_settings_scan_address'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='device',
|
||||
name='name',
|
||||
field=models.SlugField(default='Unknown', max_length=100),
|
||||
),
|
||||
]
|
||||
@@ -1,64 +0,0 @@
|
||||
# Generated by Django 3.2.12 on 2022-03-12 10:05
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('wol', '0012_alter_device_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Port',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('number', models.PositiveIntegerField()),
|
||||
('name', models.SlugField()),
|
||||
],
|
||||
),
|
||||
migrations.RenameField(
|
||||
model_name='settings',
|
||||
old_name='enable_notifications',
|
||||
new_name='notifications',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='device',
|
||||
name='scheduled_wake',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='settings',
|
||||
name='enable_console_logging',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='device',
|
||||
name='shutdown_cmd',
|
||||
field=models.TextField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='settings',
|
||||
name='interval',
|
||||
field=models.PositiveSmallIntegerField(blank=True, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='device',
|
||||
name='id',
|
||||
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='settings',
|
||||
name='id',
|
||||
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='websocket',
|
||||
name='id',
|
||||
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='device',
|
||||
name='port',
|
||||
field=models.ManyToManyField(blank=True, to='wol.Port'),
|
||||
),
|
||||
]
|
||||
@@ -1,26 +0,0 @@
|
||||
from django.db import models
|
||||
|
||||
|
||||
class Port(models.Model):
|
||||
number = models.PositiveIntegerField()
|
||||
name = models.SlugField()
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
class Device(models.Model):
|
||||
name = models.SlugField(default="Unknown", max_length=100)
|
||||
ip = models.GenericIPAddressField()
|
||||
mac = models.CharField(max_length=17)
|
||||
netmask = models.CharField(max_length=15, default="255.255.255.0", blank=False, null=False)
|
||||
port = models.ManyToManyField(Port, blank=True)
|
||||
shutdown_cmd = models.TextField(null=True, blank=True)
|
||||
|
||||
class Websocket(models.Model):
|
||||
visitors = models.PositiveSmallIntegerField(blank=False, null=False, default=0)
|
||||
|
||||
class Settings(models.Model):
|
||||
sort_by = models.SlugField(default="name")
|
||||
scan_address = models.GenericIPAddressField(null=True, blank=True)
|
||||
interval = models.PositiveSmallIntegerField(null=True, blank=True)
|
||||
notifications = models.BooleanField(default=True)
|
||||
@@ -1,7 +0,0 @@
|
||||
from django.urls import path
|
||||
|
||||
from wol.consumers import WSConsumer
|
||||
|
||||
ws_urlpatterns = [
|
||||
path("wol/", WSConsumer.as_asgi())
|
||||
]
|
||||
@@ -1,144 +0,0 @@
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
from celery import shared_task
|
||||
from channels.layers import get_channel_layer
|
||||
from django_celery_beat.models import CrontabSchedule, PeriodicTask
|
||||
|
||||
from wol.commands import shutdown, wake
|
||||
from wol.models import Device, Port, Websocket
|
||||
|
||||
channel_layer = get_channel_layer()
|
||||
|
||||
|
||||
class WolDevice:
|
||||
def ping_device(self, ip):
|
||||
try:
|
||||
subprocess.check_output(["ping", "-c", "1", "-W", "0.5", ip])
|
||||
return True
|
||||
except subprocess.CalledProcessError:
|
||||
return False
|
||||
|
||||
def check_port(self, ip, port):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(0.5)
|
||||
if sock.connect_ex((ip, port)) == 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
def start(self, dev):
|
||||
data = {
|
||||
"id": dev.id,
|
||||
"name": dev.name,
|
||||
"ip": dev.ip,
|
||||
"mac": dev.mac,
|
||||
"netmask": dev.netmask,
|
||||
"up": False,
|
||||
"ports": [],
|
||||
"wake": {
|
||||
"enabled": False,
|
||||
"cron": ""
|
||||
},
|
||||
"shutdown": {
|
||||
"enabled": False,
|
||||
"cron": "",
|
||||
"command": dev.shutdown_cmd
|
||||
}
|
||||
}
|
||||
|
||||
# add ports
|
||||
for p in Port.objects.all().order_by("number"):
|
||||
data["ports"].append({
|
||||
"number": p.number,
|
||||
"name": p.name,
|
||||
"checked": True if p in dev.port.all() else False,
|
||||
"open": False
|
||||
})
|
||||
|
||||
# set status for device and ports
|
||||
if self.ping_device(dev.ip):
|
||||
data["up"] = True
|
||||
for port in dev.port.all():
|
||||
index = next(i for i, d in enumerate(
|
||||
data["ports"]) if d["number"] == port.number)
|
||||
if self.check_port(dev.ip, port.number):
|
||||
data["ports"][index]["checked"] = True
|
||||
data["ports"][index]["open"] = True
|
||||
else:
|
||||
data["ports"][index]["checked"] = True
|
||||
data["ports"][index]["open"] = False
|
||||
|
||||
# set cron for wake and shutdown
|
||||
for action in ["wake", "shutdown"]:
|
||||
try:
|
||||
task = PeriodicTask.objects.filter(
|
||||
name=f"{data['name']}-{action}",
|
||||
task=f"wol.tasks.scheduled_{action}", crontab_id__isnull=False).get()
|
||||
if task:
|
||||
wake = CrontabSchedule.objects.get(id=task.crontab_id)
|
||||
data[action]["enabled"] = task.enabled
|
||||
data[action]["cron"] = " ".join(
|
||||
[wake.minute, wake.hour, wake.day_of_week, wake.day_of_month, wake.month_of_year])
|
||||
except PeriodicTask.DoesNotExist:
|
||||
pass
|
||||
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
"wol", {"type": "send_group", "message": {
|
||||
"type": "status",
|
||||
"message": data
|
||||
}})
|
||||
|
||||
|
||||
@shared_task
|
||||
def ping_all_devices():
|
||||
if Websocket.objects.first().visitors == 0:
|
||||
return
|
||||
|
||||
devices = Device.objects.all()
|
||||
|
||||
for dev in devices:
|
||||
d = WolDevice()
|
||||
t = threading.Thread(target=d.start, args=(dev,))
|
||||
t.start()
|
||||
|
||||
|
||||
@shared_task
|
||||
def scheduled_wake(id):
|
||||
try:
|
||||
device = Device.objects.get(id=id)
|
||||
except Device.DoesNotExist:
|
||||
for task in PeriodicTask.objects.filter(args=id):
|
||||
task.delete()
|
||||
return
|
||||
|
||||
d = WolDevice()
|
||||
up = d.ping_device(device.ip)
|
||||
if not up:
|
||||
wake(device.mac, device.ip, device.netmask)
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
"wol", {"type": "send_group", "message": {
|
||||
"type": "pending",
|
||||
"message": id
|
||||
}})
|
||||
|
||||
|
||||
@shared_task
|
||||
def scheduled_shutdown(id):
|
||||
try:
|
||||
device = Device.objects.get(id=id)
|
||||
except Device.DoesNotExist:
|
||||
for task in PeriodicTask.objects.filter(args=id):
|
||||
task.delete()
|
||||
return
|
||||
|
||||
d = WolDevice()
|
||||
up = d.ping_device(device.ip)
|
||||
if up:
|
||||
shutdown(device.shutdown_cmd)
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
"wol", {"type": "send_group", "message": {
|
||||
"type": "pending",
|
||||
"message": id
|
||||
}})
|
||||
@@ -1,3 +0,0 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
@@ -1,4 +0,0 @@
|
||||
/node_modules/
|
||||
/public/build/
|
||||
|
||||
.DS_Store
|
||||
@@ -1,109 +0,0 @@
|
||||
*Psst — looking for a more complete solution? Check out [SvelteKit](https://kit.svelte.dev), the official framework for building web applications of all sizes, with a beautiful development experience and flexible filesystem-based routing.*
|
||||
|
||||
*Looking for a shareable component template instead? You can [use SvelteKit for that as well](https://kit.svelte.dev/docs#packaging) or the older [sveltejs/component-template](https://github.com/sveltejs/component-template)*
|
||||
|
||||
---
|
||||
|
||||
# svelte app
|
||||
|
||||
This is a project template for [Svelte](https://svelte.dev) apps. It lives at https://github.com/sveltejs/template.
|
||||
|
||||
To create a new project based on this template using [degit](https://github.com/Rich-Harris/degit):
|
||||
|
||||
```bash
|
||||
npx degit sveltejs/template svelte-app
|
||||
cd svelte-app
|
||||
```
|
||||
|
||||
*Note that you will need to have [Node.js](https://nodejs.org) installed.*
|
||||
|
||||
|
||||
## Get started
|
||||
|
||||
Install the dependencies...
|
||||
|
||||
```bash
|
||||
cd svelte-app
|
||||
npm install
|
||||
```
|
||||
|
||||
...then start [Rollup](https://rollupjs.org):
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Navigate to [localhost:8080](http://localhost:8080). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.
|
||||
|
||||
By default, the server will only respond to requests from localhost. To allow connections from other computers, edit the `sirv` commands in package.json to include the option `--host 0.0.0.0`.
|
||||
|
||||
If you're using [Visual Studio Code](https://code.visualstudio.com/) we recommend installing the official extension [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode). If you are using other editors you may need to install a plugin in order to get syntax highlighting and intellisense.
|
||||
|
||||
## Building and running in production mode
|
||||
|
||||
To create an optimised version of the app:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can run the newly built app with `npm run start`. This uses [sirv](https://github.com/lukeed/sirv), which is included in your package.json's `dependencies` so that the app will work when you deploy to platforms like [Heroku](https://heroku.com).
|
||||
|
||||
|
||||
## Single-page app mode
|
||||
|
||||
By default, sirv will only respond to requests that match files in `public`. This is to maximise compatibility with static fileservers, allowing you to deploy your app anywhere.
|
||||
|
||||
If you're building a single-page app (SPA) with multiple routes, sirv needs to be able to respond to requests for *any* path. You can make it so by editing the `"start"` command in package.json:
|
||||
|
||||
```js
|
||||
"start": "sirv public --single"
|
||||
```
|
||||
|
||||
## Using TypeScript
|
||||
|
||||
This template comes with a script to set up a TypeScript development environment, you can run it immediately after cloning the template with:
|
||||
|
||||
```bash
|
||||
node scripts/setupTypeScript.js
|
||||
```
|
||||
|
||||
Or remove the script via:
|
||||
|
||||
```bash
|
||||
rm scripts/setupTypeScript.js
|
||||
```
|
||||
|
||||
If you want to use `baseUrl` or `path` aliases within your `tsconfig`, you need to set up `@rollup/plugin-alias` to tell Rollup to resolve the aliases. For more info, see [this StackOverflow question](https://stackoverflow.com/questions/63427935/setup-tsconfig-path-in-svelte).
|
||||
|
||||
## Deploying to the web
|
||||
|
||||
### With [Vercel](https://vercel.com)
|
||||
|
||||
Install `vercel` if you haven't already:
|
||||
|
||||
```bash
|
||||
npm install -g vercel
|
||||
```
|
||||
|
||||
Then, from within your project folder:
|
||||
|
||||
```bash
|
||||
cd public
|
||||
vercel deploy --name my-project
|
||||
```
|
||||
|
||||
### With [surge](https://surge.sh/)
|
||||
|
||||
Install `surge` if you haven't already:
|
||||
|
||||
```bash
|
||||
npm install -g surge
|
||||
```
|
||||
|
||||
Then, from within your project folder:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
surge public my-project.surge.sh
|
||||
```
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"name": "svelte-app",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "rollup -c",
|
||||
"dev": "rollup -c -w",
|
||||
"start": "sirv public --no-clear --host"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^17.0.0",
|
||||
"@rollup/plugin-node-resolve": "^11.0.0",
|
||||
"rollup": "^2.3.4",
|
||||
"rollup-plugin-copy": "^3.4.0",
|
||||
"rollup-plugin-css-only": "^3.1.0",
|
||||
"rollup-plugin-livereload": "^2.0.0",
|
||||
"rollup-plugin-svelte": "^7.0.0",
|
||||
"rollup-plugin-terser": "^7.0.0",
|
||||
"svelte": "^3.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-free": "^6.0.0",
|
||||
"@rollup/plugin-replace": "^4.0.0",
|
||||
"bootstrap": "^5.1.3",
|
||||
"dotenv": "^16.0.0",
|
||||
"node-sass": "^7.0.1",
|
||||
"postcss": "^8.4.6",
|
||||
"sirv-cli": "^2.0.0",
|
||||
"svelte-preprocess": "^4.10.3"
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 8.5 KiB |
@@ -1,19 +0,0 @@
|
||||
main.svelte-1tky8bj {
|
||||
text-align: center;
|
||||
padding: 1em;
|
||||
max-width: 240px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
h1.svelte-1tky8bj {
|
||||
color: #ff3e00;
|
||||
text-transform: uppercase;
|
||||
font-size: 4em;
|
||||
font-weight: 100;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
main.svelte-1tky8bj {
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset='utf-8'>
|
||||
<meta name='viewport' content='width=device-width,initial-scale=1'>
|
||||
|
||||
<title>UpSnap</title>
|
||||
|
||||
<link rel='icon' type='image/png' href='/favicon.png'>
|
||||
<link rel='stylesheet' href='/global.css'>
|
||||
<link rel='stylesheet' href='/build/bundle.css'>
|
||||
|
||||
<script defer src='/build/bundle.js'></script>
|
||||
<script defer src='/build/bootstrap.min.js'></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,99 +0,0 @@
|
||||
import svelte from 'rollup-plugin-svelte';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import livereload from 'rollup-plugin-livereload';
|
||||
import { terser } from 'rollup-plugin-terser';
|
||||
import css from 'rollup-plugin-css-only';
|
||||
import preprocess from 'svelte-preprocess';
|
||||
import copy from 'rollup-plugin-copy';
|
||||
import dotenv from "dotenv";
|
||||
import replace from '@rollup/plugin-replace';
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const production = !process.env.ROLLUP_WATCH;
|
||||
|
||||
function serve() {
|
||||
let server;
|
||||
|
||||
function toExit() {
|
||||
if (server) server.kill(0);
|
||||
}
|
||||
|
||||
return {
|
||||
writeBundle() {
|
||||
if (server) return;
|
||||
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
|
||||
stdio: ['ignore', 'inherit', 'inherit'],
|
||||
shell: true
|
||||
});
|
||||
|
||||
process.on('SIGTERM', toExit);
|
||||
process.on('exit', toExit);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
input: 'src/main.js',
|
||||
output: {
|
||||
sourcemap: true,
|
||||
format: 'iife',
|
||||
name: 'app',
|
||||
file: 'public/build/bundle.js'
|
||||
},
|
||||
plugins: [
|
||||
svelte({
|
||||
compilerOptions: {
|
||||
// enable run-time checks when not in production
|
||||
dev: !production,
|
||||
},
|
||||
preprocess: preprocess(),
|
||||
}),
|
||||
replace({
|
||||
BACKEND_PORT: JSON.stringify(process.env.BACKEND_PORT),
|
||||
preventAssignment: true
|
||||
}),
|
||||
// we'll extract any component CSS out into
|
||||
// a separate file - better for performance
|
||||
css({ output: 'bundle.css' }),
|
||||
copy({
|
||||
targets: [
|
||||
{
|
||||
src: [
|
||||
"node_modules/@fortawesome/fontawesome-free/webfonts",
|
||||
"node_modules/bootstrap/dist/js/bootstrap.min.js",
|
||||
"node_modules/bootstrap/dist/js/bootstrap.min.js.map"
|
||||
],
|
||||
dest: "public/build/"
|
||||
}
|
||||
]
|
||||
}),
|
||||
|
||||
// If you have external dependencies installed from
|
||||
// npm, you'll most likely need these plugins. In
|
||||
// some cases you'll need additional configuration -
|
||||
// consult the documentation for details:
|
||||
// https://github.com/rollup/plugins/tree/master/packages/commonjs
|
||||
resolve({
|
||||
browser: true,
|
||||
dedupe: ['svelte']
|
||||
}),
|
||||
commonjs(),
|
||||
|
||||
// In dev mode, call `npm run start` once
|
||||
// the bundle has been generated
|
||||
!production && serve(),
|
||||
|
||||
// Watch the `public` directory and refresh the
|
||||
// browser on changes when not in production
|
||||
!production && livereload('public'),
|
||||
|
||||
// If we're building for production (npm run build
|
||||
// instead of npm run dev), minify
|
||||
production && terser()
|
||||
],
|
||||
watch: {
|
||||
clearScreen: false
|
||||
}
|
||||
};
|
||||
@@ -1,121 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/** This script modifies the project to support TS code in .svelte files like:
|
||||
|
||||
<script lang="ts">
|
||||
export let name: string;
|
||||
</script>
|
||||
|
||||
As well as validating the code for CI.
|
||||
*/
|
||||
|
||||
/** To work on this script:
|
||||
rm -rf test-template template && git clone sveltejs/template test-template && node scripts/setupTypeScript.js test-template
|
||||
*/
|
||||
|
||||
const fs = require("fs")
|
||||
const path = require("path")
|
||||
const { argv } = require("process")
|
||||
|
||||
const projectRoot = argv[2] || path.join(__dirname, "..")
|
||||
|
||||
// Add deps to pkg.json
|
||||
const packageJSON = JSON.parse(fs.readFileSync(path.join(projectRoot, "package.json"), "utf8"))
|
||||
packageJSON.devDependencies = Object.assign(packageJSON.devDependencies, {
|
||||
"svelte-check": "^2.0.0",
|
||||
"svelte-preprocess": "^4.0.0",
|
||||
"@rollup/plugin-typescript": "^8.0.0",
|
||||
"typescript": "^4.0.0",
|
||||
"tslib": "^2.0.0",
|
||||
"@tsconfig/svelte": "^2.0.0"
|
||||
})
|
||||
|
||||
// Add script for checking
|
||||
packageJSON.scripts = Object.assign(packageJSON.scripts, {
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json"
|
||||
})
|
||||
|
||||
// Write the package JSON
|
||||
fs.writeFileSync(path.join(projectRoot, "package.json"), JSON.stringify(packageJSON, null, " "))
|
||||
|
||||
// mv src/main.js to main.ts - note, we need to edit rollup.config.js for this too
|
||||
const beforeMainJSPath = path.join(projectRoot, "src", "main.js")
|
||||
const afterMainTSPath = path.join(projectRoot, "src", "main.ts")
|
||||
fs.renameSync(beforeMainJSPath, afterMainTSPath)
|
||||
|
||||
// Switch the app.svelte file to use TS
|
||||
const appSveltePath = path.join(projectRoot, "src", "App.svelte")
|
||||
let appFile = fs.readFileSync(appSveltePath, "utf8")
|
||||
appFile = appFile.replace("<script>", '<script lang="ts">')
|
||||
appFile = appFile.replace("export let name;", 'export let name: string;')
|
||||
fs.writeFileSync(appSveltePath, appFile)
|
||||
|
||||
// Edit rollup config
|
||||
const rollupConfigPath = path.join(projectRoot, "rollup.config.js")
|
||||
let rollupConfig = fs.readFileSync(rollupConfigPath, "utf8")
|
||||
|
||||
// Edit imports
|
||||
rollupConfig = rollupConfig.replace(`'rollup-plugin-terser';`, `'rollup-plugin-terser';
|
||||
import sveltePreprocess from 'svelte-preprocess';
|
||||
import typescript from '@rollup/plugin-typescript';`)
|
||||
|
||||
// Replace name of entry point
|
||||
rollupConfig = rollupConfig.replace(`'src/main.js'`, `'src/main.ts'`)
|
||||
|
||||
// Add preprocessor
|
||||
rollupConfig = rollupConfig.replace(
|
||||
'compilerOptions:',
|
||||
'preprocess: sveltePreprocess({ sourceMap: !production }),\n\t\t\tcompilerOptions:'
|
||||
);
|
||||
|
||||
// Add TypeScript
|
||||
rollupConfig = rollupConfig.replace(
|
||||
'commonjs(),',
|
||||
'commonjs(),\n\t\ttypescript({\n\t\t\tsourceMap: !production,\n\t\t\tinlineSources: !production\n\t\t}),'
|
||||
);
|
||||
fs.writeFileSync(rollupConfigPath, rollupConfig)
|
||||
|
||||
// Add TSConfig
|
||||
const tsconfig = `{
|
||||
"extends": "@tsconfig/svelte/tsconfig.json",
|
||||
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
|
||||
}`
|
||||
const tsconfigPath = path.join(projectRoot, "tsconfig.json")
|
||||
fs.writeFileSync(tsconfigPath, tsconfig)
|
||||
|
||||
// Add global.d.ts
|
||||
const dtsPath = path.join(projectRoot, "src", "global.d.ts")
|
||||
fs.writeFileSync(dtsPath, `/// <reference types="svelte" />`)
|
||||
|
||||
// Delete this script, but not during testing
|
||||
if (!argv[2]) {
|
||||
// Remove the script
|
||||
fs.unlinkSync(path.join(__filename))
|
||||
|
||||
// Check for Mac's DS_store file, and if it's the only one left remove it
|
||||
const remainingFiles = fs.readdirSync(path.join(__dirname))
|
||||
if (remainingFiles.length === 1 && remainingFiles[0] === '.DS_store') {
|
||||
fs.unlinkSync(path.join(__dirname, '.DS_store'))
|
||||
}
|
||||
|
||||
// Check if the scripts folder is empty
|
||||
if (fs.readdirSync(path.join(__dirname)).length === 0) {
|
||||
// Remove the scripts folder
|
||||
fs.rmdirSync(path.join(__dirname))
|
||||
}
|
||||
}
|
||||
|
||||
// Adds the extension recommendation
|
||||
fs.mkdirSync(path.join(projectRoot, ".vscode"), { recursive: true })
|
||||
fs.writeFileSync(path.join(projectRoot, ".vscode", "extensions.json"), `{
|
||||
"recommendations": ["svelte.svelte-vscode"]
|
||||
}
|
||||
`)
|
||||
|
||||
console.log("Converted to TypeScript.")
|
||||
|
||||
if (fs.existsSync(path.join(projectRoot, "node_modules"))) {
|
||||
console.log("\nYou will need to re-run your dependency manager to get started.")
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
import store from './store.js';
|
||||
import Navbar from "./components/Navbar.svelte";
|
||||
import DeviceCard from "./components/DeviceCard.svelte";
|
||||
import Toast from "./components/Toast.svelte";
|
||||
|
||||
let visitors = 0;
|
||||
let devices = [];
|
||||
let settings = {}
|
||||
let toast = {
|
||||
title: "",
|
||||
message: "",
|
||||
color: "",
|
||||
show: false
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
store.subscribe(currentMessage => {
|
||||
if (currentMessage.type == "init") {
|
||||
// create devices
|
||||
devices = [...currentMessage.message.devices]
|
||||
devices = devices;
|
||||
devices.sort(compare);
|
||||
settings = currentMessage.message.settings;
|
||||
} else if (currentMessage.type == "status") {
|
||||
// set device array and sort
|
||||
const index = devices.findIndex(x => x.id == currentMessage.message.id);
|
||||
if (devices.length === 0 || index === -1) {
|
||||
devices.push(currentMessage.message);
|
||||
devices = devices;
|
||||
} else {
|
||||
devices[index] = currentMessage.message;
|
||||
}
|
||||
devices.sort(compare)
|
||||
// set device status
|
||||
if (currentMessage.message.up == true) {
|
||||
setUp(currentMessage.message);
|
||||
} else {
|
||||
setDown(currentMessage.message);
|
||||
}
|
||||
} else if (currentMessage.type == "pending") {
|
||||
// set device pending
|
||||
setPending(currentMessage.message)
|
||||
} else if (currentMessage.type == "visitor") {
|
||||
// update visitor count
|
||||
visitors = currentMessage.message;
|
||||
} else if (currentMessage.type == "delete") {
|
||||
// delete device
|
||||
const devCol = document.querySelector(`#device-col-${currentMessage.message}`);
|
||||
devCol.remove();
|
||||
} else if (currentMessage.type == "scan_network") {
|
||||
// set scanned network devices
|
||||
if (!currentMessage.message) {
|
||||
return
|
||||
}
|
||||
settings["scan_network"] = currentMessage.message;
|
||||
const btnScan = document.querySelector("#btnScan");
|
||||
const btnScanSpinner = document.querySelector("#btnScanSpinner");
|
||||
const btnScanText = document.querySelector("#btnScanText");
|
||||
btnScan.disabled = false;
|
||||
btnScanSpinner.classList.add("d-none");
|
||||
btnScanText.innerText = "Scan";
|
||||
} else if (currentMessage.type == "backup") {
|
||||
// download backup file
|
||||
const now = new Date();
|
||||
const fileName = `upsnap_backup_${now.toISOString()}.json`
|
||||
const a = document.createElement("a");
|
||||
const file = new Blob([JSON.stringify(currentMessage.message)], { type: "text/plain" });
|
||||
a.href = URL.createObjectURL(file);
|
||||
a.download = fileName;
|
||||
a.click();
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
function setUp(device) {
|
||||
const dot = document.querySelector(`#dot-${device.id}`)
|
||||
const spinner = document.querySelector(`#spinner-${device.id}`);
|
||||
if (dot) {
|
||||
if (dot.classList.contains("danger")) {
|
||||
showToast(device.name, "Device is up!", "success")
|
||||
}
|
||||
dot.style.animation = "none";
|
||||
dot.offsetWidth;
|
||||
if (!spinner.classList.contains("d-none")) {
|
||||
if (dot.classList.contains("danger")) {
|
||||
spinner.classList.add("d-none");
|
||||
dot.classList.remove("d-none", "danger");
|
||||
dot.classList.add("success");
|
||||
}
|
||||
} else {
|
||||
dot.style.animation = "on-pulse 1s normal";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setDown(device) {
|
||||
const dot = document.querySelector(`#dot-${device.id}`)
|
||||
const spinner = document.querySelector(`#spinner-${device.id}`);
|
||||
if (dot) {
|
||||
if (dot.classList.contains("success")) {
|
||||
showToast(device.name, "Device is down!", "danger")
|
||||
}
|
||||
dot.style.animation = "none";
|
||||
dot.offsetWidth;
|
||||
if (!spinner.classList.contains("d-none")) {
|
||||
if (dot.classList.contains("success")) {
|
||||
spinner.classList.add("d-none");
|
||||
dot.classList.remove("d-none", "success");
|
||||
dot.classList.add("danger");
|
||||
}
|
||||
} else {
|
||||
dot.style.animation = "off-pulse 1s normal";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setPending(id) {
|
||||
const dot = document.querySelector(`#dot-${id}`);
|
||||
const spinner = document.querySelector(`#spinner-${id}`);
|
||||
dot.classList.add("d-none");
|
||||
spinner.classList.remove("d-none");
|
||||
}
|
||||
|
||||
function showToast(title, message, color) {
|
||||
if (settings.notifications === false) {
|
||||
return
|
||||
}
|
||||
toast.title = title;
|
||||
toast.message = message;
|
||||
toast.color = color;
|
||||
toast.show = true;
|
||||
setTimeout(() => {
|
||||
toast.show = false;
|
||||
}, 4000)
|
||||
}
|
||||
|
||||
function compare(a, b) {
|
||||
if (a.name < b.name){
|
||||
return -1;
|
||||
}
|
||||
if (a.name > b.name){
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<main>
|
||||
<Navbar settings={settings} visitors={visitors} />
|
||||
<div class="container mb-3">
|
||||
<div class="row">
|
||||
{#each devices as device}
|
||||
<DeviceCard device={device}/>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
<Toast toast={toast} />
|
||||
</main>
|
||||
|
||||
<style lang="scss" global>
|
||||
@import "./variables.scss";
|
||||
@import "../node_modules/bootstrap/scss/bootstrap";
|
||||
@import "../node_modules/@fortawesome/fontawesome-free/scss/fontawesome.scss";
|
||||
@import "../node_modules/@fortawesome/fontawesome-free/scss/regular.scss";
|
||||
@import "../node_modules/@fortawesome/fontawesome-free/scss/solid.scss";
|
||||
@import "theme.scss";
|
||||
|
||||
body {
|
||||
color: var(--color-text);
|
||||
background-color: var(--color-bg);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: var(--bg-modal);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
border-bottom: 1px solid var(--color-text);
|
||||
|
||||
.btn-close {
|
||||
background: var(--svg-close);
|
||||
}
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
border-top: 1px solid var(--color-text);
|
||||
}
|
||||
|
||||
.btn, button {
|
||||
&.btn-light {
|
||||
color: var(--color-text);
|
||||
background-color: var(--bg-lighter);
|
||||
border-width: 0px;
|
||||
}
|
||||
|
||||
&.btn-outline-success {
|
||||
border-color: $success;
|
||||
&:hover {
|
||||
background-color: $success;
|
||||
}
|
||||
}
|
||||
|
||||
&.btn-outline-danger {
|
||||
border-color: $danger;
|
||||
&:hover {
|
||||
background-color: $danger;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.form-control{
|
||||
&:focus {
|
||||
border-color: inherit;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.callout {
|
||||
padding: 1rem;
|
||||
border-left-width: 0.25rem;
|
||||
border-radius: 0.25rem;
|
||||
|
||||
&.callout-info {
|
||||
background-color: var(--info-dark-transparent);
|
||||
border: 1px solid var(--info-dark-transparent);
|
||||
border-left: 5px solid var(--info);
|
||||
}
|
||||
|
||||
&.callout-danger {
|
||||
background-color: var(--danger-dark-transparent);
|
||||
border: 1px solid var(--danger-dark-transparent);
|
||||
border-left: 5px solid var(--danger);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes on-pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 $success;
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 15px rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes off-pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 $danger;
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 15px rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,48 +0,0 @@
|
||||
<script>
|
||||
|
||||
const preferesDark = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
|
||||
preferesDark.addEventListener("change", e => {
|
||||
setTheme(e.matches ? "dark" : "light");
|
||||
})
|
||||
|
||||
if (localStorage.getItem("data-theme") === null) {
|
||||
setTheme(preferesDark.matches ? "dark" : "light");
|
||||
} else {
|
||||
setTheme(localStorage.getItem("data-theme"));
|
||||
}
|
||||
|
||||
function setTheme(color) {
|
||||
if (color == "system") {
|
||||
document.documentElement.setAttribute("data-theme", preferesDark ? "dark" : "light");
|
||||
localStorage.setItem("data-theme", preferesDark ? "dark" : "light");
|
||||
} else {
|
||||
document.documentElement.setAttribute("data-theme", color);
|
||||
localStorage.setItem("data-theme", color);
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-light dropdown-toggle px-3 me-2 py-2" type="button" id="darkModeButton" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<i class="fa-solid fa-palette me-2"></i>Theme
|
||||
</button>
|
||||
<ul class="dropdown-menu" aria-labelledby="darkModeButton">
|
||||
<li>
|
||||
<button class="dropdown-item" on:click={() => setTheme("dark")}>
|
||||
<i class="fa-solid fa-moon me-2"></i>Dark
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button class="dropdown-item" on:click={() => setTheme("light")}>
|
||||
<i class="fa-solid fa-sun me-2"></i>Light
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button class="dropdown-item" on:click={() => setTheme("system")}>
|
||||
<i class="fa-solid fa-desktop me-2"></i>System
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -1,330 +0,0 @@
|
||||
<script>
|
||||
import store from '../store.js';
|
||||
export let device;
|
||||
|
||||
let modalDevice = JSON.parse(JSON.stringify(device));
|
||||
let customPort = {}
|
||||
|
||||
function wake(id) {
|
||||
store.sendMessage({
|
||||
type: "wake",
|
||||
id: id
|
||||
})
|
||||
}
|
||||
|
||||
function shutdown(id) {
|
||||
store.sendMessage({
|
||||
type: "shutdown",
|
||||
id: id
|
||||
})
|
||||
}
|
||||
|
||||
function deleteDevice() {
|
||||
store.sendMessage({
|
||||
type: "delete_device",
|
||||
id: modalDevice.id
|
||||
})
|
||||
}
|
||||
|
||||
function updateDevice() {
|
||||
device = modalDevice;
|
||||
store.sendMessage({
|
||||
type: "update_device",
|
||||
data: modalDevice
|
||||
})
|
||||
}
|
||||
|
||||
function updatePort() {
|
||||
if (!customPort.number) {
|
||||
return
|
||||
}
|
||||
const index = modalDevice.ports.findIndex(x => x.number == customPort.number);
|
||||
if (customPort.name) {
|
||||
// add port
|
||||
if (index === -1) {
|
||||
customPort.checked = true;
|
||||
modalDevice.ports.push(JSON.parse(JSON.stringify(customPort)));
|
||||
} else {
|
||||
customPort.checked = modalDevice.ports[index].checked;
|
||||
modalDevice.ports[index] = JSON.parse(JSON.stringify(customPort));
|
||||
}
|
||||
} else {
|
||||
// delete port
|
||||
if (index >= 0) {
|
||||
modalDevice.ports.splice(index, 1)
|
||||
}
|
||||
}
|
||||
modalDevice = modalDevice;
|
||||
// send to backend
|
||||
store.sendMessage({
|
||||
type: "update_port",
|
||||
data: customPort
|
||||
})
|
||||
}
|
||||
|
||||
function openModal() {
|
||||
modalDevice = Object.assign({}, device)
|
||||
}
|
||||
|
||||
function validatePort() {
|
||||
if (typeof customPort.number != "number") {
|
||||
customPort.number = 1
|
||||
} else if (customPort.number > 65535) {
|
||||
customPort.number = 65535
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div id="device-col-{device.id}" class="col-xs-12 col-sm-6 col-md-4 col-lg-3 g-4">
|
||||
<div class="card border-0 p-3 pt-2">
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-auto me-auto">
|
||||
<div id="spinner-{device.id}" class="spinner-border warning d-none" role="status"></div>
|
||||
{#if device.up === true}
|
||||
{#if device.shutdown.command}
|
||||
<div class="hover" on:click="{() => shutdown(device.id)}" data-bs-toggle="tooltip" title="Shutdown command: {device.shutdown.command}" role="button">
|
||||
<i id="dot-{device.id}" class="fa-solid fa-power-off fa-2x success"></i>
|
||||
</div>
|
||||
{:else}
|
||||
<i id="dot-{device.id}" class="fa-solid fa-power-off fa-2x success"></i>
|
||||
{/if}
|
||||
{:else if device.up === false}
|
||||
<div class="hover" on:click="{() => wake(device.id)}" role="button">
|
||||
<i id="dot-{device.id}" class="fa-solid fa-power-off fa-2x danger"></i>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="hover" role="button">
|
||||
<i id="dot-{device.id}" class="fa-solid fa-power-off fa-2x text-muted"></i>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if device.wake.enabled}
|
||||
<div class="col-auto px-2" data-bs-toggle="tooltip" title="Wake cron: {device.wake.cron}">
|
||||
<i class="fa-solid fa-circle-play fa-2x text-muted"></i>
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.shutdown.enabled}
|
||||
<div class="col-auto px-2" data-bs-toggle="tooltip" title="Shutdown cron: {device.wake.cron}">
|
||||
<i class="fa-solid fa-circle-stop fa-2x text-muted"></i>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="col-auto hover" data-bs-toggle="modal" data-bs-target="#device-modal-{device.id}" role="button" on:click="{() => openModal()}">
|
||||
<i class="fa-solid fa-ellipsis-vertical fa-2x"></i>
|
||||
</div>
|
||||
</div>
|
||||
<h5 class="card-title fw-bold my-2">{device.name}</h5>
|
||||
<h6 class="card-subtitle mb-2 text-muted">{device.ip}</h6>
|
||||
<ul class="list-group">
|
||||
{#each device.ports as port}
|
||||
{#if port.checked === true}
|
||||
<li class="list-group-item">
|
||||
<i class="fa-solid fa-circle align-middle {port.open ? 'success' : 'danger'}"></i>
|
||||
{port.name} <span class="text-muted">({port.number})</span>
|
||||
</li>
|
||||
{/if}
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade" id="device-modal-{device.id}" tabindex="-1" aria-labelledby="device-modal-{device.id}-label" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-scrollable">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title fw-bold" id="device-modal-{modalDevice.id}-label">{modalDevice.name}</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="form-{modalDevice.id}" on:submit|preventDefault={updateDevice}>
|
||||
<!-- general -->
|
||||
<h5 class="fw-bold">General</h5>
|
||||
<div class="row mb-2">
|
||||
<div class="col-sm">
|
||||
<label for="inputName{modalDevice.id}" class="form-label">Device name</label>
|
||||
<input type="text" class="form-control" id="inputName{modalDevice.id}" bind:value="{modalDevice.name}" required>
|
||||
</div>
|
||||
<div class="col-sm">
|
||||
<label for="inputMac{modalDevice.id}" class="form-label">Mac address</label>
|
||||
<input type="text" class="form-control" id="inputMac{modalDevice.mac}" bind:value="{modalDevice.mac}" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-sm">
|
||||
<label for="inputIp{modalDevice.id}" class="form-label">IP address</label>
|
||||
<input type="text" class="form-control" id="inputIp{modalDevice.id}" bind:value="{modalDevice.ip}" pattern="^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.(?:[01]?\d\d?|2[0-4]\d|25[0-5])){'{'}3{'}'}$" required>
|
||||
</div>
|
||||
<div class="col-sm">
|
||||
<label for="inputNetmask{modalDevice.id}" class="form-label">Netmask</label>
|
||||
<input type="text" class="form-control" id="inputNetmask{modalDevice.id}" bind:value="{modalDevice.netmask}" pattern="^(((255\.){'{'}3{'}'}(255|254|252|248|240|224|192|128|0+))|((255\.){'{'}2{'}'}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){'{'}2{'}'})|((255|254|252|248|240|224|192|128|0+)(\.0+){'{'}3{'}'}))$" required>
|
||||
</div>
|
||||
</div>
|
||||
<!-- ports -->
|
||||
<h5 class="fw-bold mt-4">Ports</h5>
|
||||
<p class="mb-2">Select ports to check if they are open.</p>
|
||||
{#if modalDevice.ports.length === 0}
|
||||
<p class="mb-0">No ports available. Add ports below.</p>
|
||||
{/if}
|
||||
{#each modalDevice.ports as port}
|
||||
<div class="form-check">
|
||||
<input type="checkbox" class="form-check-input" id="{device.id}-port-{port.number}" bind:checked="{port['checked']}">
|
||||
<label class="form-check-label" for="{device.id}-port-{port.number}">{port.name} <span class="text-muted">({port.number})</span></label>
|
||||
</div>
|
||||
{/each}
|
||||
<label class="form-label mt-2" for="{device.id}-custom-port">Custom port</label>
|
||||
<div class="input-group mb-2">
|
||||
<input type="text" id="{device.id}-custom-port" class="form-control rounded-0 rounded-start" placeholder="Name" aria-label="Name" aria-describedby="button-addon2" bind:value={customPort.name}>
|
||||
<input type="number" min="1" max="65535" class="form-control rounded-0" placeholder="Port" aria-label="Port" aria-describedby="button-addon2" bind:value={customPort.number} on:input={validatePort}>
|
||||
<button class="btn btn-secondary" type="button" id="button-addon2" on:click="{updatePort}">Update Port</button>
|
||||
</div>
|
||||
<button class="btn btn-secondary mt-2" type="button" data-bs-toggle="collapse" data-bs-target="#info-ports" aria-expanded="false" aria-controls="info-ports">
|
||||
<i class="fa-solid fa-angle-down me-2"></i>How to use
|
||||
</button>
|
||||
<div class="collapse mt-3" id="info-ports">
|
||||
<div class="callout callout-info">
|
||||
<p class="mb-0">Ports must be between 1 and 65535. Enter the same port with a differen name to change it. Leave name empty to delete port.</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- scheduled wake -->
|
||||
<h5 class="fw-bold mt-4">Scheduled wake</h5>
|
||||
<p class="mb-2">Wake your device at a given time.</p>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="radio" name="wake-disable" id="wake-radio-disabled-{modalDevice.id}"
|
||||
bind:group={modalDevice["wake"]["enabled"]} value={false} checked={!modalDevice["wake"]["enabled"]}>
|
||||
<label class="form-check-label" for="wake-radio-disabled-{modalDevice.id}">
|
||||
Disabled
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="radio" name="wake-cron" id="wake-radio-cron-{modalDevice.id}"
|
||||
bind:group={modalDevice["wake"]["enabled"]} value={true} checked={modalDevice["wake"]["enabled"]}>
|
||||
<label class="form-check-label" for="wake-radio-cron-{modalDevice.id}">
|
||||
Enabled
|
||||
</label>
|
||||
</div>
|
||||
<div class="input-group my-1" hidden={!modalDevice["wake"]["enabled"]}>
|
||||
<span class="input-group-text rounded-0 rounded-start" id="wake-cron-{modalDevice.id}">Cron</span>
|
||||
<input type="text" class="form-control rounded-0 rounded-end" placeholder="* /4 * * *" aria-label="Crontab" aria-describedby="wake-cron-{modalDevice.id}" bind:value={modalDevice["wake"]["cron"]}>
|
||||
</div>
|
||||
<button class="btn btn-secondary mt-2" type="button" data-bs-toggle="collapse" data-bs-target="#info-wake" aria-expanded="false" aria-controls="info-wake">
|
||||
<i class="fa-solid fa-angle-down me-2"></i>How to use
|
||||
</button>
|
||||
<div class="collapse mt-3" id="info-wake">
|
||||
<div class="callout callout-info">
|
||||
<p class="mb-2">Cron is a syntax describing a time pattern when to execute jobs. The above field uses common cron syntax. Examples:</p>
|
||||
<pre class="mb-2">Minute Hour DayOfMonth Month DayOfWeek
|
||||
* /4 * * * (Wake every 4 hours)
|
||||
0 9 * * 1-5 (Wake from Mo-Fr at 9 a.m.)
|
||||
</pre>
|
||||
<p class="mb-0">Read more about <a href="https://linux.die.net/man/5/crontab" target="_blank">valid syntax here</a> or <a href="https://crontab.guru/" target="_blank">use a generator</a>. Expressions starting with "@..." are not supported.</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- scheduled shutdown -->
|
||||
<h5 class="fw-bold mt-4">Shutdown</h5>
|
||||
<p class="mb-2">Set the shutdown command here. This shell command will be executed when clicking the power button on the device card. You can use cron below, which will then execute the command at the given time.</p>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text rounded-0 rounded-start" id="shutdown-command-{modalDevice.id}">Command</span>
|
||||
<input type="text" class="form-control rounded-0 rounded-end" placeholder="sshpass -p your_password ssh -o 'StrictHostKeyChecking=no' user@hostname 'sudo shutdown'" aria-label="Ccommand" aria-describedby="shutdown-command-{modalDevice.id}" bind:value={modalDevice["shutdown"]["command"]}>
|
||||
</div>
|
||||
<button class="btn btn-secondary mt-2" type="button" data-bs-toggle="collapse" data-bs-target="#info-shutdown" aria-expanded="false" aria-controls="info-shutdown">
|
||||
<i class="fa-solid fa-angle-down me-2"></i>How to use
|
||||
</button>
|
||||
<div class="collapse mt-3" id="info-shutdown">
|
||||
<div class="callout callout-info">
|
||||
<p class="mb-2">This field takes a shell command to trigger the shutdown. You can use <code>sshpass</code> for Linux or <code>net rpc</code> for Windows hosts.</p>
|
||||
<div class="callout callout-danger mb-2">Note: This command is safed as cleartext. Meaning, passwords are clearly visible in the database.</div>
|
||||
<p class="mb-2">Examples:</p>
|
||||
<pre class="mb-2"># wake linux hosts
|
||||
sshpass -p your_password ssh -o 'StrictHostKeyChecking=no' user@hostname 'sudo shutdown'
|
||||
|
||||
# wake windows hosts
|
||||
net rpc shutdown --ipaddress 192.168.1.1 --user user%password
|
||||
</pre>
|
||||
<p class="mb-0">Read more about <a href="https://linux.die.net/man/1/sshpass" target="_blank">sshpass</a> or <a href="https://linux.die.net/man/8/net" target="_blank">net rpc</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="form-label mt-2" for="{device.id}-shutdown-cron">Use cron</label>
|
||||
</div>
|
||||
<div class="form-check" id="{device.id}-shutdown-cron">
|
||||
<input class="form-check-input" type="radio" name="shutdown-disable" id="shutdown-radio-disabled-{modalDevice.id}"
|
||||
bind:group={modalDevice["shutdown"]["enabled"]} value={false} checked={!modalDevice["shutdown"]["enabled"]}>
|
||||
<label class="form-check-label" for="shutdown-radio-disabled-{modalDevice.id}">
|
||||
Disabled
|
||||
</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="radio" name="shutdown-enable" id="shutdown-radio-enabled-{modalDevice.id}"
|
||||
bind:group={modalDevice["shutdown"]["enabled"]} value={true} checked={modalDevice["shutdown"]["enabled"]}>
|
||||
<label class="form-check-label" for="shutdown-radio-enabled-{modalDevice.id}">
|
||||
Enabled
|
||||
</label>
|
||||
</div>
|
||||
<div class="input-group my-1" hidden={!modalDevice["shutdown"]["enabled"]}>
|
||||
<span class="input-group-text rounded-0 rounded-start" id="shutdown-cron-{modalDevice.id}">Cron</span>
|
||||
<input type="text" class="form-control rounded-0 rounded-end" placeholder="* /4 * * *" aria-label="Crontab" aria-describedby="shutdown-cron-{modalDevice.id}" bind:value={modalDevice["shutdown"]["cron"]}>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-between">
|
||||
<button type="button" class="btn btn-outline-danger" data-bs-dismiss="modal" on:click={deleteDevice}>Delete</button>
|
||||
<button type="submit" form="form-{modalDevice.id}" class="btn btn-outline-success">Save changes</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
.success {
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.warning {
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
pre {
|
||||
white-space: pre-line;
|
||||
background-color: var(--color-bg);
|
||||
padding: 1em;
|
||||
border-radius: 1em;
|
||||
}
|
||||
|
||||
.card {
|
||||
border-radius: 2em;
|
||||
background-color: var(--bg-lighter);
|
||||
}
|
||||
|
||||
.spinner-border {
|
||||
width: 1.5em;
|
||||
height: 1.5em;
|
||||
}
|
||||
|
||||
.hover {
|
||||
&:hover {
|
||||
text-shadow: 0px 0px 20px rgb(155, 155, 155);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
}
|
||||
|
||||
.fa-2x {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
|
||||
.fa-power-off {
|
||||
border-radius: 1em;
|
||||
}
|
||||
|
||||
.fa-circle {
|
||||
font-size: 0.8em;
|
||||
}
|
||||
|
||||
.list-group-item {
|
||||
color: var(--color-text);
|
||||
}
|
||||
</style>
|
||||
@@ -1,307 +0,0 @@
|
||||
<script>
|
||||
import store from '../store.js';
|
||||
import DarkToggle from "./DarkToggle.svelte";
|
||||
export let visitors;
|
||||
export let settings;
|
||||
|
||||
let addDevice = {
|
||||
wake: {
|
||||
enabled: false,
|
||||
cron: ""
|
||||
},
|
||||
shutdown: {
|
||||
enabled: false,
|
||||
cron: "",
|
||||
command: ""
|
||||
}
|
||||
}
|
||||
|
||||
function updateDevice(data) {
|
||||
if (Object.keys(data).length < 4) {
|
||||
return
|
||||
}
|
||||
store.sendMessage({
|
||||
type: "update_device",
|
||||
data: data
|
||||
})
|
||||
}
|
||||
|
||||
function updateSettings() {
|
||||
store.sendMessage({
|
||||
type: "update_settings",
|
||||
data: settings
|
||||
})
|
||||
hideModal("settings");
|
||||
}
|
||||
|
||||
function scanNetwork() {
|
||||
store.sendMessage({
|
||||
type: "scan_network"
|
||||
})
|
||||
const btnScan = document.querySelector("#btnScan");
|
||||
const btnScanSpinner = document.querySelector("#btnScanSpinner");
|
||||
const btnScanText = document.querySelector("#btnScanText");
|
||||
btnScan.disabled = true;
|
||||
btnScanSpinner.classList.remove("d-none");
|
||||
btnScanText.innerText = "Scanning...";
|
||||
}
|
||||
|
||||
function addScan(i) {
|
||||
document.querySelector(`#btnAdd${i}`).disabled = true;
|
||||
const dev = settings.scan_network[i];
|
||||
updateDevice(dev);
|
||||
}
|
||||
|
||||
const restoreFromFile = (e) => {
|
||||
let file = e.target.files[0];
|
||||
let reader = new FileReader();
|
||||
reader.readAsText(file);
|
||||
reader.onload = e => {
|
||||
let data = JSON.parse(e.target.result);
|
||||
if (Array.isArray(data)) {
|
||||
// v2 file restore
|
||||
data.forEach((device) => {
|
||||
updateDevice(device)
|
||||
})
|
||||
} else {
|
||||
// v1 file restore
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
value["mac"] = key
|
||||
updateDevice(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
hideModal("settings");
|
||||
}
|
||||
|
||||
function backupToFile() {
|
||||
store.sendMessage({
|
||||
type: "backup"
|
||||
})
|
||||
}
|
||||
|
||||
function hideModal(id) {
|
||||
const modalEl = document.querySelector(`#${id}`);
|
||||
const modal = bootstrap.Modal.getInstance(modalEl);
|
||||
modal.hide();
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<nav class="navbar navbar-expand-sm">
|
||||
<div class="container-fluid">
|
||||
<div class="navbar-brand" href="/">
|
||||
<img src="/favicon.png" alt="Logo" width="24" height="24" class="me-2">
|
||||
UpSnap
|
||||
</div>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
|
||||
<span class="ms-auto d-flex">
|
||||
<DarkToggle />
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-light dropdown-toggle px-3 me-2 py-2" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<i class="fa-solid fa-wrench me-2"></i>More
|
||||
</button>
|
||||
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
|
||||
<li>
|
||||
<button class="dropdown-item" data-bs-toggle="modal" data-bs-target="#addDevice">
|
||||
<i class="fa-solid fa-plus me-2"></i>Add device
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button class="dropdown-item" data-bs-toggle="modal" data-bs-target="#settings">
|
||||
<i class="fa-solid fa-sliders me-2"></i>Settings
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="btn btn-light px-3 me-2 py-2 pe-none">
|
||||
<i class="me-2 fa-solid {visitors === 1 ? "fa-user" : "fa-user-group"}"></i>{visitors} {visitors === 1 ? "Visitor" : "Visitors"}
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="modal fade" id="addDevice" tabindex="-1" aria-labelledby="addDeviceLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title fw-bold" id="addDeviceLabel">Add device</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="addForm" on:submit|preventDefault={() => updateDevice(addDevice)}>
|
||||
<div class="row">
|
||||
<div class="col-sm">
|
||||
<div class="mb-3">
|
||||
<label for="inputNameAddDevice" class="form-label">Device name</label>
|
||||
<input type="text" class="form-control" id="inputNameAddDevice" placeholder="Max PC" bind:value="{addDevice.name}" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm">
|
||||
<div class="mb-3">
|
||||
<label for="inputMacAddDevice" class="form-label">Mac address</label>
|
||||
<input type="text" class="form-control" id="inputMacAddDevice" placeholder="aa:aa:aa:aa:aa:aa" bind:value="{addDevice.mac}" pattern="^([0-9A-Fa-f]{'{'}2{'}'}[:-]){'{'}5{'}'}([0-9A-Fa-f]{'{'}2{'}'})|([0-9a-fA-F]{'{'}4{'}'}\\.[0-9a-fA-F]{'{'}4{'}'}\\.[0-9a-fA-F]{'{'}4{'}'})$" required>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-sm">
|
||||
<div class="mb-3">
|
||||
<label for="inputIpAddDevice" class="form-label">IP address</label>
|
||||
<input type="text" class="form-control" id="inputIpAddDevice" placeholder="192.168.1.1" bind:value="{addDevice.ip}" pattern="^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.(?:[01]?\d\d?|2[0-4]\d|25[0-5])){'{'}3{'}'}$" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm">
|
||||
<div class="mb-3">
|
||||
<label for="inputNetmaskAddDevice" class="form-label">Netmask</label>
|
||||
<input type="text" class="form-control" id="inputNetmaskAddDevice" placeholder="255.255.255.0" bind:value="{addDevice.netmask}" pattern="^(((255\.){'{'}3{'}'}(255|254|252|248|240|224|192|128|0+))|((255\.){'{'}2{'}'}(255|254|252|248|240|224|192|128|0+)\.0)|((255\.)(255|254|252|248|240|224|192|128|0+)(\.0+){'{'}2{'}'})|((255|254|252|248|240|224|192|128|0+)(\.0+){'{'}3{'}'}))$" required>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-auto ms-auto">
|
||||
<button type="submit" form="addForm" class="btn btn-outline-success">Add device</button>
|
||||
</div>
|
||||
</div>
|
||||
<h5 class="fw-bold">Network discovery</h5>
|
||||
{#if !settings.discovery}
|
||||
<div class="callout callout-danger mb-2">
|
||||
<p class="m-0">To enable this option, please enter your network address in the settings.</p>
|
||||
</div>
|
||||
{/if}
|
||||
<button id="btnScan" class="btn btn-secondary" type="button" on:click={scanNetwork} disabled={!settings.discovery}>
|
||||
<span id="btnScanSpinner" class="spinner-grow spinner-grow-sm d-none" role="status" aria-hidden="true"></span>
|
||||
<span id="btnScanText">Scan</span>
|
||||
</button>
|
||||
{#if settings.scan_network?.length}
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<td>Name</td>
|
||||
<td>IP</td>
|
||||
<td>Netmask</td>
|
||||
<td>Mac</td>
|
||||
<td>Add</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each settings.scan_network as device, i}
|
||||
<tr>
|
||||
<td>{device.name}</td>
|
||||
<td>{device.ip}</td>
|
||||
<td>{device.netmask}</td>
|
||||
<td>{device.mac}</td>
|
||||
<td>
|
||||
<button type="button" id="btnAdd{i}" class="btn btn-outline-secondary py-0" on:click={() => addScan(i)}>
|
||||
<i class="fa-solid fa-plus fa-sm"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
{/if}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade" id="settings" tabindex="-1" aria-labelledby="settingsLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title fw-bold" id="settingsLabel">Settings</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="settingsForm" on:submit|preventDefault={updateSettings}>
|
||||
<h5 class="fw-bold">General</h5>
|
||||
<div class="row">
|
||||
<div class="col-sm-8">
|
||||
<div class="mb-3">
|
||||
<label for="inputNetworkDiscovery" class="form-label">Network discovery address</label>
|
||||
<input type="text" class="form-control" id="inputNetworkDiscovery" placeholder="192.168.1.0/24" bind:value="{settings.discovery}" pattern="^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.(?:[01]?\d\d?|2[0-4]\d|25[0-5])){'{'}2{'}'}(?:\.(?:0))(?:/[0-2]\d|/3[0-2])$">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-4">
|
||||
<div class="mb-3">
|
||||
<label for="inputIntervalSettings" class="form-label">Interval (seconds)</label>
|
||||
<input type="number" class="form-control" id="inputIntervalSettings" min="5" bind:value="{settings.interval}" required>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-sm">
|
||||
<div class="form-check">
|
||||
<label class="form-check-label" for="flexCheckDefault">
|
||||
Enable notifications
|
||||
</label>
|
||||
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" bind:checked={settings.notifications}>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<div class="row mb-3">
|
||||
<div class="col-auto ms-auto">
|
||||
<button type="submit" form="settingsForm" class="btn btn-outline-success">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
<h5 class="fw-bold">Backup/Restore</h5>
|
||||
<div class="callout callout-info mb-2">
|
||||
<p class="m-0">Backup file structure has changed in v2. You can still restore both versions with this file upload.</p>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="inputRestore" class="form-label">Restore from .json</label>
|
||||
<input id="inputRestore" type="file" class="form-control" accept=".json" on:change={(e) => restoreFromFile(e)}>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="button" class="btn btn-secondary" on:click={backupToFile}>
|
||||
<i class="fa-solid fa-download me-2"></i>
|
||||
Export .json
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style lang="scss" global>
|
||||
.table {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.dropdown-menu {
|
||||
background-color: var(--bg-lighter);
|
||||
|
||||
li:first-child>button {
|
||||
border-radius: 0.5rem 0.5rem 0rem 0rem;
|
||||
}
|
||||
|
||||
li:last-child>button {
|
||||
border-radius: 0rem 0rem 0.5rem 0.5rem;
|
||||
}
|
||||
|
||||
li:only-child>button {
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.dropdown-item {
|
||||
color: var(--color-text);
|
||||
background-color: var(--bg-lighter);
|
||||
|
||||
&:hover {
|
||||
color: var(--color-bg);
|
||||
background-color: var(--color-text);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,36 +0,0 @@
|
||||
<script>
|
||||
export let toast;
|
||||
</script>
|
||||
|
||||
<div class="position-fixed bottom-0 end-0 p-3 toast-container">
|
||||
<div class="toast fade {toast.show ? 'show' : 'hide'} {toast.color}-bg" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="toast-header">
|
||||
<strong id="toast-title" class="me-auto">{toast.title}</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="toast-body fw-bold">
|
||||
{toast.message}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style lang="scss">
|
||||
@import "../variables.scss";
|
||||
|
||||
.toast-container {
|
||||
z-index: 11;
|
||||
border-radius: $toast-border-radius;
|
||||
|
||||
div>.toast-body {
|
||||
color: $dark-lighter;
|
||||
}
|
||||
}
|
||||
|
||||
.success-bg {
|
||||
background-color: var(--success);
|
||||
}
|
||||
|
||||
.danger-bg {
|
||||
background-color: var(--danger);
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +0,0 @@
|
||||
import App from './App.svelte';
|
||||
|
||||
|
||||
const app = new App({
|
||||
target: document.body
|
||||
});
|
||||
|
||||
export default app;
|
||||
@@ -1,27 +0,0 @@
|
||||
import {
|
||||
writable
|
||||
} from 'svelte/store';
|
||||
|
||||
const messageStore = writable('');
|
||||
const socket = new WebSocket(`ws://${location.hostname}:${BACKEND_PORT}/wol/`);
|
||||
|
||||
// Connection opened
|
||||
socket.addEventListener('open', function (event) {
|
||||
return
|
||||
});
|
||||
|
||||
// Listen for messages
|
||||
socket.addEventListener('message', function (event) {
|
||||
messageStore.set(JSON.parse(event.data));
|
||||
});
|
||||
|
||||
const sendMessage = (message) => {
|
||||
if (socket.readyState <= 1) {
|
||||
socket.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
subscribe: messageStore.subscribe,
|
||||
sendMessage
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
:root {
|
||||
--success: #{$success};
|
||||
--warning: #{$warning};
|
||||
--danger: #{$danger};
|
||||
--danger-dark-transparent: #{$danger-dark-transparent};
|
||||
--info: #{$info};
|
||||
--info-dark-transparent: #{$info-dark-transparent};
|
||||
}
|
||||
|
||||
html[data-theme="light"] {
|
||||
--color-bg: #{$light};
|
||||
--color-text: #{$dark};
|
||||
--bg-lighter: #{$light-darker};
|
||||
--bg-modal: #{$light};
|
||||
--svg-close: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23000'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] {
|
||||
--color-bg: #{$dark};
|
||||
--color-text: #{$light};
|
||||
--bg-lighter: #{$dark-lighter};
|
||||
--bg-modal: #{$dark-lighter};
|
||||
--svg-close: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
// colors
|
||||
$light: #f6f6fb;
|
||||
$light-darker: #e2e4eb;
|
||||
$success: #06d6a0;
|
||||
$danger: #ef476f;
|
||||
$danger-dark-transparent: #ef476f1f;
|
||||
$warning: #ffd166;
|
||||
$info: #1177b2;
|
||||
$info-dark-transparent: #1177b21f;
|
||||
$dark: #131316;
|
||||
$dark-lighter: #25252b;
|
||||
|
||||
// bootstrap
|
||||
$list-group-border-width: 0px;
|
||||
$list-group-item-padding-x: 0px;
|
||||
$list-group-item-padding-y: 0px;
|
||||
$list-group-bg: transparent;
|
||||
$modal-content-border-radius: 2em;
|
||||
$modal-inner-padding: 1.5rem;
|
||||
$btn-border-radius: 0.7rem;
|
||||
$dropdown-border-radius: 1em;
|
||||
$dropdown-border-width: 0px;
|
||||
$dropdown-min-width: 8rem;
|
||||
$toast-border-radius: 0.7rem;
|
||||
$toast-box-shadow: none;
|
||||
$toast-border-width: 0px;
|
||||
|
||||
// font awesome
|
||||
$fa-font-path: "webfonts";
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
# init django
|
||||
cd /app/backend/ || exit
|
||||
python3 manage.py makemigrations
|
||||
python3 manage.py migrate
|
||||
python3 manage.py collectstatic --noinput
|
||||
python3 manage.py shell < setup.py
|
||||
python3 -m celery -A backend worker &
|
||||
python3 -m celery -A backend beat &
|
||||
python3 -m gunicorn --bind 0.0.0.0:"${BACKEND_PORT}" --workers 4 backend.asgi:application -k uvicorn.workers.UvicornWorker &
|
||||
|
||||
# start frontend
|
||||
cd /app/frontend/ || exit
|
||||
npm install
|
||||
npm run build
|
||||
PORT=$FRONTEND_PORT npm start
|
||||
|
Before Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 140 KiB |
|
Before Width: | Height: | Size: 140 KiB |
|
After Width: | Height: | Size: 326 KiB |
|
After Width: | Height: | Size: 324 KiB |
|
After Width: | Height: | Size: 230 KiB |
|
After Width: | Height: | Size: 223 KiB |
|
Before Width: | Height: | Size: 70 KiB |
|
Before Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
Before Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 690 KiB |
|
After Width: | Height: | Size: 696 KiB |
@@ -0,0 +1,36 @@
|
||||
release:
|
||||
# draft: true
|
||||
prerelease: auto
|
||||
before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
builds:
|
||||
- binary: upsnap
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
ldflags:
|
||||
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Version }}
|
||||
goos:
|
||||
- linux
|
||||
- windows
|
||||
- darwin
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
- arm
|
||||
goarm:
|
||||
- 6
|
||||
- 7
|
||||
ignore:
|
||||
- goos: windows
|
||||
goarch: arm
|
||||
- goos: darwin
|
||||
goarch: arm
|
||||
archives:
|
||||
- format: zip
|
||||
checksum:
|
||||
name_template: "checksums.txt"
|
||||
snapshot:
|
||||
name_template: "{{ .Version }}"
|
||||
changelog:
|
||||
sort: asc
|
||||
@@ -0,0 +1,130 @@
|
||||
package cronjobs
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
"github.com/robfig/cron/v3"
|
||||
"github.com/seriousm4x/upsnap/logger"
|
||||
"github.com/seriousm4x/upsnap/networking"
|
||||
)
|
||||
|
||||
var Devices []*models.Record
|
||||
var CronPing *cron.Cron
|
||||
var CronWakeShutdown *cron.Cron
|
||||
|
||||
func RunPing(app *pocketbase.PocketBase) {
|
||||
settingsPrivateRecords, err := app.Dao().FindRecordsByExpr("settings_private")
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
|
||||
// init cronjob
|
||||
CronPing = cron.New()
|
||||
CronPing.AddFunc(settingsPrivateRecords[0].GetString("interval"), func() {
|
||||
// skip cron if no realtime clients connected
|
||||
realtimeClients := len(app.SubscriptionsBroker().Clients())
|
||||
if realtimeClients == 0 {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
} else {
|
||||
if oldStatus == "online" || oldStatus == "" {
|
||||
device.Set("status", "offline")
|
||||
app.Dao().SaveRecord(device)
|
||||
}
|
||||
}
|
||||
}(device)
|
||||
|
||||
// scan ports
|
||||
go func(device *models.Record) {
|
||||
ports, err := app.Dao().FindRecordsByIds("ports", device.GetStringSlice("ports"))
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
for _, port := range ports {
|
||||
isUp := networking.CheckPort(device.GetString("ip"), port.GetString("number"))
|
||||
if isUp != port.GetBool("status") {
|
||||
port.Set("status", isUp)
|
||||
app.Dao().SaveRecord(port)
|
||||
device.RefreshUpdated()
|
||||
app.Dao().SaveRecord(device)
|
||||
}
|
||||
}
|
||||
}(device)
|
||||
}
|
||||
})
|
||||
CronPing.Run()
|
||||
}
|
||||
|
||||
func RunWakeShutdown(app *pocketbase.PocketBase) {
|
||||
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")
|
||||
|
||||
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 := networking.WakeDevice(d); err != nil {
|
||||
logger.Error.Println(err)
|
||||
d.Set("status", "offline")
|
||||
app.Dao().SaveRecord(d)
|
||||
} else {
|
||||
d.Set("status", "online")
|
||||
app.Dao().SaveRecord(d)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
}(device)
|
||||
}
|
||||
|
||||
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 := networking.ShutdownDevice(d); err != nil {
|
||||
logger.Error.Println(err)
|
||||
d.Set("status", "online")
|
||||
app.Dao().SaveRecord(d)
|
||||
} else {
|
||||
d.Set("status", "offline")
|
||||
app.Dao().SaveRecord(d)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
}(device)
|
||||
}
|
||||
}
|
||||
CronWakeShutdown.Run()
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
module github.com/seriousm4x/upsnap
|
||||
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/labstack/echo/v5 v5.0.0-20220201181537-ed2888cfa198
|
||||
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
|
||||
github.com/pocketbase/dbx v1.10.0
|
||||
github.com/pocketbase/pocketbase v0.16.3
|
||||
github.com/prometheus-community/pro-bing v0.1.0
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/AlecAivazis/survey/v2 v2.3.6 // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/aws/aws-sdk-go v1.44.273 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.18.0 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.18.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.13.24 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.3 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.67 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.33 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.3.34 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.0.25 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.11 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.28 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.27 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.14.2 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.33.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.12.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.10 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.19.0 // indirect
|
||||
github.com/aws/smithy-go v1.13.5 // indirect
|
||||
github.com/disintegration/imaging v1.6.2 // indirect
|
||||
github.com/domodwyer/mailyak/v3 v3.6.0 // 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
|
||||
github.com/ganigeorgiev/fexpr v0.3.0 // indirect
|
||||
github.com/go-ozzo/ozzo-validation/v4 v4.3.0 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.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/wire v0.5.0 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.10.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jmespath/go-jmespath v0.4.0 // indirect
|
||||
github.com/josharian/native v1.1.0 // indirect
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.17 // indirect
|
||||
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
|
||||
github.com/mdlayher/packet v1.1.2 // indirect
|
||||
github.com/mdlayher/socket v0.4.1 // indirect
|
||||
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/spf13/cast v1.5.1 // indirect
|
||||
github.com/spf13/cobra v1.7.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
gocloud.dev v0.29.0 // indirect
|
||||
golang.org/x/crypto v0.9.0 // indirect
|
||||
golang.org/x/image v0.7.0 // indirect
|
||||
golang.org/x/mod v0.10.0 // indirect
|
||||
golang.org/x/net v0.10.0 // indirect
|
||||
golang.org/x/oauth2 v0.8.0 // indirect
|
||||
golang.org/x/sync v0.2.0 // indirect
|
||||
golang.org/x/sys v0.8.0 // indirect
|
||||
golang.org/x/term v0.8.0 // indirect
|
||||
golang.org/x/text v0.9.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
golang.org/x/tools v0.9.2 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
|
||||
google.golang.org/api v0.125.0 // indirect
|
||||
google.golang.org/appengine v1.6.7 // indirect
|
||||
google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
||||
google.golang.org/grpc v1.55.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
lukechampine.com/uint128 v1.3.0 // indirect
|
||||
modernc.org/cc/v3 v3.40.0 // indirect
|
||||
modernc.org/ccgo/v3 v3.16.13 // indirect
|
||||
modernc.org/libc v1.22.6 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
modernc.org/memory v1.5.0 // indirect
|
||||
modernc.org/opt v0.1.3 // indirect
|
||||
modernc.org/sqlite v1.22.1 // indirect
|
||||
modernc.org/strutil v1.1.3 // indirect
|
||||
modernc.org/token v1.1.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
flags = log.Ldate | log.Ltime | log.Lshortfile
|
||||
)
|
||||
|
||||
var (
|
||||
Info = log.New(os.Stdout, "[INFO] ", flags)
|
||||
Debug = log.New(os.Stdout, "[DEBUG] ", flags)
|
||||
Warning = log.New(os.Stdout, "[WARNING] ", flags)
|
||||
Error = log.New(os.Stderr, "[ERROR] ", flags)
|
||||
)
|
||||
|
||||
func init() {
|
||||
// TODO: decide if you want to log to a file to max
|
||||
// output := io.MultiWriter(os.Stdout, logFile)
|
||||
output := os.Stdout
|
||||
Info.SetOutput(output)
|
||||
Error.SetOutput(output)
|
||||
Debug.SetOutput(output)
|
||||
|
||||
log.SetOutput(Debug.Writer())
|
||||
log.SetPrefix("[DEBUG]")
|
||||
log.SetFlags(flags)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/seriousm4x/upsnap/pb"
|
||||
)
|
||||
|
||||
//go:embed all:pb_public
|
||||
var distDir embed.FS
|
||||
var distDirFS = echo.MustSubFS(distDir, "pb_public")
|
||||
|
||||
func main() {
|
||||
pb.StartPocketBase(distDirFS)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
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": "z5lghx2r3tm45n1",
|
||||
"created": "2023-01-28 19:10:29.223Z",
|
||||
"updated": "2023-01-28 19:10:29.223Z",
|
||||
"name": "devices",
|
||||
"type": "base",
|
||||
"system": false,
|
||||
"schema": [
|
||||
{
|
||||
"system": false,
|
||||
"id": "tiqcmnjo",
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "1si6ajha",
|
||||
"name": "ip",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "fyqmpon6",
|
||||
"name": "mac",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "s8c5z7n0",
|
||||
"name": "netmask",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "qqvyfrex",
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "ilrwvlev",
|
||||
"name": "ports",
|
||||
"type": "relation",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"maxSelect": null,
|
||||
"collectionId": "cti4l8f4mz8df3r",
|
||||
"cascadeDelete": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "gdctb8hj",
|
||||
"name": "link",
|
||||
"type": "url",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"exceptDomains": null,
|
||||
"onlyDomains": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "kzvdbbws",
|
||||
"name": "wake_cron",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "dcd3vuc3",
|
||||
"name": "wake_cron_enabled",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "91bs6clw",
|
||||
"name": "shutdown_cron",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "vnlymcuw",
|
||||
"name": "shutdown_cron_enabled",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "1a7yrwo9",
|
||||
"name": "shutdown_cmd",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "iarksm3l",
|
||||
"name": "password",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}
|
||||
],
|
||||
"listRule": "",
|
||||
"viewRule": "",
|
||||
"createRule": "",
|
||||
"updateRule": "",
|
||||
"deleteRule": "",
|
||||
"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("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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": "cti4l8f4mz8df3r",
|
||||
"created": "2023-01-28 19:10:29.223Z",
|
||||
"updated": "2023-01-28 19:10:29.223Z",
|
||||
"name": "ports",
|
||||
"type": "base",
|
||||
"system": false,
|
||||
"schema": [
|
||||
{
|
||||
"system": false,
|
||||
"id": "8nwuncgg",
|
||||
"name": "number",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": 65535
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "o0he3pu6",
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "w0bh39gv",
|
||||
"name": "status",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
}
|
||||
],
|
||||
"listRule": "",
|
||||
"viewRule": "",
|
||||
"createRule": "",
|
||||
"updateRule": "",
|
||||
"deleteRule": "",
|
||||
"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("cti4l8f4mz8df3r")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
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": "nmj3ko20gzkg8n3",
|
||||
"created": "2023-01-28 19:10:29.223Z",
|
||||
"updated": "2023-01-28 19:10:29.223Z",
|
||||
"name": "settings",
|
||||
"type": "base",
|
||||
"system": false,
|
||||
"schema": [
|
||||
{
|
||||
"system": false,
|
||||
"id": "ph88gaa5",
|
||||
"name": "interval",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "agw2fyd1",
|
||||
"name": "scan_range",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "slrjkipw",
|
||||
"name": "website_title",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}
|
||||
],
|
||||
"listRule": "",
|
||||
"viewRule": "",
|
||||
"createRule": "",
|
||||
"updateRule": "",
|
||||
"deleteRule": "",
|
||||
"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("nmj3ko20gzkg8n3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
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 {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("_pb_users_auth_")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
jsonData := `{
|
||||
"id": "_pb_users_auth_",
|
||||
"created": "2023-01-28 19:10:12.835Z",
|
||||
"updated": "2023-01-28 19:10:12.835Z",
|
||||
"name": "users",
|
||||
"type": "auth",
|
||||
"system": false,
|
||||
"schema": [
|
||||
{
|
||||
"system": false,
|
||||
"id": "users_name",
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "users_avatar",
|
||||
"name": "avatar",
|
||||
"type": "file",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"maxSelect": 1,
|
||||
"maxSize": 5242880,
|
||||
"mimeTypes": [
|
||||
"image/jpg",
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/svg+xml",
|
||||
"image/gif",
|
||||
"image/webp"
|
||||
],
|
||||
"thumbs": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"listRule": "id = @request.auth.id",
|
||||
"viewRule": "id = @request.auth.id",
|
||||
"createRule": "",
|
||||
"updateRule": "id = @request.auth.id",
|
||||
"deleteRule": "id = @request.auth.id",
|
||||
"options": {
|
||||
"allowEmailAuth": true,
|
||||
"allowOAuth2Auth": true,
|
||||
"allowUsernameAuth": true,
|
||||
"exceptEmailDomains": null,
|
||||
"manageRule": null,
|
||||
"minPasswordLength": 8,
|
||||
"onlyEmailDomains": null,
|
||||
"requireEmail": false
|
||||
}
|
||||
}`
|
||||
|
||||
collection := &models.Collection{}
|
||||
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return daos.New(db).SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
jsonData := `{
|
||||
"id": "27do0wbcuyfmbmx",
|
||||
"created": "2023-03-04 20:33:00.558Z",
|
||||
"updated": "2023-03-04 20:33:00.558Z",
|
||||
"name": "users",
|
||||
"type": "auth",
|
||||
"system": false,
|
||||
"schema": [],
|
||||
"listRule": null,
|
||||
"viewRule": null,
|
||||
"createRule": null,
|
||||
"updateRule": null,
|
||||
"deleteRule": null,
|
||||
"options": {
|
||||
"allowEmailAuth": true,
|
||||
"allowOAuth2Auth": false,
|
||||
"allowUsernameAuth": true,
|
||||
"exceptEmailDomains": [],
|
||||
"manageRule": null,
|
||||
"minPasswordLength": 8,
|
||||
"onlyEmailDomains": [],
|
||||
"requireEmail": false
|
||||
}
|
||||
}`
|
||||
|
||||
collection := &models.Collection{}
|
||||
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return daos.New(db).SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("27do0wbcuyfmbmx")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = nil
|
||||
|
||||
collection.ViewRule = nil
|
||||
|
||||
collection.CreateRule = types.Pointer("")
|
||||
|
||||
collection.UpdateRule = types.Pointer("")
|
||||
|
||||
collection.DeleteRule = types.Pointer("")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = nil
|
||||
|
||||
collection.ViewRule = nil
|
||||
|
||||
collection.CreateRule = types.Pointer("")
|
||||
|
||||
collection.UpdateRule = types.Pointer("")
|
||||
|
||||
collection.DeleteRule = types.Pointer("")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
collection.CreateRule = nil
|
||||
|
||||
collection.UpdateRule = nil
|
||||
|
||||
collection.DeleteRule = nil
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.ListRule = nil
|
||||
|
||||
collection.ViewRule = nil
|
||||
|
||||
collection.CreateRule = types.Pointer("")
|
||||
|
||||
collection.UpdateRule = types.Pointer("")
|
||||
|
||||
collection.DeleteRule = types.Pointer("")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
jsonData := `{
|
||||
"id": "t1rajoyzl6691g3",
|
||||
"created": "2023-03-09 22:17:29.463Z",
|
||||
"updated": "2023-03-09 22:17:29.463Z",
|
||||
"name": "settings_public",
|
||||
"type": "base",
|
||||
"system": false,
|
||||
"schema": [
|
||||
{
|
||||
"system": false,
|
||||
"id": "s1grje98",
|
||||
"name": "website_title",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"system": false,
|
||||
"id": "tlzz87pj",
|
||||
"name": "favicon",
|
||||
"type": "file",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"maxSelect": 1,
|
||||
"maxSize": 5242880,
|
||||
"mimeTypes": [
|
||||
"image/x-icon",
|
||||
"image/png",
|
||||
"image/svg+xml",
|
||||
"image/gif",
|
||||
"image/jpeg"
|
||||
],
|
||||
"thumbs": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"listRule": "",
|
||||
"viewRule": "",
|
||||
"createRule": null,
|
||||
"updateRule": null,
|
||||
"deleteRule": null,
|
||||
"options": {}
|
||||
}`
|
||||
|
||||
collection := &models.Collection{}
|
||||
if err := json.Unmarshal([]byte(jsonData), &collection); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return daos.New(db).SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("t1rajoyzl6691g3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return dao.DeleteCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
"github.com/pocketbase/pocketbase/tools/types"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.Name = "settings_private"
|
||||
|
||||
collection.ListRule = nil
|
||||
|
||||
collection.ViewRule = nil
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("slrjkipw")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("nmj3ko20gzkg8n3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
collection.Name = "settings"
|
||||
|
||||
collection.ListRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
collection.ViewRule = types.Pointer("@request.auth.id != \"\"")
|
||||
|
||||
// add
|
||||
del_website_title := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "slrjkipw",
|
||||
"name": "website_title",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}`), del_website_title)
|
||||
collection.Schema.AddField(del_website_title)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("t1rajoyzl6691g3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add
|
||||
new_setup_completed := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "vrxqcsnv",
|
||||
"name": "setup_completed",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
}`), new_setup_completed)
|
||||
collection.Schema.AddField(new_setup_completed)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("t1rajoyzl6691g3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("vrxqcsnv")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package networking
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/mdlayher/wol"
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
)
|
||||
|
||||
func SendMagicPacket(device *models.Record) error {
|
||||
ip := device.GetString("ip")
|
||||
mac := device.GetString("mac")
|
||||
netmask := device.GetString("netmask")
|
||||
password := device.GetString("password")
|
||||
|
||||
// parse inputs
|
||||
parsedMac, err := net.ParseMAC(mac)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var bytePassword []byte
|
||||
if len(password) == 0 || len(password) == 4 || len(password) == 6 {
|
||||
bytePassword = []byte(password)
|
||||
} else {
|
||||
return fmt.Errorf("error: password must be 0, 4 or 6 characters long")
|
||||
}
|
||||
|
||||
// get target addr
|
||||
broadcastIp, err := getBroadcastIp(ip, netmask)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
targetAddr := fmt.Sprintf("%s:%d", broadcastIp, 9)
|
||||
|
||||
// send wake via udp port 9
|
||||
if err := wakeUDP(targetAddr, parsedMac, bytePassword); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func wakeUDP(addr string, target net.HardwareAddr, password []byte) error {
|
||||
c, err := wol.NewClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.Close()
|
||||
return c.WakePassword(addr, target, password)
|
||||
}
|
||||
|
||||
func getBroadcastIp(ipStr, maskStr string) (string, error) {
|
||||
ip := net.ParseIP(ipStr)
|
||||
if ip == nil {
|
||||
return "", errors.New("ip not a valid ipv4 address")
|
||||
}
|
||||
ip = ip.To4()
|
||||
if ip == nil {
|
||||
return "", errors.New("ip not a valid ipv4 address")
|
||||
}
|
||||
|
||||
mask := net.ParseIP(maskStr)
|
||||
if mask == nil {
|
||||
return "", errors.New("subnet mask not a valid ipv4 address")
|
||||
}
|
||||
mask = mask.To4()
|
||||
ip = ip.To4()
|
||||
if ip == nil {
|
||||
return "", errors.New("subnet mask not a valid ipv4 address")
|
||||
}
|
||||
|
||||
broadcast := make(net.IP, 4)
|
||||
for i := range ip {
|
||||
broadcast[i] = ip[i] | ^mask[i]
|
||||
}
|
||||
|
||||
return broadcast.String(), nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package networking
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
probing "github.com/prometheus-community/pro-bing"
|
||||
"github.com/seriousm4x/upsnap/logger"
|
||||
)
|
||||
|
||||
func PingDevice(device *models.Record) bool {
|
||||
pinger, err := probing.NewPinger(device.GetString("ip"))
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
return false
|
||||
}
|
||||
pinger.Count = 1
|
||||
pinger.Timeout = 500 * 1000000 // 500ms
|
||||
pinger.SetPrivileged(true)
|
||||
err = pinger.Run()
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
return false
|
||||
}
|
||||
stats := pinger.Statistics()
|
||||
if stats.PacketLoss > 0 {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func CheckPort(host string, port string) bool {
|
||||
timeout := 500 * time.Millisecond
|
||||
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if conn != nil {
|
||||
defer conn.Close()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package networking
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
"github.com/seriousm4x/upsnap/logger"
|
||||
)
|
||||
|
||||
func ShutdownDevice(device *models.Record) error {
|
||||
logger.Info.Println("shutdown triggered for", device.GetString("name"))
|
||||
shutdown_cmd := device.GetString("shutdown_cmd")
|
||||
if shutdown_cmd == "" {
|
||||
return fmt.Errorf("%s: no shutdown_cmd definded", device.GetString("name"))
|
||||
}
|
||||
|
||||
var shell string
|
||||
var shell_arg string
|
||||
if runtime.GOOS == "windows" {
|
||||
shell = "cmd"
|
||||
shell_arg = "/C"
|
||||
} else {
|
||||
shell = "/bin/sh"
|
||||
shell_arg = "-c"
|
||||
}
|
||||
|
||||
cmd := exec.Command(shell, shell_arg, shutdown_cmd)
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("%s", stderr.String())
|
||||
}
|
||||
|
||||
// check state every second for 2 min
|
||||
start := time.Now()
|
||||
for {
|
||||
time.Sleep(1 * time.Second)
|
||||
isOnline := PingDevice(device)
|
||||
if !isOnline {
|
||||
return nil
|
||||
}
|
||||
if time.Since(start) >= 2*time.Minute {
|
||||
break
|
||||
}
|
||||
}
|
||||
return fmt.Errorf(device.GetString("name"), "not offline after 2 min")
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package networking
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
"github.com/seriousm4x/upsnap/logger"
|
||||
)
|
||||
|
||||
func WakeDevice(device *models.Record) error {
|
||||
logger.Info.Println("wake triggered for", device.GetString("name"))
|
||||
err := SendMagicPacket(device)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// check state every second for 2 min
|
||||
start := time.Now()
|
||||
for {
|
||||
time.Sleep(1 * time.Second)
|
||||
isOnline := PingDevice(device)
|
||||
if isOnline {
|
||||
return nil
|
||||
}
|
||||
if time.Since(start) >= 2*time.Minute {
|
||||
break
|
||||
}
|
||||
}
|
||||
return fmt.Errorf(device.GetString("name"), "not online after 2 min")
|
||||
}
|
||||