-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlaundromates.go
More file actions
1796 lines (1558 loc) · 52.9 KB
/
Copy pathlaundromates.go
File metadata and controls
1796 lines (1558 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Laundromates is a simple go HTTP server to be called via hx-post from a frontend or GET from a user
scanning an NFC tag with preset query parameters. Users will be identified using the WhoIs response
from the tsnet client connected to the tailnet.
The server will also handle washer/dryer ntfy topics for each user that users can subscribe to for updates.
After starting a machine, a ntfy message is published to the topic laundromates-<user> after <duration> has passed
to notify the user that the machine is done. If a user requests a machine that is already in use,
the server will publish a message to the ntfy topic of the user who is currently using the machine,
indicating that someone else is requesting to use the machine. If a user clears a machine and a user is waiting
for that machine, the server will publish a message to the ntfy topic of the user who is waiting to notify them
that the machine has been cleared and is now available for use.
*/
package main
import (
"bytes"
"context"
"crypto/tls"
"embed"
"encoding/json"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"tailscale.com/tsnet"
)
//go:embed assets/static/* assets/templates/*
var assets embed.FS
type server struct {
mux *http.ServeMux
tsnet *tsnet.Server
state *state
users map[string]*user
mu sync.RWMutex
serverBaseURL string
nonTSURL string
ntfyBaseURL string
discordWebhook string
allowNonTS bool
allowedDomains []string
debugEnabled bool
}
var srv *server = &server{}
type user struct {
Name string `json:"name"`
NameLower string `json:"name_lower"`
SanitizedName string `json:"sanitized_name"` // Name sanitized for ntfy topic usage
IPs []string `json:"ips,omitempty"` // Only used if LAUNDROMATES_ALLOW_NON_TS is true
}
type machine struct {
Active bool `json:"active"`
Name string `json:"name"` // "washer" or "dryer"
User *user `json:"user,omitempty"`
Timer *time.Timer `json:"-"`
StartTime time.Time `json:"start_time,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
Waiter *user `json:"waiter,omitempty"`
WaitingFor *time.Timer `json:"-"`
WaitStartTime time.Time `json:"wait_start_time,omitempty"`
Scheduled *scheduledLoad `json:"scheduled,omitempty"`
cancelFunc context.CancelFunc `json:"-"`
reminderCancels []context.CancelFunc `json:"-"`
scheduledCancel context.CancelFunc `json:"-"` // Cancel function for scheduled notifications
mu sync.RWMutex
}
type scheduledLoad struct {
User *user `json:"user"`
ScheduledTime time.Time `json:"scheduled_time"`
}
// TimeRemaining calculates how much time is left on the machine
func (mch *machine) TimeRemaining() time.Duration {
mch.mu.RLock()
if !mch.Active || mch.StartTime.IsZero() {
return 0
}
elapsed := time.Since(mch.StartTime)
remaining := mch.Duration - elapsed
mch.mu.RUnlock()
if remaining < 0 {
return 0
}
return remaining
}
// TimeRemainingFormatted returns the remaining time formatted as "HHh MMm SSs"
func (mch *machine) TimeRemainingFormatted() string {
remaining := mch.TimeRemaining()
if remaining == 0 {
return "0s"
}
hours := int(remaining.Hours())
minutes := int(remaining.Minutes()) % 60
seconds := int(remaining.Seconds()) % 60
out := fmt.Sprintf("%02ds", seconds)
if minutes > 0 {
out = fmt.Sprintf("%02dm %s", minutes, out)
}
if hours > 0 {
out = fmt.Sprintf("%02dh %s", hours, out)
}
return out
}
// WaitingTimeFormatted returns how long the waiter has been waiting, formatted as "HHh MMm SSs"
func (mch *machine) WaitingTimeFormatted() string {
mch.mu.RLock()
defer mch.mu.RUnlock()
if mch.Waiter == nil || mch.WaitStartTime.IsZero() {
return ""
}
elapsed := time.Since(mch.WaitStartTime)
hours := int(elapsed.Hours())
minutes := int(elapsed.Minutes()) % 60
seconds := int(elapsed.Seconds()) % 60
out := fmt.Sprintf("%02ds", seconds)
if minutes > 0 {
out = fmt.Sprintf("%02dm %s", minutes, out)
}
if hours > 0 {
out = fmt.Sprintf("%02dh %s", hours, out)
}
return out
}
// IsExpired checks if the machine's time has expired
func (mch *machine) IsExpired() bool {
mch.mu.RLock()
defer mch.mu.RUnlock()
return mch.Active && mch.TimeRemaining() == 0
}
type state struct {
Washer *machine `json:"washer"`
Dryer *machine `json:"dryer"`
Users map[string]*user `json:"users"`
}
func (srv *server) DebugLog(format string, v ...interface{}) {
if srv.debugEnabled {
log.Printf(format, v...)
}
}
// sanitizeNtfyTopic sanitizes a username for use in ntfy topic names
// by replacing spaces and @ symbols with dashes
func sanitizeNtfyTopic(name string) string {
sanitized := strings.ReplaceAll(name, " ", "-")
sanitized = strings.ReplaceAll(sanitized, "@", "-")
return sanitized
}
func main() {
log.Println("Starting Laundromates server...")
if _, err := os.Stat("state"); os.IsNotExist(err) {
log.Println("State directory does not exist, if this is running in a container please make sure a volume is mounted to /app/state. Creating (potentially transient) state directory...")
if err := os.Mkdir("state", 0755); err != nil {
log.Fatalf("Failed to create state directory: %v", err)
}
} else if err != nil {
log.Fatalf("Failed to check state directory: %v", err)
}
// Configure Tailscale client credentials
clientSecret := os.Getenv("TS_CLIENT_SECRET")
clientID := os.Getenv("TS_CLIENT_ID")
// Validate authentication configuration
hasOAuth := clientSecret != "" && clientID != ""
hasAuthKey := os.Getenv("TS_AUTHKEY") != ""
if hasOAuth {
log.Println("Using TS_CLIENT_SECRET and TS_CLIENT_ID for OAuth authentication")
} else if !hasAuthKey {
log.Fatal("Either TS_AUTHKEY or both TS_CLIENT_SECRET and TS_CLIENT_ID must be set")
} else if (clientSecret != "" && clientID == "") || (clientSecret == "" && clientID != "") {
log.Fatal("Both TS_CLIENT_SECRET and TS_CLIENT_ID must be set together for OAuth authentication")
}
// Configure ntfy server
srv.ntfyBaseURL = os.Getenv("LAUNDROMATES_NTFY_SERVER")
if srv.ntfyBaseURL == "" {
srv.ntfyBaseURL = "https://ntfy.sh/"
}
if !strings.HasSuffix(srv.ntfyBaseURL, "/") {
srv.ntfyBaseURL += "/"
}
log.Printf("Using ntfy server: %s", srv.ntfyBaseURL)
srv.debugEnabled = os.Getenv("LAUNDROMATES_DEBUG") == "true"
// Configure non-Tailscale URL for notifications
srv.nonTSURL = os.Getenv("LAUNDROMATES_NON_TS_URL")
if srv.nonTSURL != "" {
log.Printf("Using non-Tailscale URL for notifications: %s", srv.nonTSURL)
}
// Configure Discord webhook
srv.discordWebhook = os.Getenv("LAUNDROMATES_DISCORD_WEBHOOK")
if srv.discordWebhook != "" {
log.Printf("Discord webhook notifications enabled")
}
// Configure non-Tailscale access
srv.allowNonTS = os.Getenv("LAUNDROMATES_ALLOW_NON_TS") == "true"
if srv.allowNonTS {
log.Printf("Allowing non-Tailscale access: %v", srv.allowNonTS)
}
// Configure allowed tailnet user domains (for invited users or node sharing)
allowedDomainsStr := os.Getenv("LAUNDROMATES_ALLOWED_DOMAINS")
if allowedDomainsStr != "" {
domains := strings.Split(allowedDomainsStr, ",")
for _, domain := range domains {
if domain == "" {
continue
}
srv.allowedDomains = append(srv.allowedDomains, strings.TrimSpace(strings.ToLower(domain)))
}
log.Printf("Allowed domains: %v", srv.allowedDomains)
}
hostname := os.Getenv("TS_HOSTNAME")
if hostname == "" {
log.Println("TS_HOSTNAME environment variable is not set, using default hostname 'laundromates'")
hostname = "laundromates"
}
// Configure control server URL
controlURL := os.Getenv("TS_CONTROL_URL")
if controlURL != "" {
log.Printf("Using custom control URL: %s", controlURL)
}
// Configure advertise tags
var advertiseTags []string
advertiseTagsStr := os.Getenv("TS_ADVERTISE_TAGS")
if advertiseTagsStr != "" {
tags := strings.Split(advertiseTagsStr, ",")
for _, tag := range tags {
tag = strings.TrimSpace(tag)
if tag != "" {
advertiseTags = append(advertiseTags, tag)
}
}
log.Printf("Advertising tags: %v", advertiseTags)
}
// Configure HTTP port
httpPort := os.Getenv("LAUNDROMATES_HTTP_PORT")
if httpPort == "" {
httpPort = "12012"
}
log.Printf("HTTP server will listen on port %s", httpPort)
log.Println("Starting Tailscale...")
if _, err := os.Stat("state/tsnet"); os.IsNotExist(err) {
log.Println("State directory for Tailscale does not exist, creating...")
if err := os.MkdirAll("state/tsnet", 0755); err != nil {
log.Fatalf("Failed to create Tailscale state directory: %v", err)
}
} else if err != nil {
log.Fatalf("Failed to check Tailscale state directory: %v", err)
}
srv.tsnet = &tsnet.Server{
Hostname: hostname,
AuthKey: os.Getenv("TS_AUTHKEY"),
ClientSecret: clientSecret,
ClientID: clientID,
ControlURL: controlURL,
AdvertiseTags: advertiseTags,
Ephemeral: true,
Dir: "state/tsnet",
}
if err := srv.tsnet.Start(); err != nil {
log.Fatalf("Failed to start Tailscale: %v", err)
}
defer srv.tsnet.Close()
// Wait for Tailscale to be ready
for {
lc, err := srv.tsnet.LocalClient()
if err != nil {
log.Printf("Failed to get Tailscale local client: %v", err)
time.Sleep(1 * time.Second)
continue
}
status, err := lc.Status(context.Background())
if err != nil {
log.Printf("Failed to get Tailscale status: %v", err)
time.Sleep(1 * time.Second)
continue
}
if status.BackendState == "Running" {
if os.Getenv("LAUNDROMATES_URL_OVERRIDE") != "" {
srv.DebugLog("publishMessage: Using URL override: %s", os.Getenv("LAUNDROMATES_URL_OVERRIDE"))
srv.serverBaseURL = os.Getenv("LAUNDROMATES_URL_OVERRIDE")
} else {
srv.serverBaseURL = fmt.Sprintf("https://%s", status.CertDomains[0])
}
log.Printf("Application will be reachable at %s", srv.serverBaseURL)
break
}
log.Printf("Tailscale is not running yet, current state: %s", status.BackendState)
time.Sleep(2 * time.Second)
}
// Initialize state
srv.users = make(map[string]*user)
srv.state = &state{
Washer: &machine{
Active: false,
Name: "washer",
User: nil,
Timer: nil,
StartTime: time.Time{},
Duration: 1 * time.Hour,
Waiter: nil,
WaitingFor: nil,
WaitStartTime: time.Time{},
reminderCancels: make([]context.CancelFunc, 0),
},
Dryer: &machine{
Active: false,
Name: "dryer",
User: nil,
Timer: nil,
StartTime: time.Time{},
Duration: 1 * time.Hour,
Waiter: nil,
WaitingFor: nil,
WaitStartTime: time.Time{},
reminderCancels: make([]context.CancelFunc, 0),
},
Users: srv.users,
}
// Load state from file if it exists
loadState()
// Start periodic state saving
go func() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for range ticker.C {
saveState()
}
}()
// Set up HTTP routes
srv.mux = http.NewServeMux()
// Serve static files from embedded assets
staticFS, err := fs.Sub(assets, "assets/static")
if err != nil {
log.Fatalf("Failed to create static file system: %v", err)
}
srv.mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
srv.mux.HandleFunc("POST /identify", userIDResponseHandler)
srv.mux.Handle("/machine", userMiddleware(http.HandlerFunc(machineHandler)))
srv.mux.Handle("/schedule", userMiddleware(http.HandlerFunc(scheduleHandler)))
srv.mux.Handle("/", userMiddleware(http.HandlerFunc(indexHandler)))
tsLn, err := srv.tsnet.Listen("tcp", ":443")
if err != nil {
log.Fatalf("Failed to listen on Tailscale interface: %v", err)
}
defer tsLn.Close()
// Get TLS config from tsnet
lc, err := srv.tsnet.LocalClient()
if err != nil {
log.Fatalf("Failed to get local client: %v", err)
}
// Create TLS config
tlsConfig := &tls.Config{
GetCertificate: lc.GetCertificate,
}
tsHTTPS := &http.Server{
Handler: srv.mux,
TLSConfig: tlsConfig,
}
// Listen on all interfaces on configured HTTP port
httpAddr := ":" + httpPort
httpLn, err := net.Listen("tcp", httpAddr)
if err != nil {
log.Fatalf("Failed to listen on port %s: %v", httpPort, err)
}
defer httpLn.Close()
httpServer := &http.Server{
Handler: srv.mux,
}
srv.DebugLog("Server started on :443 (Tailscale HTTPS) and :%s (HTTP)", httpPort)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
serverErr := make(chan error, 2)
// Start HTTPS server on Tailscale interface
go func() {
serverErr <- tsHTTPS.ServeTLS(tsLn, "", "")
}()
// Start HTTP server on all interfaces
go func() {
serverErr <- httpServer.Serve(httpLn)
}()
select {
case <-ctx.Done():
log.Println("Received shutdown signal, shutting down...")
srv.mu.Lock()
// Ignore any scheduled notifications, those goroutines will exit on shutdown
srv.state.Washer.cancelFunc = nil
srv.state.Dryer.cancelFunc = nil
for _, mch := range []*machine{srv.state.Washer, srv.state.Dryer} {
for _, cancel := range mch.reminderCancels {
cancel()
}
mch.reminderCancels = make([]context.CancelFunc, 0)
}
srv.mu.Unlock()
// Save state before shutdown
saveState()
// Logout from Tailscale
lc, err := srv.tsnet.LocalClient()
if err != nil {
log.Printf("Failed to get Tailscale local client: %v", err)
} else {
if err := lc.Logout(context.Background()); err != nil {
log.Printf("Failed to logout Tailscale client: %v", err)
} else {
log.Println("Successfully logged out Tailscale client")
}
}
// Shutdown servers
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := tsHTTPS.Shutdown(shutdownCtx); err != nil {
log.Printf("Failed to shutdown HTTPS server: %v", err)
}
if err := httpServer.Shutdown(shutdownCtx); err != nil {
log.Printf("Failed to shutdown HTTP server: %v", err)
}
log.Println("Server shutdown complete")
return
case err := <-serverErr:
if err != nil {
log.Fatalf("Server error: %v", err)
}
}
}
const stateFile = "state/laundromates_state.json"
func loadState() {
data, err := os.ReadFile(stateFile)
if err != nil {
if !os.IsNotExist(err) {
log.Printf("Failed to read state file: %v", err)
}
return
}
var savedState state
if err := json.Unmarshal(data, &savedState); err != nil {
log.Printf("Failed to unmarshal state: %v", err)
return
}
srv.mu.Lock()
defer srv.mu.Unlock()
// Restore users
srv.users = savedState.Users
srv.state.Users = savedState.Users
// Ensure all users have SanitizedName set (for backward compatibility)
for _, u := range srv.users {
if u.SanitizedName == "" {
u.SanitizedName = sanitizeNtfyTopic(u.NameLower)
}
}
// Restore machine states
if savedState.Washer != nil {
srv.state.Washer.Active = savedState.Washer.Active
srv.state.Washer.User = savedState.Washer.User
srv.state.Washer.StartTime = savedState.Washer.StartTime
srv.state.Washer.Duration = savedState.Washer.Duration
srv.state.Washer.Waiter = savedState.Washer.Waiter
srv.state.Washer.WaitStartTime = savedState.Washer.WaitStartTime
srv.state.Washer.Scheduled = savedState.Washer.Scheduled
// Restart timers if machine is active
if srv.state.Washer.Active && !srv.state.Washer.StartTime.IsZero() {
remaining := srv.state.Washer.TimeRemaining()
if remaining > 0 {
restartMachineTimer(srv.state.Washer, remaining)
}
}
// Restart scheduled notification if present
if srv.state.Washer.Scheduled != nil {
scheduleNotification(srv.state.Washer)
}
}
if savedState.Dryer != nil {
srv.state.Dryer.Active = savedState.Dryer.Active
srv.state.Dryer.User = savedState.Dryer.User
srv.state.Dryer.StartTime = savedState.Dryer.StartTime
srv.state.Dryer.Duration = savedState.Dryer.Duration
srv.state.Dryer.Waiter = savedState.Dryer.Waiter
srv.state.Dryer.WaitStartTime = savedState.Dryer.WaitStartTime
srv.state.Dryer.Scheduled = savedState.Dryer.Scheduled
// Restart timers if machine is active
if srv.state.Dryer.Active && !srv.state.Dryer.StartTime.IsZero() {
remaining := srv.state.Dryer.TimeRemaining()
if remaining > 0 {
restartMachineTimer(srv.state.Dryer, remaining)
}
}
// Restart scheduled notification if present
if srv.state.Dryer.Scheduled != nil {
scheduleNotification(srv.state.Dryer)
}
}
srv.DebugLog("State loaded from %s", stateFile)
}
func saveState() {
srv.mu.RLock()
defer srv.mu.RUnlock()
stateToSave := state{
Washer: srv.state.Washer,
Dryer: srv.state.Dryer,
Users: srv.users,
}
data, err := json.MarshalIndent(stateToSave, "", " ")
if err != nil {
log.Printf("Failed to marshal state: %v", err)
return
}
if err := os.WriteFile(stateFile, data, 0644); err != nil {
log.Printf("Failed to write state file: %v", err)
return
}
srv.DebugLog("State saved to %s", stateFile)
}
func restartMachineTimer(mch *machine, remaining time.Duration) {
ctx, cancel := context.WithCancel(context.Background())
mch.mu.Lock()
mch.cancelFunc = cancel
dryerAvailable := srv.state.Dryer.User == nil
mch.mu.Unlock()
go func(ctx context.Context, delay time.Duration) {
select {
case <-time.After(delay):
if err := publishMessage(mch.User.SanitizedName, mch.Name, "start", dryerAvailable); err != nil {
log.Printf("restartMachineTimer: Failed to publish completion message: %v", err)
} else {
log.Printf("restartMachineTimer: Successfully published completion message to topic laundromates-%s", mch.User.SanitizedName)
}
case <-ctx.Done():
log.Printf("restartMachineTimer: Scheduled completion message cancelled for %s", mch.Name)
}
}(ctx, remaining)
}
// indexHandler handles the index page requests
func indexHandler(w http.ResponseWriter, r *http.Request) {
srv.DebugLog("indexHandler: Received request")
currentUser := r.Context().Value("userName")
if currentUser == nil {
srv.DebugLog("indexHandler: User not identified, prompting for identification")
if srv.allowNonTS {
promptUserForIdentification(w, r)
} else {
http.Error(w, "Forbidden", http.StatusForbidden)
}
return
}
srv.mu.RLock()
cu, ok := srv.users[currentUser.(string)]
srv.mu.RUnlock()
if !ok {
log.Printf("indexHandler: User could not be retrieved: %s", currentUser)
http.Error(w, "User not found", http.StatusInternalServerError)
return
}
// Ensure SanitizedName is set (defensive programming)
srv.mu.Lock()
if cu.SanitizedName == "" {
cu.SanitizedName = sanitizeNtfyTopic(cu.NameLower)
log.Printf("indexHandler: Set SanitizedName for user %s to %s", cu.Name, cu.SanitizedName)
}
srv.mu.Unlock()
ntfyURL := srv.ntfyBaseURL + "laundromates-" + cu.SanitizedName
if strings.HasPrefix(ntfyURL, "https://") {
ntfyURL = strings.TrimPrefix(ntfyURL, "https://")
} else if strings.HasPrefix(ntfyURL, "http://") {
ntfyURL = strings.TrimPrefix(ntfyURL, "http://")
}
srv.DebugLog("indexHandler: ntfyURL constructed as: %s", ntfyURL)
srv.mu.RLock()
data := struct {
Washer *machine
Dryer *machine
CurrentUser *user
NtfyURL string
NtfyMobileURL string
}{
Washer: srv.state.Washer,
Dryer: srv.state.Dryer,
CurrentUser: cu,
NtfyURL: ntfyURL,
}
srv.mu.RUnlock()
tmpl, err := template.ParseFS(assets, "assets/templates/index.html", "assets/templates/machine.html")
if err != nil {
log.Printf("indexHandler: Failed to parse template: %v", err)
http.Error(w, "Failed to parse template", http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, data); err != nil {
log.Printf("indexHandler: Failed to render template: %v", err)
http.Error(w, "Failed to render template", http.StatusInternalServerError)
return
}
srv.DebugLog("indexHandler: Successfully handled request")
}
func promptUserForIdentification(w http.ResponseWriter, r *http.Request) {
srv.DebugLog("promptUserForIdentification: Prompting user for identification")
tmpl, err := template.ParseFS(assets, "assets/templates/identify.html")
if err != nil {
log.Printf("promptUserForIdentification: Failed to parse template: %v", err)
http.Error(w, "Failed to parse template", http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, nil); err != nil {
log.Printf("promptUserForIdentification: Failed to render template: %v", err)
http.Error(w, "Failed to render template", http.StatusInternalServerError)
return
}
srv.DebugLog("promptUserForIdentification: Successfully prompted user for identification")
}
func userIDResponseHandler(w http.ResponseWriter, r *http.Request) {
if !srv.allowNonTS {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
srv.DebugLog("userIDResponseHandler: Received user response for identification")
name := r.FormValue("name")
nameLower := strings.ToLower(name)
if name == "" {
log.Println("userIDResponseHandler: No name provided, prompting user again")
promptUserForIdentification(w, r)
return
}
srv.DebugLog("userIDResponseHandler: User identified as %s", name)
srv.mu.Lock()
reqUser, exists := srv.users[nameLower]
if !exists {
log.Printf("userIDResponseHandler: User %s not found, creating new user", name)
newUser := &user{
Name: name,
NameLower: nameLower,
SanitizedName: sanitizeNtfyTopic(nameLower),
IPs: []string{},
}
srv.users[nameLower] = newUser
reqUser = newUser
}
if r.RemoteAddr != "" {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
srv.mu.Unlock()
log.Printf("userIDResponseHandler: Failed to parse remote address: %v", err)
http.Error(w, "Failed to parse remote address", http.StatusInternalServerError)
return
}
if !strings.Contains(strings.Join(reqUser.IPs, ","), ip) {
log.Printf("userIDResponseHandler: Adding IP %s to user %s", ip, reqUser.Name)
reqUser.IPs = append(reqUser.IPs, ip)
} else {
log.Printf("userIDResponseHandler: IP %s already exists for user %s", ip, reqUser.Name)
}
}
srv.mu.Unlock()
ctx := context.WithValue(r.Context(), "userName", reqUser.NameLower)
indexHandler(w, r.WithContext(ctx))
}
func machineHandler(w http.ResponseWriter, r *http.Request) {
srv.DebugLog("machineHandler: Received request")
userName := r.Context().Value("userName").(string)
srv.DebugLog("machineHandler: User identified as %s", userName)
if userName == "" {
log.Println("machineHandler: User not identified, reprompting for identification")
if srv.allowNonTS {
promptUserForIdentification(w, r)
} else {
http.Error(w, "Forbidden", http.StatusForbidden)
}
return
}
srv.mu.RLock()
reqUser := srv.users[userName]
srv.mu.RUnlock()
if reqUser == nil {
log.Printf("machineHandler: Error retrieving user %s", userName)
http.Error(w, "User not found", http.StatusInternalServerError)
return
}
srv.DebugLog("machineHandler: User %s found", reqUser.Name)
// Parse form values
action := r.FormValue("action")
machineType := r.FormValue("machine")
// Fallback to query parameters if form values are not set
if action == "" || machineType == "" {
action = r.URL.Query().Get("action")
machineType = r.URL.Query().Get("machine")
}
if action == "" || (action != "start" && action != "clear" && action != "request" && action != "move") {
log.Println("machineHandler: Invalid or missing action")
http.Error(w, "Invalid action", http.StatusBadRequest)
return
}
if machineType == "" || (machineType != "washer" && machineType != "dryer") {
log.Println("machineHandler: Machine type not specified or invalid")
http.Error(w, "No machine type specified", http.StatusBadRequest)
return
}
var mch *machine
srv.mu.RLock()
if machineType == "washer" {
mch = srv.state.Washer
} else {
mch = srv.state.Dryer
}
srv.mu.RUnlock()
// Perform the requested action
switch action {
case "start":
duration := parseDuration(r.FormValue("duration"))
if duration == 0 {
durationParam := r.URL.Query().Get("duration")
duration = parseDuration(durationParam)
}
log.Printf("machineHandler: Parsed duration: %v minutes", duration.Minutes())
if err := mch.start(reqUser, duration); err != nil {
log.Printf("machineHandler: Failed to start %s: %v", machineType, err)
http.Error(w, fmt.Sprintf("Failed to start %s", machineType), http.StatusInternalServerError)
return
}
srv.DebugLog("machineHandler: User %s started %s for %v", reqUser.Name, machineType, duration)
saveState() // Save state after starting
case "clear":
if err := mch.clear(); err != nil {
log.Printf("machineHandler: Failed to clear %s: %v", machineType, err)
http.Error(w, fmt.Sprintf("Failed to clear %s", machineType), http.StatusInternalServerError)
return
}
srv.DebugLog("machineHandler: User %s cleared %s", reqUser.Name, machineType)
saveState()
case "move":
duration := parseDuration(r.FormValue("duration"))
if duration == 0 {
durationParam := r.URL.Query().Get("duration")
duration = parseDuration(durationParam)
}
srv.DebugLog("machineHandler: Parsed duration for move: %v minutes", duration.Minutes())
if machineType != "washer" {
log.Printf("machineHandler: Invalid machine type for move: %s", machineType)
http.Error(w, "Invalid machine type for move", http.StatusBadRequest)
return
}
if srv.state.Dryer.Active {
log.Printf("machineHandler: Cannot move to dryer, it is already being used")
http.Error(w, "Dryer is already in use", http.StatusConflict)
return
}
if err := mch.clear(); err != nil {
log.Printf("machineHandler: Failed to clear %s before moving: %v", machineType, err)
http.Error(w, fmt.Sprintf("Failed to clear %s before moving", machineType), http.StatusInternalServerError)
return
}
if err := srv.state.Dryer.start(reqUser, duration); err != nil {
log.Printf("machineHandler: Failed to start dryer after moving from %s: %v", machineType, err)
http.Error(w, "Failed to start dryer after moving", http.StatusInternalServerError)
return
}
srv.DebugLog("machineHandler: User %s moved from %s to dryer for %v", reqUser.Name, machineType, duration)
saveState()
case "request":
if err := mch.request(reqUser); err != nil {
log.Printf("machineHandler: Failed to request %s: %v", machineType, err)
http.Error(w, fmt.Sprintf("Failed to request %s", machineType), http.StatusInternalServerError)
return
}
srv.DebugLog("machineHandler: User %s requested %s", reqUser.Name, machineType)
saveState()
}
if r.Method == http.MethodGet {
log.Println("machineHandler: Redirecting to index after action")
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
// Render the machine template for the specific machine
srv.mu.RLock()
data := struct {
Washer *machine
Dryer *machine
CurrentUser *user
}{
Washer: srv.state.Washer,
Dryer: srv.state.Dryer,
CurrentUser: reqUser,
}
srv.mu.RUnlock()
tmpl, err := template.ParseFS(assets, "assets/templates/machine.html")
if err != nil {
log.Printf("machineHandler: Failed to parse template: %v", err)
http.Error(w, "Failed to parse template", http.StatusInternalServerError)
return
}
// Use the appropriate template based on machine type and view
var templateName string
if r.FormValue("view") == "desktop" {
templateName = fmt.Sprintf("machine-row-%s", machineType)
} else {
templateName = fmt.Sprintf("machine-card-%s", machineType)
}
if err := tmpl.ExecuteTemplate(w, templateName, data); err != nil {
log.Printf("machineHandler: Failed to render template: %v", err)
http.Error(w, "Failed to render template", http.StatusInternalServerError)
return
}
srv.DebugLog("machineHandler: Successfully handled request")
}
func scheduleHandler(w http.ResponseWriter, r *http.Request) {
srv.DebugLog("scheduleHandler: Received request")
userName := r.Context().Value("userName").(string)
if userName == "" {
log.Println("scheduleHandler: User not identified")
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
srv.mu.RLock()
reqUser := srv.users[userName]
srv.mu.RUnlock()
if reqUser == nil {
log.Printf("scheduleHandler: Error retrieving user %s", userName)
http.Error(w, "User not found", http.StatusInternalServerError)
return
}
action := r.FormValue("action")
machineType := r.FormValue("machine")
if machineType == "" || (machineType != "washer" && machineType != "dryer") {
log.Println("scheduleHandler: Machine type not specified or invalid")
http.Error(w, "No machine type specified", http.StatusBadRequest)
return
}
var mch *machine
srv.mu.RLock()
if machineType == "washer" {
mch = srv.state.Washer
} else {
mch = srv.state.Dryer
}
srv.mu.RUnlock()
switch action {
case "schedule":
day := r.FormValue("day")
timeOfDay := r.FormValue("time")
scheduledTime, err := parseScheduledTime(day, timeOfDay)
if err != nil {
log.Printf("scheduleHandler: Failed to parse scheduled time: %v", err)
http.Error(w, "Invalid scheduled time", http.StatusBadRequest)
return
}
mch.mu.Lock()
// Cancel existing scheduled notification if present
if mch.scheduledCancel != nil {
mch.scheduledCancel()
}
mch.Scheduled = &scheduledLoad{
User: reqUser,
ScheduledTime: scheduledTime,
}
mch.mu.Unlock()
// Start the scheduled notification
scheduleNotification(mch)
srv.DebugLog("scheduleHandler: User %s scheduled %s for %v", reqUser.Name, machineType, scheduledTime)
saveState()
case "cancel":
mch.mu.Lock()
if mch.Scheduled != nil && mch.Scheduled.User.NameLower == reqUser.NameLower {
// Cancel the scheduled notification
if mch.scheduledCancel != nil {
mch.scheduledCancel()
mch.scheduledCancel = nil
}
mch.Scheduled = nil
srv.DebugLog("scheduleHandler: User %s cancelled scheduled %s", reqUser.Name, machineType)
}
mch.mu.Unlock()
saveState()
default: