first commit

This commit is contained in:
Adrian Zürcher
2026-01-16 07:51:28 +01:00
commit 4d9e0836e5
15 changed files with 764 additions and 0 deletions

5
.env Normal file
View File

@@ -0,0 +1,5 @@
ENV= #empty|development
PHOTO_DIR=images
HOST=0.0.0.0
PORT=8080
INTERVAL_DEFAULT=120

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
images/
slideshow_app

34
env/enviroment.go vendored Normal file
View File

@@ -0,0 +1,34 @@
package env
import (
"os"
"strings"
"github.com/joho/godotenv"
)
const (
Env EnvKey = "ENV"
PhotoDir EnvKey = "PHOTO_DIR"
Host EnvKey = "HOST"
Port EnvKey = "PORT"
IntervalDefault EnvKey = "INTERVAL_DEFAULT"
)
type EnvKey string
func Load(path string) error {
if path == "" {
path = ".env"
}
return godotenv.Load(path)
}
func (key EnvKey) GetValue() string {
return os.Getenv(string(key))
}
func (key EnvKey) GetBoolValue() bool {
value := strings.ToLower(os.Getenv(string(key)))
return value == "true" || value == "1"
}

211
frame.html Normal file
View File

@@ -0,0 +1,211 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Photo Frame</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body, html { margin: 0; background: black; height: 100%; overflow: hidden; }
#viewer {
width: 100vw;
height: 100vh;
object-fit: contain;
transition: opacity 0.8s ease-in-out;
}
.fade-out { opacity: 0; }
.fade-in { opacity: 1; }
.hide-mouse { cursor: none; }
</style>
</head>
<body class="flex items-center justify-center hide-mouse">
<img id="viewer" src="" class="fade-out">
<div id="ui" class="fixed bottom-6 left-1/2 -translate-x-1/2 flex items-center gap-4 bg-black/70 backdrop-blur-md text-white px-6 py-3 rounded-2xl border border-white/10 opacity-0 transition-opacity duration-300 hover:opacity-100">
<div class="flex items-center gap-2">
<span class="text-xs uppercase font-bold text-gray-400">Interval:</span>
<input type="number" id="speed" value="5" min="1"
class="bg-white/10 border border-white/20 rounded px-2 py-1 w-14 text-center focus:outline-none focus:ring-2 focus:ring-blue-500 text-white">
<span class="text-xs text-gray-400">s</span>
</div>
<div class="h-4 w-[1px] bg-white/20"></div>
<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>
Shuffle: <span id="shuffleStatus">OFF</span>
</button>
<button onclick="toggleFullScreen()" class="text-sm hover:text-blue-400 transition-colors">Full Screen</button>
<a href="/" class="text-sm bg-blue-600 hover:bg-blue-500 px-4 py-1.5 rounded-lg transition-colors">Back</a>
</div>
<div id="qr-container" class="fixed top-6 right-6 p-3 bg-white rounded-xl shadow-2xl opacity-0 transition-opacity duration-300">
<div id="qrcode"></div>
<p class="text-black text-[10px] font-bold text-center mt-2 uppercase tracking-tighter">Scan to Upload</p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
let images = [];
let playlist = [];
let index = 0;
let timer;
let isShuffle = true;
const viewer = document.getElementById('viewer');
const speedInput = document.getElementById('speed');
const shuffleStatus = document.getElementById('shuffleStatus');
// Fisher-Yates Shuffle Algorithm
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function rebuildPlaylist() {
if (images.length === 0) return;
playlist = [...images];
if (isShuffle) {
shuffleArray(playlist);
}
index = 0;
}
async function checkSchedule() {
try {
const res = await fetch('/api/get-schedule');
const schedule = await res.json();
const now = new Date();
const day = now.toLocaleDateString('en-US', { weekday: 'long' });
// Format current time as HH:MM
const currentTime = now.getHours().toString().padStart(2, '0') + ":" +
now.getMinutes().toString().padStart(2, '0');
const isActive = schedule[day + "_active"];
const start = schedule[day + "_start"];
const end = schedule[day + "_end"];
// Check if we should be "OFF"
if (isActive && (currentTime < start || currentTime > end)) {
viewer.classList.add('hidden'); // Hide image
document.body.style.backgroundColor = "black";
return false; // Tells the slideshow to skip this turn
} else {
viewer.classList.remove('hidden');
return true; // Everything is fine
}
} catch (err) {
return true; // If API fails, show photos anyway
}
}
function toggleShuffle() {
isShuffle = !isShuffle;
shuffleStatus.textContent = isShuffle ? "ON" : "OFF";
shuffleStatus.parentElement.classList.toggle('text-blue-400', isShuffle);
rebuildPlaylist();
}
async function loadImages() {
try {
const res = await fetch('/api/images');
const newList = await res.json();
if (JSON.stringify(images) !== JSON.stringify(newList)) {
images = newList;
rebuildPlaylist();
if (images.length > 0 && !timer) {
start();
}
}
} catch (err) {
console.error("Failed to fetch image list:", err);
}
}
async function showNext() {
if (playlist.length === 0) return;
const isRunning = await checkSchedule();
if (!isRunning) return;
viewer.classList.replace('fade-in', 'fade-out');
setTimeout(() => {
viewer.src = "/uploads/" + playlist[index];
index++;
if (index >= playlist.length) {
rebuildPlaylist();
}
viewer.onload = () => {
viewer.classList.replace('fade-out', 'fade-in');
};
}, 800);
}
function start() {
clearInterval(timer);
showNext();
const ms = Math.max(speedInput.value, 1) * 1000;
timer = setInterval(showNext, ms);
}
// WebSocket Logic
const socket = new WebSocket("ws://" + window.location.host + "/ws");
socket.onmessage = (event) => {
if (event.data === "refresh") {
loadImages();
}
};
// UI Helpers
function toggleFullScreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
}
let mouseTimer;
document.addEventListener('mousemove', () => {
document.body.classList.remove('hide-mouse');
document.getElementById('ui').classList.add('opacity-100');
document.getElementById('qr-container').classList.add('opacity-100');
clearTimeout(mouseTimer);
mouseTimer = setTimeout(() => {
document.body.classList.add('hide-mouse');
document.getElementById('ui').classList.remove('opacity-100');
document.getElementById('qr-container').classList.remove('opacity-100');
}, 3000);
});
async function setupQRCode() {
try {
const res = await fetch('/api/info');
const data = await res.json();
const uploadUrl = `http://${data.ip}:${data.port}/`;
new QRCode(document.getElementById("qrcode"), {
text: uploadUrl,
width: 128,
height: 128
});
} catch (err) {}
}
speedInput.addEventListener('change', start);
// Initial setup
setupQRCode();
loadImages();
</script>
</body>
</html>

