mirror of
https://github.com/seriousm4x/UpSnap.git
synced 2026-11-29 13:14:12 +00:00
Compare commits
20 Commits
4.0.0-beta.3
...
4.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 15a5663934 | |||
| 834c42ba75 | |||
| d7b18c8513 | |||
| c335903233 | |||
| d57520c66d | |||
| 8d2e3a5ade | |||
| 733d6d519f | |||
| 05686bf271 | |||
| a237fba8c7 | |||
| b8fdb4202f | |||
| 7b5dddfc06 | |||
| f8186ba015 | |||
| b2f2dfdcf9 | |||
| 5270661bb5 | |||
| 67ea231f39 | |||
| 58d497eab1 | |||
| e52d7f44b2 | |||
| 6982184ab6 | |||
| 4009a5c3e1 | |||
| a55152250b |
@@ -27,7 +27,7 @@ jobs:
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm --prefix=./frontend i
|
||||
UPSNAP_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
|
||||
PUBLIC_VERSION=${GITHUB_REF##*/} pnpm --prefix=./frontend run build
|
||||
cp -r ./frontend/build/* ./backend/pb_public/
|
||||
|
||||
# setup go
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
release:
|
||||
# draft: true
|
||||
draft: true
|
||||
prerelease: auto
|
||||
before:
|
||||
hooks:
|
||||
@@ -9,7 +9,7 @@ builds:
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
ldflags:
|
||||
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Version }}
|
||||
- -s -w -X github.com/seriousm4x/upsnap/pb.Version={{ .Tag }}
|
||||
goos:
|
||||
- linux
|
||||
- windows
|
||||
|
||||
@@ -8,11 +8,14 @@ import (
|
||||
"github.com/seriousm4x/upsnap/networking"
|
||||
)
|
||||
|
||||
var Devices []*models.Record
|
||||
var PingRunning bool = false
|
||||
var WakeShutdownRunning bool = false
|
||||
var CronPing *cron.Cron
|
||||
var CronWakeShutdown *cron.Cron
|
||||
|
||||
func RunPing(app *pocketbase.PocketBase) {
|
||||
PingRunning = true
|
||||
|
||||
settingsPrivateRecords, err := app.Dao().FindRecordsByExpr("settings_private")
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
@@ -26,54 +29,61 @@ func RunPing(app *pocketbase.PocketBase) {
|
||||
if realtimeClients == 0 && settingsPrivateRecords[0].GetBool("lazy_ping") {
|
||||
return
|
||||
}
|
||||
|
||||
devices, err := app.Dao().FindRecordsByExpr("devices")
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
// expand ports field
|
||||
expandFetchFunc := func(c *models.Collection, ids []string) ([]*models.Record, error) {
|
||||
return app.Dao().FindRecordsByIds(c.Id, ids, nil)
|
||||
}
|
||||
merr := app.Dao().ExpandRecords(Devices, []string{"ports"}, expandFetchFunc)
|
||||
merr := app.Dao().ExpandRecords(devices, []string{"ports"}, expandFetchFunc)
|
||||
if len(merr) > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for _, device := range Devices {
|
||||
// ping
|
||||
go func(device *models.Record) {
|
||||
oldStatus := device.Get("status")
|
||||
newStatus := networking.PingDevice(device)
|
||||
if newStatus {
|
||||
if oldStatus == "offline" || oldStatus == "" {
|
||||
device.Set("status", "online")
|
||||
if err := app.Dao().SaveRecord(device); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
for _, device := range devices {
|
||||
// ping device
|
||||
go func(d *models.Record) {
|
||||
status := d.GetString("status")
|
||||
if status == "pending" {
|
||||
return
|
||||
}
|
||||
if networking.PingDevice(d) {
|
||||
if status == "online" {
|
||||
return
|
||||
}
|
||||
d.Set("status", "online")
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
} else {
|
||||
if oldStatus == "online" || oldStatus == "" {
|
||||
device.Set("status", "offline")
|
||||
if err := app.Dao().SaveRecord(device); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
if status == "offline" {
|
||||
return
|
||||
}
|
||||
d.Set("status", "offline")
|
||||
if err := app.Dao().SaveRecord(d); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}
|
||||
}(device)
|
||||
|
||||
// scan ports
|
||||
go func(device *models.Record) {
|
||||
ports, err := app.Dao().FindRecordsByIds("ports", device.GetStringSlice("ports"))
|
||||
// ping ports
|
||||
go func(d *models.Record) {
|
||||
ports, err := app.Dao().FindRecordsByIds("ports", d.GetStringSlice("ports"))
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
for _, port := range ports {
|
||||
isUp := networking.CheckPort(device.GetString("ip"), port.GetString("number"))
|
||||
isUp := networking.CheckPort(d.GetString("ip"), port.GetString("number"))
|
||||
if isUp != port.GetBool("status") {
|
||||
port.Set("status", isUp)
|
||||
if err := app.Dao().SaveRecord(port); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
device.RefreshUpdated()
|
||||
if err := app.Dao().SaveRecord(device); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}(device)
|
||||
@@ -83,16 +93,22 @@ func RunPing(app *pocketbase.PocketBase) {
|
||||
}
|
||||
|
||||
func RunWakeShutdown(app *pocketbase.PocketBase) {
|
||||
WakeShutdownRunning = true
|
||||
|
||||
CronWakeShutdown = cron.New()
|
||||
for _, device := range Devices {
|
||||
wake_cron := device.GetString("wake_cron")
|
||||
wake_cron_enabled := device.GetBool("wake_cron_enabled")
|
||||
shutdown_cron := device.GetString("shutdown_cron")
|
||||
shutdown_cron_enabled := device.GetBool("shutdown_cron_enabled")
|
||||
devices, err := app.Dao().FindRecordsByExpr("devices")
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
return
|
||||
}
|
||||
for _, device := range devices {
|
||||
dev := device
|
||||
wake_cron := dev.GetString("wake_cron")
|
||||
wake_cron_enabled := dev.GetBool("wake_cron_enabled")
|
||||
shutdown_cron := dev.GetString("shutdown_cron")
|
||||
shutdown_cron_enabled := dev.GetBool("shutdown_cron_enabled")
|
||||
|
||||
if wake_cron_enabled && wake_cron != "" {
|
||||
// avoid using last element
|
||||
// https://github.com/robfig/cron/issues/115
|
||||
go func(d *models.Record) {
|
||||
_, err := CronWakeShutdown.AddFunc(wake_cron, func() {
|
||||
d.Set("status", "pending")
|
||||
@@ -115,12 +131,10 @@ func RunWakeShutdown(app *pocketbase.PocketBase) {
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
}(device)
|
||||
}(dev)
|
||||
}
|
||||
|
||||
if shutdown_cron_enabled && shutdown_cron != "" {
|
||||
// avoid using last element
|
||||
// https://github.com/robfig/cron/issues/115
|
||||
go func(d *models.Record) {
|
||||
_, err := CronWakeShutdown.AddFunc(shutdown_cron, func() {
|
||||
d.Set("status", "pending")
|
||||
@@ -143,8 +157,22 @@ func RunWakeShutdown(app *pocketbase.PocketBase) {
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
}
|
||||
}(device)
|
||||
}(dev)
|
||||
}
|
||||
}
|
||||
CronWakeShutdown.Run()
|
||||
}
|
||||
|
||||
func StopAll() {
|
||||
if PingRunning {
|
||||
logger.Info.Println("stopping ping cronjob")
|
||||
ctx := CronPing.Stop()
|
||||
<-ctx.Done()
|
||||
|
||||
}
|
||||
if WakeShutdownRunning {
|
||||
logger.Info.Println("stopping wake/shutdown cronjob")
|
||||
ctx := CronWakeShutdown.Stop()
|
||||
<-ctx.Done()
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ require (
|
||||
github.com/labstack/echo/v5 v5.0.0-20230722203903-ec5b858dab61
|
||||
github.com/mdlayher/wol v0.0.0-20220221231636-b763a792253a
|
||||
github.com/pocketbase/dbx v1.10.0
|
||||
github.com/pocketbase/pocketbase v0.17.4
|
||||
github.com/pocketbase/pocketbase v0.17.5
|
||||
github.com/prometheus-community/pro-bing v0.3.0
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
)
|
||||
|
||||
+2
-2
@@ -173,8 +173,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pocketbase/dbx v1.10.0 h1:58VIT7r6T+BnVbYVosvGBsPjQEic3/VFRYGT823vWSQ=
|
||||
github.com/pocketbase/dbx v1.10.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
|
||||
github.com/pocketbase/pocketbase v0.17.4 h1:PwT84MMoXPVdv/EC/dfanCsqfByY1xMNlaNWvlM5MfY=
|
||||
github.com/pocketbase/pocketbase v0.17.4/go.mod h1:IqsgywiDX5ewaUdeG+0NNckBLWp5mFhJSca1PH9zSp4=
|
||||
github.com/pocketbase/pocketbase v0.17.5 h1:3KwMrlSMt1rcwZK2Z1/wFa5p/rkDHpcyeCRvUDXMb+Y=
|
||||
github.com/pocketbase/pocketbase v0.17.5/go.mod h1:IqsgywiDX5ewaUdeG+0NNckBLWp5mFhJSca1PH9zSp4=
|
||||
github.com/prometheus-community/pro-bing v0.3.0 h1:SFT6gHqXwbItEDJhTkzPWVqU6CLEtqEfNAPp47RUON4=
|
||||
github.com/prometheus-community/pro-bing v0.3.0/go.mod h1:p9dLb9zdmv+eLxWfCT6jESWuDrS+YzpPkQBgysQF8a0=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add
|
||||
new_sol_enabled := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "ueieydw5",
|
||||
"name": "sol_enabled",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
}`), new_sol_enabled)
|
||||
collection.Schema.AddField(new_sol_enabled)
|
||||
|
||||
// add
|
||||
new_sol_auth := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "yfszwhpw",
|
||||
"name": "sol_auth",
|
||||
"type": "bool",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {}
|
||||
}`), new_sol_auth)
|
||||
collection.Schema.AddField(new_sol_auth)
|
||||
|
||||
// add
|
||||
new_sol_user := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "dbcmnrmp",
|
||||
"name": "sol_user",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}`), new_sol_user)
|
||||
collection.Schema.AddField(new_sol_user)
|
||||
|
||||
// add
|
||||
new_sol_password := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "hvz8stfy",
|
||||
"name": "sol_password",
|
||||
"type": "text",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": null,
|
||||
"pattern": ""
|
||||
}
|
||||
}`), new_sol_password)
|
||||
collection.Schema.AddField(new_sol_password)
|
||||
|
||||
// add
|
||||
new_sol_port := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "6kfqheid",
|
||||
"name": "sol_port",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), new_sol_port)
|
||||
collection.Schema.AddField(new_sol_port)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("ueieydw5")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("yfszwhpw")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("dbcmnrmp")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("hvz8stfy")
|
||||
|
||||
// remove
|
||||
collection.Schema.RemoveField("6kfqheid")
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_number := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "8nwuncgg",
|
||||
"name": "number",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_number)
|
||||
collection.Schema.AddField(edit_number)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("cti4l8f4mz8df3r")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_number := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "8nwuncgg",
|
||||
"name": "number",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": null,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_number)
|
||||
collection.Schema.AddField(edit_number)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/daos"
|
||||
m "github.com/pocketbase/pocketbase/migrations"
|
||||
"github.com/pocketbase/pocketbase/models/schema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
m.Register(func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_sol_port := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "6kfqheid",
|
||||
"name": "sol_port",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_sol_port)
|
||||
collection.Schema.AddField(edit_sol_port)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
}, func(db dbx.Builder) error {
|
||||
dao := daos.New(db);
|
||||
|
||||
collection, err := dao.FindCollectionByNameOrId("z5lghx2r3tm45n1")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update
|
||||
edit_sol_port := &schema.SchemaField{}
|
||||
json.Unmarshal([]byte(`{
|
||||
"system": false,
|
||||
"id": "6kfqheid",
|
||||
"name": "sol_port",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"min": 1,
|
||||
"max": 65535
|
||||
}
|
||||
}`), edit_sol_port)
|
||||
collection.Schema.AddField(edit_sol_port)
|
||||
|
||||
return dao.SaveCollection(collection)
|
||||
})
|
||||
}
|
||||
@@ -16,7 +16,7 @@ func PingDevice(device *models.Record) bool {
|
||||
return false
|
||||
}
|
||||
pinger.Count = 1
|
||||
pinger.Timeout = 500 * 1000000 // 500ms
|
||||
pinger.Timeout = 500 * time.Millisecond
|
||||
pinger.SetPrivileged(true)
|
||||
err = pinger.Run()
|
||||
if err != nil {
|
||||
|
||||
@@ -35,7 +35,7 @@ func ShutdownDevice(device *models.Record) error {
|
||||
return fmt.Errorf("%s", stderr.String())
|
||||
}
|
||||
|
||||
// check state every second for 2 min
|
||||
// check state every seconds for 2 min
|
||||
start := time.Now()
|
||||
for {
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package networking
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/pocketbase/pocketbase/models"
|
||||
"github.com/seriousm4x/upsnap/logger"
|
||||
)
|
||||
|
||||
type SolResponse struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func SleepDevice(device *models.Record) (SolResponse, error) {
|
||||
logger.Info.Println("sleep triggered for", device.GetString("name"))
|
||||
|
||||
var solResp SolResponse
|
||||
var url string
|
||||
|
||||
if device.GetBool("sol_auth") {
|
||||
url = fmt.Sprintf("http://%s:%s@%s:%d/sleep?format=JSON",
|
||||
device.GetString("sol_user"), device.GetString("sol_password"), device.GetString("ip"), device.GetInt("sol_port"))
|
||||
} else {
|
||||
url = fmt.Sprintf("http://%s:%d/sleep?format=JSON", device.GetString("ip"), device.GetInt("sol_port"))
|
||||
}
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return solResp, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return solResp, err
|
||||
}
|
||||
|
||||
var solResp SolResponse
|
||||
if err := json.Unmarshal(body, &solResp); err != nil {
|
||||
return solResp, err
|
||||
}
|
||||
|
||||
return solResp, errors.New("status code was not 200")
|
||||
}
|
||||
|
||||
return solResp, nil
|
||||
}
|
||||
@@ -15,7 +15,7 @@ func WakeDevice(device *models.Record) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// check state every second for 2 min
|
||||
// check state every seconds for 2 min
|
||||
start := time.Now()
|
||||
for {
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
+70
-15
@@ -7,6 +7,7 @@ import (
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
@@ -20,18 +21,72 @@ func HandlerWake(c echo.Context) error {
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
go func(*models.Record) {
|
||||
record.Set("status", "pending")
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
go func(r *models.Record) {
|
||||
if err := networking.WakeDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
r.Set("status", "offline")
|
||||
} else {
|
||||
r.Set("status", "online")
|
||||
}
|
||||
if err := App.Dao().SaveRecord(r); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}(record)
|
||||
return c.JSON(http.StatusOK, record)
|
||||
}
|
||||
|
||||
func HandlerSleep(c echo.Context) error {
|
||||
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
resp, err := networking.SleepDevice(record)
|
||||
if err != nil {
|
||||
logger.Error.Println(err)
|
||||
record.Set("status", "online")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
if err := networking.WakeDevice(record); err != nil {
|
||||
return apis.NewBadRequestError(resp.Message, nil)
|
||||
}
|
||||
record.Set("status", "offline")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, nil)
|
||||
}
|
||||
|
||||
func HandlerReboot(c echo.Context) error {
|
||||
record, err := App.Dao().FindFirstRecordByData("devices", "id", c.PathParam("id"))
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
go func(r *models.Record) {
|
||||
if err := networking.ShutdownDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
record.Set("status", "offline")
|
||||
r.Set("status", "online")
|
||||
} else {
|
||||
record.Set("status", "online")
|
||||
time.Sleep(15 * time.Second) // some devices might not respond to ping but are still shutting down
|
||||
if err := networking.WakeDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
r.Set("status", "offline")
|
||||
} else {
|
||||
r.Set("status", "online")
|
||||
}
|
||||
}
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
if err := App.Dao().SaveRecord(r); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}(record)
|
||||
@@ -43,18 +98,18 @@ func HandlerShutdown(c echo.Context) error {
|
||||
if err != nil {
|
||||
return apis.NewNotFoundError("The device does not exist.", err)
|
||||
}
|
||||
go func(*models.Record) {
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
if err := networking.ShutdownDevice(record); err != nil {
|
||||
record.Set("status", "pending")
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
go func(r *models.Record) {
|
||||
if err := networking.ShutdownDevice(r); err != nil {
|
||||
logger.Error.Println(err)
|
||||
record.Set("status", "online")
|
||||
r.Set("status", "online")
|
||||
} else {
|
||||
record.Set("status", "offline")
|
||||
r.Set("status", "offline")
|
||||
}
|
||||
if err := App.Dao().SaveRecord(record); err != nil {
|
||||
if err := App.Dao().SaveRecord(r); err != nil {
|
||||
logger.Error.Println("Failed to save record:", err)
|
||||
}
|
||||
}(record)
|
||||
|
||||
+28
-41
@@ -32,10 +32,8 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
|
||||
// event hooks
|
||||
App.OnBeforeServe().Add(func(e *core.ServeEvent) error {
|
||||
// set static website path
|
||||
e.Router.GET("/*", apis.StaticDirectoryHandler(distDirFS, true))
|
||||
|
||||
// add wake route to api
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/wake/:id",
|
||||
@@ -46,7 +44,26 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
},
|
||||
})
|
||||
|
||||
// add shutdown route to api
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/sleep/:id",
|
||||
Handler: HandlerSleep,
|
||||
Middlewares: []echo.MiddlewareFunc{
|
||||
apis.ActivityLogger(App),
|
||||
RequireUpSnapPermission(),
|
||||
},
|
||||
})
|
||||
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/reboot/:id",
|
||||
Handler: HandlerReboot,
|
||||
Middlewares: []echo.MiddlewareFunc{
|
||||
apis.ActivityLogger(App),
|
||||
RequireUpSnapPermission(),
|
||||
},
|
||||
})
|
||||
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/shutdown/:id",
|
||||
@@ -57,7 +74,6 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
},
|
||||
})
|
||||
|
||||
// add network scan route to api
|
||||
e.Router.AddRoute(echo.Route{
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/upsnap/scan",
|
||||
@@ -68,17 +84,14 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
},
|
||||
})
|
||||
|
||||
// import environment and set settings
|
||||
if err := importSettings(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// reset device states
|
||||
if err := resetDeviceStates(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// run cronjobs
|
||||
go cronjobs.RunPing(App)
|
||||
go cronjobs.RunWakeShutdown(App)
|
||||
|
||||
@@ -92,10 +105,6 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
}
|
||||
go cronjobs.RunPing(App)
|
||||
} else if e.Model.TableName() == "devices" {
|
||||
if err := refreshDeviceList(); err != nil {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
for _, job := range cronjobs.CronWakeShutdown.Entries() {
|
||||
cronjobs.CronWakeShutdown.Remove(job.ID)
|
||||
}
|
||||
@@ -135,14 +144,6 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if e.Model.TableName() == "devices" || e.Model.TableName() == "ports" {
|
||||
// refresh the device list on database events
|
||||
if err := refreshDeviceList(); err != nil {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
App.OnModelAfterDelete().Add(func(e *core.ModelEvent) error {
|
||||
@@ -151,23 +152,21 @@ func StartPocketBase(distDirFS fs.FS) {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
} else if e.Model.TableName() == "devices" || e.Model.TableName() == "ports" {
|
||||
if err := refreshDeviceList(); err != nil {
|
||||
logger.Error.Println(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// start pocketbase
|
||||
App.OnTerminate().Add(func(e *core.TerminateEvent) error {
|
||||
cronjobs.StopAll()
|
||||
return nil
|
||||
})
|
||||
|
||||
if err := App.Start(); err != nil {
|
||||
logger.Error.Fatalln(err)
|
||||
}
|
||||
}
|
||||
|
||||
func importSettings() error {
|
||||
// get first settingsPrivate record
|
||||
settingsPrivateRecords, err := App.Dao().FindRecordsByExpr("settings_private")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -181,7 +180,6 @@ func importSettings() error {
|
||||
settingsPrivate = settingsPrivateRecords[0]
|
||||
}
|
||||
|
||||
// get first settingsPublic record
|
||||
settingsPublicRecords, err := App.Dao().FindRecordsByExpr("settings_public")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -207,18 +205,15 @@ func importSettings() error {
|
||||
interval = os.Getenv("UPSNAP_INTERVAL")
|
||||
}
|
||||
|
||||
// set private settings
|
||||
settingsPrivate.Set("interval", interval)
|
||||
if scanRange := os.Getenv("UPSNAP_SCAN_RANGE"); scanRange != "" {
|
||||
settingsPrivate.Set("scan_range", scanRange)
|
||||
}
|
||||
|
||||
// set public settings
|
||||
if websiteTitle := os.Getenv("UPSNAP_WEBSITE_TITLE"); websiteTitle != "" {
|
||||
settingsPublic.Set("website_title", websiteTitle)
|
||||
}
|
||||
|
||||
// save records
|
||||
if err := App.Dao().SaveRecord(settingsPrivate); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -240,20 +235,12 @@ func resetDeviceStates() error {
|
||||
return err
|
||||
}
|
||||
for _, device := range devices {
|
||||
device.Set("status", "offline")
|
||||
if err := App.Dao().SaveRecord(device); err != nil {
|
||||
d := device
|
||||
d.Set("status", "offline")
|
||||
if err := App.Dao().SaveRecord(d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
cronjobs.Devices = devices
|
||||
return nil
|
||||
}
|
||||
|
||||
func refreshDeviceList() error {
|
||||
var err error
|
||||
if cronjobs.Devices, err = App.Dao().FindRecordsByExpr("devices"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
"devDependencies": {
|
||||
"@sveltejs/adapter-static": "^2.0.3",
|
||||
"@sveltejs/kit": "^1.22.6",
|
||||
"@typescript-eslint/eslint-plugin": "^6.3.0",
|
||||
"@typescript-eslint/parser": "^6.3.0",
|
||||
"@typescript-eslint/eslint-plugin": "^6.4.0",
|
||||
"@typescript-eslint/parser": "^6.4.0",
|
||||
"autoprefixer": "^10.4.15",
|
||||
"daisyui": "^3.5.1",
|
||||
"eslint": "^8.47.0",
|
||||
|
||||
Generated
+39
-47
@@ -32,11 +32,11 @@ devDependencies:
|
||||
specifier: ^1.22.6
|
||||
version: 1.22.6(svelte@4.2.0)(vite@4.4.9)
|
||||
'@typescript-eslint/eslint-plugin':
|
||||
specifier: ^6.3.0
|
||||
version: 6.3.0(@typescript-eslint/parser@6.3.0)(eslint@8.47.0)(typescript@5.1.6)
|
||||
specifier: ^6.4.0
|
||||
version: 6.4.0(@typescript-eslint/parser@6.4.0)(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/parser':
|
||||
specifier: ^6.3.0
|
||||
version: 6.3.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
specifier: ^6.4.0
|
||||
version: 6.4.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
autoprefixer:
|
||||
specifier: ^10.4.15
|
||||
version: 10.4.15(postcss@8.4.27)
|
||||
@@ -676,10 +676,10 @@ packages:
|
||||
}
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/eslint-plugin@6.3.0(@typescript-eslint/parser@6.3.0)(eslint@8.47.0)(typescript@5.1.6):
|
||||
/@typescript-eslint/eslint-plugin@6.4.0(@typescript-eslint/parser@6.4.0)(eslint@8.47.0)(typescript@5.1.6):
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-IZYjYZ0ifGSLZbwMqIip/nOamFiWJ9AH+T/GYNZBWkVcyNQOFGtSMoWV7RvY4poYCMZ/4lHzNl796WOSNxmk8A==
|
||||
integrity: sha512-62o2Hmc7Gs3p8SLfbXcipjWAa6qk2wZGChXG2JbBtYpwSRmti/9KHLqfbLs9uDigOexG+3PaQ9G2g3201FWLKg==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
peerDependencies:
|
||||
@@ -691,17 +691,16 @@ packages:
|
||||
optional: true
|
||||
dependencies:
|
||||
'@eslint-community/regexpp': 4.6.2
|
||||
'@typescript-eslint/parser': 6.3.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/scope-manager': 6.3.0
|
||||
'@typescript-eslint/type-utils': 6.3.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/utils': 6.3.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/visitor-keys': 6.3.0
|
||||
'@typescript-eslint/parser': 6.4.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/scope-manager': 6.4.0
|
||||
'@typescript-eslint/type-utils': 6.4.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/utils': 6.4.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/visitor-keys': 6.4.0
|
||||
debug: 4.3.4
|
||||
eslint: 8.47.0
|
||||
graphemer: 1.4.0
|
||||
ignore: 5.2.4
|
||||
natural-compare: 1.4.0
|
||||
natural-compare-lite: 1.4.0
|
||||
semver: 7.5.4
|
||||
ts-api-utils: 1.0.1(typescript@5.1.6)
|
||||
typescript: 5.1.6
|
||||
@@ -709,10 +708,10 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/parser@6.3.0(eslint@8.47.0)(typescript@5.1.6):
|
||||
/@typescript-eslint/parser@6.4.0(eslint@8.47.0)(typescript@5.1.6):
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-ibP+y2Gr6p0qsUkhs7InMdXrwldjxZw66wpcQq9/PzAroM45wdwyu81T+7RibNCh8oc0AgrsyCwJByncY0Ongg==
|
||||
integrity: sha512-I1Ah1irl033uxjxO9Xql7+biL3YD7w9IU8zF+xlzD/YxY6a4b7DYA08PXUUCbm2sEljwJF6ERFy2kTGAGcNilg==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
peerDependencies:
|
||||
@@ -722,10 +721,10 @@ packages:
|
||||
typescript:
|
||||
optional: true
|
||||
dependencies:
|
||||
'@typescript-eslint/scope-manager': 6.3.0
|
||||
'@typescript-eslint/types': 6.3.0
|
||||
'@typescript-eslint/typescript-estree': 6.3.0(typescript@5.1.6)
|
||||
'@typescript-eslint/visitor-keys': 6.3.0
|
||||
'@typescript-eslint/scope-manager': 6.4.0
|
||||
'@typescript-eslint/types': 6.4.0
|
||||
'@typescript-eslint/typescript-estree': 6.4.0(typescript@5.1.6)
|
||||
'@typescript-eslint/visitor-keys': 6.4.0
|
||||
debug: 4.3.4
|
||||
eslint: 8.47.0
|
||||
typescript: 5.1.6
|
||||
@@ -733,21 +732,21 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/scope-manager@6.3.0:
|
||||
/@typescript-eslint/scope-manager@6.4.0:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-WlNFgBEuGu74ahrXzgefiz/QlVb+qg8KDTpknKwR7hMH+lQygWyx0CQFoUmMn1zDkQjTBBIn75IxtWss77iBIQ==
|
||||
integrity: sha512-TUS7vaKkPWDVvl7GDNHFQMsMruD+zhkd3SdVW0d7b+7Zo+bd/hXJQ8nsiUZMi1jloWo6c9qt3B7Sqo+flC1nig==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
dependencies:
|
||||
'@typescript-eslint/types': 6.3.0
|
||||
'@typescript-eslint/visitor-keys': 6.3.0
|
||||
'@typescript-eslint/types': 6.4.0
|
||||
'@typescript-eslint/visitor-keys': 6.4.0
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/type-utils@6.3.0(eslint@8.47.0)(typescript@5.1.6):
|
||||
/@typescript-eslint/type-utils@6.4.0(eslint@8.47.0)(typescript@5.1.6):
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-7Oj+1ox1T2Yc8PKpBvOKWhoI/4rWFd1j7FA/rPE0lbBPXTKjdbtC+7Ev0SeBjEKkIhKWVeZSP+mR7y1Db1CdfQ==
|
||||
integrity: sha512-TvqrUFFyGY0cX3WgDHcdl2/mMCWCDv/0thTtx/ODMY1QhEiyFtv/OlLaNIiYLwRpAxAtOLOY9SUf1H3Q3dlwAg==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
peerDependencies:
|
||||
@@ -757,8 +756,8 @@ packages:
|
||||
typescript:
|
||||
optional: true
|
||||
dependencies:
|
||||
'@typescript-eslint/typescript-estree': 6.3.0(typescript@5.1.6)
|
||||
'@typescript-eslint/utils': 6.3.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
'@typescript-eslint/typescript-estree': 6.4.0(typescript@5.1.6)
|
||||
'@typescript-eslint/utils': 6.4.0(eslint@8.47.0)(typescript@5.1.6)
|
||||
debug: 4.3.4
|
||||
eslint: 8.47.0
|
||||
ts-api-utils: 1.0.1(typescript@5.1.6)
|
||||
@@ -767,18 +766,18 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/types@6.3.0:
|
||||
/@typescript-eslint/types@6.4.0:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-K6TZOvfVyc7MO9j60MkRNWyFSf86IbOatTKGrpTQnzarDZPYPVy0oe3myTMq7VjhfsUAbNUW8I5s+2lZvtx1gg==
|
||||
integrity: sha512-+FV9kVFrS7w78YtzkIsNSoYsnOtrYVnKWSTVXoL1761CsCRv5wpDOINgsXpxD67YCLZtVQekDDyaxfjVWUJmmg==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/typescript-estree@6.3.0(typescript@5.1.6):
|
||||
/@typescript-eslint/typescript-estree@6.4.0(typescript@5.1.6):
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-Xh4NVDaC4eYKY4O3QGPuQNp5NxBAlEvNQYOqJquR2MePNxO11E5K3t5x4M4Mx53IZvtpW+mBxIT0s274fLUocg==
|
||||
integrity: sha512-iDPJArf/K2sxvjOR6skeUCNgHR/tCQXBsa+ee1/clRKr3olZjZ/dSkXPZjG6YkPtnW6p5D1egeEPMCW6Gn4yLA==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
peerDependencies:
|
||||
@@ -787,8 +786,8 @@ packages:
|
||||
typescript:
|
||||
optional: true
|
||||
dependencies:
|
||||
'@typescript-eslint/types': 6.3.0
|
||||
'@typescript-eslint/visitor-keys': 6.3.0
|
||||
'@typescript-eslint/types': 6.4.0
|
||||
'@typescript-eslint/visitor-keys': 6.4.0
|
||||
debug: 4.3.4
|
||||
globby: 11.1.0
|
||||
is-glob: 4.0.3
|
||||
@@ -799,10 +798,10 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/utils@6.3.0(eslint@8.47.0)(typescript@5.1.6):
|
||||
/@typescript-eslint/utils@6.4.0(eslint@8.47.0)(typescript@5.1.6):
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-hLLg3BZE07XHnpzglNBG8P/IXq/ZVXraEbgY7FM0Cnc1ehM8RMdn9mat3LubJ3KBeYXXPxV1nugWbQPjGeJk6Q==
|
||||
integrity: sha512-BvvwryBQpECPGo8PwF/y/q+yacg8Hn/2XS+DqL/oRsOPK+RPt29h5Ui5dqOKHDlbXrAeHUTnyG3wZA0KTDxRZw==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
peerDependencies:
|
||||
@@ -811,9 +810,9 @@ packages:
|
||||
'@eslint-community/eslint-utils': 4.4.0(eslint@8.47.0)
|
||||
'@types/json-schema': 7.0.12
|
||||
'@types/semver': 7.5.0
|
||||
'@typescript-eslint/scope-manager': 6.3.0
|
||||
'@typescript-eslint/types': 6.3.0
|
||||
'@typescript-eslint/typescript-estree': 6.3.0(typescript@5.1.6)
|
||||
'@typescript-eslint/scope-manager': 6.4.0
|
||||
'@typescript-eslint/types': 6.4.0
|
||||
'@typescript-eslint/typescript-estree': 6.4.0(typescript@5.1.6)
|
||||
eslint: 8.47.0
|
||||
semver: 7.5.4
|
||||
transitivePeerDependencies:
|
||||
@@ -821,14 +820,14 @@ packages:
|
||||
- typescript
|
||||
dev: true
|
||||
|
||||
/@typescript-eslint/visitor-keys@6.3.0:
|
||||
/@typescript-eslint/visitor-keys@6.4.0:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-kEhRRj7HnvaSjux1J9+7dBen15CdWmDnwrpyiHsFX6Qx2iW5LOBUgNefOFeh2PjWPlNwN8TOn6+4eBU3J/gupw==
|
||||
integrity: sha512-yJSfyT+uJm+JRDWYRYdCm2i+pmvXJSMtPR9Cq5/XQs4QIgNoLcoRtDdzsLbLsFM/c6um6ohQkg/MLxWvoIndJA==
|
||||
}
|
||||
engines: { node: ^16.0.0 || >=18.0.0 }
|
||||
dependencies:
|
||||
'@typescript-eslint/types': 6.3.0
|
||||
'@typescript-eslint/types': 6.4.0
|
||||
eslint-visitor-keys: 3.4.3
|
||||
dev: true
|
||||
|
||||
@@ -2117,13 +2116,6 @@ packages:
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/natural-compare-lite@1.4.0:
|
||||
resolution:
|
||||
{
|
||||
integrity: sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==
|
||||
}
|
||||
dev: true
|
||||
|
||||
/natural-compare@1.4.0:
|
||||
resolution:
|
||||
{
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
<script lang="ts">
|
||||
import { formatDistance, parseISO } from 'date-fns';
|
||||
import { pocketbase, isAdmin, backendUrl, permission } from '$lib/stores/pocketbase';
|
||||
import DeviceCardNic from './DeviceCardNic.svelte';
|
||||
import { scale } from 'svelte/transition';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faCircleArrowDown, faCircleArrowUp, faLock } from '@fortawesome/free-solid-svg-icons';
|
||||
import { isAdmin, permission } from '$lib/stores/pocketbase';
|
||||
import {
|
||||
faBed,
|
||||
faCircleArrowDown,
|
||||
faCircleArrowUp,
|
||||
faLock,
|
||||
faPen,
|
||||
faRotateLeft
|
||||
} from '@fortawesome/free-solid-svg-icons';
|
||||
import { scale } from 'svelte/transition';
|
||||
import { formatDistance, parseISO } from 'date-fns';
|
||||
import toast from 'svelte-french-toast';
|
||||
import type { Device } from '$lib/types/device';
|
||||
|
||||
export let device: Device;
|
||||
@@ -18,6 +26,26 @@
|
||||
now = Date.now();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function sleep() {
|
||||
fetch(`${backendUrl}api/upsnap/sleep/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function reboot() {
|
||||
fetch(`${backendUrl}api/upsnap/reboot/${device.id}`, {
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="card bg-base-300 shadow-md rounded-3xl" transition:scale={{ delay: 0, duration: 200 }}>
|
||||
@@ -33,36 +61,59 @@
|
||||
<!-- TODO: change to nic array once backend supports it -->
|
||||
<DeviceCardNic {device} />
|
||||
</ul>
|
||||
<div class="flex flex-row flex-wrap gap-2">
|
||||
{#if device.wake_cron_enabled}
|
||||
<div class="tooltip" data-tip="Wake cron">
|
||||
<span class="badge badge-success gap-1 p-3"
|
||||
><Fa icon={faCircleArrowUp} />{device.wake_cron}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.shutdown_cron_enabled}
|
||||
<div class="tooltip" data-tip="Shutdown cron">
|
||||
<span class="badge badge-error gap-1 p-3"
|
||||
><Fa icon={faCircleArrowDown} />{device.shutdown_cron}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.password}
|
||||
<div class="tooltip" data-tip="Wake password">
|
||||
<span class="badge gap-1 p-3"><Fa icon={faLock} />Password</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="card-actions mt-auto">
|
||||
{#if device.wake_cron_enabled || device.shutdown_cron_enabled || device.password}
|
||||
<div class="flex flex-row flex-wrap gap-2">
|
||||
{#if device.wake_cron_enabled}
|
||||
<div class="tooltip" data-tip="Wake cron">
|
||||
<span class="badge badge-success gap-1 p-3"
|
||||
><Fa icon={faCircleArrowUp} />{device.wake_cron}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.shutdown_cron_enabled}
|
||||
<div class="tooltip" data-tip="Shutdown cron">
|
||||
<span class="badge badge-error gap-1 p-3"
|
||||
><Fa icon={faCircleArrowDown} />{device.shutdown_cron}</span
|
||||
>
|
||||
</div>
|
||||
{/if}
|
||||
{#if device.password}
|
||||
<div class="tooltip" data-tip="Wake password">
|
||||
<span class="badge gap-1 p-3"><Fa icon={faLock} />Password</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="card-actions mt-auto items-center">
|
||||
<span class="tooltip" data-tip="Last status change: {device.updated}">
|
||||
{formatDistance(parseISO(device.updated), now, {
|
||||
includeSeconds: true,
|
||||
addSuffix: true
|
||||
})}
|
||||
</span>
|
||||
{#if $isAdmin || $permission.update?.includes(device.id)}
|
||||
<a class="btn btn-sm btn-neutral ms-auto" href="/device/{device.id}">Edit</a>
|
||||
{#if $isAdmin || $permission.update?.includes(device.id) || $permission.power?.includes(device.id)}
|
||||
<div class="dropdown dropdown-top dropdown-end bg-base-300 ms-auto">
|
||||
<label tabindex="-1" class="btn btn-sm m-1" for="more-{device.id}">More</label>
|
||||
<ul
|
||||
id="more-{device.id}"
|
||||
tabindex="-1"
|
||||
class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-fit"
|
||||
>
|
||||
{#if ($isAdmin || $permission.power?.includes(device.id)) && device.status === 'online'}
|
||||
{#if device.shutdown_cmd !== ''}
|
||||
<li><button on:click={() => reboot()}><Fa icon={faRotateLeft} />Reboot</button></li>
|
||||
{/if}
|
||||
{#if device.sol_enabled}
|
||||
<li><button on:click={() => sleep()}><Fa icon={faBed} />Sleep</button></li>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if $isAdmin || $permission.update?.includes(device.id)}
|
||||
<li>
|
||||
<a href="/device/{device.id}"><Fa icon={faPen} />Edit</a>
|
||||
</li>
|
||||
{/if}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,21 +2,21 @@
|
||||
import { pocketbase, backendUrl, permission, isAdmin } from '$lib/stores/pocketbase';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faCircle, faPowerOff } from '@fortawesome/free-solid-svg-icons';
|
||||
import type { Device } from '$lib/types/device';
|
||||
import toast from 'svelte-french-toast';
|
||||
import type { Device } from '$lib/types/device';
|
||||
|
||||
export let device: Device;
|
||||
|
||||
let hoverText = '';
|
||||
let disabled = false;
|
||||
let interval: number;
|
||||
let timeout = 120;
|
||||
var interval: number;
|
||||
|
||||
$: if (device.status === 'pending' && !interval) {
|
||||
countdown(Date.parse(device.updated));
|
||||
}
|
||||
$: minutes = Math.floor(timeout / 60);
|
||||
$: seconds = timeout % 60;
|
||||
$: if (device.status === 'pending') {
|
||||
countdown();
|
||||
}
|
||||
|
||||
$: if (device.status === 'pending' || device.status === '') {
|
||||
disabled = true;
|
||||
hoverText = 'Pending';
|
||||
@@ -47,9 +47,14 @@
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
})
|
||||
.then(async (data) => {
|
||||
const dev = (await data.json()) as Device;
|
||||
countdown(Date.parse(dev.updated));
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
@@ -57,19 +62,22 @@
|
||||
headers: {
|
||||
Authorization: $pocketbase.authStore.token
|
||||
}
|
||||
}).catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
})
|
||||
.then(async (data) => {
|
||||
const dev = (await data.json()) as Device;
|
||||
countdown(Date.parse(dev.updated));
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(err.message);
|
||||
});
|
||||
}
|
||||
|
||||
function countdown() {
|
||||
clearInterval(interval);
|
||||
const end = Date.parse(device.updated) + 2 * 60 * 1000;
|
||||
function countdown(updated: number) {
|
||||
timeout = 120;
|
||||
const end = updated + 2 * 60 * 1000;
|
||||
interval = setInterval(() => {
|
||||
const left = Math.round((end - Date.now()) / 1000);
|
||||
if (left >= 0) {
|
||||
timeout = left;
|
||||
} else {
|
||||
timeout = Math.round((end - Date.now()) / 1000);
|
||||
if (timeout <= 0 || device.status !== 'pending') {
|
||||
clearInterval(interval);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
@@ -325,6 +325,128 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Sleep-On-LAN</h2>
|
||||
<p class="mt-2">
|
||||
You can put computers to sleep using the <a
|
||||
class="link"
|
||||
href="https://github.com/SR-G/sleep-on-lan"
|
||||
target="_blank">Sleep-On-LAN</a
|
||||
>
|
||||
tool. Sleep-On-LAN (SOL) is an external tool/daemon that operates on the PCs you want to put
|
||||
to sleep, providing a REST endpoint to put the PC to sleep. For instructions on setting up Sleep-On-LAN,
|
||||
please refer to the
|
||||
<a href="https://github.com/SR-G/sleep-on-lan#usage" class="link" target="_blank">Usage</a> section.
|
||||
</p>
|
||||
<p>
|
||||
SOL is confiugred to send requests over HTTP instead of UDP to enable authorization and make
|
||||
requests more reliable.
|
||||
</p>
|
||||
<p class="font-bold">
|
||||
Therefore, please ensure that you include <span class="badge">HTTP:<YOURPORT></span>
|
||||
in the <span class="badge">Listeners</span> section of the
|
||||
<a href="https://github.com/SR-G/sleep-on-lan#configuration" class="link" target="_blank"
|
||||
>SOL configuration</a
|
||||
>.
|
||||
</p>
|
||||
<div class="flex flex-row flex-wrap gap-4 items-end mt-4">
|
||||
<div>
|
||||
<div class="form-control flex flex-row flex-wrap gap-4">
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<input
|
||||
id="sol-enable"
|
||||
type="checkbox"
|
||||
class="toggle toggle-success"
|
||||
bind:checked={device.sol_enabled}
|
||||
/>
|
||||
<label class="label cursor-pointer" for="sol-enable">
|
||||
<span class="label-text">Enable Sleep-On-LAN</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control flex flex-col">
|
||||
<label class="label" for="sol-port">
|
||||
<span class="label-text"
|
||||
>SOL Port
|
||||
{#if device.sol_enabled}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="sol-port"
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
placeholder="Default: 8009"
|
||||
class="input w-80"
|
||||
bind:value={device.sol_port}
|
||||
disabled={!device.sol_enabled}
|
||||
required={device.sol_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if device.sol_enabled}
|
||||
<div>
|
||||
<div class="form-control flex flex-row flex-wrap gap-4">
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<input
|
||||
id="sol-auth"
|
||||
type="checkbox"
|
||||
class="toggle toggle-success"
|
||||
bind:checked={device.sol_auth}
|
||||
/>
|
||||
<label class="label cursor-pointer" for="sol-auth">
|
||||
<span class="label-text">Authorization</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control flex flex-col">
|
||||
<label class="label" for="sol-user">
|
||||
<span class="label-text"
|
||||
>SOL User
|
||||
{#if device.sol_auth}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="sol-user"
|
||||
type="text"
|
||||
placeholder="username"
|
||||
class="input w-80"
|
||||
bind:value={device.sol_user}
|
||||
disabled={!device.sol_auth}
|
||||
required={device.sol_auth}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control flex flex-col">
|
||||
<label class="label" for="sol-password">
|
||||
<span class="label-text"
|
||||
>SOL Password
|
||||
{#if device.sol_auth}
|
||||
<span class="text-error">*</span>
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
<input
|
||||
id="sol-password"
|
||||
type="password"
|
||||
placeholder="password"
|
||||
class="input w-80"
|
||||
bind:value={device.sol_password}
|
||||
disabled={!device.sol_auth}
|
||||
required={device.sol_auth}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card w-full bg-base-300 shadow-xl mt-6">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title">Shutdown</h2>
|
||||
@@ -346,7 +468,7 @@
|
||||
<div class="mockup-code text-sm max-w-fit">
|
||||
<pre data-prefix="#"><code>Shutdown remote linux machine:</code></pre>
|
||||
<pre data-prefix="$" class="text-warning"><code
|
||||
>sshpass -p your_password ssh -o "StrictHostKeyChecking=no" user@hostname "sudo poweroff"</code
|
||||
>sshpass -p password ssh -o "StrictHostKeyChecking=no" user@192.168.1.13 "sudo poweroff"</code
|
||||
></pre>
|
||||
</div>
|
||||
<div class="form-control w-full">
|
||||
|
||||
@@ -20,6 +20,11 @@ export type Device = Record & {
|
||||
groups: Group[];
|
||||
};
|
||||
created_by: string;
|
||||
sol_enabled: boolean;
|
||||
sol_auth: boolean;
|
||||
sol_user: string;
|
||||
sol_passwort: string;
|
||||
sol_port: number;
|
||||
};
|
||||
|
||||
export type Port = Record & {
|
||||
|
||||
@@ -63,6 +63,12 @@
|
||||
return;
|
||||
}
|
||||
|
||||
// only refresh token if valid less than 1 day
|
||||
const jwt = parseJwt($pocketbase.authStore.token);
|
||||
if (jwt.exp > Date.now() / 1000 + 60 * 60 * 24) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($pocketbase.authStore.model?.collectionName === 'users') {
|
||||
await $pocketbase
|
||||
.collection('users')
|
||||
@@ -76,6 +82,22 @@
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function parseJwt(token: string) {
|
||||
var base64Url = token.split('.')[1];
|
||||
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
||||
var jsonPayload = decodeURIComponent(
|
||||
window
|
||||
.atob(base64)
|
||||
.split('')
|
||||
.map(function (c) {
|
||||
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
|
||||
})
|
||||
.join('')
|
||||
);
|
||||
|
||||
return JSON.parse(jsonPayload);
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { faLockOpen, faEye } from '@fortawesome/free-solid-svg-icons';
|
||||
import { toggleVisibility } from '$lib/helpers/forms';
|
||||
import toast from 'svelte-french-toast';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let inputPassword: HTMLInputElement;
|
||||
let form = {
|
||||
@@ -13,6 +14,12 @@
|
||||
password: ''
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
if ($pocketbase.authStore.isValid) {
|
||||
goto('/');
|
||||
}
|
||||
});
|
||||
|
||||
function tryAdminThenUser() {
|
||||
$pocketbase.admins
|
||||
.authWithPassword(form.email, form.password)
|
||||
|
||||
@@ -8,13 +8,13 @@
|
||||
import { faSave } from '@fortawesome/free-solid-svg-icons';
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import { PUBLIC_VERSION } from '$env/static/public';
|
||||
import type { SettingsPublic, SettingsPrivate } from '$lib/types/settings';
|
||||
|
||||
let settingsPubClone: SettingsPublic | undefined;
|
||||
let settingsPrivClone: SettingsPrivate | undefined;
|
||||
let faviconPreview: HTMLImageElement;
|
||||
let faviconInputElement: HTMLInputElement;
|
||||
let version = import.meta.env.UPSNAP_VERSION;
|
||||
|
||||
onMount(() => {
|
||||
if (!$isAdmin) {
|
||||
@@ -185,12 +185,12 @@
|
||||
</div>
|
||||
</form>
|
||||
<div class="container mx-auto text-center mt-6">
|
||||
{#if version === undefined}
|
||||
{#if PUBLIC_VERSION === undefined}
|
||||
UpSnap version: (untracked)
|
||||
{:else}
|
||||
UpSnap version: <a
|
||||
href="https://github.com/seriousm4x/UpSnap/releases/tag/{version}"
|
||||
class="text-reset">{version}</a
|
||||
href="https://github.com/seriousm4x/UpSnap/releases/tag/{PUBLIC_VERSION}"
|
||||
class="text-reset">{PUBLIC_VERSION}</a
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import toast from 'svelte-french-toast';
|
||||
import Fa from 'svelte-fa';
|
||||
import { faArrowRight, faEye } from '@fortawesome/free-solid-svg-icons';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let stepsCompleted = 0;
|
||||
let inputPassword: HTMLInputElement;
|
||||
@@ -16,6 +17,12 @@
|
||||
confirm: ''
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
if (!$settingsPub.setup_completed && $pocketbase.authStore.isValid) {
|
||||
$pocketbase.authStore.clear();
|
||||
}
|
||||
});
|
||||
|
||||
async function register() {
|
||||
$pocketbase.admins
|
||||
.create({
|
||||
|
||||
Reference in New Issue
Block a user