-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathinit.go
More file actions
276 lines (235 loc) · 9.61 KB
/
Copy pathinit.go
File metadata and controls
276 lines (235 loc) · 9.61 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
// 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/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"
// whatsAppPairingTimeout bounds interactive pairing so an absent user can't hang the process.
whatsAppPairingTimeout = 10 * time.Minute
)
var (
whatsAppPairingCli *whatsmeow.Client
whatsAppSynced = make(chan struct{}, 1)
)
// init initializes the GitTag, GitCommit, GitDirty, and BuildTime variables.
//
// It trims leading and trailing white spaces from the values of GitTag, GitCommit,
// GitDirty, and BuildTime.
//
//nolint:gochecknoinits
func init() {
GitTag = strings.TrimSpace(GitTag)
GitCommit = strings.TrimSpace(GitCommit)
GitDirty = strings.TrimSpace(GitDirty)
BuildTime = strings.TrimSpace(BuildTime)
}
// checkCalendarConf checks the Calendar configuration and enables or disables the Calendar integration based on the existence of the Google Calendar API credentials file and token file.
//
// Parameters:
// - config: a pointer to the TomlConfig struct containing the configuration settings.
// - ctx: the context object for cancellation and timeout.
func checkCalendar(ctx context.Context, config *config.TomlConfig) {
if config == nil {
return
}
if _, err := os.Stat(*calTokFile); errors.Is(err, fs.ErrNotExist) {
if !isTerminal() {
logger.Warn().Msgf("Google Calendar token file %q not found; first-run OAuth requires an interactive terminal. Disabling Calendar integration.", *calTokFile)
config.CalendarEnabled = false
} else {
_, _, err := messenger.InitCalendar(ctx, *calTokFile, config.Calendar.Name)
if err != nil {
logger.Error().Msgf("Error initializing Google Calendar API: %v. Disabling Calendar integration.", err)
config.CalendarEnabled = false
}
}
}
}
// checkWhatsApp checks the WhatsApp configuration and enables or disables the WhatsApp integration based on the existence of the WhatsApp device ID.
//
// It will request syncing for the last 3-months and print the QR code if the WhatsApp device ID is not found in the database. It will also handle the pairing process if the WhatsApp device ID is not found.
//
// Parameters:
// - ctx: the context object for cancellation and timeout.
// - config: a pointer to the TomlConfig struct containing the configuration settings.
func checkWhatsApp(ctx context.Context, config *config.TomlConfig) {
if config == nil {
return
}
// LIFO defers ensure Disconnect/Close complete before messenger's whatsAppInit sees the lock released.
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)
}
// Request 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)
}
// Single-device only; 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)
}
defer 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")
// Extra grace period for full sync; honours cancellation.
select {
case <-time.After(initialWhatsAppDelay):
case <-ctx.Done():
logger.Warn().Msg("Context cancelled while waiting for WhatsApp post-sync delay")
}
}
// whatsappPairingEventHandler is a callback function that handles events from the
// WhatsApp client. It switches on the type of the event and performs the
// appropriate action.
//
// Events handled:
// - *events.AppStateSyncComplete: checks if the client has a push name and
// sends an available presence if so. Logs a message if the online sync
// completed and signals that the WhatsApp client is fully synced.
// - *events.Connected, *events.PushNameSetting: checks if the client has a
// push name and sends an available presence if so.
// - *events.PairSuccess, *events.PairError: checks if the client has a device
// ID and removes the database file if not. Logs a message if the linking
// process failed.
// - *events.LoggedOut: removes the database file and logs a message.
// - *events.Disconnected, *events.StreamReplaced, *events.KeepAliveTimeout:
// logs a message, disconnects the client, and reconnects if possible.
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.PairSuccess, *events.PairError:
if whatsAppPairingCli.Store.ID == nil {
_ = os.Remove(messenger.WhatsAppDBName)
logger.Fatal().Msgf("%v", messenger.ErrWhatsAppFailLinkDevice)
} else {
logger.Info().Msg("WhatsApp device successfully paired")
}
case *events.LoggedOut:
_ = os.Remove(messenger.WhatsAppDBName)
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 checks if the current output is a terminal.
//
// It returns true if the environment does not disable color output, the terminal
// is not set to "dumb", and the output file descriptor is a terminal. It also
// considers Cygwin terminals as valid terminals.
func isTerminal() bool {
fd := os.Stdout.Fd()
return os.Getenv("NO_COLOR") == "" && os.Getenv("TERM") != "dumb" &&
(isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd))
}