9
go.mod Normal file
View File

@@ -0,0 +1,9 @@
module slideshowApp
go 1.25.4
require (
github.com/gorilla/mux v1.8.1
github.com/gorilla/websocket v1.5.3
github.com/joho/godotenv v1.5.1
)

6
go.sum Normal file
View File

@@ -0,0 +1,6 @@
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
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/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=

96
handlers/files.go Normal file
View File

@@ -0,0 +1,96 @@
package handlers
import (
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"slideshowApp/env"
"sync"
"github.com/gorilla/websocket"
)
var (
// Keep track of all open slideshow connections
clients = make(map[*websocket.Conn]bool)
clientsMu sync.Mutex
)
func UploadHandler(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(50 << 20)
files := r.MultipartForm.File["myPictures"]
uploadDir := env.PhotoDir.GetValue()
os.MkdirAll(uploadDir, os.ModePerm)
for _, fileHeader := range files {
file, _ := fileHeader.Open()
dstPath := filepath.Join(uploadDir, fileHeader.Filename)
dst, _ := os.Create(dstPath)
io.Copy(dst, file)
file.Close()
dst.Close()
}
// NEW: Tell all slideshows to update their lists
notifyClients()
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func ListFilesHandler(w http.ResponseWriter, r *http.Request) {
files, err := os.ReadDir(env.PhotoDir.GetValue())
if err != nil {
http.Error(w, "Unable to read directory", http.StatusInternalServerError)
return
}
var fileNames []string
for _, file := range files {
if !file.IsDir() {
fileNames = append(fileNames, file.Name())
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(fileNames)
}
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 1. Get filenames from request body
var filenames []string
err := json.NewDecoder(r.Body).Decode(&filenames)
if err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
uploadDir := env.PhotoDir.GetValue()
// 2. Delete each file
for _, name := range filenames {
fullPath := filepath.Join(uploadDir, filepath.Base(name)) // Base() for security
os.Remove(fullPath)
}
// 3. Notify slideshows to refresh their lists
notifyClients()
w.WriteHeader(http.StatusOK)
}
func notifyClients() {
clientsMu.Lock()
defer clientsMu.Unlock()
for client := range clients {
err := client.WriteMessage(websocket.TextMessage, []byte("refresh"))
if err != nil {
client.Close()
delete(clients, client)
}
}
}

51
handlers/infos.go Normal file
View File

@@ -0,0 +1,51 @@
package handlers
import (
"encoding/json"
"net"
"net/http"
"slideshowApp/env"
"strings"
)
// Helper to get the local network IP address
func getLocalIP() string {
if env.Host.GetValue() != "0.0.0.0" && env.Host.GetValue() != "localhost" {
return env.Host.GetValue()
}
addrs, err := net.InterfaceAddrs()
if err != nil {
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"
}
func InfoHandler(w http.ResponseWriter, r *http.Request) {
port := env.Port.GetValue()
if port == "" {
port = "8080"
}
speed := env.IntervalDefault.GetValue()
if speed == "" {
speed = "10"
}
data := map[string]string{
"ip": getLocalIP(),
"port": port,
"speed": speed,
}
json.NewEncoder(w).Encode(data)
}

26
handlers/scheduler.go Normal file
View File

@@ -0,0 +1,26 @@
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)
}

23
handlers/websocket.go Normal file
View File

@@ -0,0 +1,23 @@
package handlers
import (
"net/http"
"github.com/gorilla/websocket"
)
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
)
func Websocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
clientsMu.Lock()
clients[conn] = true
clientsMu.Unlock()
}

