Compare commits
No commits in common. "main" and "v0.0.8" have entirely different histories.
19 changed files with 70 additions and 246 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
|
|
|
@ -19,24 +19,17 @@ var (
|
||||||
listenAddress = flag.String("listenAddress", shared.DefaultServerConfig.ListenAddress, "IP address to listen on")
|
listenAddress = flag.String("listenAddress", shared.DefaultServerConfig.ListenAddress, "IP address to listen on")
|
||||||
listenPort = flag.Int("listenPort", shared.DefaultServerConfig.ListenPort, "Port to listen on")
|
listenPort = flag.Int("listenPort", shared.DefaultServerConfig.ListenPort, "Port to listen on")
|
||||||
password = flag.String("password", "", "Control password for pomodoro session (optional)")
|
password = flag.String("password", "", "Control password for pomodoro session (optional)")
|
||||||
showVersion = flag.Bool("version", false, "Output version")
|
showVersionFlag = flag.Bool("version", false, "Output version")
|
||||||
)
|
)
|
||||||
|
|
||||||
// Start the pomodoro server
|
// Start the pomodoro server
|
||||||
func Start() {
|
func Start() {
|
||||||
// Update usage output
|
|
||||||
flag.Usage = func() {
|
|
||||||
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", "GoTomato")
|
|
||||||
flag.PrintDefaults()
|
|
||||||
fmt.Println("\nPoint your client to 'ws://<listenAddress>:<listenPort>'")
|
|
||||||
}
|
|
||||||
|
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
// show server and protocl version and exit
|
// show server and protocl version and exit
|
||||||
if *showVersion {
|
if *showVersionFlag {
|
||||||
fmt.Printf("GoTomato v%s\n", metadata.GoTomatoVersion)
|
fmt.Println("Server-Version:", metadata.GoTomatoVersion)
|
||||||
fmt.Printf("Protocol-Version: %s\n", metadata.ProtocolVersion)
|
fmt.Println("Protocol-Version:", metadata.ProtocolVersion)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -52,9 +45,8 @@ func Start() {
|
||||||
|
|
||||||
// start connection handler and broadcast
|
// start connection handler and broadcast
|
||||||
r := http.NewServeMux()
|
r := http.NewServeMux()
|
||||||
r.HandleFunc("/", websocket.HandleConnection)
|
r.HandleFunc("/ws", websocket.HandleConnection)
|
||||||
go websocket.SendPermanentBroadCastMessage()
|
go websocket.SendPermanentBroadCastMessage()
|
||||||
go websocket.RemoveStaleClients()
|
|
||||||
|
|
||||||
helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion)
|
helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion)
|
||||||
helper.Logger.Info("Websocket listening", "address", listen)
|
helper.Logger.Info("Websocket listening", "address", listen)
|
||||||
|
|
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,37 +1,6 @@
|
||||||
package metadata
|
package metadata
|
||||||
|
|
||||||
import (
|
import "strings"
|
||||||
"os/exec"
|
|
||||||
"runtime/debug"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
const GoTomatoVersion = "v0.0.8" // The GoTomato version
|
||||||
GoTomatoVersion = "" // The GoTomato version
|
var ProtocolVersion = strings.Split(GoTomatoVersion, ".")[0] // The protocol 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]
|
|
||||||
}
|
|
||||||
|
|
|
@ -26,7 +26,7 @@ func waitForTimer(t Timer) bool {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// RunPomodoro iterates the Pomodoro focus/break sessions
|
// RunPomodoro iterates the Pomodoro work/break sessions
|
||||||
func RunPomodoro() {
|
func RunPomodoro() {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
shared.State.Ongoing = true
|
shared.State.Ongoing = true
|
||||||
|
@ -40,9 +40,9 @@ func RunPomodoro() {
|
||||||
|
|
||||||
shared.State.Session = session
|
shared.State.Session = session
|
||||||
|
|
||||||
// Focus
|
// Work
|
||||||
shared.State.Mode = "Focus"
|
shared.State.Mode = "Work"
|
||||||
timer.StartAsync(pomodoroConfig.Focus)
|
timer.StartAsync(pomodoroConfig.Work)
|
||||||
if !waitForTimer(timer) {
|
if !waitForTimer(timer) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
@ -74,7 +74,7 @@ func RunPomodoro() {
|
||||||
|
|
||||||
shared.State.Mode = "Idle"
|
shared.State.Mode = "Idle"
|
||||||
shared.State.Session = 0
|
shared.State.Session = 0
|
||||||
shared.State.TimeLeft = shared.State.Settings.Focus
|
shared.State.TimeLeft = shared.State.Settings.Work
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResetPomodoro() {
|
func ResetPomodoro() {
|
||||||
|
@ -111,6 +111,6 @@ func IsPomodoroPaused() bool {
|
||||||
func UpdateSettings(settings models.PomodoroConfig) {
|
func UpdateSettings(settings models.PomodoroConfig) {
|
||||||
if settings != (models.PomodoroConfig{}) {
|
if settings != (models.PomodoroConfig{}) {
|
||||||
shared.State.Settings = settings
|
shared.State.Settings = settings
|
||||||
shared.State.TimeLeft = settings.Focus
|
shared.State.TimeLeft = settings.Work
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,7 @@ var DefaultServerConfig = models.ServerConfig{
|
||||||
|
|
||||||
// The default pomodoro config if nothing else is set
|
// The default pomodoro config if nothing else is set
|
||||||
var DefaultPomodoroConfig = models.PomodoroConfig{
|
var DefaultPomodoroConfig = models.PomodoroConfig{
|
||||||
Focus: 25 * 60,
|
Work: 25 * 60,
|
||||||
ShortBreak: 5 * 60,
|
ShortBreak: 5 * 60,
|
||||||
LongBreak: 15 * 60,
|
LongBreak: 15 * 60,
|
||||||
Sessions: 4,
|
Sessions: 4,
|
||||||
|
|
|
@ -10,7 +10,7 @@ var State = models.ServerMessage{
|
||||||
Mode: "Idle",
|
Mode: "Idle",
|
||||||
Settings: DefaultPomodoroConfig,
|
Settings: DefaultPomodoroConfig,
|
||||||
Session: 0,
|
Session: 0,
|
||||||
TimeLeft: DefaultPomodoroConfig.Focus,
|
TimeLeft: DefaultPomodoroConfig.Work,
|
||||||
Ongoing: false,
|
Ongoing: false,
|
||||||
Paused: false,
|
Paused: false,
|
||||||
ProtocolVersion: metadata.ProtocolVersion,
|
ProtocolVersion: metadata.ProtocolVersion,
|
||||||
|
|
|
@ -11,27 +11,22 @@ import (
|
||||||
|
|
||||||
// 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)
|
tick := time.NewTicker(time.Second)
|
||||||
defer ticker.Stop()
|
for {
|
||||||
|
|
||||||
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.State)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
helper.Logger.Error("Error marshalling message:", "msg", err)
|
helper.Logger.Error("Error marshalling message:", "msg", 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))
|
helper.Logger.Error("Error broadcasting to client:", "msg", err)
|
||||||
|
// The client is responsible for closing itself on error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
mu.Unlock()
|
<-tick.C
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func checkSettings(settings models.PomodoroConfig) bool {
|
func checkSettings(settings models.PomodoroConfig) bool {
|
||||||
return settings.Focus > 0 && settings.ShortBreak > 0 && settings.LongBreak > 0 && settings.Sessions > 0
|
return settings.Work > 0 && settings.ShortBreak > 0 && settings.LongBreak > 0 && settings.Sessions > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// Listens for commands from a client and handles them
|
// Listens for commands from a client and handles them
|
||||||
|
@ -21,10 +21,7 @@ func handleClientCommands(c models.WebsocketClient) {
|
||||||
|
|
||||||
_, message, err := ws.ReadMessage()
|
_, message, err := ws.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// remove client on error/disconnect
|
|
||||||
mu.Lock()
|
|
||||||
delete(Clients, ws.LocalAddr())
|
delete(Clients, ws.LocalAddr())
|
||||||
mu.Unlock()
|
|
||||||
helper.Logger.Info("Client disconnected:", "msg", err, "host", c.RealIP, "clients", len(Clients))
|
helper.Logger.Info("Client disconnected:", "msg", err, "host", c.RealIP, "clients", len(Clients))
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,13 +2,18 @@ package websocket
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"sync"
|
||||||
|
|
||||||
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
||||||
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
var mu sync.Mutex // Mutex to protect access to the Clients map
|
||||||
|
|
||||||
// Upgrade HTTP requests to WebSocket connections
|
// Upgrade HTTP requests to WebSocket connections
|
||||||
var upgrader = websocket.Upgrader{
|
var upgrader = websocket.Upgrader{
|
||||||
CheckOrigin: func(r *http.Request) bool { return true },
|
CheckOrigin: func(r *http.Request) bool { return true },
|
||||||
|
@ -27,14 +32,8 @@ func HandleConnection(w http.ResponseWriter, r *http.Request) {
|
||||||
// Register the new client
|
// Register the new client
|
||||||
client := models.WebsocketClient{
|
client := models.WebsocketClient{
|
||||||
Conn: ws,
|
Conn: ws,
|
||||||
LastPong: time.Now(),
|
|
||||||
RealIP: r.RemoteAddr,
|
RealIP: r.RemoteAddr,
|
||||||
}
|
}
|
||||||
client.Conn.SetPongHandler(func(s string) error {
|
|
||||||
client.LastPong = time.Now()
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
Clients[ws.LocalAddr()] = &client
|
Clients[ws.LocalAddr()] = &client
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
|
|
|
@ -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,9 +1,9 @@
|
||||||
package models
|
package models
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
|
|
||||||
|
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Represents a command from the client (start/stop)
|
// Represents a command from the client (start/stop)
|
||||||
|
@ -16,6 +16,16 @@ type ClientCommand struct {
|
||||||
// Represents a single client
|
// Represents a single client
|
||||||
type WebsocketClient struct {
|
type WebsocketClient struct {
|
||||||
Conn *websocket.Conn
|
Conn *websocket.Conn
|
||||||
LastPong time.Time
|
|
||||||
RealIP string
|
RealIP string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sends a message to the websocket.
|
||||||
|
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
|
||||||
|
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
|
||||||
|
err := c.Conn.WriteMessage(messageType, data)
|
||||||
|
if err != nil {
|
||||||
|
helper.Logger.Error("Error writing to WebSocket:", "msg", err)
|
||||||
|
c.Conn.Close() // Close the connection on error
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
|
@ -4,7 +4,7 @@ import "fmt"
|
||||||
|
|
||||||
// Represents the configuration of a pomodoro
|
// Represents the configuration of a pomodoro
|
||||||
type PomodoroConfig struct {
|
type PomodoroConfig struct {
|
||||||
Focus int `json:"focus"` // Length of focus sessions in seconds
|
Work int `json:"work"` // Length of work 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 of long break in seconds
|
||||||
Sessions int `json:"sessions"` // Number of total sessions
|
Sessions int `json:"sessions"` // Number of total sessions
|
||||||
|
@ -12,7 +12,7 @@ type PomodoroConfig struct {
|
||||||
|
|
||||||
// Stringer interface for the PomodocoConfig model
|
// Stringer interface for the PomodocoConfig model
|
||||||
func (c PomodoroConfig) String() string {
|
func (c PomodoroConfig) String() string {
|
||||||
return fmt.Sprintf("{focus: %d, short: %d, long: %d, sessions: %d}", c.Focus, c.ShortBreak, c.LongBreak, c.Sessions)
|
return fmt.Sprintf("{work: %d, short: %d, long: %d, sessions: %d}", c.Work, c.ShortBreak, c.LongBreak, c.Sessions)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Represents the server configuration
|
// Represents the server configuration
|
||||||
|
|
|
@ -2,7 +2,7 @@ package models
|
||||||
|
|
||||||
// Represents the data sent to the client via WebSocket
|
// 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
|
Settings PomodoroConfig `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
|
||||||
|
|
Loading…
Reference in a new issue