Compare commits
No commits in common. "main" and "v0.0.2" have entirely different histories.
24 changed files with 209 additions and 555 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -1,3 +1 @@
|
||||||
GoTomato
|
GoTomato
|
||||||
|
|
||||||
dist/
|
|
||||||
|
|
|
@ -1,43 +0,0 @@
|
||||||
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
|
|
||||||
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
|
|
||||||
|
|
||||||
version: 2
|
|
||||||
|
|
||||||
before:
|
|
||||||
hooks:
|
|
||||||
- go mod tidy
|
|
||||||
|
|
||||||
builds:
|
|
||||||
- goos:
|
|
||||||
- linux
|
|
||||||
goarch:
|
|
||||||
- amd64
|
|
||||||
- arm64
|
|
||||||
env:
|
|
||||||
- CGO_ENABLED=0
|
|
||||||
ldflags:
|
|
||||||
- -s -w -X {{.ModulePath}}/internal/metadata.GoTomatoVersion={{.Version}}
|
|
||||||
|
|
||||||
upx:
|
|
||||||
- enabled: true
|
|
||||||
compress: best
|
|
||||||
lzma: true
|
|
||||||
|
|
||||||
changelog:
|
|
||||||
use: gitea
|
|
||||||
filters:
|
|
||||||
exclude:
|
|
||||||
- "chore: bump version to"
|
|
||||||
|
|
||||||
archives:
|
|
||||||
- format: binary
|
|
||||||
|
|
||||||
release:
|
|
||||||
gitea:
|
|
||||||
owner: pomodoro
|
|
||||||
name: GoTomato
|
|
||||||
mode: replace
|
|
||||||
|
|
||||||
gitea_urls:
|
|
||||||
download: http://git.smsvc.net
|
|
||||||
api: http://git.smsvc.net/api/v1
|
|
|
@ -2,11 +2,5 @@
|
||||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||||
"extends": [
|
"extends": [
|
||||||
"local>infrastructure/renovate-config"
|
"local>infrastructure/renovate-config"
|
||||||
],
|
|
||||||
"packageRules": [
|
|
||||||
{
|
|
||||||
"matchManagers": ["gomod"],
|
|
||||||
"semanticCommitType": "chore"
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
26
README.md
26
README.md
|
@ -34,17 +34,17 @@ Here are the available commands:
|
||||||
| `pause` | Pauses the current session | `{"command": "pause", "password": ""}` |
|
| `pause` | Pauses the current session | `{"command": "pause", "password": ""}` |
|
||||||
| `resume` | Resumes a paused session | `{"command": "resume", "password": ""}` |
|
| `resume` | Resumes a paused session | `{"command": "resume", "password": ""}` |
|
||||||
| `reset` | Stops and resets the current session | `{"command": "reset", "password": ""}` |
|
| `reset` | Stops and resets the current session | `{"command": "reset", "password": ""}` |
|
||||||
| `updateSettings` | Update Pomodoro settings | `{"command": "updateSettings", "password": "", "settings": {"focus": 600, "shortBreak": 60, "longBreak": 300, "sessions": 2}}` |
|
| `updateSettings` | Update Pomodoro settings | `{"command": "updateSettings", "password": "", "settings": {"work": 600, "shortBreak": 60, "longBreak": 300, "sessions": 2}}` |
|
||||||
|
|
||||||
#### Update Settings Command (`updateSettings`)
|
#### Update Settings Command (`updateSettings`)
|
||||||
|
|
||||||
The `updateSettings` command allows clients to modify the Pomodoro timer configuration, including the length of focus sessions, short breaks, long breaks, and the total number of sessions in a cycle. This command must include a valid password to be accepted by the server. The updateSettings command can be used when the timer is stopped.
|
The `updateSettings` command allows clients to modify the Pomodoro timer configuration, including the length of work sessions, short breaks, long breaks, and the total number of sessions in a cycle. This command must include a valid password to be accepted by the server. The updateSettings command can be used when the timer is stopped.
|
||||||
|
|
||||||
- Fields in the `settings` Object:
|
- Fields in the `settings` Object:
|
||||||
- `focus`: Length of the focus session (in seconds).
|
- `work`: Length of the work session (in seconds).
|
||||||
- `shortBreak`: Length of the short break (in seconds).
|
- `shortBreak`: Length of the short break (in seconds).
|
||||||
- `longBreak`: Length of the long break (in seconds).
|
- `longBreak`: Length of the long break (in seconds).
|
||||||
- `sessions`: Total number of focus/break sessions in the Pomodoro cycle.
|
- `sessions`: Total number of work/break sessions in the Pomodoro cycle.
|
||||||
|
|
||||||
All fields are mandatory and may not be ommitted.
|
All fields are mandatory and may not be ommitted.
|
||||||
|
|
||||||
|
@ -52,14 +52,14 @@ All fields are mandatory and may not be ommitted.
|
||||||
|
|
||||||
The server periodically (every second) sends JSON-encoded messages to all connected clients to update them on the current state of the Pomodoro session. These messages contain the following fields:
|
The server periodically (every second) sends JSON-encoded messages to all connected clients to update them on the current state of the Pomodoro session. These messages contain the following fields:
|
||||||
|
|
||||||
- mode: Indicates the current phase of the Pomodoro session ("Focus", "ShortBreak", "LongBreak", "End" or "Idle").
|
- mode: Indicates the current phase of the Pomodoro session ("Work", "ShortBreak", "LongBreak", "End" or "Idle").
|
||||||
- "End" is send only once, after all sessions are finished
|
- "End" is send only once, after all sessions are finished
|
||||||
- settings: Contains the current Pomodoro settings:
|
- settings: Contains the current Pomodoro settings:
|
||||||
- focus: Length of the focus session in seconds (e.g., 1500 for 25 minutes).
|
- work: Length of the work session in seconds (e.g., 1500 for 25 minutes).
|
||||||
- shortBreak: Length of the short break in seconds (e.g., 300 for 5 minutes).
|
- shortBreak: Length of the short break in seconds (e.g., 300 for 5 minutes).
|
||||||
- longBreak: Length of the long break in seconds (e.g., 900 for 15 minutes).
|
- longBreak: Length of the long break in seconds (e.g., 900 for 15 minutes).
|
||||||
- sessions: The total number of focus/break sessions (e.g., 4).
|
- sessions: The total number of work/break sessions (e.g., 4).
|
||||||
- session: The current session number (e.g., 1 for the first focus session).
|
- session: The current session number (e.g., 1 for the first work session).
|
||||||
- time_left: The remaining time for the current mode, in seconds (e.g., 900 for 15 minutes).
|
- time_left: The remaining time for the current mode, in seconds (e.g., 900 for 15 minutes).
|
||||||
- ongoing: Whether a Pomodoro session is currently ongoing.
|
- ongoing: Whether a Pomodoro session is currently ongoing.
|
||||||
- paused: Whether the timer is paused.
|
- paused: Whether the timer is paused.
|
||||||
|
@ -67,11 +67,11 @@ The server periodically (every second) sends JSON-encoded messages to all connec
|
||||||
|
|
||||||
| Message Type | Example |
|
| Message Type | Example |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Welcome Message | {"mode":"Idle", "settings":{"focus":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":0, "time_left":1500, "ongoing":false, "paused":false, "version":"0"} |
|
| Welcome Message | {"mode":"Idle", "settings":{"work":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":0, "time_left":1500, "ongoing":false, "paused":false, "version":"v0"} |
|
||||||
| Session Running | {"mode":"Focus", "settings":{"focus":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":1, "time_left":900, "ongoing":true, "paused":false, "version":"0"} |
|
| Session Running | {"mode":"Work", "settings":{"work":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":1, "time_left":900, "ongoing":true, "paused":false, "version":"v0"} |
|
||||||
| Session Running | {"mode":"ShortBreak", "settings":{"focus":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":2, "time_left":50, "ongoing":true, "paused":false, "version":"0"} |
|
| Session Running | {"mode":"ShortBreak", "settings":{"work":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":2, "time_left":50, "ongoing":true, "paused":false, "version":"v0"} |
|
||||||
| Session Paused | {"mode":"Focus", "settings":{"focus":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":2, "time_left":456, "ongoing":true, "paused":true, "version":"0"} |
|
| Session Paused | {"mode":"Work", "settings":{"work":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":2, "time_left":456, "ongoing":true, "paused":true, "version":"v0"} |
|
||||||
| Session End/Reset | {"mode":"End", "settings":{"focus":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":0, "time_left":0, "ongoing":false, "paused":false, "version":"0"} |
|
| Session End/Reset | {"mode":"End", "settings":{"work":1500, "shortBreak":300, "longBreak":900, "sessions":4}, "session":0, "time_left":0, "ongoing":false, "paused":false, "version":"v0"} |
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
|
|
34
Taskfile.yml
34
Taskfile.yml
|
@ -1,34 +0,0 @@
|
||||||
# yaml-language-server: $schema=https://taskfile.dev/schema.json
|
|
||||||
#
|
|
||||||
# github.com/go-task/task/v3/cmd/task@latest
|
|
||||||
# Requirements:
|
|
||||||
# github.com/caarlos0/svu@latest
|
|
||||||
# github.com/goreleaser/goreleaser/v2@latest
|
|
||||||
|
|
||||||
version: '3'
|
|
||||||
|
|
||||||
tasks:
|
|
||||||
|
|
||||||
release:
|
|
||||||
desc: Create and publish an new release
|
|
||||||
vars:
|
|
||||||
RELEASE:
|
|
||||||
sh: svu next
|
|
||||||
BRANCH:
|
|
||||||
sh: git branch --show-current
|
|
||||||
COMMIT:
|
|
||||||
sh: git rev-parse --short --verify {{.BRANCH}}
|
|
||||||
preconditions:
|
|
||||||
- sh: test "{{.BRANCH}}" == "main"
|
|
||||||
msg: "You must be on the main branch to release"
|
|
||||||
prompt: Create new release {{.RELEASE}} from {{.COMMIT}}@{{.BRANCH}}?
|
|
||||||
cmds:
|
|
||||||
- git tag {{.RELEASE}}
|
|
||||||
- git push
|
|
||||||
- git push origin tag {{.RELEASE}}
|
|
||||||
- goreleaser release --clean
|
|
||||||
|
|
||||||
snapshot:
|
|
||||||
desc: Create a local snapshot release
|
|
||||||
cmds:
|
|
||||||
- goreleaser release --clean --snapshot
|
|
|
@ -3,65 +3,45 @@ package server
|
||||||
import (
|
import (
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/gorilla/handlers"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/metadata"
|
"git.smsvc.net/pomodoro/GoTomato/internal/metadata"
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/websocket"
|
"git.smsvc.net/pomodoro/GoTomato/internal/websocket"
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
// define CLI flags
|
|
||||||
listenAddress = flag.String("listenAddress", shared.DefaultServerConfig.ListenAddress, "IP address to listen on")
|
|
||||||
listenPort = flag.Int("listenPort", shared.DefaultServerConfig.ListenPort, "Port to listen on")
|
|
||||||
password = flag.String("password", "", "Control password for pomodoro session (optional)")
|
|
||||||
showVersion = flag.Bool("version", false, "Output version")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Start the pomodoro server
|
|
||||||
func Start() {
|
func Start() {
|
||||||
// Update usage output
|
// Define CLI flags for ListenAddress and ListenPort
|
||||||
flag.Usage = func() {
|
listenAddress := flag.String("listenAddress", shared.DefaultServerConfig.ListenAddress, "IP address to listen on")
|
||||||
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", "GoTomato")
|
listenPort := flag.Int("listenPort", shared.DefaultServerConfig.ListenPort, "Port to listen on")
|
||||||
flag.PrintDefaults()
|
password := flag.String("password", "", "Control password for pomodoro session (optional)")
|
||||||
fmt.Println("\nPoint your client to 'ws://<listenAddress>:<listenPort>'")
|
showVersionFlag := flag.Bool("version", false, "Output version")
|
||||||
}
|
|
||||||
|
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
// show server and protocl version and exit
|
shared.Message.GoTomatoVersion = strings.Split(metadata.GoTomatoVersion, ".")[0]
|
||||||
if *showVersion {
|
if *showVersionFlag {
|
||||||
fmt.Printf("GoTomato v%s\n", metadata.GoTomatoVersion)
|
fmt.Printf("App-Version: %s\n", metadata.GoTomatoVersion)
|
||||||
fmt.Printf("Protocol-Version: %s\n", metadata.ProtocolVersion)
|
fmt.Printf("Protocol-Version: %s\n", shared.Message.GoTomatoVersion)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// set server config
|
serverConfig := models.GoTomatoServerConfig{
|
||||||
serverConfig := models.ServerConfig{
|
|
||||||
ListenAddress: *listenAddress,
|
ListenAddress: *listenAddress,
|
||||||
ListenPort: *listenPort,
|
ListenPort: *listenPort,
|
||||||
}
|
}
|
||||||
shared.PomodoroPassword = *password
|
shared.PomodoroPassword = *password
|
||||||
|
|
||||||
// define listen address for websocket
|
|
||||||
listen := fmt.Sprintf("%s:%d", serverConfig.ListenAddress, serverConfig.ListenPort)
|
listen := fmt.Sprintf("%s:%d", serverConfig.ListenAddress, serverConfig.ListenPort)
|
||||||
|
|
||||||
// start connection handler and broadcast
|
http.HandleFunc("/ws", websocket.HandleConnections)
|
||||||
r := http.NewServeMux()
|
|
||||||
r.HandleFunc("/", websocket.HandleConnection)
|
|
||||||
go websocket.SendPermanentBroadCastMessage()
|
go websocket.SendPermanentBroadCastMessage()
|
||||||
go websocket.RemoveStaleClients()
|
|
||||||
|
|
||||||
helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion)
|
log.Printf("Pomodoro WebSocket server started on %s\n", listen)
|
||||||
helper.Logger.Info("Websocket listening", "address", listen)
|
err := http.ListenAndServe(listen, nil)
|
||||||
|
|
||||||
// start the listener
|
|
||||||
err := http.ListenAndServe(listen, handlers.ProxyHeaders(r))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
helper.Logger.Fatal("Error starting server:", "msg", err)
|
log.Fatalf("Error starting server: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
21
go.mod
21
go.mod
|
@ -2,23 +2,4 @@ module git.smsvc.net/pomodoro/GoTomato
|
||||||
|
|
||||||
go 1.23
|
go 1.23
|
||||||
|
|
||||||
require (
|
require github.com/gorilla/websocket v1.5.3
|
||||||
github.com/charmbracelet/log v0.4.0
|
|
||||||
github.com/gorilla/handlers v1.5.2
|
|
||||||
github.com/gorilla/websocket v1.5.3
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
|
||||||
github.com/charmbracelet/lipgloss v0.10.0 // indirect
|
|
||||||
github.com/felixge/httpsnoop v1.0.3 // indirect
|
|
||||||
github.com/go-logfmt/logfmt v0.6.0 // indirect
|
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
|
||||||
github.com/mattn/go-isatty v0.0.18 // indirect
|
|
||||||
github.com/mattn/go-runewidth v0.0.15 // indirect
|
|
||||||
github.com/muesli/reflow v0.3.0 // indirect
|
|
||||||
github.com/muesli/termenv v0.15.2 // indirect
|
|
||||||
github.com/rivo/uniseg v0.4.7 // indirect
|
|
||||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect
|
|
||||||
golang.org/x/sys v0.13.0 // indirect
|
|
||||||
)
|
|
||||||
|
|
40
go.sum
40
go.sum
|
@ -1,42 +1,2 @@
|
||||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
|
||||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
|
||||||
github.com/charmbracelet/lipgloss v0.10.0 h1:KWeXFSexGcfahHX+54URiZGkBFazf70JNMtwg/AFW3s=
|
|
||||||
github.com/charmbracelet/lipgloss v0.10.0/go.mod h1:Wig9DSfvANsxqkRsqj6x87irdy123SR4dOXlKa91ciE=
|
|
||||||
github.com/charmbracelet/log v0.4.0 h1:G9bQAcx8rWA2T3pWvx7YtPTPwgqpk7D68BX21IRW8ZM=
|
|
||||||
github.com/charmbracelet/log v0.4.0/go.mod h1:63bXt/djrizTec0l11H20t8FDSvA4CRZJ1KH22MdptM=
|
|
||||||
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/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=
|
|
||||||
github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
|
||||||
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
|
|
||||||
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
|
|
||||||
github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
|
|
||||||
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
|
|
||||||
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/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
|
||||||
github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=
|
|
||||||
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
|
||||||
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
|
||||||
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
|
|
||||||
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
|
||||||
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
|
|
||||||
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
|
|
||||||
github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
|
|
||||||
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
|
|
||||||
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/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
|
||||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
|
||||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
|
||||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
|
||||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
|
||||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
|
||||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
|
|
10
index.html
10
index.html
|
@ -40,8 +40,8 @@
|
||||||
<input type="text" id="password" placeholder="Password" />
|
<input type="text" id="password" placeholder="Password" />
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<label for="focusDuration">Focus Duration (seconds):</label>
|
<label for="workDuration">Work Duration (seconds):</label>
|
||||||
<input type="number" id="foucsDuration" placeholder="Focus time in seconds" value="900" />
|
<input type="number" id="workDuration" placeholder="Work time in seconds" value="900" />
|
||||||
<br />
|
<br />
|
||||||
<label for="shortBreakDuration">Short Break Duration (seconds):</label>
|
<label for="shortBreakDuration">Short Break Duration (seconds):</label>
|
||||||
<input type="number" id="shortBreakDuration" placeholder="Short break in seconds" value="300" />
|
<input type="number" id="shortBreakDuration" placeholder="Short break in seconds" value="300" />
|
||||||
|
@ -64,7 +64,7 @@
|
||||||
<button id="resetButton" style="display: none;">Reset</button>
|
<button id="resetButton" style="display: none;">Reset</button>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
var ws = new WebSocket("ws://localhost:8080");
|
var ws = new WebSocket("ws://localhost:8080/ws");
|
||||||
var isPaused = false; // Track if the timer is paused
|
var isPaused = false; // Track if the timer is paused
|
||||||
|
|
||||||
ws.onopen = function () {
|
ws.onopen = function () {
|
||||||
|
@ -98,7 +98,7 @@
|
||||||
document.getElementById("saveButton").addEventListener("click", function () {
|
document.getElementById("saveButton").addEventListener("click", function () {
|
||||||
// Get the values from the input fields
|
// Get the values from the input fields
|
||||||
var password = document.getElementById("password").value;
|
var password = document.getElementById("password").value;
|
||||||
var focus = parseInt(document.getElementById("focusDuration").value);
|
var work = parseInt(document.getElementById("workDuration").value);
|
||||||
var shortBreak = parseInt(document.getElementById("shortBreakDuration").value);
|
var shortBreak = parseInt(document.getElementById("shortBreakDuration").value);
|
||||||
var longBreak = parseInt(document.getElementById("longBreakDuration").value);
|
var longBreak = parseInt(document.getElementById("longBreakDuration").value);
|
||||||
var sessions = parseInt(document.getElementById("sessions").value);
|
var sessions = parseInt(document.getElementById("sessions").value);
|
||||||
|
@ -108,7 +108,7 @@
|
||||||
command: "updateSettings",
|
command: "updateSettings",
|
||||||
password: password,
|
password: password,
|
||||||
settings: {
|
settings: {
|
||||||
focus: focus,
|
work: work,
|
||||||
shortBreak: shortBreak,
|
shortBreak: shortBreak,
|
||||||
longBreak: longBreak,
|
longBreak: longBreak,
|
||||||
sessions: sessions
|
sessions: sessions
|
||||||
|
|
|
@ -1,12 +0,0 @@
|
||||||
package helper
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/charmbracelet/log"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var Logger = log.NewWithOptions(os.Stdout, log.Options{
|
|
||||||
ReportTimestamp: true,
|
|
||||||
TimeFormat: time.RFC3339,
|
|
||||||
})
|
|
|
@ -1,37 +1,3 @@
|
||||||
package metadata
|
package metadata
|
||||||
|
|
||||||
import (
|
const GoTomatoVersion = "v0.0.2" // The GoTomato Version
|
||||||
"os/exec"
|
|
||||||
"runtime/debug"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
GoTomatoVersion = "" // The GoTomato version
|
|
||||||
ProtocolVersion = "" // The protocol version
|
|
||||||
)
|
|
||||||
|
|
||||||
func stripVersionPrefix(version string) string {
|
|
||||||
return strings.TrimLeft(version, "v")
|
|
||||||
}
|
|
||||||
|
|
||||||
func getLatestTag() string {
|
|
||||||
bytes, _ := exec.Command("git", "describe", "--tags").Output()
|
|
||||||
output := strings.TrimSpace(string(bytes))
|
|
||||||
return stripVersionPrefix(output)
|
|
||||||
}
|
|
||||||
|
|
||||||
// set GoTomatoVersion from runtime/debug.Main.Version
|
|
||||||
// use latest git tag as fallback
|
|
||||||
// can be overwritten via ldflags (e,g. by goreleaser)
|
|
||||||
func init() {
|
|
||||||
if GoTomatoVersion == "" {
|
|
||||||
info, _ := debug.ReadBuildInfo()
|
|
||||||
if info.Main.Version != "(devel)" {
|
|
||||||
GoTomatoVersion = stripVersionPrefix(info.Main.Version)
|
|
||||||
} else {
|
|
||||||
GoTomatoVersion = getLatestTag()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ProtocolVersion = strings.Split(GoTomatoVersion, ".")[0]
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,116 +1,89 @@
|
||||||
package pomodoro
|
package pomodoro
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var pomodoroResetChannel = make(chan bool, 1)
|
||||||
|
var pomodoroPauseChannel = make(chan bool, 1)
|
||||||
|
var pomodoroResumeChannel = make(chan bool, 1)
|
||||||
|
|
||||||
var mu sync.Mutex // to synchronize access to shared state
|
var mu sync.Mutex // to synchronize access to shared state
|
||||||
var timer Timer
|
|
||||||
|
|
||||||
// Update `State` with the remaining seconds of the passed timer
|
// RunPomodoro iterates the Pomodoro work/break sessions.
|
||||||
// until the timer sends an End or Abort signal
|
|
||||||
func waitForTimer(t Timer) bool {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-t.End:
|
|
||||||
return true
|
|
||||||
case <-t.Abort:
|
|
||||||
return false
|
|
||||||
case shared.State.TimeLeft = <-t.TimeLeft:
|
|
||||||
// do nothing, just let the timer update the message
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// RunPomodoro iterates the Pomodoro focus/break sessions
|
|
||||||
func RunPomodoro() {
|
func RunPomodoro() {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
shared.State.Ongoing = true
|
shared.Message.Ongoing = true
|
||||||
shared.State.Paused = false
|
shared.Message.Paused = false
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
|
|
||||||
pomodoroConfig := shared.State.Settings
|
pomodoroConfig := shared.Message.PomodoroSettings
|
||||||
|
|
||||||
for session := 1; session <= pomodoroConfig.Sessions; session++ {
|
for session := 1; session <= pomodoroConfig.Sessions; session++ {
|
||||||
timer = timer.Init()
|
shared.Message.Session = session
|
||||||
|
shared.Message.Mode = "Work"
|
||||||
shared.State.Session = session
|
if !startTimer(pomodoroConfig.Work) {
|
||||||
|
|
||||||
// Focus
|
|
||||||
shared.State.Mode = "Focus"
|
|
||||||
timer.StartAsync(pomodoroConfig.Focus)
|
|
||||||
if !waitForTimer(timer) {
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
if session == pomodoroConfig.Sessions {
|
||||||
// Breaks
|
shared.Message.Mode = "LongBreak"
|
||||||
if session < pomodoroConfig.Sessions {
|
if !startTimer(pomodoroConfig.LongBreak) {
|
||||||
shared.State.Mode = "ShortBreak"
|
|
||||||
timer.StartAsync(pomodoroConfig.ShortBreak)
|
|
||||||
if !waitForTimer(timer) {
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
} else { // last phase, prepare for finish
|
} else {
|
||||||
shared.State.Mode = "LongBreak"
|
shared.Message.Mode = "ShortBreak"
|
||||||
timer.StartAsync(pomodoroConfig.LongBreak)
|
if !startTimer(pomodoroConfig.ShortBreak) {
|
||||||
if !waitForTimer(timer) {
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// send "End" state for one second
|
|
||||||
shared.State.Mode = "End"
|
|
||||||
time.Sleep(time.Second)
|
|
||||||
}
|
}
|
||||||
|
shared.Message.Mode = "End"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
shared.State.Ongoing = false
|
shared.Message.Ongoing = false
|
||||||
shared.State.Paused = false
|
shared.Message.Paused = false
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
|
|
||||||
shared.State.Mode = "Idle"
|
shared.Message.Mode = "Idle"
|
||||||
shared.State.Session = 0
|
shared.Message.Session = 0
|
||||||
shared.State.TimeLeft = shared.State.Settings.Focus
|
shared.Message.TimeLeft = shared.Message.PomodoroSettings.Work
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stops and resets the running Pomodoro
|
||||||
func ResetPomodoro() {
|
func ResetPomodoro() {
|
||||||
timer.Stop()
|
shared.Message.Mode = "Idle"
|
||||||
|
shared.Message.Session = 0
|
||||||
|
shared.Message.TimeLeft = shared.Message.PomodoroSettings.Work
|
||||||
|
pomodoroResetChannel <- true
|
||||||
}
|
}
|
||||||
|
|
||||||
func PausePomodoro() {
|
func PausePomodoro() {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
shared.State.Paused = true
|
shared.Message.Paused = true
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
|
|
||||||
timer.Pause()
|
pomodoroPauseChannel <- true
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResumePomodoro() {
|
func ResumePomodoro() {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
shared.State.Paused = false
|
shared.Message.Paused = false
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
timer.Resume()
|
pomodoroResumeChannel <- true
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsPomodoroOngoing() bool {
|
func IsPomodoroOngoing() bool {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock() // Ensures that the mutex is unlocked after the function is done
|
||||||
return shared.State.Ongoing
|
return shared.Message.Ongoing
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsPomodoroPaused() bool {
|
func IsPomodoroPaused() bool {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock() // Ensures that the mutex is unlocked after the function is done
|
||||||
return shared.State.Paused
|
return shared.Message.Paused
|
||||||
}
|
|
||||||
|
|
||||||
func UpdateSettings(settings models.PomodoroConfig) {
|
|
||||||
if settings != (models.PomodoroConfig{}) {
|
|
||||||
shared.State.Settings = settings
|
|
||||||
shared.State.TimeLeft = settings.Focus
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,65 +1,32 @@
|
||||||
package pomodoro
|
package pomodoro
|
||||||
|
|
||||||
import "time"
|
import (
|
||||||
|
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
// Represents a timer
|
// runs the countdown and updates shared.Message.TimeLeft every second.
|
||||||
type Timer struct {
|
func startTimer(remainingSeconds int) bool {
|
||||||
TimeLeft chan int // signals time left on every second
|
for remainingSeconds > 0 {
|
||||||
End chan bool // signal on successful end
|
|
||||||
Abort chan bool // signal on premature end
|
|
||||||
stop chan bool // internal channel
|
|
||||||
wait chan bool // internal channel
|
|
||||||
resume chan bool // internal channel
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initializes a new timer with fresh channels
|
|
||||||
func (t Timer) Init() Timer {
|
|
||||||
return Timer{
|
|
||||||
TimeLeft: make(chan int),
|
|
||||||
End: make(chan bool, 1),
|
|
||||||
Abort: make(chan bool, 1),
|
|
||||||
stop: make(chan bool, 1),
|
|
||||||
wait: make(chan bool, 1),
|
|
||||||
resume: make(chan bool, 1),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start the timer (goroutine)
|
|
||||||
func (t *Timer) StartAsync(duration int) {
|
|
||||||
go t.Start(duration)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start the timer (blocking)
|
|
||||||
func (t *Timer) Start(duration int) {
|
|
||||||
tick := time.NewTicker(time.Second)
|
|
||||||
for timeLeft := duration; timeLeft > 0; {
|
|
||||||
select {
|
select {
|
||||||
case <-t.stop:
|
case <-pomodoroResetChannel:
|
||||||
t.Abort <- true
|
return false
|
||||||
return
|
case <-pomodoroPauseChannel:
|
||||||
case <-t.wait:
|
// Nothing to set here, just waiting for the signal
|
||||||
<-t.resume
|
case <-pomodoroResumeChannel:
|
||||||
continue
|
// Nothing to set here, just waiting for the signal
|
||||||
case <-tick.C:
|
|
||||||
timeLeft--
|
|
||||||
default:
|
default:
|
||||||
t.TimeLeft <- timeLeft
|
// Broadcast the current state to all clients
|
||||||
|
if !IsPomodoroPaused() {
|
||||||
|
shared.Message.TimeLeft = remainingSeconds
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
remainingSeconds--
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.TimeLeft <- 0
|
|
||||||
|
|
||||||
t.End <- true
|
// Final shared.Message when time reaches zero
|
||||||
}
|
shared.Message.TimeLeft = remainingSeconds
|
||||||
|
|
||||||
func (t *Timer) Stop() {
|
return true
|
||||||
t.resume <- true
|
|
||||||
t.stop <- true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Timer) Pause() {
|
|
||||||
t.wait <- true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Timer) Resume() {
|
|
||||||
t.resume <- true
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
package shared
|
package shared
|
||||||
|
|
||||||
import "git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
import (
|
||||||
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||||||
|
)
|
||||||
|
|
||||||
// The default server config if nothing else is set
|
var DefaultServerConfig = models.GoTomatoServerConfig{
|
||||||
var DefaultServerConfig = models.ServerConfig{
|
|
||||||
ListenAddress: "0.0.0.0",
|
ListenAddress: "0.0.0.0",
|
||||||
ListenPort: 8080,
|
ListenPort: 8080,
|
||||||
}
|
}
|
||||||
|
|
||||||
// The default pomodoro config if nothing else is set
|
var DefaultPomodoroConfig = models.GoTomatoPomodoroConfig{
|
||||||
var DefaultPomodoroConfig = models.PomodoroConfig{
|
Work: 25 * 60,
|
||||||
Focus: 25 * 60,
|
|
||||||
ShortBreak: 5 * 60,
|
ShortBreak: 5 * 60,
|
||||||
LongBreak: 15 * 60,
|
LongBreak: 15 * 60,
|
||||||
Sessions: 4,
|
Sessions: 4,
|
||||||
|
|
|
@ -1,20 +1,16 @@
|
||||||
package shared
|
package shared
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/metadata"
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The global state of the pomodoro
|
var Message = models.ServerMessage{
|
||||||
var State = models.ServerMessage{
|
Mode: "Idle",
|
||||||
Mode: "Idle",
|
PomodoroSettings: DefaultPomodoroConfig,
|
||||||
Settings: DefaultPomodoroConfig,
|
Session: 0,
|
||||||
Session: 0,
|
TimeLeft: DefaultPomodoroConfig.Work,
|
||||||
TimeLeft: DefaultPomodoroConfig.Focus,
|
Ongoing: false,
|
||||||
Ongoing: false,
|
Paused: false,
|
||||||
Paused: false,
|
|
||||||
ProtocolVersion: metadata.ProtocolVersion,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The password needed to execute client commands or change the pomodoro config
|
|
||||||
var PomodoroPassword string
|
var PomodoroPassword string
|
||||||
|
|
|
@ -2,36 +2,29 @@ package websocket
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Sends continous messages to all connected WebSocket clients
|
// sends continous messages to all connected WebSocket clients.
|
||||||
func SendPermanentBroadCastMessage() {
|
func SendPermanentBroadCastMessage() {
|
||||||
ticker := time.NewTicker(BROADCAST_INTERVAL * time.Second)
|
for {
|
||||||
defer ticker.Stop()
|
|
||||||
|
|
||||||
for range ticker.C {
|
|
||||||
// Marshal the message into JSON format
|
// Marshal the message into JSON format
|
||||||
jsonMessage, err := json.Marshal(shared.State)
|
jsonMessage, err := json.Marshal(shared.Message)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
helper.Logger.Error("Error marshalling message:", "msg", err)
|
log.Printf("Error marshalling message: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iterate over all connected clients and broadcast the message
|
// Iterate over all connected clients and broadcast the message
|
||||||
mu.Lock()
|
|
||||||
for _, client := range Clients {
|
for _, client := range Clients {
|
||||||
// Send message to client
|
err := client.SendMessage(websocket.TextMessage, jsonMessage)
|
||||||
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
|
|
||||||
err := client.Conn.WriteMessage(websocket.TextMessage, jsonMessage)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
helper.Logger.Error("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
|
log.Printf("Error broadcasting to client: %v", err)
|
||||||
|
// The client is responsible for closing itself on error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
mu.Unlock()
|
time.Sleep(time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,37 +2,29 @@ package websocket
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/pomodoro"
|
"git.smsvc.net/pomodoro/GoTomato/internal/pomodoro"
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
"log"
|
||||||
)
|
)
|
||||||
|
|
||||||
func checkSettings(settings models.PomodoroConfig) bool {
|
// handleClientCommands listens for commands from WebSocket clients
|
||||||
return settings.Focus > 0 && settings.ShortBreak > 0 && settings.LongBreak > 0 && settings.Sessions > 0
|
func handleClientCommands(ws *websocket.Conn) {
|
||||||
}
|
|
||||||
|
|
||||||
// Listens for commands from a client and handles them
|
|
||||||
func handleClientCommands(c models.WebsocketClient) {
|
|
||||||
ws := c.Conn
|
|
||||||
for {
|
for {
|
||||||
var clientCommand models.ClientCommand
|
var clientCommand models.ClientCommand
|
||||||
|
|
||||||
_, message, err := ws.ReadMessage()
|
_, message, err := ws.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// remove client on error/disconnect
|
log.Printf("Client disconnected from %s (%v) (total: %d)", ws.NetConn().RemoteAddr(), err, len(Clients)-1)
|
||||||
mu.Lock()
|
delete(Clients, ws)
|
||||||
delete(Clients, ws.LocalAddr())
|
|
||||||
mu.Unlock()
|
|
||||||
helper.Logger.Info("Client disconnected:", "msg", err, "host", c.RealIP, "clients", len(Clients))
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle incoming commands
|
// Handle incoming commands
|
||||||
err = json.Unmarshal(message, &clientCommand)
|
err = json.Unmarshal(message, &clientCommand)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
helper.Logger.Error("Error unmarshalling command:", "msg", err)
|
log.Printf("Error unmarshalling command: %v", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -57,12 +49,11 @@ func handleClientCommands(c models.WebsocketClient) {
|
||||||
}
|
}
|
||||||
case "updateSettings":
|
case "updateSettings":
|
||||||
if !pomodoro.IsPomodoroOngoing() {
|
if !pomodoro.IsPomodoroOngoing() {
|
||||||
if !checkSettings(clientCommand.Settings) {
|
if clientCommand.PomodoroSettings != (models.GoTomatoPomodoroConfig{}) {
|
||||||
helper.Logger.Warn("Ignoring invalid config:", "msg", clientCommand.Settings, "host", c.Conn.RemoteAddr())
|
shared.Message.PomodoroSettings = clientCommand.PomodoroSettings
|
||||||
break
|
shared.Message.TimeLeft = clientCommand.PomodoroSettings.Work
|
||||||
}
|
}
|
||||||
helper.Logger.Info("Client send config", "config", clientCommand.Settings, "host", c.Conn.RemoteAddr())
|
|
||||||
pomodoro.UpdateSettings(clientCommand.Settings)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,46 +0,0 @@
|
||||||
package websocket
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Upgrade HTTP requests to WebSocket connections
|
|
||||||
var upgrader = websocket.Upgrader{
|
|
||||||
CheckOrigin: func(r *http.Request) bool { return true },
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upgrades HTTP requests to WebSocket connections and manages the client lifecycle
|
|
||||||
func HandleConnection(w http.ResponseWriter, r *http.Request) {
|
|
||||||
// Upgrade initial GET request to a WebSocket
|
|
||||||
ws, err := upgrader.Upgrade(w, r, nil)
|
|
||||||
if err != nil {
|
|
||||||
helper.Logger.Error("WebSocket upgrade error:", "msg", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer ws.Close()
|
|
||||||
|
|
||||||
// Register the new client
|
|
||||||
client := models.WebsocketClient{
|
|
||||||
Conn: ws,
|
|
||||||
LastPong: time.Now(),
|
|
||||||
RealIP: r.RemoteAddr,
|
|
||||||
}
|
|
||||||
client.Conn.SetPongHandler(func(s string) error {
|
|
||||||
client.LastPong = time.Now()
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
mu.Lock()
|
|
||||||
Clients[ws.LocalAddr()] = &client
|
|
||||||
mu.Unlock()
|
|
||||||
|
|
||||||
helper.Logger.Info("Client connected", "host", client.RealIP, "clients", len(Clients))
|
|
||||||
|
|
||||||
// Listen for commands from the connected client
|
|
||||||
handleClientCommands(client)
|
|
||||||
}
|
|
41
internal/websocket/handle_connections.go
Normal file
41
internal/websocket/handle_connections.go
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
package websocket
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Clients is a map of connected WebSocket clients, where each client is represented by the Client struct
|
||||||
|
var Clients = make(map[*websocket.Conn]*models.Client)
|
||||||
|
var mu sync.Mutex // Mutex to protect access to the Clients map
|
||||||
|
|
||||||
|
// Upgrader to upgrade HTTP requests to WebSocket connections
|
||||||
|
var upgrader = websocket.Upgrader{
|
||||||
|
CheckOrigin: func(r *http.Request) bool { return true },
|
||||||
|
}
|
||||||
|
|
||||||
|
// HandleConnections upgrades HTTP requests to WebSocket connections and manages the client lifecycle.
|
||||||
|
func HandleConnections(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Upgrade initial GET request to a WebSocket
|
||||||
|
ws, err := upgrader.Upgrade(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("WebSocket upgrade error: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer ws.Close()
|
||||||
|
|
||||||
|
log.Printf("Client connected from %v (total: %d)", ws.NetConn().RemoteAddr(), len(Clients)+1)
|
||||||
|
|
||||||
|
// Register the new client
|
||||||
|
mu.Lock()
|
||||||
|
Clients[ws] = &models.Client{
|
||||||
|
Conn: ws, // Store the WebSocket connection
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
|
||||||
|
// Listen for commands from the connected client
|
||||||
|
handleClientCommands(ws)
|
||||||
|
}
|
|
@ -1,34 +0,0 @@
|
||||||
package websocket
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Check and remove stale clients
|
|
||||||
func RemoveStaleClients() {
|
|
||||||
ticker := time.NewTicker(STALE_CHECK_INTERVALL * time.Second)
|
|
||||||
defer ticker.Stop()
|
|
||||||
|
|
||||||
for range ticker.C {
|
|
||||||
mu.Lock()
|
|
||||||
for _, client := range Clients {
|
|
||||||
client.Conn.SetWriteDeadline(time.Now().Add(SEND_TIMEOUT * time.Second))
|
|
||||||
client.Conn.WriteMessage(websocket.PingMessage, nil)
|
|
||||||
|
|
||||||
if isStale(client) {
|
|
||||||
helper.Logger.Info("Removing stale client", "host", client.RealIP, "lastPong", client.LastPong.Format(time.RFC3339))
|
|
||||||
client.Conn.Close()
|
|
||||||
delete(Clients, client.Conn.LocalAddr())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
mu.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func isStale(client *models.WebsocketClient) bool {
|
|
||||||
return time.Since(client.LastPong) > (STALE_CLIENT_TIMEOUT * time.Second)
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
package websocket
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
const BROADCAST_INTERVAL = 1
|
|
||||||
const SEND_TIMEOUT = 10
|
|
||||||
const STALE_CLIENT_TIMEOUT = 90
|
|
||||||
const STALE_CHECK_INTERVALL = 30
|
|
||||||
|
|
||||||
// Clients is a map of connected WebSocket clients, where each client is represented by the WebsocketClient struct
|
|
||||||
var Clients = make(map[net.Addr]*models.WebsocketClient)
|
|
||||||
|
|
||||||
// Mutex to protect access to the Clients map
|
|
||||||
var mu sync.Mutex
|
|
|
@ -1,21 +1,32 @@
|
||||||
package models
|
package models
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Represents a command from the client (start/stop)
|
// ClientCommand represents a command from the client (start/stop).
|
||||||
type ClientCommand struct {
|
type ClientCommand struct {
|
||||||
Command string `json:"command"` // Command send to the server
|
Command string `json:"command"` // comman send to the server
|
||||||
Password string `json:"password"` // Pomodoro control password
|
Password string `json:"password"` // pomodoro control password
|
||||||
Settings PomodoroConfig `json:"settings"` // Pomodoro config
|
PomodoroSettings GoTomatoPomodoroConfig `json:"settings"` // pomodoro config
|
||||||
}
|
}
|
||||||
|
|
||||||
// Represents a single client
|
type Client struct {
|
||||||
type WebsocketClient struct {
|
Conn *websocket.Conn
|
||||||
Conn *websocket.Conn
|
Mutex sync.Mutex
|
||||||
LastPong time.Time
|
}
|
||||||
RealIP string
|
|
||||||
|
// It automatically locks and unlocks the mutex to ensure that only one goroutine can write at a time.
|
||||||
|
func (c *Client) SendMessage(messageType int, data []byte) error {
|
||||||
|
c.Mutex.Lock()
|
||||||
|
defer c.Mutex.Unlock()
|
||||||
|
|
||||||
|
err := c.Conn.WriteMessage(messageType, data)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error writing to WebSocket: %v", err)
|
||||||
|
c.Conn.Close() // Close the connection on error
|
||||||
|
}
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,22 +1,13 @@
|
||||||
package models
|
package models
|
||||||
|
|
||||||
import "fmt"
|
type GoTomatoPomodoroConfig struct {
|
||||||
|
Work int `json:"work"` // Length of work sessions in seconds
|
||||||
// Represents the configuration of a pomodoro
|
|
||||||
type PomodoroConfig struct {
|
|
||||||
Focus int `json:"focus"` // Length of focus sessions in seconds
|
|
||||||
ShortBreak int `json:"shortBreak"` // Length of short break in seconds
|
ShortBreak int `json:"shortBreak"` // Length of short break in seconds
|
||||||
LongBreak int `json:"longBreak"` // Length of long break in seconds
|
LongBreak int `json:"longBreak"` // Length if ling break in seconds
|
||||||
Sessions int `json:"sessions"` // Number of total sessions
|
Sessions int `json:"sessions"` // Number of total sessions
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stringer interface for the PomodocoConfig model
|
type GoTomatoServerConfig struct {
|
||||||
func (c PomodoroConfig) String() string {
|
|
||||||
return fmt.Sprintf("{focus: %d, short: %d, long: %d, sessions: %d}", c.Focus, c.ShortBreak, c.LongBreak, c.Sessions)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Represents the server configuration
|
|
||||||
type ServerConfig struct {
|
|
||||||
ListenAddress string `json:"listenAddress"` // Server listen address
|
ListenAddress string `json:"listenAddress"` // Server listen address
|
||||||
ListenPort int `json:"listenPort"` // Server listen port
|
ListenPort int `json:"listenPort"` // Server listen port
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
package models
|
package models
|
||||||
|
|
||||||
// Represents the data sent to the client via WebSocket
|
// ServerMessage represents the data sent to the client via WebSocket.
|
||||||
type ServerMessage struct {
|
type ServerMessage struct {
|
||||||
Mode string `json:"mode"` // "Idle", "Focus", "ShortBreak", "LongBreak" or "End"
|
Mode string `json:"mode"` // "Idle", "Work", "ShortBreak", "LongBreak" or "End"
|
||||||
Settings PomodoroConfig `json:"settings"` // The currrent pomodoro settings
|
PomodoroSettings GoTomatoPomodoroConfig `json:"settings"` // The currrent pomodoro settings
|
||||||
Session int `json:"session"` // Current session number
|
Session int `json:"session"` // Current session number
|
||||||
TimeLeft int `json:"time_left"` // Remaining time in seconds
|
TimeLeft int `json:"time_left"` // Remaining time in seconds
|
||||||
Ongoing bool `json:"ongoing"` // Pomodoro ongoing
|
Ongoing bool `json:"ongoing"` // Ongoing pomodoro
|
||||||
Paused bool `json:"paused"` // Is timer paused
|
Paused bool `json:"paused"` // Is timer paused
|
||||||
ProtocolVersion string `json:"version"` // Version of the protocol
|
GoTomatoVersion string `json:"version"` // Version of the server
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue