-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
1385 lines (1207 loc) · 42.4 KB
/
Copy pathapp.go
File metadata and controls
1385 lines (1207 loc) · 42.4 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
package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
"sctroll/internal/actions"
"sctroll/internal/autostart"
"sctroll/internal/config"
"sctroll/internal/debuglog"
"sctroll/internal/input"
"sctroll/internal/keylock"
"sctroll/internal/starcitizen"
"sctroll/internal/twitch"
"sctroll/internal/updater"
"sctroll/internal/version"
)
type App struct {
ctx context.Context
cfg *config.Config
twClient *twitch.Client
executor *actions.Executor
keyLocker *keylock.KeyLocker
rewardMu sync.Mutex // serializes SyncRewards / DeleteAllRewards
}
func NewApp() *App {
return &App{}
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
cfg, err := config.Load()
if err != nil {
cfg = config.DefaultConfig()
}
a.cfg = cfg
a.keyLocker = keylock.New(cfg.TargetWindow)
a.keyLocker.Start()
a.keyLocker.SetOnKeyBlocked(func(key string) {
runtime.EventsEmit(a.ctx, "key-blocked", key)
})
input.SetMode(cfg.InputMode)
a.executor = actions.NewExecutor(cfg, a.keyLocker)
a.executor.SetOnAction(func(actionID, userName string) {
runtime.EventsEmit(a.ctx, "action-executed", map[string]string{
"action": actionID,
"user": userName,
})
})
// Reste eines vorherigen Updates wegräumen, solange nichts anderes läuft.
updater.CleanupOld()
// Nach einem Update oder einem verschobenen Ordner zeigt ein bestehender
// Autostart-Eintrag womöglich ins Leere.
autostart.Refresh()
// Alte Twitch-App ablösen. Die Rewards der alten App sind für die neue nicht
// mehr verwaltbar, deshalb müssen auch die Verknüpfungen weg -- sonst hält
// SCTroll Reward-IDs fest, die es nicht mehr anfassen darf.
if twitch.MigrateLegacyApp(&cfg.Twitch) {
for _, act := range cfg.GetActions() {
if act.RewardID != "" {
act.RewardID = ""
cfg.SetAction(act)
}
}
_ = cfg.Save()
go func() {
<-time.After(2 * time.Second) // erst wenn die Oberfläche lauscht
runtime.EventsEmit(a.ctx, "twitch-log",
"Twitch-App gewechselt — bitte einmal neu verbinden und die Rewards neu anlegen")
runtime.EventsEmit(a.ctx, "twitch-disconnected", "App gewechselt")
}()
}
go a.autoDetectStarCitizen()
go a.autoCheckUpdate()
// Der Refresh Token entscheidet, nicht der Access Token: der ist nach ein
// paar Stunden ohnehin abgelaufen und wird beim Verbinden erneuert.
if cfg.Twitch.HasLogin() {
go a.autoConnect()
}
}
// autoDetectStarCitizen sucht die Installation, sofern noch keine (oder eine
// nicht mehr existierende) hinterlegt ist.
func (a *App) autoDetectStarCitizen() {
known := false
if a.cfg.SCDir != "" {
if _, err := os.Stat(a.cfg.SCDir); err == nil {
known = true
} else {
debuglog.Log("autoDetect: hinterlegter Pfad existiert nicht mehr: %s", a.cfg.SCDir)
}
}
if !known {
installs := starcitizen.FindInstalls()
if len(installs) == 0 {
runtime.EventsEmit(a.ctx, "twitch-log",
"Star Citizen nicht gefunden — Ordner bitte in den Einstellungen wählen")
return
}
a.cfg.SCDir = installs[0].Dir
a.cfg.SCChannel = installs[0].Channel
_ = a.cfg.Save()
runtime.EventsEmit(a.ctx, "sc-detected", installs[0])
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Star Citizen %s gefunden: %s", installs[0].Channel, installs[0].Dir))
}
a.fillMissingKeys()
}
// fillMissingKeys holt beim Start die Tasten fuer Aktionen, die noch keine
// haben, aus dem Spielprofil.
//
// Betrifft vor allem Aktionen, die Star Citizen ab Werk nicht belegt -- Emotes
// und Tueren. Wer die im Spiel gebunden hat, soll sie nicht jedes Mal von Hand
// nachtragen muessen. Bereits gesetzte Tasten bleiben unangetastet; ein
// vollstaendiger Abgleich passiert nur ueber den Knopf in den Einstellungen.
func (a *App) fillMissingKeys() {
path, err := a.actionMapsPath()
if err != nil {
return
}
am, err := starcitizen.Load(path)
if err != nil {
return
}
overrides := am.AllKeyboardBinds()
filled := 0
for _, act := range a.cfg.GetActions() {
if act.SCAction == "" || act.Key != "" {
continue
}
key, source, hold := effectiveBind(act, overrides)
if key == "" {
continue
}
act.Key = key
if hold > act.HoldMs {
act.HoldMs = hold
}
a.cfg.SetAction(act)
filled++
debuglog.Log("fillMissingKeys: %s (%s) -> %q [%s]", act.ID, act.SCAction, key, source)
}
if filled > 0 {
_ = a.cfg.Save()
runtime.EventsEmit(a.ctx, "actions-updated", nil)
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("%d fehlende Tasten aus dem Spielprofil ergänzt", filled))
}
}
func (a *App) shutdown(ctx context.Context) {
debuglog.Log("=== SCTroll beendet ===")
if a.twClient != nil {
a.twClient.Disconnect()
}
a.keyLocker.Stop()
a.cfg.Save()
debuglog.Close()
}
// --- Config Methods ---
func (a *App) GetConfig() *config.Config {
return a.cfg
}
func (a *App) GetActions() []config.Action {
return a.cfg.GetActions()
}
func (a *App) UpdateAction(action config.Action) error {
a.cfg.SetAction(action)
if err := a.cfg.Save(); err != nil {
return err
}
// Sync changes to Twitch if connected and reward exists
if a.twClient != nil && a.twClient.IsConnected() && action.RewardID != "" {
if err := a.twClient.UpdateRewardSpec(action.RewardID, rewardSpec(action)); err != nil {
debuglog.Log("UpdateAction: Twitch sync error: %s", err)
} else {
debuglog.Log("UpdateAction: Twitch reward updated for %s", action.ID)
}
}
return nil
}
// rewardSpec uebersetzt eine Aktion in die Beschreibung ihrer Twitch-Belohnung.
//
// An einer Stelle, damit Anlegen und Aendern nicht auseinanderlaufen -- genau
// das war frueher der Fall, weshalb Aenderungen an Grenzen oder Beschreibung
// beim Anlegen anders behandelt wurden als beim Bearbeiten.
func rewardSpec(a config.Action) twitch.RewardSpec {
cooldownMs := a.Cooldown
if a.TwitchCooldown > 0 {
cooldownMs = a.TwitchCooldown * 1000
}
return twitch.RewardSpec{
Title: a.RewardTitle,
Cost: a.RewardCost,
CooldownMs: cooldownMs,
Color: a.RewardColor,
Prompt: a.Description,
MaxPerStream: a.MaxPerStream,
MaxPerUserPerStream: a.MaxPerUserPerStream,
}
}
func (a *App) AddCustomAction(action config.Action) (config.Action, error) {
action.ID = fmt.Sprintf("custom_%d", time.Now().UnixNano())
action.Custom = true
action.Enabled = false
if action.Name == "" || action.Key == "" || action.RewardTitle == "" {
return action, fmt.Errorf("Name, Key und Reward-Titel sind erforderlich")
}
a.cfg.SetAction(action)
if err := a.cfg.Save(); err != nil {
return action, err
}
debuglog.Log("AddCustomAction: created %s (%s)", action.ID, action.Name)
runtime.EventsEmit(a.ctx, "actions-updated", nil)
return action, nil
}
func (a *App) DeleteAction(id string) error {
actions := a.cfg.GetActions()
var target *config.Action
for _, act := range actions {
if act.ID == id {
act := act
target = &act
break
}
}
if target == nil {
return fmt.Errorf("action not found: %s", id)
}
if !target.Custom {
return fmt.Errorf("cannot delete default action: %s", id)
}
// Delete Twitch reward if it exists
if target.RewardID != "" && a.twClient != nil && a.twClient.IsConnected() {
if err := a.twClient.DeleteReward(target.RewardID); err != nil {
debuglog.Log("DeleteAction: Twitch reward delete error: %s", err)
}
}
if !a.cfg.DeleteAction(id) {
return fmt.Errorf("failed to delete action: %s", id)
}
debuglog.Log("DeleteAction: deleted %s (%s)", id, target.Name)
runtime.EventsEmit(a.ctx, "actions-updated", nil)
return a.cfg.Save()
}
// ToggleAction schaltet eine Aktion an oder aus und zieht den Reward auf Twitch
// nach.
//
// Der Schalter selbst wird immer gespeichert, auch wenn es auf Twitch hakt --
// sonst springt er in der Oberflaeche zurueck und man weiss nicht, woran es lag.
// Probleme auf Twitch-Seite kommen als Meldung, nicht als Fehler.
func (a *App) ToggleAction(id string, enabled bool) error {
a.cfg.ToggleAction(id, enabled)
var target *config.Action
for _, act := range a.cfg.GetActions() {
if act.ID == id {
target = &act
break
}
}
if target == nil {
return fmt.Errorf("Aktion nicht gefunden: %s", id)
}
connected := a.twClient != nil && a.twClient.IsConnected()
debuglog.Log("ToggleAction: %s enabled=%v rewardID=%q twitch=%v",
id, enabled, target.RewardID, connected)
// Zuerst sichern: der Zustand des Schalters haengt nicht davon ab, ob
// Twitch gerade erreichbar ist.
if err := a.cfg.Save(); err != nil {
return err
}
if !connected {
runtime.EventsEmit(a.ctx, "twitch-log", fmt.Sprintf(
"%q %s — Twitch ist nicht verbunden, der Reward wird beim nächsten Verbinden nachgezogen",
target.Name, map[bool]string{true: "aktiviert", false: "deaktiviert"}[enabled]))
return nil
}
if target.RewardID != "" {
// Vorhandenen Reward auf Twitch pausieren beziehungsweise freigeben.
err := a.twClient.UpdateRewardEnabled(target.RewardID, enabled, target.RewardColor)
if err == nil {
return nil
}
// Zeigt die gespeicherte ID ins Leere, wurde der Reward auf Twitch
// geloescht. Die Verknuepfung wegwerfen und unten neu anlegen -- sonst
// bliebe die Aktion dauerhaft ohne Reward und waere nie ausloesbar.
if !errors.Is(err, twitch.ErrRewardNotFound) {
debuglog.Log("ToggleAction: UpdateRewardEnabled fehlgeschlagen: %s", err)
runtime.EventsEmit(a.ctx, "twitch-log", fmt.Sprintf(
"%q konnte auf Twitch nicht umgeschaltet werden: %s", target.Name, err))
return nil
}
debuglog.Log("ToggleAction: %s hatte eine veraltete Reward-ID (%s) — wird neu angelegt",
id, target.RewardID)
target.RewardID = ""
a.cfg.SetAction(*target)
}
if !enabled {
return nil // nichts anzulegen
}
// Noch kein Reward auf dem Kanal: anlegen.
rewardID, err := a.twClient.CreateReward(rewardSpec(*target))
if err != nil {
// Bisher wurde dieser Fehler verschluckt: der Schalter ging an, auf
// Twitch entstand nichts, und niemand erfuhr davon.
debuglog.Log("ToggleAction: CreateReward für %s fehlgeschlagen: %s", id, err)
msg := fmt.Sprintf("Reward %q konnte nicht angelegt werden: %s", target.RewardTitle, err)
switch {
case errors.Is(err, twitch.ErrRewardExists):
msg = fmt.Sprintf(
"%q existiert schon auf deinem Kanal, gehört aber einer anderen App. "+
"Einlösungen darauf lösen nichts aus — im Twitch-Dashboard löschen, dann erneut aktivieren",
target.RewardTitle)
case errors.Is(err, twitch.ErrTooManyRewards):
msg = fmt.Sprintf(
"%q konnte nicht angelegt werden: dein Kanal hat die von Twitch erlaubte Zahl an "+
"Kanalpunkt-Belohnungen erreicht. Nicht benötigte Belohnungen im Twitch-Dashboard "+
"entfernen oder hier weniger Aktionen aktivieren", target.RewardTitle)
}
runtime.EventsEmit(a.ctx, "twitch-log", msg)
runtime.EventsEmit(a.ctx, "action-error", map[string]string{"action": id, "error": msg})
return nil
}
target.RewardID = rewardID
a.cfg.SetAction(*target)
debuglog.Log("ToggleAction: %s Reward angelegt → %s", id, rewardID)
return a.cfg.Save()
}
// SetGlobalEnable ist der Not-Aus: er blendet alle Rewards auf dem Kanal aus
// beziehungsweise wieder ein.
//
// Frueher wurden die Rewards dabei geloescht und beim Einschalten neu angelegt.
// Das war aus drei Gruenden schlecht: es kostet pro Umschaltung ein Dutzend
// API-Aufrufe, es verwirft Bild, Farbe und Reihenfolge der Belohnungen auf dem
// Kanal, und beim Neuanlegen kann es an Twitchs Obergrenze scheitern -- dann
// waeren die Rewards weg und liessen sich nicht zurueckholen.
//
// Twitch kann Belohnungen ausblenden (is_enabled), genau dafuer ist das da.
func (a *App) SetGlobalEnable(enabled bool) error {
a.cfg.GlobalEnable = enabled
runtime.EventsEmit(a.ctx, "global-toggle", enabled)
if a.twClient != nil && a.twClient.IsConnected() {
go func() {
if enabled {
// Fehlende Rewards anlegen -- vorhandene bleiben unangetastet.
runtime.EventsEmit(a.ctx, "twitch-log", "Rewards werden freigegeben...")
_ = a.SyncRewards()
} else {
runtime.EventsEmit(a.ctx, "twitch-log", "Rewards werden ausgeblendet...")
}
shown, hidden := a.applyRewardVisibility(enabled)
if enabled {
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("%d Reward(s) sind wieder auf dem Kanal sichtbar", shown))
} else {
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("%d Reward(s) ausgeblendet — Einlösungen sind gesperrt", hidden))
}
}()
}
return a.cfg.Save()
}
// applyRewardVisibility blendet die Rewards passend zum Not-Aus und zum
// Zustand der einzelnen Aktionen ein oder aus.
func (a *App) applyRewardVisibility(globalEnabled bool) (shown, hidden int) {
for _, act := range a.cfg.GetActions() {
if act.RewardID == "" {
continue
}
want := globalEnabled && act.Enabled
if err := a.twClient.UpdateRewardEnabled(act.RewardID, want, act.RewardColor); err != nil {
debuglog.Log("applyRewardVisibility: %s (%s): %s", act.ID, act.RewardID, err)
// Veraltete Verknüpfung: beim nächsten Aktivieren wird neu angelegt.
if errors.Is(err, twitch.ErrRewardNotFound) {
act.RewardID = ""
a.cfg.SetAction(act)
}
continue
}
if want {
shown++
} else {
hidden++
}
}
_ = a.cfg.Save()
return shown, hidden
}
func (a *App) GetGlobalEnable() bool {
return a.cfg.GlobalEnable
}
func (a *App) SetTargetWindow(name string) error {
a.cfg.TargetWindow = name
return a.cfg.Save()
}
// --- Twitch Device Code Flow ---
type DeviceAuthInfo struct {
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
}
func (a *App) StartTwitchAuth() (*DeviceAuthInfo, error) {
a.twClient = twitch.NewClient(&a.cfg.Twitch)
a.setupTwitchCallbacks()
dcr, err := a.twClient.RequestDeviceCode()
if err != nil {
return nil, err
}
// Open the verification URL in the browser
runtime.BrowserOpenURL(a.ctx, dcr.VerificationURI)
// Poll for token in background, then auto-connect EventSub
go func() {
err := a.twClient.PollForToken(dcr.DeviceCode, dcr.Interval, dcr.ExpiresIn)
if err != nil {
runtime.EventsEmit(a.ctx, "twitch-error", err.Error())
return
}
a.cfg.Save()
runtime.EventsEmit(a.ctx, "twitch-authenticated", a.cfg.Twitch.ChannelName)
// Auto-connect to EventSub
if err := a.twClient.Connect(); err != nil {
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("EventSub Auto-Connect fehlgeschlagen: %s", err.Error()))
return
}
a.twClient.StartTokenRefresher()
runtime.EventsEmit(a.ctx, "twitch-log", "EventSub verbunden")
// Sync rewards
if a.cfg.GlobalEnable {
a.SyncRewards()
runtime.EventsEmit(a.ctx, "twitch-log", "Rewards synchronisiert")
}
}()
return &DeviceAuthInfo{
UserCode: dcr.UserCode,
VerificationURI: dcr.VerificationURI,
}, nil
}
func (a *App) ConnectTwitch() error {
return a.connectTwitch()
}
func (a *App) DisconnectTwitch() {
if a.twClient != nil {
a.twClient.Disconnect()
// Verworfen, nicht wiederverwendet: der Client ist nach Disconnect
// endgueltig gestoppt. Ein erneutes Verbinden legt einen neuen an.
a.twClient = nil
runtime.EventsEmit(a.ctx, "twitch-disconnected", nil)
}
}
func (a *App) IsTwitchConnected() bool {
return a.twClient != nil && a.twClient.IsConnected()
}
func (a *App) GetTwitchChannel() string {
return a.cfg.Twitch.ChannelName
}
// TwitchApp beschreibt die verwendete Twitch-Anwendung fuer die Oberflaeche.
// Das Secret wird nur als "gesetzt/nicht gesetzt" gemeldet, nicht im Klartext.
type TwitchApp struct {
ClientID string `json:"client_id"`
HasSecret bool `json:"has_secret"`
IsDefault bool `json:"is_default"`
}
func (a *App) GetTwitchApp() TwitchApp {
return TwitchApp{
ClientID: a.cfg.Twitch.ClientID,
HasSecret: a.cfg.Twitch.ClientSecret != "",
IsDefault: a.cfg.Twitch.ClientID == twitch.DefaultClientID,
}
}
// SetTwitchApp hinterlegt eine eigene Twitch-Anwendung.
//
// Ein Wechsel der Client-ID macht die bisherige Anmeldung ungueltig -- Tokens
// gehoeren immer zu genau einer App. Rewards, die unter der alten ID angelegt
// wurden, lassen sich danach ausserdem nicht mehr verwalten und muessen neu
// erstellt werden.
func (a *App) SetTwitchApp(clientID, clientSecret string) error {
clientID = strings.TrimSpace(clientID)
clientSecret = strings.TrimSpace(clientSecret)
if clientID == "" {
clientID = twitch.DefaultClientID
}
changedApp := clientID != a.cfg.Twitch.ClientID
if changedApp {
debuglog.Log("SetTwitchApp: Client-ID gewechselt — Anmeldung wird zurückgesetzt")
a.cfg.Twitch.AccessToken = ""
a.cfg.Twitch.RefreshToken = ""
a.cfg.Twitch.ExpiresAt = time.Time{}
for _, act := range a.cfg.GetActions() {
if act.RewardID != "" {
act.RewardID = ""
a.cfg.SetAction(act)
}
}
if a.twClient != nil {
a.twClient.Disconnect()
a.twClient = nil
}
runtime.EventsEmit(a.ctx, "twitch-disconnected", "App gewechselt")
}
a.cfg.Twitch.ClientID = clientID
a.cfg.Twitch.ClientSecret = clientSecret
if err := a.cfg.Save(); err != nil {
return err
}
runtime.EventsEmit(a.ctx, "twitch-log", map[bool]string{
true: "Twitch-App gewechselt — bitte neu verbinden",
false: "Twitch-App aktualisiert",
}[changedApp])
return nil
}
// autoConnect stellt die Anmeldung beim Start wieder her.
//
// Es wird so lange erneut versucht, wie der Fehler voruebergehend sein kann --
// beim Systemstart ist das Netz oft noch nicht da. Nur wenn Twitch den Refresh
// Token endgueltig ablehnt, ist eine neue Anmeldung noetig.
func (a *App) autoConnect() {
a.twClient = twitch.NewClient(&a.cfg.Twitch)
a.setupTwitchCallbacks()
runtime.EventsEmit(a.ctx, "twitch-log", "Anmeldung wird wiederhergestellt...")
delays := []time.Duration{0, 3 * time.Second, 10 * time.Second, 30 * time.Second, time.Minute}
for i, d := range delays {
if d > 0 {
time.Sleep(d)
}
err := a.twClient.Connect()
if err == nil {
a.cfg.Save()
a.twClient.StartTokenRefresher()
runtime.EventsEmit(a.ctx, "twitch-authenticated", a.cfg.Twitch.ChannelName)
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Angemeldet als %s", a.cfg.Twitch.ChannelName))
return
}
// Falsch registrierte App: erneutes Versuchen bringt nichts, eine
// Neuanmeldung genauso wenig. Das muss der Nutzer einmal einrichten.
if errors.Is(err, twitch.ErrClientSecretRequired) {
debuglog.Log("autoConnect: %s", err)
runtime.EventsEmit(a.ctx, "twitch-log", err.Error())
runtime.EventsEmit(a.ctx, "twitch-needs-secret", err.Error())
runtime.EventsEmit(a.ctx, "twitch-disconnected", "App-Einrichtung unvollständig")
return
}
if errors.Is(err, twitch.ErrLoginRequired) {
debuglog.Log("autoConnect: Anmeldung abgelaufen: %s", err)
runtime.EventsEmit(a.ctx, "twitch-log", err.Error())
runtime.EventsEmit(a.ctx, "twitch-disconnected", "Anmeldung abgelaufen")
return
}
debuglog.Log("autoConnect: Versuch %d fehlgeschlagen: %s", i+1, err)
if i < len(delays)-1 {
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Verbindung fehlgeschlagen (%s) — neuer Versuch in %s", err, delays[i+1]))
}
}
runtime.EventsEmit(a.ctx, "twitch-log",
"Twitch nicht erreichbar — Anmeldung bleibt gespeichert, im Twitch-Tab neu verbinden")
runtime.EventsEmit(a.ctx, "twitch-disconnected", "nicht erreichbar")
}
func (a *App) connectTwitch() error {
if a.twClient == nil {
a.twClient = twitch.NewClient(&a.cfg.Twitch)
a.setupTwitchCallbacks()
}
// Connect erneuert den Token selbst, falls noetig.
if err := a.twClient.Connect(); err != nil {
return err
}
a.twClient.StartTokenRefresher()
return a.cfg.Save()
}
func (a *App) reconnectLoop() {
retries := 0
maxRetries := 10
for retries < maxRetries {
retries++
delay := time.Duration(min(retries*5, 30)) * time.Second
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Reconnect in %ds... (Versuch %d/%d)", int(delay.Seconds()), retries, maxRetries))
time.Sleep(delay)
if a.twClient == nil {
return
}
if err := a.twClient.Connect(); err != nil {
// Bei abgelaufener Anmeldung oder falsch registrierter App hilft
// kein weiterer Versuch.
if errors.Is(err, twitch.ErrClientSecretRequired) {
runtime.EventsEmit(a.ctx, "twitch-log", err.Error())
runtime.EventsEmit(a.ctx, "twitch-needs-secret", err.Error())
runtime.EventsEmit(a.ctx, "twitch-disconnected", "App-Einrichtung unvollständig")
return
}
if errors.Is(err, twitch.ErrLoginRequired) {
runtime.EventsEmit(a.ctx, "twitch-log", err.Error())
runtime.EventsEmit(a.ctx, "twitch-disconnected", "Anmeldung abgelaufen")
return
}
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Reconnect fehlgeschlagen: %s", err.Error()))
continue
}
a.cfg.Save()
runtime.EventsEmit(a.ctx, "twitch-log", "Reconnect erfolgreich!")
return
}
runtime.EventsEmit(a.ctx, "twitch-log", "Reconnect aufgegeben — bitte manuell verbinden")
}
func (a *App) setupTwitchCallbacks() {
a.twClient.SetOnRedemption(func(rewardID, redemptionID, userName, rewardTitle string) {
debuglog.Log("Redemption: user=%s reward=%q id=%s redemption=%s", userName, rewardTitle, rewardID, redemptionID)
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Einlösung von %s: %s", userName, rewardTitle))
for _, action := range a.cfg.GetActions() {
if action.RewardID != rewardID {
continue
}
debuglog.Log("Redemption matched: action=%s", action.ID)
err := a.executor.Execute(action.ID, userName)
if err == nil {
a.finishRedemption(rewardID, redemptionID, "FULFILLED")
return
}
// Cooldown, Spiel nicht im Vordergrund, Aktion aus, Queue voll --
// in all diesen Faellen ist nichts passiert, also Punkte zurueck.
debuglog.Log("Redemption execute error: %s", err)
runtime.EventsEmit(a.ctx, "action-error", map[string]string{
"action": action.ID,
"error": err.Error(),
})
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("%s nicht ausgeführt (%s) — Punkte zurück", rewardTitle, err.Error()))
a.finishRedemption(rewardID, redemptionID, "CANCELED")
return
}
// Kein Treffer über die Reward-ID. Passt aber der Titel zu einer unserer
// Aktionen, dann ist der Reward ein Rest einer früheren App-Registrierung:
// er liegt auf dem Kanal, gehört uns aber nicht und ist deshalb nicht
// verknüpft. Ohne diesen Hinweis sucht man den Fehler beim Tastendruck.
for _, action := range a.cfg.GetActions() {
if !strings.EqualFold(action.RewardTitle, rewardTitle) {
continue
}
debuglog.Log("Redemption: %q passt zu Aktion %s, ist aber nicht verknüpft "+
"(fremder Reward, reward_id=%s)", rewardTitle, action.ID, rewardID)
runtime.EventsEmit(a.ctx, "twitch-log", fmt.Sprintf(
"%q gehört einer anderen App und löst deshalb nichts aus — "+
"im Twitch-Dashboard löschen und Rewards neu synchronisieren", rewardTitle))
return
}
// Reward eines anderen Tools oder von Hand angelegt: geht uns nichts an.
debuglog.Log("Redemption: NO MATCH for rewardID=%s (%q)", rewardID, rewardTitle)
})
a.twClient.SetOnConnect(func() {
runtime.EventsEmit(a.ctx, "twitch-connected", nil)
})
a.twClient.SetOnDisconnect(func(err error) {
msg := "disconnected"
if err != nil {
msg = err.Error()
}
runtime.EventsEmit(a.ctx, "twitch-disconnected", msg)
// Auto-reconnect if we have tokens
if a.cfg.Twitch.RefreshToken != "" && err != nil {
go a.reconnectLoop()
}
})
a.twClient.SetOnLog(func(msg string) {
runtime.EventsEmit(a.ctx, "twitch-log", msg)
})
a.twClient.SetOnTokenRefresh(func() {
_ = a.cfg.Save()
debuglog.Log("Twitch: access token auto-refreshed and saved")
})
}
// finishRedemption schliesst eine Einloesung ab. CANCELED erstattet die
// Kanalpunkte. Schlaegt fehl, wenn der Reward nicht von dieser App stammt --
// das ist kein Grund fuer eine Fehlermeldung im UI, deshalb nur ins Log.
func (a *App) finishRedemption(rewardID, redemptionID, status string) {
if a.twClient == nil || redemptionID == "" {
return
}
if err := a.twClient.SetRedemptionStatus(rewardID, redemptionID, status); err != nil {
debuglog.Log("finishRedemption(%s): %s", status, err)
}
}
// --- Reward Management ---
func (a *App) SyncRewards() error {
a.rewardMu.Lock()
defer a.rewardMu.Unlock()
if a.twClient == nil || !a.twClient.IsConnected() {
debuglog.Log("SyncRewards: nicht verbunden")
return fmt.Errorf("not connected to Twitch")
}
// Rewards, die gleichnamig schon auf dem Kanal liegen, aber einer anderen
// App gehören. Die bleiben unverknüpft und werden am Ende gesammelt gemeldet.
var orphaned []string
debuglog.Log("=== SyncRewards START ===")
// Fetch existing rewards to avoid duplicates
existing, err := a.twClient.GetExistingRewards()
if err != nil {
debuglog.Log("SyncRewards: GetExistingRewards error: %s", err)
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Konnte bestehende Rewards nicht laden: %s", err.Error()))
existing = nil
}
// Build a title -> ID map of existing rewards
existingByTitle := make(map[string]string)
existingByID := make(map[string]bool)
for _, r := range existing {
existingByTitle[r.Title] = r.ID
existingByID[r.ID] = true
}
debuglog.Log("SyncRewards: %d Rewards auf Twitch gefunden", len(existing))
actns := a.cfg.GetActions()
debuglog.Log("SyncRewards: %d Aktionen in Config", len(actns))
for _, action := range actns {
debuglog.Log("SyncRewards: action=%s enabled=%v rewardID=%q title=%q",
action.ID, action.Enabled, action.RewardID, action.RewardTitle)
if !action.Enabled {
// Wenn disabled aber noch eine RewardID hat, aufräumen
if action.RewardID != "" {
debuglog.Log("SyncRewards: %s ist disabled aber hat RewardID=%s — lösche", action.ID, action.RewardID)
a.twClient.DeleteReward(action.RewardID)
action.RewardID = ""
a.cfg.SetAction(action)
}
continue
}
// Check if already linked AND reward still exists on Twitch
if action.RewardID != "" {
if existingByID[action.RewardID] {
debuglog.Log("SyncRewards: %s bereits verknüpft und existiert (ID: %s)", action.ID, action.RewardID)
// Beschreibung nachziehen: bestehende Rewards wurden ohne
// angelegt, sonst bliebe der Zuschauer bei ihnen im Dunkeln.
if p := twitch.TrimPrompt(action.Description); p != "" {
if err := a.twClient.UpdateReward(action.RewardID,
map[string]interface{}{"prompt": p}, ""); err != nil {
debuglog.Log("SyncRewards: Beschreibung für %s nicht gesetzt: %s", action.ID, err)
}
}
continue
}
// RewardID saved but doesn't exist on Twitch anymore — clear it
debuglog.Log("SyncRewards: %s hat RewardID=%s aber existiert NICHT auf Twitch — wird neu erstellt", action.ID, action.RewardID)
action.RewardID = ""
}
// Check if reward already exists on Twitch by title
if existingID, ok := existingByTitle[action.RewardTitle]; ok {
debuglog.Log("SyncRewards: %s gefunden über Titel: %q → ID=%s", action.ID, action.RewardTitle, existingID)
action.RewardID = existingID
a.cfg.SetAction(action)
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Bestehender Reward gefunden: %s (ID: %s)", action.RewardTitle, existingID))
continue
}
// Create new reward
debuglog.Log("SyncRewards: erstelle neuen Reward für %s: title=%q cost=%d", action.ID, action.RewardTitle, action.RewardCost)
rewardID, err := a.twClient.CreateReward(rewardSpec(action))
if err != nil {
debuglog.Log("SyncRewards: FEHLER beim Erstellen von %s: %s", action.ID, err)
// Fremder Reward gleichen Namens: die Aktion bleibt unverknüpft und
// jede Einlösung läuft ins Leere. Das muss deutlich werden, sonst
// sucht man den Fehler beim Tastendruck.
if errors.Is(err, twitch.ErrRewardExists) {
orphaned = append(orphaned, action.RewardTitle)
runtime.EventsEmit(a.ctx, "twitch-log", fmt.Sprintf(
"%q existiert schon auf deinem Kanal, gehört aber einer anderen App — "+
"bitte im Twitch-Dashboard löschen und erneut synchronisieren", action.RewardTitle))
continue
}
// Obergrenze erreicht: alle weiteren Versuche scheitern genauso.
// Einmal deutlich melden und aufhören, statt es 20-mal zu probieren.
if errors.Is(err, twitch.ErrTooManyRewards) {
runtime.EventsEmit(a.ctx, "twitch-log",
"Dein Kanal hat die von Twitch erlaubte Zahl an Kanalpunkt-Belohnungen erreicht. "+
"Nicht benötigte im Twitch-Dashboard entfernen oder hier weniger Aktionen aktivieren — "+
"die restlichen Rewards wurden nicht angelegt.")
break
}
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Fehler beim Erstellen von '%s': %s", action.RewardTitle, err.Error()))
continue
}
action.RewardID = rewardID
a.cfg.SetAction(action)
debuglog.Log("SyncRewards: %s erstellt → ID=%s", action.ID, rewardID)
runtime.EventsEmit(a.ctx, "twitch-log",
fmt.Sprintf("Reward erstellt: %s (ID: %s)", action.RewardTitle, rewardID))
}
if len(orphaned) > 0 {
debuglog.Log("SyncRewards: %d fremde Rewards blockieren die Verknüpfung: %v",
len(orphaned), orphaned)
runtime.EventsEmit(a.ctx, "rewards-orphaned", orphaned)
runtime.EventsEmit(a.ctx, "twitch-log", fmt.Sprintf(
"%d Reward(s) konnten nicht verknüpft werden. Einlösungen darauf lösen NICHTS aus. "+
"Im Twitch-Dashboard unter Kanalpunkte löschen, dann erneut synchronisieren: %s",
len(orphaned), strings.Join(orphaned, ", ")))
}
debuglog.Log("=== SyncRewards ENDE ===")
return a.cfg.Save()
}
func (a *App) DeleteAllRewards() error {
a.rewardMu.Lock()
defer a.rewardMu.Unlock()
if a.twClient == nil {
return fmt.Errorf("not connected to Twitch")
}
debuglog.Log("=== DeleteAllRewards START ===")
actns := a.cfg.GetActions()
for _, action := range actns {
if action.RewardID == "" {
continue
}
debuglog.Log("DeleteAllRewards: lösche %s (RewardID=%s)", action.ID, action.RewardID)
a.twClient.DeleteReward(action.RewardID)
action.RewardID = ""
a.cfg.SetAction(action)
}
debuglog.Log("=== DeleteAllRewards ENDE ===")
return a.cfg.Save()
}
func (a *App) GetDebugLogPath() string {
return debuglog.GetLogPath()
}
// --- Language ---
func (a *App) GetLanguage() string {
if a.cfg.Language == "" {
return "de"
}
return a.cfg.Language
}
func (a *App) SetLanguage(lang string) error {
a.cfg.Language = lang
return a.cfg.Save()
}
// --- Star Citizen: Installation und Tastenbelegungen ---
// BindStatus vergleicht fuer eine Aktion die Taste, die sctroll drueckt, mit
// der, die im Spiel tatsaechlich gilt.
//
// Die gueltige Taste ergibt sich aus zwei Quellen: was in der actionmaps.xml
// steht (eigene Belegung) und sonst aus Star Citizens defaultProfile.xml
// (Standardbelegung). Manche Aktionen haben ab Werk gar keine Taste -- Tueren
// und Emotes zum Beispiel -- die muss man im Spiel selbst binden.
type BindStatus struct {
ActionID string `json:"action_id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
SCAction string `json:"sc_action"`
Key string `json:"key"` // was sctroll drueckt
Effective string `json:"effective"` // was im Spiel gilt
Source string `json:"source"` // "profil" | "standard" | "unbelegt"
Mismatch bool `json:"mismatch"` // sctroll drueckt etwas anderes als im Spiel gilt
}
// effectiveBind loest die im Spiel gueltige Taste einer Aktion auf.
func effectiveBind(act config.Action, overrides map[string]string) (key, source string, hold int) {
id := act.SCActionMap + "|" + act.SCAction
def := starcitizen.DefaultBinds()[id]
if k, ok := overrides[id]; ok && k != "" {
// Eigene Belegung. Die Aktivierungsart kommt weiterhin aus dem
// Standardprofil -- die aendert sich beim Umbinden nicht.
return k, "profil", def.HoldMs
}
if def.Key != "" {
return def.Key, "standard", def.HoldMs
}
return "", "unbelegt", def.HoldMs
}