Compare commits
29 Commits
45c400e7d3
...
v0.0.21
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7aef03a7cd | ||
|
|
d1f1ad563b | ||
|
|
66c6d9a3fb | ||
|
|
2c718824d2 | ||
|
|
f8dce0b817 | ||
|
|
0eb781a6d3 | ||
|
|
9150550609 | ||
|
|
84abf6b820 | ||
|
|
4904589086 | ||
|
|
6f7e149c9a | ||
|
|
df344b4c13 | ||
|
|
d82f213ca7 | ||
|
|
3241429e98 | ||
|
|
8165b2d843 | ||
|
|
e480141e89 | ||
|
|
e1ae34a336 | ||
|
|
3aac950b9c | ||
|
|
96bfcb7d0e | ||
|
|
64744e218a | ||
|
|
7d3db6b485 | ||
|
|
9cde384a36 | ||
| f9a92e4e4a | |||
| 40b13a0661 | |||
|
|
ff473d0e8d | ||
|
|
4798b76b2d | ||
|
|
80d637f03e | ||
|
|
793929ad82 | ||
|
|
281548c166 | ||
|
|
9543bf407b |
7
.env
7
.env
@@ -1,5 +1,8 @@
|
|||||||
ENV= #empty|development
|
#empty|development|debug
|
||||||
|
ENV=
|
||||||
PHOTO_DIR=images
|
PHOTO_DIR=images
|
||||||
HOST=0.0.0.0
|
HOST=0.0.0.0
|
||||||
PORT=8080
|
PORT=8080
|
||||||
INTERVAL_DEFAULT=120
|
INTERVAL_DEFAULT=120
|
||||||
|
#path for logger files default {executable name}.log
|
||||||
|
LOG_PATH=
|
||||||
217
.gitea/workflows/build.yml
Normal file
217
.gitea/workflows/build.yml
Normal file
@@ -0,0 +1,217 @@
|
|||||||
|
name: Build Slideshow App
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
|
||||||
|
env:
|
||||||
|
APP_NAME: slideshowApp
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- os: windows
|
||||||
|
arch: amd64
|
||||||
|
ext: .exe
|
||||||
|
- os: linux
|
||||||
|
arch: amd64
|
||||||
|
ext: ""
|
||||||
|
- os: linux
|
||||||
|
arch: arm64
|
||||||
|
ext: ""
|
||||||
|
- os: linux
|
||||||
|
arch: arm
|
||||||
|
arm_version: 7
|
||||||
|
ext: ""
|
||||||
|
|
||||||
|
steps:
|
||||||
|
|
||||||
|
- name: Checkout repo
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Ensure latest Go is installed in /data/go
|
||||||
|
run: |
|
||||||
|
export GOROOT=/data/go/go
|
||||||
|
export PATH=$GOROOT/bin:$PATH
|
||||||
|
export GOCACHE=/data/gocache
|
||||||
|
export GOMODCACHE=/data/gomodcache
|
||||||
|
mkdir -p $GOCACHE $GOMODCACHE
|
||||||
|
|
||||||
|
if [ ! -x "$GOROOT/bin/go" ]; then
|
||||||
|
echo "Go not found in $GOROOT, downloading latest stable..."
|
||||||
|
|
||||||
|
GO_VERSION=$(curl -s https://go.dev/VERSION?m=text | head -n1)
|
||||||
|
echo "Latest version is $GO_VERSION"
|
||||||
|
|
||||||
|
mkdir -p /data/go
|
||||||
|
curl -sSL "https://go.dev/dl/${GO_VERSION}.linux-amd64.tar.gz" -o /tmp/go.tar.gz
|
||||||
|
tar -C /data/go -xzf /tmp/go.tar.gz
|
||||||
|
else
|
||||||
|
echo "Using cached Go from $GOROOT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
go version
|
||||||
|
|
||||||
|
- name: Download Go dependencies
|
||||||
|
run: |
|
||||||
|
export GOROOT=/data/go/go
|
||||||
|
export PATH=$GOROOT/bin:$PATH
|
||||||
|
export GOCACHE=/data/gocache
|
||||||
|
export GOMODCACHE=/data/gomodcache
|
||||||
|
mkdir -p $GOCACHE $GOMODCACHE
|
||||||
|
go mod download
|
||||||
|
|
||||||
|
- name: Build binary
|
||||||
|
run: |
|
||||||
|
export GOROOT=/data/go/go
|
||||||
|
export PATH=$GOROOT/bin:$PATH
|
||||||
|
export GOCACHE=/data/gocache
|
||||||
|
export GOMODCACHE=/data/gomodcache
|
||||||
|
mkdir -p $GOCACHE $GOMODCACHE
|
||||||
|
|
||||||
|
OUTPUT="${APP_NAME}"
|
||||||
|
if [ -n "${{ matrix.arm_version }}" ]; then
|
||||||
|
export GOARM=${{ matrix.arm_version }}
|
||||||
|
fi
|
||||||
|
|
||||||
|
OUTPUT="${OUTPUT}${{ matrix.ext }}"
|
||||||
|
echo "Building $OUTPUT"
|
||||||
|
GOOS=${{ matrix.os }} GOARCH=${{ matrix.arch }} go build -ldflags="-s -w" -trimpath -o "$OUTPUT"
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Create Debian Package
|
||||||
|
if: matrix.os == 'linux'
|
||||||
|
run: |
|
||||||
|
# 1. Setup Variables
|
||||||
|
VERSION=${GITHUB_REF_NAME#v} # Extracts 1.0.0 from v1.0.0
|
||||||
|
ARCH=${{ matrix.arch }}
|
||||||
|
if [ "$ARCH" == "arm" ]; then ARCH="armhf"; fi
|
||||||
|
|
||||||
|
PKG_NAME="slideshowapp"
|
||||||
|
BUILD_DIR="${PKG_NAME}_${VERSION}_${ARCH}"
|
||||||
|
|
||||||
|
# 2. Create Directory Structure
|
||||||
|
mkdir -p $BUILD_DIR/usr/bin
|
||||||
|
mkdir -p $BUILD_DIR/usr/share/$PKG_NAME
|
||||||
|
mkdir -p $BUILD_DIR/usr/share/$PKG_NAME/data
|
||||||
|
mkdir -p $BUILD_DIR/etc/systemd/system
|
||||||
|
mkdir -p $BUILD_DIR/DEBIAN
|
||||||
|
|
||||||
|
# 3. Copy Files
|
||||||
|
cp ${APP_NAME} $BUILD_DIR/usr/bin/$PKG_NAME
|
||||||
|
cp -r ./web $BUILD_DIR/usr/share/$PKG_NAME/
|
||||||
|
chmod +x $BUILD_DIR/usr/bin/$PKG_NAME
|
||||||
|
|
||||||
|
# 4. Handle .env (Copy as a .template so it doesn't overwrite existing ones)
|
||||||
|
if [ -f ".env" ]; then
|
||||||
|
cp .env $BUILD_DIR/usr/share/$PKG_NAME/.env.template
|
||||||
|
else
|
||||||
|
echo "PORT=8080" > $BUILD_DIR/usr/share/$PKG_NAME/.env.template
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 5. Create a Template Autostart File (Instead of Systemd)
|
||||||
|
mkdir -p $BUILD_DIR/usr/share/$PKG_NAME/setup
|
||||||
|
cat <<'EOF' > $BUILD_DIR/usr/share/$PKG_NAME/setup/$PKG_NAME.desktop
|
||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Slideshow App
|
||||||
|
Exec=sh -c 'i=0; while [ $i -lt 30 ]; do if [ "$(ls -A /media/$USER 2>/dev/null)" ] && ping -c 1 -W 1 8.8.8.8 >/dev/null 2>&1; then break; fi; i=$((i+1)); sleep 1; done; cd /usr/share/slideshowapp && /usr/bin/slideshowapp'
|
||||||
|
Terminal=false
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# 6. Create Control File
|
||||||
|
cat <<EOF > $BUILD_DIR/DEBIAN/control
|
||||||
|
Package: $PKG_NAME
|
||||||
|
Version: $VERSION
|
||||||
|
Section: utils
|
||||||
|
Priority: optional
|
||||||
|
Architecture: $ARCH
|
||||||
|
Maintainer: Adrian Zuercher <zuercher@tecamino.ch>
|
||||||
|
Description: Slideshow Application
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# 7. Add post-install script for Autostart and Permissions
|
||||||
|
cat <<'EOF' > $BUILD_DIR/DEBIAN/postinst
|
||||||
|
#!/bin/sh
|
||||||
|
set -e # Exit on error
|
||||||
|
|
||||||
|
# 1. Detect the real user
|
||||||
|
# We use 'who' and 'awk' as a fallback because $SUDO_USER is sometimes empty in Gitea/CI environments
|
||||||
|
REAL_USER=${SUDO_USER:-$(who | awk '{print $1}' | head -n1)}
|
||||||
|
|
||||||
|
# If still empty, default to 'mst' or 'pi' (adjust to your primary user)
|
||||||
|
if [ -z "$REAL_USER" ] || [ "$REAL_USER" = "root" ]; then
|
||||||
|
REAL_USER="mst"
|
||||||
|
fi
|
||||||
|
|
||||||
|
USER_HOME=$(getent passwd "$REAL_USER" | cut -d: -f6)
|
||||||
|
|
||||||
|
echo "Setting permissions for /usr/share/slideshowapp..."
|
||||||
|
chown -R "$REAL_USER:$REAL_USER" /usr/share/slideshowapp
|
||||||
|
chmod -R 755 /usr/share/slideshowapp
|
||||||
|
|
||||||
|
echo "Post-install: Target user is $REAL_USER"
|
||||||
|
echo "Post-install: Target home is $USER_HOME"
|
||||||
|
|
||||||
|
# 2. Setup .env from template
|
||||||
|
if [ ! -f "/usr/share/slideshowapp/.env" ]; then
|
||||||
|
echo "Creating .env from template..."
|
||||||
|
cp /usr/share/slideshowapp/env.template /usr/share/slideshowapp/.env || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3. Setup Autostart
|
||||||
|
# We use -p to ensure parent directories exist and set ownership immediately
|
||||||
|
AUTOSTART_DIR="$USER_HOME/.config/autostart"
|
||||||
|
|
||||||
|
if [ -d "$USER_HOME" ]; then
|
||||||
|
echo "Creating autostart directory at $AUTOSTART_DIR"
|
||||||
|
mkdir -p "$AUTOSTART_DIR"
|
||||||
|
cp /usr/share/slideshowapp/setup/slideshowapp.desktop "$AUTOSTART_DIR/"
|
||||||
|
|
||||||
|
# Critical: Change ownership of the folder and the file
|
||||||
|
chown -R "$REAL_USER:$REAL_USER" "$USER_HOME/.config"
|
||||||
|
chmod 644 "$AUTOSTART_DIR/slideshowapp.desktop"
|
||||||
|
else
|
||||||
|
echo "ERROR: Home directory $USER_HOME not found. Autostart not configured."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4. Fix Chromium Profile Permissions
|
||||||
|
if [ -d "$USER_HOME/.config/chromium" ]; then
|
||||||
|
echo "Cleaning up Chromium locks for $REAL_USER..."
|
||||||
|
chown -R "$REAL_USER:$REAL_USER" "$USER_HOME/.config/chromium"
|
||||||
|
rm -f "$USER_HOME/.config/chromium/SingletonLock"
|
||||||
|
rm -f "$USER_HOME/.config/chromium/SingletonCookie"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Installation complete."
|
||||||
|
EOF
|
||||||
|
chmod 555 $BUILD_DIR/DEBIAN/postinst
|
||||||
|
|
||||||
|
# 8. Build .deb
|
||||||
|
dpkg-deb --build $BUILD_DIR
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
# Upload for Windows (Binary + Web folder)
|
||||||
|
- name: Upload Windows Artifact
|
||||||
|
if: matrix.os == 'windows'
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: ${{ env.APP_NAME }}-windows
|
||||||
|
path: |
|
||||||
|
${{ env.APP_NAME }}.exe
|
||||||
|
./web
|
||||||
|
|
||||||
|
# Upload for Linux (Binary + .deb)
|
||||||
|
- name: Upload Linux Artifact
|
||||||
|
if: matrix.os == 'linux'
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: ${{ env.APP_NAME }}-linux-${{ matrix.arch }}
|
||||||
|
path: |
|
||||||
|
${{ env.APP_NAME }}
|
||||||
|
*.deb
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,2 +1,4 @@
|
|||||||
images/
|
images/
|
||||||
slideshow_app
|
slideshowApp
|
||||||
|
schedule.json
|
||||||
|
*.log
|
||||||
5
env/enviroment.go
vendored
5
env/enviroment.go
vendored
@@ -13,6 +13,7 @@ const (
|
|||||||
Host EnvKey = "HOST"
|
Host EnvKey = "HOST"
|
||||||
Port EnvKey = "PORT"
|
Port EnvKey = "PORT"
|
||||||
IntervalDefault EnvKey = "INTERVAL_DEFAULT"
|
IntervalDefault EnvKey = "INTERVAL_DEFAULT"
|
||||||
|
LogPath EnvKey = "LOG_PATH"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EnvKey string
|
type EnvKey string
|
||||||
@@ -28,6 +29,10 @@ func (key EnvKey) GetValue() string {
|
|||||||
return os.Getenv(string(key))
|
return os.Getenv(string(key))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (key EnvKey) SetValue(value string) {
|
||||||
|
os.Setenv(string(key), value)
|
||||||
|
}
|
||||||
|
|
||||||
func (key EnvKey) GetBoolValue() bool {
|
func (key EnvKey) GetBoolValue() bool {
|
||||||
value := strings.ToLower(os.Getenv(string(key)))
|
value := strings.ToLower(os.Getenv(string(key)))
|
||||||
return value == "true" || value == "1"
|
return value == "true" || value == "1"
|
||||||
|
|||||||
7
go.mod
7
go.mod
@@ -3,7 +3,14 @@ module slideshowApp
|
|||||||
go 1.25.4
|
go 1.25.4
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
gitea.tecamino.com/paadi/tecamino-logger v1.0.1
|
||||||
github.com/gorilla/mux v1.8.1
|
github.com/gorilla/mux v1.8.1
|
||||||
github.com/gorilla/websocket v1.5.3
|
github.com/gorilla/websocket v1.5.3
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
)
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
go.uber.org/multierr v1.10.0 // indirect
|
||||||
|
go.uber.org/zap v1.27.0 // indirect
|
||||||
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||||
|
)
|
||||||
|
|||||||
18
go.sum
18
go.sum
@@ -1,6 +1,24 @@
|
|||||||
|
gitea.tecamino.com/paadi/tecamino-logger v1.0.1 h1:NCF/foyuf0wVKLkyy2y1FYvHo9pVaUuHc1GSU5bNVbc=
|
||||||
|
gitea.tecamino.com/paadi/tecamino-logger v1.0.1/go.mod h1:FkzRTldUBBOd/iy2upycArDftSZ5trbsX5Ira5OzJgM=
|
||||||
|
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/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
|
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/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
|
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||||
|
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||||
|
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||||
|
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||||
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||||
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ func DeleteHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// 2. Delete each file
|
// 2. Delete each file
|
||||||
for _, name := range filenames {
|
for _, name := range filenames {
|
||||||
fullPath := filepath.Join(uploadDir, filepath.Base(name)) // Base() for security
|
fullPath := filepath.Join(uploadDir, filepath.Base(name))
|
||||||
os.Remove(fullPath)
|
os.Remove(fullPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,32 +5,34 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"slideshowApp/env"
|
"slideshowApp/env"
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Helper to get the local network IP address
|
// Helper to get the local network IP address
|
||||||
func getLocalIP() string {
|
func GetLocalIP() string {
|
||||||
if env.Host.GetValue() != "0.0.0.0" && env.Host.GetValue() != "localhost" {
|
if env.Host.GetValue() != "0.0.0.0" && env.Host.GetValue() != "localhost" {
|
||||||
return env.Host.GetValue()
|
return env.Host.GetValue()
|
||||||
}
|
}
|
||||||
|
|
||||||
addrs, err := net.InterfaceAddrs()
|
if ip := getActiveIP(); ip != "" {
|
||||||
if err != nil {
|
return ip
|
||||||
return "localhost"
|
|
||||||
}
|
|
||||||
for _, address := range addrs {
|
|
||||||
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
|
||||||
if ipnet.IP.To4() != nil {
|
|
||||||
if env.Env.GetValue() == "development" && !strings.Contains(ipnet.IP.String(), "192.168") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return ipnet.IP.String()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return "localhost"
|
return "localhost"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getActiveIP() string {
|
||||||
|
conn, err := net.Dial("udp", "8.8.8.8:80")
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
addr := conn.LocalAddr()
|
||||||
|
if udpAddr, ok := addr.(*net.UDPAddr); ok {
|
||||||
|
return udpAddr.IP.String()
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func InfoHandler(w http.ResponseWriter, r *http.Request) {
|
func InfoHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
port := env.Port.GetValue()
|
port := env.Port.GetValue()
|
||||||
if port == "" {
|
if port == "" {
|
||||||
@@ -43,9 +45,9 @@ func InfoHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
data := map[string]string{
|
data := map[string]string{
|
||||||
"ip": getLocalIP(),
|
"ip": GetLocalIP(),
|
||||||
"port": port,
|
"port": port,
|
||||||
"speed": speed,
|
"speed": GetInterval(),
|
||||||
}
|
}
|
||||||
json.NewEncoder(w).Encode(data)
|
json.NewEncoder(w).Encode(data)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Schedule map[string]interface{}
|
|
||||||
|
|
||||||
func SaveSchedule(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var s Schedule
|
|
||||||
json.NewDecoder(r.Body).Decode(&s)
|
|
||||||
data, _ := json.Marshal(s)
|
|
||||||
os.WriteFile("schedule.json", data, 0644)
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetSchedule(w http.ResponseWriter, r *http.Request) {
|
|
||||||
data, err := os.ReadFile("schedule.json")
|
|
||||||
if err != nil {
|
|
||||||
json.NewEncoder(w).Encode(Schedule{})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Write(data)
|
|
||||||
}
|
|
||||||
81
handlers/settings.go
Normal file
81
handlers/settings.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"slideshowApp/env"
|
||||||
|
"slideshowApp/utils"
|
||||||
|
)
|
||||||
|
|
||||||
|
var settingsFile = "settings.json"
|
||||||
|
|
||||||
|
type Settings map[string]any
|
||||||
|
|
||||||
|
func SaveSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var s Settings
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&s); err != nil {
|
||||||
|
fmt.Println(12, err)
|
||||||
|
utils.SendJSONError(w, "Invalid input", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.MarshalIndent(s, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(13, err)
|
||||||
|
|
||||||
|
utils.SendJSONError(w, "Encoding failed", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = os.WriteFile(getFilePath(), data, 0644)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(14, err)
|
||||||
|
|
||||||
|
utils.SendJSONError(w, "write file failed", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
data, err := os.ReadFile(getFilePath())
|
||||||
|
if err != nil {
|
||||||
|
json.NewEncoder(w).Encode(Settings{"default_interval": GetInterval()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetInterval() string {
|
||||||
|
data, err := os.ReadFile(getFilePath())
|
||||||
|
if err != nil {
|
||||||
|
interval := env.IntervalDefault.GetValue()
|
||||||
|
if interval == "" {
|
||||||
|
interval = "10"
|
||||||
|
}
|
||||||
|
return interval
|
||||||
|
}
|
||||||
|
var settings Settings
|
||||||
|
err = json.Unmarshal(data, &settings)
|
||||||
|
if err != nil {
|
||||||
|
return "10"
|
||||||
|
}
|
||||||
|
|
||||||
|
if interval, ok := settings["default_interval"]; ok {
|
||||||
|
return interval.(string)
|
||||||
|
}
|
||||||
|
return "10"
|
||||||
|
}
|
||||||
|
|
||||||
|
func getFilePath() string {
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "linux":
|
||||||
|
return filepath.Join(".", "data", settingsFile)
|
||||||
|
default:
|
||||||
|
return settingsFile
|
||||||
|
}
|
||||||
|
}
|
||||||
37
main.go
37
main.go
@@ -7,7 +7,10 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"slideshowApp/env"
|
"slideshowApp/env"
|
||||||
"slideshowApp/handlers"
|
"slideshowApp/handlers"
|
||||||
|
"slideshowApp/utils"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.tecamino.com/paadi/tecamino-logger/logging"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,24 +20,38 @@ func main() {
|
|||||||
|
|
||||||
env.Load(".env")
|
env.Load(".env")
|
||||||
|
|
||||||
|
logConfig := logging.DefaultConfig()
|
||||||
|
logConfig.Debug = env.Env.GetValue() == "debug"
|
||||||
|
|
||||||
|
logger, err := logging.NewLogger(env.LogPath.GetValue(), logConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
r := mux.NewRouter()
|
r := mux.NewRouter()
|
||||||
|
|
||||||
uploadFolder := env.PhotoDir.GetValue()
|
uploadFolder := env.PhotoDir.GetValue()
|
||||||
|
logger.Debug("main", "uploadfolder: "+uploadFolder)
|
||||||
|
|
||||||
if _, err := os.Stat(uploadFolder); err != nil {
|
if _, err := os.Stat(uploadFolder); err != nil {
|
||||||
fmt.Println("upload folder for images not found: ", uploadFolder)
|
fmt.Println("upload folder for images not found: ", uploadFolder)
|
||||||
fmt.Println("use fallback")
|
logger.Error("main", "upload folder for images not found: "+uploadFolder)
|
||||||
|
fmt.Println("use fallback folder")
|
||||||
uploadFolder = "./images"
|
uploadFolder = "./images"
|
||||||
|
logger.Info("main", "use fallback uploadfolder: "+uploadFolder)
|
||||||
|
env.PhotoDir.SetValue(uploadFolder)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("upload folder for images: ", uploadFolder)
|
fmt.Println("upload folder for images: ", uploadFolder)
|
||||||
|
|
||||||
r.PathPrefix("/uploads/").Handler(http.StripPrefix("/uploads/", http.FileServer(http.Dir(uploadFolder))))
|
r.PathPrefix("/uploads/").Handler(http.StripPrefix("/uploads/", http.FileServer(http.Dir(uploadFolder))))
|
||||||
r.HandleFunc("/api/images", handlers.ListFilesHandler).Methods("GET")
|
r.HandleFunc("/api/images", handlers.ListFilesHandler).Methods("GET")
|
||||||
r.HandleFunc("/ws", handlers.Websocket)
|
r.HandleFunc("/ws", handlers.Websocket)
|
||||||
r.HandleFunc("/upload", handlers.UploadHandler).Methods("POST")
|
r.HandleFunc("/upload", handlers.UploadHandler).Methods("POST")
|
||||||
r.HandleFunc("/settings", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "settings.html") })
|
r.HandleFunc("/settings", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, staticFolder+"settings.html") })
|
||||||
r.HandleFunc("/api/save-schedule", handlers.SaveSchedule).Methods("POST")
|
r.HandleFunc("/api/save-settings", handlers.SaveSettings).Methods("POST")
|
||||||
r.HandleFunc("/api/get-schedule", handlers.GetSchedule).Methods("GET")
|
r.HandleFunc("/api/get-settings", handlers.GetSettings).Methods("GET")
|
||||||
|
|
||||||
r.HandleFunc("/api/delete", handlers.DeleteHandler).Methods("POST")
|
r.HandleFunc("/api/delete", handlers.DeleteHandler).Methods("POST")
|
||||||
r.HandleFunc("/manage", func(w http.ResponseWriter, r *http.Request) {
|
r.HandleFunc("/manage", func(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -54,6 +71,16 @@ func main() {
|
|||||||
host := env.Host.GetValue()
|
host := env.Host.GetValue()
|
||||||
port := env.Port.GetValue()
|
port := env.Port.GetValue()
|
||||||
url := fmt.Sprintf("%s:%s", host, port)
|
url := fmt.Sprintf("%s:%s", host, port)
|
||||||
|
go func() {
|
||||||
|
logger.Debug("main", "start go routine with a 3 second wait")
|
||||||
|
time.Sleep(3 * time.Second)
|
||||||
|
if err := utils.OpenBrowser(logger, fmt.Sprintf("%s:%s/slideshow", handlers.GetLocalIP(), port)); err != nil {
|
||||||
|
logger.Error("main", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
fmt.Println("Server running at", url)
|
fmt.Println("Server running at", url)
|
||||||
log.Fatal(http.ListenAndServe(url, r))
|
logger.Info("main", "Server running at: "+url)
|
||||||
|
if err := http.ListenAndServe(url, r); err != nil {
|
||||||
|
logger.Error("main", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
{"Friday_active":false,"Friday_end":"07:38","Friday_start":"07:00","Monday_active":false,"Monday_end":"22:00","Monday_start":"08:00","Saturday_active":false,"Saturday_end":"22:00","Saturday_start":"08:00","Sunday_active":false,"Sunday_end":"22:00","Sunday_start":"08:00","Thursday_active":false,"Thursday_end":"22:00","Thursday_start":"08:00","Tuesday_active":false,"Tuesday_end":"22:00","Tuesday_start":"08:00","Wednesday_active":false,"Wednesday_end":"22:00","Wednesday_start":"08:00"}
|
|
||||||
12
utils/http.go
Normal file
12
utils/http.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SendJSONError(w http.ResponseWriter, message string, code int) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(code)
|
||||||
|
json.NewEncoder(w).Encode(map[string]string{"error": message})
|
||||||
|
}
|
||||||
88
utils/utils.go
Normal file
88
utils/utils.go
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.tecamino.com/paadi/tecamino-logger/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
func OpenBrowser(logger *logging.Logger, url string) error {
|
||||||
|
var commands [][]string
|
||||||
|
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
logger.Debug("OpenBrowser", "os: windows")
|
||||||
|
commands = [][]string{
|
||||||
|
// Chrome (most common)
|
||||||
|
{`C:\Program Files\Google\Chrome\Application\chrome.exe`, "--kiosk", url},
|
||||||
|
{`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`, "--kiosk", url},
|
||||||
|
|
||||||
|
// Edge (default on modern Windows)
|
||||||
|
{`C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`, "--kiosk", url},
|
||||||
|
{`C:\Program Files\Microsoft\Edge\Application\msedge.exe`, "--kiosk", url},
|
||||||
|
|
||||||
|
// Firefox (no true kiosk, but fullscreen)
|
||||||
|
{`C:\Program Files\Mozilla Firefox\firefox.exe`, "--kiosk", url},
|
||||||
|
{`C:\Program Files (x86)\Mozilla Firefox\firefox.exe`, "--kiosk", url},
|
||||||
|
|
||||||
|
// System default browser (always works)
|
||||||
|
{"rundll32", "url.dll,FileProtocolHandler", url},
|
||||||
|
}
|
||||||
|
|
||||||
|
case "darwin":
|
||||||
|
logger.Debug("OpenBrowser", "os: windows")
|
||||||
|
commands = [][]string{
|
||||||
|
// Chrome
|
||||||
|
{"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "--kiosk", url},
|
||||||
|
|
||||||
|
// Edge
|
||||||
|
{"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "--kiosk", url},
|
||||||
|
|
||||||
|
// Firefox
|
||||||
|
{"/Applications/Firefox.app/Contents/MacOS/firefox", "--kiosk", url},
|
||||||
|
|
||||||
|
// Safari (no kiosk flag, opens normally)
|
||||||
|
{"open", "-a", "Safari", url},
|
||||||
|
|
||||||
|
// System default browser
|
||||||
|
{"open", url},
|
||||||
|
}
|
||||||
|
|
||||||
|
default: // Linux
|
||||||
|
logger.Debug("OpenBrowser", "os: linux")
|
||||||
|
if os.Getenv("DISPLAY") == "" &&
|
||||||
|
os.Getenv("WAYLAND_DISPLAY") == "" &&
|
||||||
|
os.Getenv("XDG_SESSION_TYPE") != "wayland" {
|
||||||
|
return fmt.Errorf("os is running in headless mode; do not start browser")
|
||||||
|
}
|
||||||
|
|
||||||
|
commands = [][]string{
|
||||||
|
// Chromium / Chrome
|
||||||
|
{"chromium-browser", "--kiosk", url},
|
||||||
|
{"chromium", "--kiosk", url},
|
||||||
|
{"google-chrome", "--kiosk", url},
|
||||||
|
|
||||||
|
// Firefox
|
||||||
|
{"firefox", "--kiosk", url},
|
||||||
|
|
||||||
|
// System default browser (best universal fallback)
|
||||||
|
{"xdg-open", url},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, cmd := range commands {
|
||||||
|
execCmd := exec.Command(cmd[0], cmd[1:]...)
|
||||||
|
if err := execCmd.Start(); err == nil {
|
||||||
|
logger.Debug("OpenBrowser", "browser started with command: "+strings.Join(cmd, ", "))
|
||||||
|
return nil
|
||||||
|
} else {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("could not open browser")
|
||||||
|
}
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
|
|
||||||
<button id="shuffleBtn" onclick="toggleShuffle()" class="text-xs uppercase font-bold text-gray-400 hover:text-white transition-colors flex items-center gap-2">
|
<button id="shuffleBtn" onclick="toggleShuffle()" class="text-xs uppercase font-bold text-gray-400 hover:text-white transition-colors flex items-center gap-2">
|
||||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
|
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
|
||||||
Shuffle: <span id="shuffleStatus">OFF</span>
|
Shuffle: <span id="shuffleStatus">ON</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button onclick="toggleFullScreen()" class="text-sm hover:text-blue-400 transition-colors">Full Screen</button>
|
<button onclick="toggleFullScreen()" class="text-sm hover:text-blue-400 transition-colors">Full Screen</button>
|
||||||
@@ -58,6 +58,18 @@
|
|||||||
const speedInput = document.getElementById('speed');
|
const speedInput = document.getElementById('speed');
|
||||||
const shuffleStatus = document.getElementById('shuffleStatus');
|
const shuffleStatus = document.getElementById('shuffleStatus');
|
||||||
|
|
||||||
|
async function initializeSlideshow() {
|
||||||
|
// 1. Get the default interval from API
|
||||||
|
const defaultInterval = await checkDefaultInterval();
|
||||||
|
speedInput.value = defaultInterval;
|
||||||
|
|
||||||
|
// 2. Setup QR Code
|
||||||
|
setupQRCode();
|
||||||
|
|
||||||
|
// 3. Load Images (which eventually calls start())
|
||||||
|
loadImages();
|
||||||
|
}
|
||||||
|
|
||||||
// Fisher-Yates Shuffle Algorithm
|
// Fisher-Yates Shuffle Algorithm
|
||||||
function shuffleArray(array) {
|
function shuffleArray(array) {
|
||||||
for (let i = array.length - 1; i > 0; i--) {
|
for (let i = array.length - 1; i > 0; i--) {
|
||||||
@@ -75,10 +87,23 @@
|
|||||||
index = 0;
|
index = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkSchedule() {
|
async function checkDefaultInterval() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/get-schedule');
|
const res = await fetch('/api/get-settings');
|
||||||
const schedule = await res.json();
|
const settings = await res.json();
|
||||||
|
|
||||||
|
// Return the saved interval, or fallback to 10 if it's missing
|
||||||
|
return settings.default_interval || "120";
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to fetch default interval:", err);
|
||||||
|
return "120";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkSettings() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/get-settings');
|
||||||
|
const settings = await res.json();
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const day = now.toLocaleDateString('en-US', { weekday: 'long' });
|
const day = now.toLocaleDateString('en-US', { weekday: 'long' });
|
||||||
@@ -86,9 +111,9 @@
|
|||||||
const currentTime = now.getHours().toString().padStart(2, '0') + ":" +
|
const currentTime = now.getHours().toString().padStart(2, '0') + ":" +
|
||||||
now.getMinutes().toString().padStart(2, '0');
|
now.getMinutes().toString().padStart(2, '0');
|
||||||
|
|
||||||
const isActive = schedule[day + "_active"];
|
const isActive = settings[day + "_active"];
|
||||||
const start = schedule[day + "_start"];
|
const start = settings[day + "_start"];
|
||||||
const end = schedule[day + "_end"];
|
const end = settings[day + "_end"];
|
||||||
|
|
||||||
// Check if we should be "OFF"
|
// Check if we should be "OFF"
|
||||||
if (isActive && (currentTime < start || currentTime > end)) {
|
if (isActive && (currentTime < start || currentTime > end)) {
|
||||||
@@ -131,7 +156,7 @@
|
|||||||
async function showNext() {
|
async function showNext() {
|
||||||
if (playlist.length === 0) return;
|
if (playlist.length === 0) return;
|
||||||
|
|
||||||
const isRunning = await checkSchedule();
|
const isRunning = await checkSettings();
|
||||||
if (!isRunning) return;
|
if (!isRunning) return;
|
||||||
|
|
||||||
viewer.classList.replace('fade-in', 'fade-out');
|
viewer.classList.replace('fade-in', 'fade-out');
|
||||||
@@ -193,6 +218,7 @@
|
|||||||
const res = await fetch('/api/info');
|
const res = await fetch('/api/info');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const uploadUrl = `http://${data.ip}:${data.port}/`;
|
const uploadUrl = `http://${data.ip}:${data.port}/`;
|
||||||
|
|
||||||
new QRCode(document.getElementById("qrcode"), {
|
new QRCode(document.getElementById("qrcode"), {
|
||||||
text: uploadUrl,
|
text: uploadUrl,
|
||||||
width: 128,
|
width: 128,
|
||||||
@@ -204,8 +230,7 @@
|
|||||||
speedInput.addEventListener('change', start);
|
speedInput.addEventListener('change', start);
|
||||||
|
|
||||||
// Initial setup
|
// Initial setup
|
||||||
setupQRCode();
|
initializeSlideshow();
|
||||||
loadImages();
|
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -8,24 +8,41 @@
|
|||||||
<body class="bg-gray-50 min-h-screen p-6">
|
<body class="bg-gray-50 min-h-screen p-6">
|
||||||
<div class="max-w-2xl mx-auto bg-white rounded-xl shadow-lg p-8 border border-gray-100">
|
<div class="max-w-2xl mx-auto bg-white rounded-xl shadow-lg p-8 border border-gray-100">
|
||||||
<div class="flex justify-between items-center mb-8">
|
<div class="flex justify-between items-center mb-8">
|
||||||
<h1 class="text-2xl font-bold text-gray-800">Weekly Scheduler</h1>
|
<h1 class="text-2xl font-bold text-gray-800">Slideshow Settings</h1>
|
||||||
<a href="/" class="text-blue-600 hover:underline text-sm">Back</a>
|
<a href="/" class="text-blue-600 hover:underline text-sm">Back</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form id="scheduleForm" class="space-y-4">
|
<form id="scheduleForm" class="space-y-8">
|
||||||
<table class="w-full text-left">
|
<div class="space-y-4">
|
||||||
<thead>
|
<h2 class="text-sm font-semibold text-gray-400 uppercase tracking-wider">General Settings</h2>
|
||||||
<tr class="text-gray-400 text-xs uppercase">
|
<div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg border border-gray-100">
|
||||||
<th class="pb-4">Day</th>
|
<label class="text-gray-700 font-medium">Default Interval (seconds)</label>
|
||||||
<th class="pb-4">Enabled</th>
|
<input type="number" name="default_interval" min="1" value="10"
|
||||||
<th class="pb-4">Start Time</th>
|
class="w-24 bg-white border rounded-md p-2 text-center focus:ring-2 focus:ring-blue-500 outline-none">
|
||||||
<th class="pb-4">End Time</th>
|
</div>
|
||||||
</tr>
|
</div>
|
||||||
</thead>
|
|
||||||
<tbody class="text-gray-600 italic text-sm">
|
<hr class="border-gray-100">
|
||||||
</tbody>
|
|
||||||
</table>
|
<div class="space-y-4">
|
||||||
<button type="submit" class="w-full bg-blue-600 text-white py-3 rounded-lg font-bold shadow-md hover:bg-blue-700 transition">Save Schedule</button>
|
<h2 class="text-sm font-semibold text-gray-400 uppercase tracking-wider">Weekly Scheduler</h2>
|
||||||
|
<table class="w-full text-left">
|
||||||
|
<thead>
|
||||||
|
<tr class="text-gray-400 text-xs uppercase">
|
||||||
|
<th class="pb-4">Day</th>
|
||||||
|
<th class="pb-4">Enabled</th>
|
||||||
|
<th class="pb-4">Start Time</th>
|
||||||
|
<th class="pb-4">End Time</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="text-gray-600 italic text-sm">
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="w-full bg-blue-600 text-white py-3 rounded-lg font-bold shadow-md hover:bg-blue-700 transition">
|
||||||
|
Save All Settings
|
||||||
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -47,32 +64,57 @@
|
|||||||
|
|
||||||
// Load existing settings
|
// Load existing settings
|
||||||
async function loadSettings() {
|
async function loadSettings() {
|
||||||
const res = await fetch('/api/get-schedule');
|
try {
|
||||||
const data = await res.json();
|
const res = await fetch('/api/get-settings');
|
||||||
Object.keys(data).forEach(key => {
|
const data = await res.json();
|
||||||
const el = document.querySelector(`[name="${key}"]`);
|
|
||||||
if(el.type === 'checkbox') el.checked = data[key];
|
Object.keys(data).forEach(key => {
|
||||||
else el.value = data[key];
|
const el = document.querySelector(`[name="${key}"]`);
|
||||||
});
|
if (el) {
|
||||||
|
if (el.type === 'checkbox') el.checked = data[key];
|
||||||
|
else el.value = data[key];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to load settings:", err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('scheduleForm').onsubmit = async (e) => {
|
document.getElementById('scheduleForm').onsubmit = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const formData = new FormData(e.target);
|
const formData = new FormData(e.target);
|
||||||
const obj = {};
|
const obj = {};
|
||||||
formData.forEach((value, key) => {
|
|
||||||
// Handle checkbox value manually
|
|
||||||
if (key.includes('_active')) obj[key] = true;
|
|
||||||
else obj[key] = value;
|
|
||||||
});
|
|
||||||
// Ensure unchecked boxes are false
|
|
||||||
days.forEach(day => { if(!obj[day+'_active']) obj[day+'_active'] = false; });
|
|
||||||
|
|
||||||
await fetch('/api/save-schedule', {
|
formData.forEach((value, key) => {
|
||||||
|
// Convert number fields to integers
|
||||||
|
if (key === 'default_interval') {
|
||||||
|
obj[key] = parseInt(value);
|
||||||
|
}
|
||||||
|
// Handle checkbox presence
|
||||||
|
else if (key.includes('_active')) {
|
||||||
|
obj[key] = true;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
obj[key] = value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ensure unchecked boxes are sent as false
|
||||||
|
days.forEach(day => {
|
||||||
|
if (!obj[day + '_active']) obj[day + '_active'] = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await fetch('/api/save-settings', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(obj)
|
body: JSON.stringify(obj)
|
||||||
});
|
});
|
||||||
alert("Schedule Saved!");
|
|
||||||
|
if (res.ok) {
|
||||||
|
alert("Settings Saved Successfully!");
|
||||||
|
} else {
|
||||||
|
alert("Error saving settings.");
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
loadSettings();
|
loadSettings();
|
||||||
|
|||||||
Reference in New Issue
Block a user