74
index.html Normal file
View File

@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Go File Center</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen flex items-center justify-center p-6">
<div class="max-w-md w-full bg-white rounded-xl shadow-lg p-8 border border-gray-100">
<a href="/settings" class="absolute top-6 right-6 text-gray-400 hover:text-blue-600 transition-colors">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</a>
<div class="text-center mb-8">
<h1 class="text-2xl font-bold text-gray-800">Photo Upload</h1>
<p class="text-gray-500 text-sm">Upload multiple PNG or JPG files</p>
</div>
<form action="/upload" method="POST" enctype="multipart/form-data" class="space-y-6">
<div class="relative border-2 border-dashed border-blue-200 rounded-lg p-6 hover:border-blue-400 transition-colors group">
<input type="file" name="myPictures" multiple accept="image/*"
class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
id="fileInput" onchange="updateFileList()">
<div class="text-center pointer-events-none">
<svg class="mx-auto h-12 w-12 text-blue-400 group-hover:scale-110 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<p class="mt-2 text-sm text-gray-600">Click to select or drag and drop</p>
</div>
</div>
<ul id="fileList" class="text-xs text-gray-500 space-y-1 max-h-32 overflow-y-auto"></ul>
<button type="submit"
class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-4 rounded-lg transition-all shadow-md active:scale-95">
Upload All Files
</button>
<div class="mt-4 text-center">
<a href="/manage" class="text-gray-400 hover:text-gray-600 text-xs transition-colors">
Manage Existing Files
</a>
</div>
</form>
<div class="mt-8 pt-6 border-t border-gray-100 text-center">
<a href="/slideshow" class="inline-flex items-center gap-2 text-blue-600 hover:text-blue-800 font-medium text-sm transition-colors">
<span>Open Fullscreen Slideshow</span>
<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="M13 7l5 5m0 0l-5 5m5-5H6" /></svg>
</a>
</div>
</div>
<script>
function updateFileList() {
const input = document.getElementById('fileInput');
const list = document.getElementById('fileList');
list.innerHTML = '';
for (let i = 0; i < input.files.length; i++) {
const li = document.createElement('li');
li.className = "flex items-center gap-2 bg-gray-50 p-1 px-2 rounded";
li.textContent = `📄 ${input.files[i].name}`;
list.appendChild(li);
}
}
</script>
</body>
</html>

58
main.go Normal file
View File

@@ -0,0 +1,58 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"slideshowApp/env"
"slideshowApp/handlers"
"github.com/gorilla/mux"
)
func main() {
env.Load(".env")
r := mux.NewRouter()
uploadFolder := env.PhotoDir.GetValue()
if _, err := os.Stat(uploadFolder); err != nil {
fmt.Println("upload folder for images not found: ", uploadFolder)
fmt.Println("use fallback")
uploadFolder = "./images"
}
fmt.Println("upload folder for images: ", uploadFolder)
r.PathPrefix("/uploads/").Handler(http.StripPrefix("/uploads/", http.FileServer(http.Dir(uploadFolder))))
r.HandleFunc("/api/images", handlers.ListFilesHandler).Methods("GET")
r.HandleFunc("/ws", handlers.Websocket)
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("/api/save-schedule", handlers.SaveSchedule).Methods("POST")
r.HandleFunc("/api/get-schedule", handlers.GetSchedule).Methods("GET")
r.HandleFunc("/api/delete", handlers.DeleteHandler).Methods("POST")
r.HandleFunc("/manage", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "manage.html")
})
r.HandleFunc("/api/info", handlers.InfoHandler).Methods("GET")
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
// We add a route for the slideshow page specifically
r.HandleFunc("/slideshow", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "frame.html")
})
host := env.Host.GetValue()
port := env.Port.GetValue()
url := fmt.Sprintf("%s:%s", host, port)
fmt.Println("Server running at", url)
log.Fatal(http.ListenAndServe(url, r))
}

