-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathinit.go
More file actions
280 lines (237 loc) · 9.24 KB
/
Copy pathinit.go
File metadata and controls
280 lines (237 loc) · 9.24 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
// SPDX-FileCopyrightText: 2025 Dinko Korunic
// SPDX-License-Identifier: MIT
package main
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"strings"
"time"
"github.com/dkorunic/e-dnevnik-bot/internal/config"
"github.com/dkorunic/e-dnevnik-bot/internal/logger"
"github.com/dkorunic/e-dnevnik-bot/internal/messenger"
"github.com/dkorunic/e-dnevnik-bot/internal/oauth"
"github.com/hako/durafmt"
"github.com/mattn/go-isatty"
"github.com/mdp/qrterminal/v3"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
_ "modernc.org/sqlite"
)
const (
initialWhatsAppDelay = 2 * time.Minute // 2 minutes sleep after successful sync
WhatsAppDBOldName = ".e-dnevnik.sqlite"
// Bounds interactive pairing, so an absent user cannot hang the process.
whatsAppPairingTimeout = 10 * time.Minute
)
var (
whatsAppPairingCli *whatsmeow.Client
whatsAppSynced = make(chan struct{}, 1)
)
// Trims the ldflags-injected build vars.
//
//nolint:gochecknoinits
func init() {
GitTag = strings.TrimSpace(GitTag)
GitCommit = strings.TrimSpace(GitCommit)
GitDirty = strings.TrimSpace(GitDirty)
BuildTime = strings.TrimSpace(BuildTime)
}
// checkCalendar runs first-run OAuth when no token file exists, deferring to the
// queue-only stub if setup fails, no terminal is present, or the file cannot be
// stat'd.
func checkCalendar(ctx context.Context, config *config.TomlConfig) {
if config == nil {
return
}
// Disables live delivery but leaves the stub, so exams survive until
// OAuth completes.
deferCal := func() {
config.CalendarEnabled = false
config.CalendarDeferred = true
}
_, err := os.Stat(*calTokFile)
switch {
case err == nil:
// Present, but it must decode: a truncated or hand-edited file
// would otherwise fail every poll cycle at runtime.
if verr := oauth.ValidateTokenFile(*calTokFile); verr != nil {
logger.Error().Msgf("Google Calendar token file %q is unreadable (%v). Deferring Calendar integration (exams will be queued); delete the file and re-run interactively to re-authenticate.",
*calTokFile, verr)
deferCal()
}
case !errors.Is(err, fs.ErrNotExist):
// EACCES and friends: defer rather than fail confusingly later.
logger.Error().Msgf("Cannot stat Google Calendar token file %q: %v. Deferring Calendar integration.", *calTokFile, err)
deferCal()
case !isTerminal():
logger.Warn().Msgf("Google Calendar token file %q not found; first-run OAuth requires an interactive terminal. Deferring Calendar integration (exams will be queued for delivery once OAuth is completed).", *calTokFile)
deferCal()
default:
if _, _, err := messenger.InitCalendar(ctx, *calTokFile, config.Calendar.Name); err != nil {
logger.Error().Msgf("Error initializing Google Calendar API: %v. Deferring Calendar integration (exams will be queued for retry).", err)
deferCal()
}
}
}
// checkWhatsApp runs first-run pairing — QR code or phone PIN — when the device
// is not yet linked, requesting a 3-month sync. Holds WhatsAppPairingMu so the
// runtime client cannot race the store handoff.
func checkWhatsApp(ctx context.Context, config *config.TomlConfig) {
if config == nil {
return
}
// LIFO: Disconnect and Close complete before whatsAppInit sees the unlock.
messenger.WhatsAppPairingMu.Lock()
defer messenger.WhatsAppPairingMu.Unlock()
if fi, err := os.Stat(WhatsAppDBOldName); err == nil && fi.Mode().IsRegular() {
logger.Debug().Msgf("Found old WhatsApp DB %v, renaming to %v", WhatsAppDBOldName, messenger.WhatsAppDBName)
_ = os.Rename(WhatsAppDBOldName, messenger.WhatsAppDBName)
}
// 3-month sync only.
store.DeviceProps.RequireFullSync = new(false)
store.DeviceProps.Os = new(messenger.WhatsAppOS)
storeContainer, err := sqlstore.New(ctx, "sqlite",
fmt.Sprintf(messenger.WhatsAppDBConnstring, messenger.WhatsAppDBName), nil)
if err != nil {
logger.Fatal().Msgf("%v: %v", messenger.ErrWhatsAppUnableConnect, err)
}
defer storeContainer.Close()
err = storeContainer.Upgrade(ctx)
if err != nil {
logger.Fatal().Msgf("%v: %v", messenger.ErrWhatsAppUnableUpgrade, err)
}
// Multi-session is unsupported.
device, err := storeContainer.GetFirstDevice(ctx)
if err != nil {
logger.Fatal().Msgf("%v: %v", messenger.ErrWhatsAppUnableDeviceID, err)
}
whatsAppPairingCli = whatsmeow.NewClient(device, nil)
whatsAppPairingCli.EnableAutoReconnect = true
whatsAppPairingCli.AutoTrustIdentity = true
whatsAppPairingCli.AddEventHandler(whatsappPairingEventHandler)
qrCtx, qrCancel := context.WithCancel(ctx)
defer qrCancel()
ch, err := whatsAppPairingCli.GetQRChannel(qrCtx)
if err != nil {
if !errors.Is(err, whatsmeow.ErrQRStoreContainsID) {
logger.Fatal().Msgf("%v: %v", messenger.ErrWhatsAppFailQR, err)
} else {
logger.Info().Msg("Logged in to WhatsApp")
return
}
}
//nolint:nestif
go func() {
for evt := range ch {
if evt.Event == "code" {
if config.WhatsApp.PhoneNumber != "" {
linkCode, err := whatsAppPairingCli.PairPhone(qrCtx, config.WhatsApp.PhoneNumber, true,
whatsmeow.PairClientChrome, messenger.WhatsAppDisplayName)
if err != nil {
logger.Fatal().Msgf("%v: %v", messenger.ErrWhatsAppFailLink, err)
}
logger.Info().Msgf("WhatsApp link code: %v", linkCode)
} else {
if isTerminal() {
logger.Info().Msg("WhatsApp QR code below")
qrterminal.GenerateHalfBlock(evt.Code, qrterminal.L, os.Stdout)
} else {
logger.Fatal().Msg("WhatsApp first run requires running under a terminal or pairing through phone number.")
}
}
}
}
}()
err = whatsAppPairingCli.Connect()
if err != nil {
logger.Fatal().Msgf("Failed to connect to WhatsApp: %v", err)
}
// LIFO: cancel before disconnecting, so a late "code" event cannot
// PairPhone on a tearing-down client.
defer func() {
qrCancel()
whatsAppPairingCli.Disconnect()
}()
logger.Info().Msg("Please wait until WhatsApp has fully synced and keep Android/iOS mobile app active and open")
select {
case <-whatsAppSynced:
case <-ctx.Done():
logger.Warn().Msg("Context cancelled while waiting for WhatsApp sync")
return
case <-time.After(whatsAppPairingTimeout):
logger.Warn().Msgf("Timed out after %v waiting for WhatsApp pairing/sync; restart the bot and re-scan the QR code or re-enter the PIN",
durafmt.Parse(whatsAppPairingTimeout).String())
return
}
logger.Info().Msg("Waiting for 2 more minutes for WhatsApp mobile app to acknowledge completed transfer")
// Grace period for the full sync.
select {
case <-time.After(initialWhatsAppDelay):
case <-ctx.Done():
logger.Warn().Msg("Context cancelled while waiting for WhatsApp post-sync delay")
}
}
// whatsappPairingEventHandler is the pairing-time whatsmeow callback, signalling
// whatsAppSynced once app-state sync completes. A failed link or logout deletes
// the session and is fatal — this is still interactive setup, with no queue.
func whatsappPairingEventHandler(rawEvt any) {
switch evt := rawEvt.(type) {
case *events.OfflineSyncPreview:
logger.Info().Msgf("WhatsApp offline sync preview: %v messages, %v receipts, %v notifications, %v app data changes",
evt.Messages, evt.Receipts, evt.Notifications, evt.AppDataChanges)
case *events.HistorySync:
logger.Info().Msg("WhatsApp history sync")
case *events.OfflineSyncCompleted:
logger.Info().Msg("WhatsApp offline sync completed")
case *events.AppStateSyncComplete:
if len(whatsAppPairingCli.Store.PushName) > 0 && evt.Name == appstate.WAPatchCriticalBlock {
messenger.SendPresenceBounded(whatsAppPairingCli, types.PresenceAvailable)
messenger.SendPresenceBounded(whatsAppPairingCli, types.PresenceUnavailable)
}
logger.Info().Msg("WhatsApp app state sync completed")
select {
case whatsAppSynced <- struct{}{}:
default:
}
case *events.Connected, *events.PushNameSetting:
if len(whatsAppPairingCli.Store.PushName) > 0 {
messenger.SendPresenceBounded(whatsAppPairingCli, types.PresenceAvailable)
messenger.SendPresenceBounded(whatsAppPairingCli, types.PresenceUnavailable)
}
case *events.PairError:
// A failure regardless of any stale Store.ID.
messenger.RemoveWhatsAppSession()
logger.Fatal().Msgf("%v", messenger.ErrWhatsAppFailLinkDevice)
case *events.PairSuccess:
// Success without a device ID is really a failure.
if whatsAppPairingCli.Store.ID == nil {
messenger.RemoveWhatsAppSession()
logger.Fatal().Msgf("%v", messenger.ErrWhatsAppFailLinkDevice)
}
logger.Info().Msg("WhatsApp device successfully paired")
case *events.LoggedOut:
messenger.RemoveWhatsAppSession()
logger.Fatal().Msgf("%v", messenger.ErrWhatsAppLoggedout)
case *events.Disconnected, *events.StreamReplaced, *events.KeepAliveTimeout:
logger.Debug().Msgf("%v", messenger.ErrWhatsAppDisconnected)
case *events.ClientOutdated:
logger.Error().Msgf("%v", messenger.ErrWhatsAppOutdated)
case *events.TemporaryBan:
duration := durafmt.Parse(evt.Expire).String()
logger.Fatal().Msgf("%v: code %v / expire %v", messenger.ErrWhatsAppBan, evt.Code, duration)
}
}
// isTerminal gates the first-run flows. TERM=dumb counts as non-interactive;
// NO_COLOR does not, controlling only colour (see initLog).
func isTerminal() bool {
fd := os.Stdout.Fd()
return os.Getenv("TERM") != "dumb" &&
(isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd))
}