Compare commits

..

1 Commits

Author SHA1 Message Date
Maxi Quoß 6b4c6b9430 add v3 update notice 2023-01-30 15:32:52 +01:00
234 changed files with 6668 additions and 19774 deletions
+4 -13
View File
@@ -1,14 +1,5 @@
.git
.gitignore
.dockerignore
Dockerfile
Dockerfile.dev
data
README.md
frontend/.svelte-kit
frontend/node_modules
frontend/build
backend/pb_data
backend/pb_public
node_modules
/app/frontend/public/build
/app/frontend/scripts
**/db.sqlite3
-1
View File
@@ -1 +0,0 @@
* text=auto eol=lf
@@ -1,10 +0,0 @@
title: "<feature-name-goes-here>"
labels: ["feature-request"]
body:
- type: textarea
id: feature
attributes:
label: The feature
validations:
required: true
-2
View File
@@ -1,2 +0,0 @@
github: seriousm4x
ko_fi: seriousm4x
-70
View File
@@ -1,70 +0,0 @@
name: 🕷️ Bug report
description: Create a bug report to help the project improve
labels: ["bug"]
title: "[BUG] <title>"
body:
- type: markdown
attributes:
value: |
This issue form is for reporting bugs only!
If you have a feature or enhancement request, please use the [feature request][fr] section of our [GitHub Discussions][fr].
[fr]: https://github.com/seriousm4x/UpSnap/discussions/new?category=feature-requests
- type: textarea
validations:
required: true
attributes:
label: The bug
description: >-
Describe the issue you are experiencing here. Tell us what you were trying to do and what happened.
Provide a clear and concise description of what the problem is.
- type: markdown
attributes:
value: |
## Environment
- type: input
validations:
required: true
attributes:
label: The OS that UpSnap is running on
placeholder: Ubuntu 22.10, Debian, Arch...
- type: input
id: version
validations:
required: true
attributes:
label: Version of UpSnap
placeholder: 4.2.0
- type: textarea
validations:
required: true
attributes:
label: Your docker-compose.yml content
render: YAML
- type: textarea
id: repro
attributes:
label: Reproduction steps
description: "How do you trigger this bug? Please walk us through it step by step."
value: |
1.
2.
3.
...
render: bash
validations:
required: true
- type: textarea
attributes:
label: Additional information
description: >
If you have any additional information for us, use the field below.
-8
View File
@@ -1,8 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: I have a question or need support
url: https://github.com/seriousm4x/UpSnap/discussions/categories/help-wanted
about: Please use our GitHub Discussion if you need help.
- name: Feature Request
url: https://github.com/seriousm4x/UpSnap/discussions/categories/feature-requests
about: Please use our GitHub Discussion for making feature requests.
-19
View File
@@ -1,19 +0,0 @@
# Sync repo to the Codeberg mirror
name: codeberg mirror
on:
push:
branches: ["master"]
tags:
- "*"
workflow_dispatch:
jobs:
codeberg:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
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 }}
-37
View File
@@ -1,37 +0,0 @@
name: go test
on:
push:
paths: backend/**
jobs:
check-runner:
runs-on: ubuntu-latest
outputs:
runner-label: ${{ steps.set-runner.outputs.runner-label }}
steps:
- name: Set runner
id: set-runner
run: |
runners=$(curl -s -H "Accept: application/vnd.github+json" -H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" "https://api.github.com/repos/${{ github.repository }}/actions/runners")
available=$(echo "$runners" | jq '.runners[] | select(.status == "online" and .busy == false and .labels[] .name == "self-hosted")')
if [ -n "$available" ]; then
echo "runner-label=self-hosted" >> "$GITHUB_OUTPUT"
else
echo "runner-label=ubuntu-latest" >> "$GITHUB_OUTPUT"
fi
build:
needs: check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: "./backend/go.mod"
cache-dependency-path: "./backend/go.sum"
- name: Test
run: |
cd backend
go test -exec sudo -v ./...
+58
View File
@@ -0,0 +1,58 @@
name: CI to Docker Hub
on:
push:
tags:
- "v*.*.*"
jobs:
build:
runs-on: ubuntu-latest
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 }}
-185
View File
@@ -1,185 +0,0 @@
name: release
on:
push:
tags:
- "*.*.*"
workflow_dispatch:
jobs:
check-runner:
runs-on: ubuntu-latest
outputs:
runner-label: ${{ steps.set-runner.outputs.runner-label }}
steps:
- name: Set runner
id: set-runner
run: |
runners=$(curl -s -H "Accept: application/vnd.github+json" \
-H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" \
"https://api.github.com/repos/${{ github.repository }}/actions/runners")
available=$(echo "$runners" | jq '.runners[] | select(.status == "online" and .busy == false and .labels[] .name == "self-hosted")')
if [ -n "$available" ]; then
echo "runner-label=self-hosted" >> "$GITHUB_OUTPUT"
else
echo "runner-label=ubuntu-latest" >> "$GITHUB_OUTPUT"
fi
frontend:
needs: check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: pnpm/action-setup@v6
with:
version: latest
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: latest
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Cache frontend build
uses: actions/cache@v5
with:
path: |
frontend/node_modules
frontend/.svelte-kit
key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-
- name: Build frontend
run: |
pnpm --prefix=./frontend install --frozen-lockfile --prefer-offline
PUBLIC_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
tar -czf frontend-dist.tar.gz -C frontend/build .
- name: Upload frontend artifact
uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: frontend-dist.tar.gz
goreleaser:
needs:
- check-runner
- frontend
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download frontend artifact
uses: actions/download-artifact@v8
with:
name: frontend-dist
- name: Extract frontend into backend
run: |
mkdir -p backend/pb_public
tar -xzf frontend-dist.tar.gz -C backend/pb_public
git reset --hard
git clean -fd
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Cache Go build
uses: actions/cache@v5
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('backend/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v7
with:
distribution: goreleaser
version: "~> v2"
args: release --clean
workdir: backend
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUR_KEY: ${{ secrets.AUR_KEY }}
- name: Upload backend artifact
uses: actions/upload-artifact@v7
with:
name: backend-dist
path: backend/dist
docker:
needs:
- check-runner
- frontend
- goreleaser
runs-on: ${{ needs.check-runner.outputs.runner-label }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Download backend artifact
uses: actions/download-artifact@v8
with:
name: backend-dist
path: backend/dist
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: |
ghcr.io/seriousm4x/UpSnap
seriousm4x/UpSnap
tags: |
type=ref,event=tag
type=semver,pattern={{version}}
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GHCR
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v7
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 }}
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
VERSION=${{ github.ref_name }}
+222 -167
View File
@@ -1,28 +1,169 @@
# Created by https://www.toptal.com/developers/gitignore/api/go,node,svelte,visualstudiocode,macos
# Edit at https://www.toptal.com/developers/gitignore?templates=go,node,svelte,visualstudiocode,macos
### 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
# 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
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# 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
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# 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
# Dependency directories (remove the comment below to include it)
# vendor/
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Go workspace file
go.work
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
pytestdebug.log
# Translations
*.mo
# Django stuff:
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
doc/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# 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
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
pythonenv*
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# profiling data
.prof
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
@@ -53,187 +194,101 @@ Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Python ###
# Byte-compiled / optimized / DLL files
### Node ###
# Logs
logs
!frontend/src/routes/logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# C extensions
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Distribution / packaging
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# 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.
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Installer logs
# Coverage directory used by tools like istanbul
coverage
*.lcov
# Unit test / coverage reports
# nyc test coverage
.nyc_output
# Translations
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Django stuff:
# Bower dependency directory (https://bower.io/)
bower_components
# Flask stuff:
# node-waf configuration
.lock-wscript
# Scrapy stuff:
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Sphinx documentation
# Dependency directories
node_modules/
jspm_packages/
# PyBuilder
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# Jupyter Notebook
# TypeScript cache
*.tsbuildinfo
# IPython
# Optional npm cache directory
.npm
# pyenv
# Optional eslint cache
.eslintcache
# 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.
# Optional stylelint cache
.stylelintcache
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Celery stuff
# Optional REPL history
.node_repl_history
# SageMath parsed files
# Output of 'npm pack'
*.tgz
# Environments
# Yarn Integrity file
.yarn-integrity
# Spyder project settings
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# Rope project settings
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# mkdocs documentation
# Next.js build output
.next
out
# mypy
# Nuxt.js build / generate output
.nuxt
dist
# Pyre type checker
# 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
# pytype static type analyzer
# vuepress build output
.vuepress/dist
# profiling data
# vuepress v2.x temp and cache directory
.temp
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Docusaurus cache and generated files
.docusaurus
# Dump file
*.stackdump
# Serverless directories
.serverless/
# Folder config file
[Dd]esktop.ini
# FuseBox cache
.fusebox/
# Recycle Bin used on file shares
$RECYCLE.BIN/
# DynamoDB Local files
.dynamodb/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# TernJS port file
.tern-port
# Windows shortcuts
*.lnk
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# End of https://www.toptal.com/developers/gitignore/api/windows,linux,macos,python,django
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.vscode
staticfiles
### Node Patch ###
# Serverless Webpack directories
.webpack/
# JetBrains WebStorm
.idea/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
### Svelte ###
# gitignore template for the SvelteKit, frontend web component framework
# website: https://kit.svelte.dev/
.svelte-kit/
package
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
# End of https://www.toptal.com/developers/gitignore/api/go,node,svelte,visualstudiocode,macos
build
data
backend/pb_data
backend/pb_public/*
!backend/pb_public/.gitkeep
dist/
vite.config.js.timestamp*
frontend/src/lib/paraglide
# custom
docker-compose.yml
db/
+34 -30
View File
@@ -1,32 +1,36 @@
FROM alpine:3 AS downloader
ARG TARGETOS
ARG TARGETARCH
ARG TARGETVARIANT
ARG VERSION
ENV BUILDX_ARCH="${TARGETOS:-linux}_${TARGETARCH:-amd64}${TARGETVARIANT}"
WORKDIR /app
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 &&\
apk update &&\
apk add --no-cache libcap &&\
setcap 'cap_net_raw=+p' ./upsnap
FROM debian:bullseye-slim as base
FROM alpine:3
ARG UPSNAP_HTTP_LISTEN=0.0.0.0:8090
ENV UPSNAP_HTTP_LISTEN=${UPSNAP_HTTP_LISTEN}
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
rm -rf /var/cache/apk/*
RUN addgroup -g 1000 upsnap &&\
adduser -G upsnap -D -H -u 1000 upsnap -s /sbin/nologin
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
WORKDIR /app
COPY --from=downloader /app/upsnap upsnap
LABEL org.opencontainers.image.source="https://github.com/seriousm4x/UpSnap" \
org.opencontainers.image.url="https://github.com/seriousm4x/UpSnap" \
org.opencontainers.image.licenses="MIT"
HEALTHCHECK --interval=10s \
CMD curl -fs "http://${UPSNAP_HTTP_LISTEN}/api/health" || exit 1
CMD ["serve","--http","${UPSNAP_HTTP_LISTEN}"]
ENTRYPOINT ["/app/upsnap"]
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 curl &&\
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 ./
CMD ["./run.sh"]
-29
View File
@@ -1,29 +0,0 @@
FROM node:bookworm AS node
WORKDIR /app
COPY frontend/ .
RUN npm i -g pnpm &&\
pnpm i &&\
pnpm run build
FROM golang:alpine AS go
WORKDIR /app
COPY backend/ .
COPY --from=node /app/build ./pb_public
ENV CGO_ENABLED=0
RUN go build -o upsnap main.go &&\
chmod +x upsnap &&\
apk update &&\
apk add --no-cache libcap &&\
setcap 'cap_net_raw=+ep' ./upsnap
FROM alpine:3
ARG UPSNAP_HTTP_LISTEN=0.0.0.0:8090
ENV UPSNAP_HTTP_LISTEN=${UPSNAP_HTTP_LISTEN}
RUN apk update &&\
apk add --no-cache tzdata ca-certificates nmap samba samba-common-tools openssh sshpass curl &&\
rm -rf /var/cache/apk/*
WORKDIR /app
COPY --from=go /app/upsnap upsnap
HEALTHCHECK --interval=10s \
CMD curl -fs "http://${UPSNAP_HTTP_LISTEN}/api/health" || exit 1
ENTRYPOINT ["sh", "-c", "./upsnap serve --http ${UPSNAP_HTTP_LISTEN}"]
+30 -164
View File
@@ -1,193 +1,59 @@
<div align="center" width="100%">
<img src="frontend/static/gopher.svg" width="150" />
<img src="app/frontend/public/favicon.png" width="128" />
</div>
<div align="center" width="100%">
<h2>UpSnap</h2>
<p>A simple wake on lan web app written with SvelteKit, Go and PocketBase.</p>
<div>
<a target="_blank" href="https://github.com/seriousm4x/upsnap"><img src="https://img.shields.io/github/stars/seriousm4x/UpSnap?style=flat&label=Stars" /></a>
<a target="_blank" href="https://hub.docker.com/r/seriousm4x/upsnap"><img src="https://img.shields.io/docker/pulls/seriousm4x/upsnap?label=docker%20hub%20pulls" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/releases"><img src="https://img.shields.io/github/downloads/seriousm4x/upsnap/total?label=binary%20downloads" /></a>
</div>
<div>
<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&label=Latest%20release" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/actions"><img src="https://github.com/seriousm4x/upsnap/actions/workflows/release.yml/badge.svg?event=push" /></a>
<a target="_blank" href="https://github.com/seriousm4x/UpSnap/commits/master"><img src="https://img.shields.io/github/last-commit/seriousm4x/upsnap" /></a>
</div>
<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>
</div>
## ✨ Features
- 🚀 One-Click Device Wake-Up Dashboard
- ⏰ Timed Events via Cron for Automation
- 🔌 Ping Any Port You Choose
- 🔍 Discover Devices with Network Scanning (nmap required)
- 📌 Optional IP Address Tracking per Device via periodic ARP scan (nmap required, no extra privileges beyond network scanning)
- 📡 Support using a Fully Qualified Domain Name for a device (refer to the Wiki: [Use FQDN](https://github.com/seriousm4x/UpSnap/wiki/Use-FQDN))
- ❎️ Shutdown Devices with a Custom Command
- 👤 Secured User Management
- 📋 Superuser Logs Page
- 🌐 i18n support for [these](/frontend/translations) languages
- 🎨 35 Themes
- 🐳 [Docker images](https://github.com/seriousm4x/UpSnap/pkgs/container/upsnap) for amd64, arm64, arm/v7, arm/v6
- 🏠 Self-Hostable
* 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
## 📸 Screenshots
| Silk | Dim |
| ---------------------------------- | --------------------------------- |
| ![](/assets/home-light.webp) | ![](/assets/home-dark.webp) |
| ![](/assets/account-light.webp) | ![](/assets/account-dark.webp) |
| ![](/assets/new-manual-light.webp) | ![](/assets/new-manual-dark.webp) |
| ![](/assets/new-scan-light.webp) | ![](/assets/new-scan-dark.webp) |
| ![](/assets/settings-light.webp) | ![](/assets/settings-dark.webp) |
| ![](/assets/users-light.webp) | ![](/assets/users-dark.webp) |
| Dark | Light |
| -------------------- | --------------------- |
| ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/index-dark.png) | ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/index-light.png) |
| ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/device-settings-dark.png) | ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/device-settings-light.png) |
| ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/settings-dark.png) | ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/settings-light.png) |
| ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/add-device-dark.png) | ![](https://raw.githubusercontent.com/seriousm4x/upsnap/master/assets/add-device-light.png) |
## 🚀 Run the binary
## 🐳 Run your own instance
Just download the latest binary from the [release page](https://github.com/seriousm4x/UpSnap/releases) and run it.
There are 3 example docker-compose files to choose from. The simplest is [docker-compose-sqlite.yml](docker-compose-sqlite.yml).
```bash
sudo ./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.
To run as non-root (Linux only), refer to the Wiki: [Use non-root user](https://github.com/seriousm4x/UpSnap/wiki/Use-non%E2%80%90root-user)
### Reverse Proxy
For more options check `./upsnap --help` or visit [PocketBase documentation](https://pocketbase.io/docs).
## 🐳 Run in Docker
Just pull and run the image: `docker run --network=host seriousm4x/upsnap:latest` or you can use the [docker-compose](docker-compose.yml) example. See the comments in the file for customization.
To run as non-root, refer to the Wiki: [Use non-root user](https://github.com/seriousm4x/UpSnap/wiki/Use-non%E2%80%90root-user)
Set `UPSNAP_LOG_LEVEL` to `DEBUG`, `INFO`, `WARN`, `ERROR`, or `OFF` to control UpSnap console logs. Default is `INFO`. PocketBase log persistence and retention remain configurable in PocketBase settings. PocketBase's `--dev` mode prints all logs regardless of this setting.
### Change port (Docker)
If you want to change the port from 8090 to something else, change the following (5000 in this case):
```yml
environment:
- UPSNAP_HTTP_LISTEN=0.0.0.0:5000
```
## ❎️ Shutting Down Devices
To shutdown devices, refer to the Wiki: [How to use shutdowns](https://github.com/seriousm4x/UpSnap/wiki/How-to-use-shutdowns)
## Reverse Proxy
If you're using a reverse proxy, make sure to set `BACKEND_IS_PROXIED` to true in docker-compose. Set your reverse proxy to the `FRONTEND_PORT` and set `/wol/` to `BACKEND_PORT`.
**Caddy example**
```
upsnap.example.com {
reverse_proxy localhost:8090
reverse_proxy localhost:8000
reverse_proxy /wol/ localhost:8001
}
```
## Run in sub path
### Databases
You can run UpSnap on a different path than `/`, e.g. `/upsnap-sub-path/`. To do this in caddy, set the following:
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
```
http://localhost:8091 {
handle /upsnap-sub-path/* {
uri strip_prefix /upsnap-sub-path
reverse_proxy localhost:8090
}
}
```
### Windows
Or nginx:
There is a partly working solution in the [issue here](https://github.com/seriousm4x/UpSnap/issues/20#issuecomment-1142593360). Windows has problems with docker networking mode host, which breaks network scan. Sending wol packages works though.
```
http {
server {
listen 8091;
server_name localhost;
location /upsnap-sub-path/ {
proxy_pass http://localhost:8090/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
```
## 📝 Other infos
Paths must end with a trailing `/`.
## 🐧 Install from the [AUR](https://aur.archlinux.org/packages/upsnap-bin)
```bash
yay -Sy upsnap-bin
```
## 🔒 User permissions
UpSnap offers unique access for each user, per device. While admins have all permissions, they can assign specific rights to users such as displaying/hiding a device, accessing device editing, deleting and powering devices on/off. See the last screenshot in the [📸 Screenshots section](#-screenshots).
## 🌍 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 (possibly as root user). 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 translating
UpSnap is available in the following languages so far:
- 🇸🇦 **Arabic (Saudi Arabia)** (ar-SA)
- 🇧🇬 **Bulgarian (Bulgaria)** (bg-BG)
- 🇨🇿 **Czech (Czech republic)** (cs-CZ)
- 🇩🇪 **German (Germany)** (de-DE)
- 🇬🇷 **Greek (Greece)** (el-GR)
- 🇺🇸 **English (United States)** (en-US)
- 🇪🇸 **Spanish (Spain)** (es-ES)
- 🇫🇷 **French (France)** (fr-FR)
- 🇮🇳 **Hindi (India)** (hi-IN)
- 🇮🇩 **Bahasa (Indonesia)** (id-ID)
- 🇮🇹 **Italian (Italy)** (it-IT)
- 🇯🇵 **Japanese (Japan)** (ja-JP)
- 🇰🇷 **Korean (Republic of Korea)** (ko-KR)
- 🇳🇴 **Norwegian (Norway)** (nb-NO)
- 🇳🇱 **Dutch (Netherlands)** (nl-NL)
- 🇵🇱 **Polish (Poland)** (pl-PL)
- 🇧🇷 **Portuguese (Brazil)** (pt-BR)
- 🇵🇹 **Portuguese (Portugal)** (pt-PT)
- 🇷🇺 **Russian (Russia)** (ru-RU)
- 🇺🇦 **Ukrainian (Ukrain)** (uk-UA)
- 🇻🇳 **Vietnamese (Vietnam)** (vi-VN)
- 🇨🇳 **Chinese (China)** (zh-CN)
- 🇹🇼 **Chinese (Taiwan)** (zh-TW)
**If you want to contribute and help translating, check the wiki: [How to add languages](https://github.com/seriousm4x/UpSnap/wiki/How-to-add-languages)**
## 🔧 Help developing
Fork this branch and clone it.
1. Start backend
```bash
cd backend
go mod tidy
go run main.go serve
```
2. Start frontend
```bash
cd frontend
pnpm i
pnpm run dev
```
Open up [http://localhost:5173/](http://localhost:5173/), create an admin user and add some devices.
* 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.
+26
View File
@@ -0,0 +1,26 @@
"""
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))
})
+10
View File
@@ -0,0 +1,10 @@
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
app = Celery("dango_wol")
app.conf.timezone = os.getenv("DJANGO_TIME_ZONE", "UTC")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
+177
View File
@@ -0,0 +1,177 @@
"""
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": "/app/backend/db/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.3.3"
+23
View File
@@ -0,0 +1,23 @@
"""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)
+16
View File
@@ -0,0 +1,16 @@
"""
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()
+22
View File
@@ -0,0 +1,22 @@
#!/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()
+11
View File
@@ -0,0 +1,11 @@
celery[redis]
channels
channels-redis==3.4.1
django
django-celery-beat
gunicorn
mysqlclient
psycopg2-binary
uvicorn[standard]
wakeonlan
whitenoise
+51
View File
@@ -0,0 +1,51 @@
import os
from django.contrib.auth.models import User
from django_celery_beat.models import IntervalSchedule, PeriodicTask, PeriodicTasks
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"
)
# reset last run to fix time zone changes
# https://django-celery-beat.readthedocs.io/en/latest/#important-warning-about-time-zones
PeriodicTask.objects.update(last_run_at=None)
for task in PeriodicTask.objects.all():
PeriodicTasks.changed(task)
View File
+25
View File
@@ -0,0 +1,25 @@
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)
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class WolConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'wol'
+12
View File
@@ -0,0 +1,12 @@
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)
+335
View File
@@ -0,0 +1,335 @@
import ipaddress
import json
import os
import subprocess
import pytz
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":
try:
await self.update_device(received["data"])
await self.send(text_data=json.dumps({
"type": "operationStatus",
"message": "Success"
}))
except Exception:
await self.send(text_data=json.dumps({
"type": "operationStatus",
"message": "Error"
}))
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,
"link": dev.link,
"ports": [],
"wake": {
"enabled": False,
"cron": ""
},
"shutdown": {
"enabled": False,
"cron": "",
"command": dev.shutdown_cmd
}
}
for p in dev.port.order_by("number"):
data["ports"].append({
"number": p.number,
"name": p.name
})
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_month, wake.month_of_year, wake.day_of_week])
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"],
"link": data["link"] if data.get("link") else "",
"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,
timezone=pytz.timezone(
os.getenv("DJANGO_TIME_ZONE", "UTC"))
)
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", os.getenv("NMAP_ARGS", "-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,
"link": "",
"ports": [],
"wake": {
"enabled": False,
"cron": ""
},
"shutdown": {
"enabled": False,
"cron": "",
"command": ""
}
})
return data
@@ -0,0 +1,23 @@
# 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)),
],
),
]
@@ -0,0 +1,18 @@
# 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),
),
]
@@ -0,0 +1,18 @@
# 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),
),
]
@@ -0,0 +1,17 @@
# 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',
),
]
@@ -0,0 +1,18 @@
# 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),
),
]
@@ -0,0 +1,20 @@
# 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)),
],
),
]
@@ -0,0 +1,18 @@
# 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),
),
]
@@ -0,0 +1,23 @@
# 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')),
],
),
]
@@ -0,0 +1,17 @@
# 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',
),
]
@@ -0,0 +1,18 @@
# 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),
),
]
@@ -0,0 +1,18 @@
# 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),
),
]
@@ -0,0 +1,18 @@
# 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),
),
]
@@ -0,0 +1,64 @@
# 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'),
),
]
+27
View File
@@ -0,0 +1,27 @@
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)
link = models.URLField(blank=True, null=True)
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)
+7
View File
@@ -0,0 +1,7 @@
from django.urls import path
from wol.consumers import WSConsumer
ws_urlpatterns = [
path("wol/", WSConsumer.as_asgi())
]
+148
View File
@@ -0,0 +1,148 @@
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.db import connection
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,
"link": dev.link,
"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
}})
connection.close()
@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
}})
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+4
View File
@@ -0,0 +1,4 @@
/node_modules/
/public/build/
.DS_Store
+109
View File
@@ -0,0 +1,109 @@
*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
```
+2872
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
{
"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",
"@popperjs/core": "^2.11.5",
"@rollup/plugin-replace": "^4.0.0",
"bootstrap": "^5.1.3",
"dotenv": "^16.0.0",
"postcss": "^8.4.6",
"sass": "^1.49.9",
"sirv-cli": "^2.0.0",
"svelte-preprocess": "^4.10.3"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
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;
}
}
+20
View File
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<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/popper.min.js'></script>
<script defer src='build/bootstrap.min.js'></script>
</head>
<body>
</body>
</html>
+103
View File
@@ -0,0 +1,103 @@
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),
BACKEND_IS_PROXIED: JSON.stringify(process.env.BACKEND_IS_PROXIED.toLowerCase() === 'true'),
PAGE_TITLE: JSON.stringify(process.env.PAGE_TITLE),
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",
"node_modules/@popperjs/core/dist/umd/popper.min.js",
"node_modules/@popperjs/core/dist/umd/popper.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
}
};
+121
View File
@@ -0,0 +1,121 @@
// @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.")
}
+302
View File
@@ -0,0 +1,302 @@
<script>
import { onMount } from "svelte";
import socketStore from "./socketStore.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(() => {
socketStore.subscribeStatus((status) => {
if (status == "open") {
showToast("Websocket", "Connected", "success");
} else if (status == "close") {
showToast(
"Websocket",
"Connection closed. Trying to reconnect ...",
"danger"
);
} else if (status == "error") {
showToast(
"Websocket",
"Error when connecting to websocket",
"danger"
);
}
});
socketStore.subscribeMsg((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();
} else if (currentMessage.type == "operationStatus") {
if (currentMessage.message == "Success") {
showToast(
currentMessage.message,
"Changes were saved",
"success"
);
} else if (currentMessage.message == "Error") {
showToast(
currentMessage.message,
"Error while saving the device. Please check the logs.",
"danger"
);
}
}
});
});
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")) {
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")) {
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} {visitors} />
<div class="container mb-3">
<div class="row">
{#each devices as device}
<DeviceCard {device} />
{/each}
</div>
</div>
<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>
@@ -0,0 +1,55 @@
<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" />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" />Dark
</button>
</li>
<li>
<button class="dropdown-item" on:click={() => setTheme("light")}>
<i class="fa-solid fa-sun me-2" />Light
</button>
</li>
<li>
<button class="dropdown-item" on:click={() => setTheme("system")}>
<i class="fa-solid fa-desktop me-2" />System
</button>
</li>
</ul>
</div>
@@ -0,0 +1,671 @@
<script>
import socketStore from "../socketStore.js";
export let device;
let modalDevice = JSON.parse(JSON.stringify(device));
let customPort = {};
function wake(id) {
socketStore.sendMessage({
type: "wake",
id: id,
});
}
function shutdown(id) {
socketStore.sendMessage({
type: "shutdown",
id: id,
});
}
function deleteDevice() {
socketStore.sendMessage({
type: "delete_device",
id: modalDevice.id,
});
}
function updateDevice() {
device = modalDevice;
socketStore.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
socketStore.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"
/>
{#if device.up === true}
{#if device.shutdown.command}
<div
class="hover"
on:click={() => shutdown(device.id)}
on:keydown={() => 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"
/>
</div>
{:else}
<i
id="dot-{device.id}"
class="fa-solid fa-power-off fa-2x success"
/>
{/if}
{:else if device.up === false}
<div
class="hover"
on:click={() => wake(device.id)}
on:keydown={() => wake(device.id)}
role="button"
>
<i
id="dot-{device.id}"
class="fa-solid fa-power-off fa-2x danger"
/>
</div>
{:else}
<div class="hover" role="button">
<i
id="dot-{device.id}"
class="fa-solid fa-power-off fa-2x text-muted"
/>
</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" />
</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" />
</div>
{/if}
<div
class="col-auto hover"
data-bs-toggle="modal"
data-bs-target="#device-modal-{device.id}"
role="button"
on:click={() => openModal()}
on:keydown={() => openModal()}
>
<i class="fa-solid fa-ellipsis-vertical fa-2x" />
</div>
</div>
{#if device.link}
<h5 class="card-title fw-bold my-2">
<a class="inherit-color" href={device.link}>{device.name}</a
>
</h5>
{:else}
<h5 class="card-title fw-bold my-2">{device.name}</h5>
{/if}
<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'}"
/>
{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"
/>
</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 mb-2">
<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}
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}
required
/>
</div>
</div>
<div class="row">
<div class="col">
<div class="mb-3">
<label
for="inputLinkAddDevice"
class="form-label">Web link</label
>
<input
type="text"
class="form-control"
id="inputILinkAddDevice"
placeholder="http://...."
bind:value={modalDevice.link}
/>
</div>
</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" />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" />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"
rel="noreferrer">valid syntax here</a
>
or
<a
href="https://crontab.guru/"
target="_blank"
rel="noreferrer">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" />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"
rel="noreferrer">sshpass</a
>
or
<a
href="https://linux.die.net/man/8/net"
target="_blank"
rel="noreferrer">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);
}
.inherit-color {
color: inherit;
}
</style>
+481
View File
@@ -0,0 +1,481 @@
<script>
import socketStore from "../socketStore.js";
import DarkToggle from "./DarkToggle.svelte";
export let visitors;
export let settings;
const pagetitle = PAGE_TITLE ? PAGE_TITLE : "UpSnap";
let addDevice = {
wake: {
enabled: false,
cron: "",
},
shutdown: {
enabled: false,
cron: "",
command: "",
},
};
function updateDevice(data) {
if (Object.keys(data).length < 4) {
return;
}
socketStore.sendMessage({
type: "update_device",
data: data,
});
}
function updateSettings() {
socketStore.sendMessage({
type: "update_settings",
data: settings,
});
hideModal("settings");
}
function scanNetwork() {
socketStore.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;
value["link"] = "";
updateDevice(value);
}
}
};
hideModal("settings");
};
function backupToFile() {
socketStore.sendMessage({
type: "backup",
});
}
function hideModal(id) {
const modalEl = document.querySelector(`#${id}`);
const modal = bootstrap.Modal.getInstance(modalEl);
modal.hide();
}
</script>
<svelte:head>
<title>{pagetitle}</title>
</svelte:head>
<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" />
{pagetitle}
</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" />
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<span class="ms-auto d-flex">
<a
class="btn btn-light px-3 me-2 py-2"
href="https://github.com/seriousm4x/UpSnap/releases/tag/3.0.0"
>
<i class="me-2 fa-solid fa-angles-up" />UpSnap v3 available!
</a>
<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" />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" />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" />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'}"
/>{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"
/>
</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}
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}
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}
required
/>
</div>
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="inputLinkAddDevice" class="form-label">Web link</label
>
<input
type="text"
class="form-control"
id="inputILinkAddDevice"
placeholder="http://...."
bind:value={addDevice.link}
/>
</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 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" />
</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"
/>
</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}
/>
</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" />
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>
+46
View File
@@ -0,0 +1,46 @@
<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"
/>
</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>
+8
View File
@@ -0,0 +1,8 @@
import App from './App.svelte';
const app = new App({
target: document.body
});
export default app;
+57
View File
@@ -0,0 +1,57 @@
import {
writable
} from 'svelte/store';
const status = writable('');
const message = writable('');
let socket;
function initSocket() {
if (BACKEND_IS_PROXIED) {
const socketUrl = new URL('wol/', window.location.href);
socketUrl.protocol = socketUrl.protocol.replace('http', 'ws');
socket = new WebSocket(socketUrl);
}
else {
socket = new WebSocket(`ws://${location.hostname}:${BACKEND_PORT}/wol/`);
}
// Connection opened
socket.addEventListener('open', function () {
status.set("open");
});
// Connection closed
socket.addEventListener('close', function () {
status.set("close");
setTimeout(function () {
initSocket();
}, 3000);
});
// Connection error
socket.addEventListener('error', function () {
status.set("error");
socket.close()
});
// Listen for messages
socket.addEventListener('message', function (event) {
message.set(JSON.parse(event.data));
});
}
initSocket()
const sendMessage = (message) => {
if (socket.readyState <= 1) {
socket.send(JSON.stringify(message));
}
}
export default {
subscribeMsg: message.subscribe,
subscribeStatus: status.subscribe,
sendMessage
}
+24
View File
@@ -0,0 +1,24 @@
: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;
}
+29
View File
@@ -0,0 +1,29 @@
// 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";
Executable
+17
View File
@@ -0,0 +1,17 @@
#!/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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

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

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

-80
View File
@@ -1,80 +0,0 @@
version: 2
release:
draft: false
prerelease: auto
before:
hooks:
- go mod tidy
builds:
- binary: upsnap
env:
- CGO_ENABLED=0
ldflags:
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Tag }}
goos:
- linux
- windows
- darwin
- freebsd
goarch:
- amd64
- arm64
- arm
- riscv64
goarm:
- "6"
- "7"
ignore:
- goos: windows
goarch: arm
- goos: darwin
goarch: arm
- goos: freebsd
goarch: arm
archives:
- formats: ["zip"]
checksum:
name_template: "checksums.txt"
snapshot:
version_template: "{{ .Version }}"
changelog:
use: github
sort: asc
groups:
- title: Features
regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
order: 0
- title: "Bug fixes"
regexp: '^.*?fix(\([[:word:]]+\))??!?:.+$'
order: 1
- title: "Go dependencies"
regexp: '^.*?go-dep(\([[:word:]]+\))??!?:.+$'
order: 3
- title: "Npm dependencies"
regexp: '^.*?npm-dep(\([[:word:]]+\))??!?:.+$'
order: 4
- title: "Github Actions"
regexp: '^.*?gh-action(\([[:word:]]+\))??!?:.+$'
order: 5
- title: Others
order: 2
git:
ignore_tags:
- "{{ if not .Prerelease}}*beta*{{ end }}"
# aurs:
# - name: upsnap-bin
# homepage: https://github.com/seriousm4x/UpSnap
# description: "A simple wake on lan web app written with SvelteKit, Go and PocketBase."
# maintainers:
# - "SeriousM4x <maxi at quoss dot org>"
# license: "MIT"
# private_key: "{{ .Env.AUR_KEY }}"
# git_url: "ssh://aur@aur.archlinux.org/upsnap-bin.git"
# package: |-
# install -Dm755 "./upsnap" "${pkgdir}/usr/bin/upsnap"
# skip_upload: auto
# optdepends:
# - "nmap: to scan for network devices"
# commit_author:
# name: goreleaserbot
# email: bot@goreleaser.com
-266
View File
@@ -1,266 +0,0 @@
package cronjobs
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/robfig/cron/v3"
"github.com/seriousm4x/upsnap/iptracking"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/networking"
)
var (
PingRunning = false
WakeShutdownRunning = false
CronPing = cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
CronWakeShutdown = cron.New(cron.WithParser(cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow,
)))
)
func SetPingJobs(app core.App) {
log := logging.Logger(app)
// remove existing jobs
for _, job := range CronPing.Entries() {
CronPing.Remove(job.ID)
}
settingsPrivateRecords, err := app.FindAllRecords("settings_private")
if err != nil {
log.Error("Failed to load private settings", "error", err)
return
}
CronPing.AddFunc(settingsPrivateRecords[0].GetString("interval"), func() {
// skip cron if no realtime clients connected and lazy_ping is turned on
realtimeClients := len(app.SubscriptionsBroker().Clients())
if realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping") {
return
}
devices, err := app.FindAllRecords("devices")
if err != nil {
log.Error("Failed to load devices for ping job", "error", err)
return
}
// expand ports field
expandFetchFunc := func(c *core.Collection, ids []string) ([]*core.Record, error) {
return app.FindRecordsByIds(c.Id, ids, nil)
}
merr := app.ExpandRecords(devices, []string{"ports"}, expandFetchFunc)
if len(merr) > 0 {
log.Error("Failed to expand device ports", "errors", merr)
return
}
for _, device := range devices {
// ping device
go func(d *core.Record) {
status := d.GetString("status")
if status == "pending" {
return
}
isUp, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device", "device", d.GetString("name"), "error", err)
}
if isUp {
if status == "online" {
return
}
d.Set("status", "online")
if err := app.Save(d); err != nil {
log.Error("Failed to save device status", "device", d.GetString("name"), "error", err)
} else {
log.Info("Device turned on", "device", d.GetString("name"))
}
} else {
if status == "offline" {
return
}
d.Set("status", "offline")
if err := app.Save(d); err != nil {
log.Error("Failed to save device status", "device", d.GetString("name"), "error", err)
} else {
log.Info("Device turned off", "device", d.GetString("name"))
}
}
}(device)
// ping ports
go func(d *core.Record) {
ports, err := app.FindRecordsByIds("ports", d.GetStringSlice("ports"))
if err != nil {
log.Error("Failed to load device ports", "device", d.GetString("name"), "error", err)
return
}
deviceIP, resolveErr := networking.ResolveToIPAddr(d.GetString("ip"))
if resolveErr != nil {
log.Error("Failed to resolve device IP", "device", d.GetString("name"), "error", resolveErr)
}
for _, port := range ports {
isUp := false
// No IP found means the device is down.
if resolveErr == nil && deviceIP != "" {
var checkErr error
isUp, checkErr = networking.CheckPort(deviceIP, port.GetString("number"))
if checkErr != nil {
log.Error("Failed to check port", "device", d.GetString("name"), "port", port.GetString("number"), "error", checkErr)
}
}
if isUp != port.GetBool("status") {
port.Set("status", isUp)
if err := app.Save(port); err != nil {
log.Error("Failed to save port status", "device", d.GetString("name"), "port", port.GetString("number"), "error", err)
}
}
}
}(device)
}
})
// update ip addresses of opted-in devices from a periodic arp scan
trackIpInterval := settingsPrivateRecords[0].GetString("track_ip_interval")
if trackIpInterval != "" {
if _, err := CronPing.AddFunc(trackIpInterval, func() {
// pause scans if no realtime clients connected and lazy_ping is
// turned on; a catch-up sweep runs when the next client connects
realtimeClients := len(app.SubscriptionsBroker().Clients())
iptracking.PeriodicSweep(app, realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping"))
}); err != nil {
log.Error("Failed to add IP tracking cron job", "error", err)
}
}
}
func SetWakeShutdownJobs(app core.App) {
log := logging.Logger(app)
// remove existing jobs
for _, job := range CronWakeShutdown.Entries() {
CronWakeShutdown.Remove(job.ID)
}
devices, err := app.FindAllRecords("devices")
if err != nil {
log.Error("Failed to load devices for wake and shutdown jobs", "error", err)
return
}
for _, dev := range devices {
wake_cron := dev.GetString("wake_cron")
wake_cron_enabled := dev.GetBool("wake_cron_enabled")
shutdown_cron := dev.GetString("shutdown_cron")
shutdown_cron_enabled := dev.GetBool("shutdown_cron_enabled")
if wake_cron_enabled && wake_cron != "" {
_, err := CronWakeShutdown.AddFunc(wake_cron, func() {
d, err := app.FindRecordById("devices", dev.Id)
if err != nil {
log.Error("Failed to load device for wake job", "device", dev.GetString("name"), "error", err)
return
}
if d.GetString("status") == "pending" {
return
}
isOnline, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device before wake", "device", d.GetString("name"), "error", err)
return
}
if isOnline {
return
}
d.Set("status", "pending")
if err := app.Save(d); err != nil {
log.Error("Failed to save pending device status", "device", d.GetString("name"), "error", err)
return
}
if err := networking.WakeDevice(app, d, "cron"); err != nil {
log.Error("Wake job failed", "device", d.GetString("name"), "error", err)
d.Set("status", "offline")
} else {
d.Set("status", "online")
}
if err := app.Save(d); err != nil {
log.Error("Failed to save device status after wake", "device", d.GetString("name"), "error", err)
}
})
if err != nil {
log.Error("Failed to add wake cron job", "device", dev.GetString("name"), "error", err)
}
}
if shutdown_cron_enabled && shutdown_cron != "" {
_, err := CronWakeShutdown.AddFunc(shutdown_cron, func() {
d, err := app.FindRecordById("devices", dev.Id)
if err != nil {
log.Error("Failed to load device for shutdown job", "device", dev.GetString("name"), "error", err)
return
}
if d.GetString("status") == "pending" {
return
}
isOnline, err := networking.PingDevice(d)
if err != nil {
log.Error("Failed to ping device before shutdown", "device", d.GetString("name"), "error", err)
return
}
if !isOnline {
return
}
// The status can be stale when lazy ping marks devices offline after
// the last client disconnects. The reachability check above is the
// authoritative signal for whether a shutdown command may run.
d.Set("status", "pending")
if err := app.Save(d); err != nil {
log.Error("Failed to save pending device status", "device", d.GetString("name"), "error", err)
}
if err := networking.ShutdownDevice(app, d, "cron"); err != nil {
log.Error("Shutdown job failed", "device", d.GetString("name"), "error", err)
d.Set("status", "online")
} else {
d.Set("status", "offline")
}
if err := app.Save(d); err != nil {
log.Error("Failed to save device status after shutdown", "device", d.GetString("name"), "error", err)
}
})
if err != nil {
log.Error("Failed to add shutdown cron job", "device", dev.GetString("name"), "error", err)
}
}
}
}
func StartWakeShutdown() {
WakeShutdownRunning = true
go CronWakeShutdown.Run()
}
func StopWakeShutdown(app core.App) {
if WakeShutdownRunning {
logging.Logger(app).Info("Stopping wake and shutdown cron jobs")
CronWakeShutdown.Stop()
}
WakeShutdownRunning = false
}
func StartPing() {
PingRunning = true
go CronPing.Run()
}
func StopPing(app core.App) {
if PingRunning {
logging.Logger(app).Info("Stopping ping cron jobs")
CronPing.Stop()
}
PingRunning = false
}
func StopAll(app core.App) {
StopPing(app)
StopWakeShutdown(app)
}
-53
View File
@@ -1,53 +0,0 @@
module github.com/seriousm4x/upsnap
go 1.27
require (
ganigeorgiev.com/pocketbase/dbx v1.13.0
ganigeorgiev.com/pocketbase/pocketbase v0.41.1
github.com/godbus/dbus/v5 v5.2.2
github.com/holoplot/go-avahi v1.0.1
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
github.com/prometheus-community/pro-bing v0.9.1
github.com/robfig/cron/v3 v3.0.1
golang.org/x/net v0.62.0
golang.org/x/sys v0.49.0
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78
)
require (
ganigeorgiev.com/fexpr v0.7.0 // indirect
ganigeorgiev.com/pocketbase/ozzo-validation/v4 v4.4.1 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/disintegration/imaging v1.6.2 // indirect
github.com/domodwyer/mailyak/v3 v3.6.2 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
github.com/mdlayher/packet v1.2.0 // indirect
github.com/mdlayher/socket v0.7.0 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/stretchr/testify v1.11.1 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/image v0.47.0 // indirect
golang.org/x/oauth2 v0.37.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/text v0.43.0 // indirect
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78 // indirect
modernc.org/libc v1.77.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.60.1 // indirect
)
-170
View File
@@ -1,170 +0,0 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
ganigeorgiev.com/fexpr v0.7.0 h1:Os5bP9dU13UNo5qDTsTPTTkodLM96kO52WIEmMmCt30=
ganigeorgiev.com/fexpr v0.7.0/go.mod h1:XrG5iYw+AGq55zq2+QY1zQvO+ovbEca08u7q0hucPdY=
ganigeorgiev.com/pocketbase/dbx v1.13.0 h1:t8S5CaMv93tEOqaOToFaVQ994zldshdhIrVHKmxRjwc=
ganigeorgiev.com/pocketbase/dbx v1.13.0/go.mod h1:QefEiWbbE/YoSipLGg33FbNc/GAX/2f3ymz02j2MGKo=
ganigeorgiev.com/pocketbase/ozzo-validation/v4 v4.4.1 h1:teL3Lw7HCGZRdIQdqE/gV5DueFaN5Wj+/r4Ewg3M2WA=
ganigeorgiev.com/pocketbase/ozzo-validation/v4 v4.4.1/go.mod h1:oV1SPPkS3PlKYYj+r9YDs48ooAWgC736cuFanXDXxbM=
ganigeorgiev.com/pocketbase/pocketbase v0.41.1 h1:qIDj5ZE8ysev7LJNcLR4eeYICme5hDF/Ry3bQ9nOcTA=
ganigeorgiev.com/pocketbase/pocketbase v0.41.1/go.mod h1:PBkQKVnCfL7Hi9MnXY9bJDME/sfEEbZ6VwAb+8xXQXE=
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/domodwyer/mailyak/v3 v3.6.2 h1:x3tGMsyFhTCaxp6ycgR0FE/bu5QiNp+hetUuCOBXMn8=
github.com/domodwyer/mailyak/v3 v3.6.2/go.mod h1:lOm/u9CyCVWHeaAmHIdF4RiKVxKUT/H5XX10lIKAL6c=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/holoplot/go-avahi v1.0.1 h1:XcqR2keL4qWRnlxHD5CAOdWpLFZJ+EOUK0vEuylfvvk=
github.com/holoplot/go-avahi v1.0.1/go.mod h1:qH5psEKb0DK+BRplMfc+RY4VMOlbf6mqfxgpMy6aP0M=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/josharian/native v1.0.0/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mdlayher/ethernet v0.0.0-20190313224307-5b5fc417d966/go.mod h1:5s5p/sMJ6sNsFl6uCh85lkFGV8kLuIYJCRJLavVJwvg=
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 h1:2oDp6OOhLxQ9JBoUuysVz9UZ9uI6oLUbvAZu0x8o+vE=
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118/go.mod h1:ZFUnHIVchZ9lJoWoEGUg8Q3M4U8aNNWA3CVSUTkW4og=
github.com/mdlayher/packet v1.0.0/go.mod h1:eE7/ctqDhoiRhQ44ko5JZU2zxB88g+JH/6jmnjzPjOU=
github.com/mdlayher/packet v1.2.0 h1:SX7/oY0+nkKo7p4Sv30+TIc3YuWgvDEf0eucTXRyPqk=
github.com/mdlayher/packet v1.2.0/go.mod h1:UtYVnQt+Zj6UD0F89HfzkqGXaYqys1NwkrS86wlLCv4=
github.com/mdlayher/raw v0.0.0-20190313224157-43dbcdd7739d/go.mod h1:r1fbeITl2xL/zLbVnNHFyOzQJTgr/3fpf1lJX/cjzR8=
github.com/mdlayher/socket v0.2.1/go.mod h1:QLlNPkFR88mRUNQIzRBMfXxwKal8H7u1h3bL1CV+f0E=
github.com/mdlayher/socket v0.7.0 h1:qVREPVwtUMg17pwvveQxpurq0PVisMxi3FGgpsorMYQ=
github.com/mdlayher/socket v0.7.0/go.mod h1:f7iKql2EK/rfsWYDKofKjk2Ig7I+6HQWdMIdn1tO4A4=
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a h1:fpQi42PM6HzbHwNg6a7OvLbh5l49Rgr7GCARozjHwio=
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a/go.mod h1:XX6nvyQpGc8E4KaQm62FyexOYd36ilpyfYf8wjgMDV8=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus-community/pro-bing v0.9.1 h1:kpuAr6AU2oRtzGihJSUcetHtjc7ku7h6PxeuW9RVrQw=
github.com/prometheus-community/pro-bing v0.9.1/go.mod h1:z79wYTxAOf6FpTng0QdIhZ3j/Nd5l3+gnFSCIT+SiSQ=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78 h1:jgqg4gyu2BaYW9L6uzEtGLf8GNREwk/z4UFdwt5F3pE=
kernel.org/pub/linux/libs/security/libcap/cap v1.2.78/go.mod h1:VjuVda6m2qGkpCVfrFkpTGyvkdlZ2N5/yfo89tujlg8=
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78 h1:PC3yNs51cX5LZ7U57a7xielBcoXB3xnV+rXD8V0H0DQ=
kernel.org/pub/linux/libs/security/libcap/psx v1.2.78/go.mod h1:+l6Ee2F59XiJ2I6WR5ObpC1utCQJZ/VLsEbQCD8RG24=
modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg=
modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE=
modernc.org/ccgo/v4 v4.36.1/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw=
modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
-136
View File
@@ -1,136 +0,0 @@
// Package iptracking updates the stored ip addresses of opted-in devices by
// scanning their local subnets for their mac addresses.
package iptracking
import (
"net"
"sync/atomic"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"github.com/seriousm4x/upsnap/logging"
"github.com/seriousm4x/upsnap/networking"
)
var sweepRunning atomic.Bool
// sweepOwed marks that a periodic sweep was skipped while no realtime
// clients were connected, so the next client to connect gets a catch-up
// sweep. Starts true so the first client after boot gets fresh ips.
var sweepOwed atomic.Bool
func init() {
sweepOwed.Store(true)
}
// nmapScan is a seam for tests to stub out the privileged nmap invocation
var nmapScan = networking.NmapScan
// TrackAllSubnets scans the local subnets of devices with ip tracking enabled
// and updates their ip address if their mac address is found at a different
// one. Non-scannable subnets are silently skipped, but their devices can
// still be updated by another subnet's scan that finds their mac address,
// as long as the new ip stays within the device's own subnet.
func TrackAllSubnets(app core.App) {
log := logging.Logger(app)
// skip if the previous sweep is still running
if !sweepRunning.CompareAndSwap(false, true) {
return
}
defer sweepRunning.Store(false)
devices, err := app.FindRecordsByFilter("devices", "track_ip = true", "", 0, 0)
if err != nil {
log.Error("Failed to load devices for IP tracking", "error", err)
return
}
// collect the unique scannable subnets of the tracked devices
subnets := make(map[string]*net.IPNet)
for _, device := range devices {
subnet, err := networking.DeviceSubnet(device.GetString("ip"), device.GetString("netmask"))
if err != nil {
log.Error("Failed to determine device subnet for IP tracking", "device", device.GetString("name"), "error", err)
continue
}
if networking.ValidateScannableSubnet(subnet) != nil {
continue
}
subnets[subnet.String()] = subnet
}
for cidr, subnet := range subnets {
if err := TrackOneSubnet(app, subnet); err != nil {
log.Error("IP tracking scan failed", "subnet", cidr, "error", err)
}
}
}
// PeriodicSweep runs the scheduled sweep, or skips it when paused — no
// realtime clients connected while lazy_ping is on — owing a catch-up
// sweep to the next client that connects.
func PeriodicSweep(app core.App, pause bool) {
if pause {
sweepOwed.Store(true)
return
}
TrackAllSubnets(app)
}
// CatchUpSweep runs a sweep if one is owed, i.e. the periodic sweep was
// skipped while nobody was connected or hasn't run since boot. Clients
// connecting while sweeps run on schedule trigger nothing.
func CatchUpSweep(app core.App) {
if !sweepOwed.CompareAndSwap(true, false) {
return
}
TrackAllSubnets(app)
}
// TrackOneSubnet runs an nmap scan of the given subnet and updates the ip
// address of any ip-tracked device whose mac address is found at a new
// address within its own subnet. Returns an error for a non-scannable subnet.
func TrackOneSubnet(app core.App, subnet *net.IPNet) error {
log := logging.Logger(app)
if err := networking.ValidateScannableSubnet(subnet); err != nil {
return err
}
scan, err := nmapScan(subnet.String())
if err != nil {
return err
}
macToIp := scan.MacToIP()
devices, err := app.FindRecordsByFilter("devices", "track_ip = true", "", 0, 0)
if err != nil {
return err
}
for _, device := range devices {
parsedMac, err := net.ParseMAC(device.GetString("mac"))
if err != nil {
continue
}
newIp, ok := macToIp[parsedMac.String()]
if !ok || newIp == device.GetString("ip") {
continue
}
// only move a device within its own subnet, so that a scan can't
// relocate devices tracked on other subnets that see the same mac
deviceSubnet, err := networking.DeviceSubnet(device.GetString("ip"), device.GetString("netmask"))
if err != nil || !deviceSubnet.Contains(net.ParseIP(newIp)) {
continue
}
oldIP := device.GetString("ip")
device.Set("ip", newIp)
// only write the changed ip field to avoid clobbering concurrent
// status updates from the ping and wake/shutdown cronjobs
device.IgnoreUnchangedFields(true)
if err := app.Save(device); err != nil {
log.Error("Failed to save tracked device IP", "device", device.GetString("name"), "error", err)
} else {
log.Info("Device IP changed", "device", device.GetString("name"), "from", oldIP, "to", newIp)
}
}
return nil
}
-347
View File
@@ -1,347 +0,0 @@
package iptracking
import (
"encoding/xml"
"fmt"
"net"
"strings"
"testing"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tests"
"github.com/seriousm4x/upsnap/networking"
// register the app migrations so test apps get the real schema
_ "github.com/seriousm4x/upsnap/migrations"
)
// newTestApp returns a throwaway app with all migrations applied.
func newTestApp(t *testing.T) *tests.TestApp {
t.Helper()
app, err := tests.NewTestApp(t.TempDir())
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
t.Cleanup(app.Cleanup)
return app
}
func buildDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
collection, err := app.FindCollectionByNameOrId("devices")
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
device := core.NewRecord(collection)
device.Set("name", name)
device.Set("ip", ip)
device.Set("netmask", netmask)
device.Set("mac", mac)
device.Set("track_ip", trackIp)
return device
}
func newDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
device := buildDevice(t, app, name, ip, netmask, mac, trackIp)
if err := app.Save(device); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return device
}
// newLegacyDevice saves a device bypassing field validation, like rows
// created before the ip and mac format rules existed.
func newLegacyDevice(t *testing.T, app core.App, name, ip, netmask, mac string, trackIp bool) *core.Record {
t.Helper()
device := buildDevice(t, app, name, ip, netmask, mac, trackIp)
if err := app.SaveNoValidate(device); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return device
}
// stubScan replaces the nmap seam with a canned scan reporting the given
// mac addresses at the given ips, and returns the list of scanned ranges.
func stubScan(t *testing.T, macToHostIp map[string]string) *[]string {
t.Helper()
var sample strings.Builder
sample.WriteString("<nmaprun>")
for mac, ip := range macToHostIp {
fmt.Fprintf(&sample, `<host><address addr=%q addrtype="ipv4"/><address addr=%q addrtype="mac"/></host>`, ip, mac)
}
sample.WriteString("</nmaprun>")
scan := networking.Nmaprun{}
if err := xml.Unmarshal([]byte(sample.String()), &scan); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
var scanned []string
orig := nmapScan
nmapScan = func(scanRange string) (networking.Nmaprun, error) {
scanned = append(scanned, scanRange)
return scan, nil
}
t.Cleanup(func() { nmapScan = orig })
return &scanned
}
func mustSubnet(t *testing.T, cidr string) *net.IPNet {
t.Helper()
_, subnet, err := net.ParseCIDR(cidr)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
return subnet
}
// The loopback /16 passes the scannable checks on any host, making it the
// only subnet a test can scan without depending on the environment.
const (
testSubnet = "127.0.0.0/16"
testNetmask = "255.255.0.0"
)
func TestTrackOneSubnetSkipsUntrackedDevices(t *testing.T) {
app := newTestApp(t)
device := newDevice(t, app, "untracked", "127.0.0.50", testNetmask, "AA:BB:CC:DD:EE:01", false)
stubScan(t, map[string]string{"AA:BB:CC:DD:EE:01": "127.0.0.99"})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != "127.0.0.50" {
t.Errorf("Ip of device without track_ip changed to %s", ip)
}
}
func TestTrackOneSubnetSkipPaths(t *testing.T) {
app := newTestApp(t)
saves := 0
app.OnRecordUpdate("devices").BindFunc(func(e *core.RecordEvent) error {
saves++
return e.Next()
})
testCases := []struct {
name string
ip string
mac string
legacy bool
}{
// A device mac that can't be parsed never matches
{
name: "Invalid Mac",
ip: "127.0.0.50",
mac: "not-a-mac",
legacy: true,
},
// A device mac missing from the scan results is left alone
{
name: "Mac Not In Scan",
ip: "127.0.0.50",
mac: "AA:BB:CC:DD:EE:02",
},
// A device ip without a computable subnet is never moved
{
name: "Invalid Device Ip",
ip: "999.999.999.999",
mac: "AA:BB:CC:DD:EE:01",
legacy: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
create := newDevice
if tc.legacy {
create = newLegacyDevice
}
device := create(t, app, tc.name, tc.ip, testNetmask, tc.mac, true)
stubScan(t, map[string]string{"AA:BB:CC:DD:EE:01": "127.0.0.99"})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != tc.ip {
t.Errorf("Ip mismatch: expected %s, got %s", tc.ip, ip)
}
if saves != 0 {
t.Errorf("Expected no record updates, got %d", saves)
}
})
}
}
func TestTrackOneSubnetUnscannable(t *testing.T) {
app := newTestApp(t)
// TEST-NET-1 (RFC 5737) is never assigned to an interface
scanned := stubScan(t, nil)
if err := TrackOneSubnet(app, mustSubnet(t, "192.0.2.0/24")); err == nil {
t.Error("Expected error but got none")
}
if len(*scanned) != 0 {
t.Errorf("Expected no scans of an unscannable subnet, got %v", *scanned)
}
}
func TestTrackOneSubnetSameSubnetGuard(t *testing.T) {
app := newTestApp(t)
testCases := []struct {
name string
ip string
netmask string
mac string
scanMac string
foundIp string
wantIp string
}{
// A move within the device's own subnet is applied, with the
// stored dashed lower case mac matching the scanned
// colon-separated upper case one
{
name: "Within Own Subnet",
ip: "127.0.0.50",
netmask: testNetmask,
mac: "aa-bb-cc-dd-01-01",
scanMac: "AA:BB:CC:DD:01:01",
foundIp: "127.0.0.99",
wantIp: "127.0.0.99",
},
// The device's own subnet bounds the move, not the scanned one
{
name: "Narrower Subnet Within Scan",
ip: "127.0.5.5",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:02",
foundIp: "127.0.5.9",
wantIp: "127.0.5.9",
},
// A found ip outside the device's narrower subnet is not applied,
// even though it is inside the scanned subnet
{
name: "Outside Own Subnet",
ip: "127.0.5.5",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:03",
foundIp: "127.0.6.9",
wantIp: "127.0.5.5",
},
// A device from a disjoint subnet is never moved into the scanned one
{
name: "Disjoint Subnet",
ip: "10.9.9.9",
netmask: "255.255.255.0",
mac: "AA:BB:CC:DD:01:04",
foundIp: "127.0.0.99",
wantIp: "10.9.9.9",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
device := newDevice(t, app, tc.name, tc.ip, tc.netmask, tc.mac, true)
scanMac := tc.scanMac
if scanMac == "" {
scanMac = tc.mac
}
stubScan(t, map[string]string{scanMac: tc.foundIp})
if err := TrackOneSubnet(app, mustSubnet(t, testSubnet)); err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
fresh, err := app.FindRecordById("devices", device.Id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != tc.wantIp {
t.Errorf("Ip mismatch: expected %s, got %s", tc.wantIp, ip)
}
})
}
}
// A paused periodic sweep scans nothing and owes a catch-up sweep, which
// runs at most once until the next pause; an unpaused sweep scans directly.
func TestPeriodicSweepAndCatchUp(t *testing.T) {
app := newTestApp(t)
newDevice(t, app, "tracked", "127.0.0.50", testNetmask, "AA:BB:CC:DD:09:01", true)
scanned := stubScan(t, map[string]string{"AA:BB:CC:DD:09:01": "127.0.0.99"})
PeriodicSweep(app, true)
if len(*scanned) != 0 {
t.Fatalf("Expected no scans while paused, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 1 {
t.Fatalf("Expected one scan after a paused sweep, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 1 {
t.Errorf("Expected no scan when none is owed, got %v", *scanned)
}
PeriodicSweep(app, false)
if len(*scanned) != 2 {
t.Errorf("Expected an unpaused sweep to scan, got %v", *scanned)
}
CatchUpSweep(app)
if len(*scanned) != 2 {
t.Errorf("Expected an unpaused sweep to owe nothing, got %v", *scanned)
}
}
// TrackAllSubnets scans each unique scannable subnet once, silently skips the
// rest, and updates any tracked device found at a new ip within its own
// subnet — even one whose own subnet couldn't be scanned.
func TestTrackAllSubnets(t *testing.T) {
app := newTestApp(t)
first := newDevice(t, app, "first", "127.0.0.10", testNetmask, "AA:BB:CC:DD:02:01", true)
second := newDevice(t, app, "second", "127.0.0.20", testNetmask, "AA:BB:CC:DD:02:02", true)
// TEST-NET-1 (RFC 5737) is never assigned to an interface
unscannable := newDevice(t, app, "unscannable", "192.0.2.5", "255.255.255.0", "AA:BB:CC:DD:02:03", true)
// a /8 subnet is too large to scan but contains the found ip
wide := newDevice(t, app, "wide", "127.0.0.60", "255.0.0.0", "AA:BB:CC:DD:02:04", true)
scanned := stubScan(t, map[string]string{
"AA:BB:CC:DD:02:01": "127.0.0.11",
"AA:BB:CC:DD:02:02": "127.0.0.21",
"AA:BB:CC:DD:02:04": "127.0.0.61",
})
TrackAllSubnets(app)
if len(*scanned) != 1 || (*scanned)[0] != testSubnet {
t.Errorf("Expected a single scan of %s, got %v", testSubnet, *scanned)
}
wantIps := map[string]string{
first.Id: "127.0.0.11",
second.Id: "127.0.0.21",
unscannable.Id: "192.0.2.5",
wide.Id: "127.0.0.61",
}
for id, wantIp := range wantIps {
fresh, err := app.FindRecordById("devices", id)
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}
if ip := fresh.GetString("ip"); ip != wantIp {
t.Errorf("Ip mismatch for %s: expected %s, got %s", fresh.GetString("name"), wantIp, ip)
}
}
}
-102
View File
@@ -1,102 +0,0 @@
package logging
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"runtime"
"strconv"
"strings"
"ganigeorgiev.com/pocketbase/pocketbase/core"
)
var consoleHandler slog.Handler
// ConfigureConsole sets console output for UpSnap logs. PocketBase persistence
// remains controlled by PocketBase's built-in log settings.
func ConfigureConsole(level string) error {
level = strings.TrimSpace(level)
if level == "" {
level = "INFO"
}
if strings.EqualFold(level, "OFF") {
consoleHandler = nil
return nil
}
var parsed slog.Level
if err := parsed.UnmarshalText([]byte(strings.ToUpper(level))); err != nil {
return fmt.Errorf("invalid UPSNAP_LOG_LEVEL %q (expected DEBUG, INFO, WARN, ERROR, or OFF)", level)
}
consoleHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: parsed,
})
return nil
}
func relativeSource(file string) string {
file = strings.ReplaceAll(file, "\\", "/")
if index := strings.LastIndex(file, "/backend/"); index >= 0 {
return file[index+1:]
}
return file
}
// Logger writes through PocketBase's logger and mirrors UpSnap logs to stdout.
func Logger(app core.App) *slog.Logger {
handlers := []slog.Handler{app.Logger().Handler()}
if consoleHandler != nil && !app.IsDev() {
handlers = append(handlers, consoleHandler)
}
return slog.New(multiHandler(handlers)).With("upsnap", true)
}
type multiHandler []slog.Handler
func (h multiHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, handler := range h {
if handler.Enabled(ctx, level) {
return true
}
}
return false
}
func (h multiHandler) Handle(ctx context.Context, record slog.Record) error {
if record.PC != 0 {
frames := runtime.CallersFrames([]uintptr{record.PC})
frame, _ := frames.Next()
record.AddAttrs(slog.String(slog.SourceKey, relativeSource(frame.File)+":"+strconv.Itoa(frame.Line)))
}
var errs []error
for _, handler := range h {
if handler.Enabled(ctx, record.Level) {
if err := handler.Handle(ctx, record.Clone()); err != nil {
errs = append(errs, err)
}
}
}
return errors.Join(errs...)
}
func (h multiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
handlers := make(multiHandler, len(h))
for i, handler := range h {
handlers[i] = handler.WithAttrs(attrs)
}
return handlers
}
func (h multiHandler) WithGroup(name string) slog.Handler {
handlers := make(multiHandler, len(h))
for i, handler := range h {
handlers[i] = handler.WithGroup(name)
}
return handlers
}
-19
View File
@@ -1,19 +0,0 @@
package main
import (
"embed"
"log"
"ganigeorgiev.com/pocketbase/pocketbase/apis"
"github.com/seriousm4x/upsnap/pb"
)
//go:embed all:pb_public
var distDir embed.FS
var distDirFS = apis.MustSubFS(distDir, "pb_public")
func main() {
if err := pb.StartPocketBase(distDirFS); err != nil {
log.Fatal(err)
}
}
File diff suppressed because it is too large Load Diff
@@ -1,43 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// add field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// remove field
collection.Fields.RemoveById("number376926767")
return app.Save(collection)
})
}
@@ -1,56 +0,0 @@
package migrations
import (
"ganigeorgiev.com/pocketbase/pocketbase/core"
m "ganigeorgiev.com/pocketbase/pocketbase/migrations"
)
func init() {
m.Register(func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": true,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
}, func(app core.App) error {
collection, err := app.FindCollectionByNameOrId("pbc_3142635823")
if err != nil {
return err
}
// update field
if err := collection.Fields.AddMarshaledJSONAt(6, []byte(`{
"hidden": false,
"id": "number376926767",
"max": 9,
"min": 0,
"name": "avatar",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
}`)); err != nil {
return err
}
return app.Save(collection)
})
}

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