87
manage.html Normal file
View File

@@ -0,0 +1,87 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Files</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<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="flex justify-between items-center mb-8">
<div>
<h1 class="text-2xl font-bold text-gray-800">Gallery Manager</h1>
<p class="text-gray-500 text-sm">Select files to remove from the slideshow</p>
</div>
<a href="/" class="text-sm text-blue-600 hover:underline">← Back to Upload</a>
</div>
<div class="flex items-center justify-between bg-gray-50 p-4 rounded-t-lg border-b border-gray-200">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" id="selectAll" onclick="toggleAll(this)" class="w-4 h-4 rounded text-blue-600">
<span class="text-sm font-medium text-gray-700">Select All</span>
</label>
<button onclick="deleteSelected()" class="bg-red-500 hover:bg-red-600 text-white text-xs font-bold py-2 px-4 rounded-lg transition-all shadow-sm">
Delete Selected
</button>
</div>
<div id="fileContainer" class="border border-gray-200 border-t-0 rounded-b-lg max-h-[500px] overflow-y-auto">
<div class="p-8 text-center text-gray-400">Loading files...</div>
</div>
</div>
<script>
async function fetchFiles() {
const res = await fetch('/api/images');
const files = await res.json();
const container = document.getElementById('fileContainer');
container.innerHTML = '';
if (files.length === 0) {
container.innerHTML = '<div class="p-8 text-center text-gray-400">No images found.</div>';
return;
}
files.forEach(file => {
const div = document.createElement('div');
div.className = "flex items-center gap-4 p-4 border-b border-gray-100 hover:bg-gray-50 transition-colors";
div.innerHTML = `
<input type="checkbox" name="fileCheck" value="${file}" class="file-checkbox w-4 h-4 rounded text-blue-600">
<img src="/uploads/${file}" class="w-12 h-12 object-cover rounded shadow-sm">
<span class="text-sm text-gray-700 truncate flex-1">${file}</span>
`;
container.appendChild(div);
});
}
function toggleAll(source) {
checkboxes = document.getElementsByClassName('file-checkbox');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
async function deleteSelected() {
const checked = document.querySelectorAll('.file-checkbox:checked');
const filesToDelete = Array.from(checked).map(cb => cb.value);
if (filesToDelete.length === 0) return alert("Select files first!");
if (!confirm(`Delete ${filesToDelete.length} files?`)) return;
const res = await fetch('/api/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(filesToDelete)
});
if (res.ok) {
fetchFiles(); // Refresh list
document.getElementById('selectAll').checked = false;
}
}
fetchFiles();
</script>
</body>
</html>

1
schedule.json Normal file
View File

@@ -0,0 +1 @@
{"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"}

81
settings.html Normal file
View File

@@ -0,0 +1,81 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sheduler Settings</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<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="flex justify-between items-center mb-8">
<h1 class="text-2xl font-bold text-gray-800">Weekly Scheduler</h1>
<a href="/" class="text-blue-600 hover:underline text-sm">Back</a>
</div>
<form id="scheduleForm" class="space-y-4">
<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>
<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>
</form>
</div>
<script>
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const tbody = document.querySelector('tbody');
// Generate Table Rows
days.forEach(day => {
tbody.innerHTML += `
<tr class="border-t border-gray-50">
<td class="py-4 font-bold text-gray-700 not-italic">${day}</td>
<td><input type="checkbox" name="${day}_active" class="rounded text-blue-600"></td>
<td><input type="time" name="${day}_start" value="08:00" class="bg-gray-50 border rounded p-1"></td>
<td><input type="time" name="${day}_end" value="22:00" class="bg-gray-50 border rounded p-1"></td>
</tr>
`;
});
// Load existing settings
async function loadSettings() {
const res = await fetch('/api/get-schedule');
const data = await res.json();
Object.keys(data).forEach(key => {
const el = document.querySelector(`[name="${key}"]`);
if(el.type === 'checkbox') el.checked = data[key];
else el.value = data[key];
});
}
document.getElementById('scheduleForm').onsubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
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', {
method: 'POST',
body: JSON.stringify(obj)
});
alert("Schedule Saved!");
};
loadSettings();
</script>
</body>
</html>