-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.go
406 lines (348 loc) · 10.4 KB
/
application.go
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
package chadango
import (
"context"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"github.com/n0h4rt/chadango/models"
"github.com/n0h4rt/chadango/utils"
"github.com/rs/zerolog/log"
)
// Application represents the main application.
//
// It provides methods for managing the application's lifecycle, including initialization, starting, stopping,
// connecting to groups and private messages, and handling events and errors.
// The application also manages data persistence and provides access to the public and private APIs.
type Application struct {
Config *Config // Config holds the configuration for the pplication.
persistence Persistence // Persistence manages data persistence for the application.
Private Private // Private represents the private chat functionality of the application.
Groups SyncMap[string, *Group] // Groups stores the groups the application is connected to.
eventHandlers []Handler // eventHandlers contains the registered event handlers for the application.
errorHandlers []Handler // errorHandlers contains the registered error handlers for the application.
context context.Context // Context for running the application.
cancelCtx context.CancelFunc // Function for stopping the application.
initialized bool // initialized indicates whether the application has been initialized.
}
// AddHandler adds a new handler to the application.
//
// Args:
// - handler: The handler to add to the application.
//
// Returns:
// - *Application: The application instance for method chaining.
func (app *Application) AddHandler(handler Handler) *Application {
if ch, ok := handler.(*CommandHandler); ok {
ch.app = app
}
app.eventHandlers = append(app.eventHandlers, handler)
return app
}
// RemoveHandler removes a handler from the application.
//
// Args:
// - handler: The handler to remove from the application.
//
// Returns:
// - *Application: The application instance for method chaining.
func (app *Application) RemoveHandler(handler Handler) *Application {
app.eventHandlers = utils.Remove(app.eventHandlers, handler)
return app
}
// AddErrorHandler adds a new error handler to the application.
//
// Args:
// - handler: The error handler to add to the application.
//
// Returns:
// - *Application: The application instance for method chaining.
func (app *Application) AddErrorHandler(handler Handler) *Application {
if ch, ok := handler.(*CommandHandler); ok {
ch.app = app
}
app.errorHandlers = append(app.errorHandlers, handler)
return app
}
// RemoveErrorHandler removes an error handler from the application.
//
// Args:
// - handler: The error handler to remove from the application.
//
// Returns:
// - *Application: The application instance for method chaining.
func (app *Application) RemoveErrorHandler(handler Handler) *Application {
app.errorHandlers = utils.Remove(app.errorHandlers, handler)
return app
}
// UsePersistence enables the persistence layer for the application.
//
// Args:
// - persistence: The persistence layer to use for the application.
//
// Returns:
// - *Application: The application instance for method chaining.
func (app *Application) UsePersistence(persistence Persistence) *Application {
app.persistence = persistence
return app
}
// dispatchEvent dispatches an event to the appropriate handler.
//
// Args:
// - event: The event to dispatch.
func (app *Application) dispatchEvent(event *Event) {
var context *Context
for _, handler := range app.eventHandlers {
if handler.Check(event) {
if context == nil {
context = &Context{
App: app,
BotData: app.persistence.GetBotData(),
}
if event.IsPrivate && event.User != nil && !event.User.IsAnon {
context.ChatData = app.persistence.GetChatData(strings.ToLower(event.User.Name))
} else if event.Group != nil {
context.ChatData = app.persistence.GetChatData(event.Group.Name)
}
}
func() {
defer func() {
if err := recover(); err != nil {
event.Error = err
app.dispatchError(event)
}
}()
handler.Invoke(event, context)
}()
}
}
}
// dispatchError dispatches an error event to the error handlers.
//
// Args:
// - event: The event to dispatch.
func (app *Application) dispatchError(event *Event) {
var context *Context
for _, handler := range app.errorHandlers {
if handler.Check(event) {
if context == nil {
context = &Context{
App: app,
BotData: app.persistence.GetBotData(),
}
if event.IsPrivate && event.User != nil && !event.User.IsAnon {
context.ChatData = app.persistence.GetChatData(strings.ToLower(event.User.Name))
} else if event.Group != nil {
context.ChatData = app.persistence.GetChatData(event.Group.Name)
}
}
func() {
defer func() {
if err := recover(); err != nil {
log.Error().
Str("Event", event.Type.String()).
AnErr("Origin", event.Error.(error)).
AnErr("Current", err.(error)).
Msg("Another error occured during handling an error.")
}
}()
handler.Invoke(event, context)
}()
}
}
}
// Initialize initializes the application.
//
// Returns:
// - *Application: The application instance for method chaining.
func (app *Application) Initialize() *Application {
if app.persistence == nil {
// Using the GobPersistence without Filename as a dummy.
app.persistence = new(GobPersistence)
}
app.persistence.Initialize()
app.Groups = NewSyncMap[string, *Group]()
app.checkConfig()
app.initialized = true
return app
}
// checkConfig checks certain configurations and assigns default values if they are left unset.
func (app *Application) checkConfig() {
if app.Config.AnonName == "" {
app.Config.AnonName = "anon0001"
}
if app.Config.NameColor == "" {
app.Config.NameColor = models.DEFAULT_COLOR
}
if app.Config.TextColor == "" {
app.Config.TextColor = models.DEFAULT_COLOR
}
if app.Config.TextFont == "" {
app.Config.TextFont = models.DEFAULT_TEXT_FONT
}
if app.Config.TextSize == 0 {
app.Config.TextSize = models.DEFAULT_TEXT_SIZE
}
}
// Start starts the application.
//
// Args:
// - ctx: The context for running the application.
//
// Returns:
// - *Application: The application instance for method chaining.
func (app *Application) Start(ctx context.Context) *Application {
if !app.initialized {
panic("the application is not initialized")
}
if ctx == nil {
ctx = context.Background()
}
app.context, app.cancelCtx = context.WithCancel(ctx)
initAPI(app.Config.Username, app.Config.Password, ctx)
for _, groupName := range app.Config.Groups {
go app.JoinGroup(groupName)
}
if app.Config.EnablePM {
go app.ConnectPM()
}
app.persistence.Runner(app.context)
app.dispatchEvent(&Event{Type: OnStart})
return app
}
// Park waits for the application to stop or receive an interrupt signal.
func (app *Application) Park() {
intCh := make(chan os.Signal, 1)
signal.Notify(intCh, os.Interrupt, syscall.SIGTERM)
select {
case <-app.context.Done():
case <-intCh:
app.Stop()
}
}
// Stop stops the application.
func (app *Application) Stop() {
app.dispatchEvent(&Event{Type: OnStop})
var wg sync.WaitGroup
wg.Add(1)
go func() {
app.DisconnectPM()
wg.Done()
}()
cb := func(_ string, group *Group) bool {
wg.Add(1)
go func() {
group.Disconnect()
wg.Done()
}()
return true
}
app.Groups.Range(cb)
wg.Wait()
app.persistence.Close()
app.cancelCtx()
}
// JoinGroup joins a group in the application.
//
// Args:
// - groupName: The name of the group to join.
//
// Returns:
// - error: An error if the group cannot be joined.
func (app *Application) JoinGroup(groupName string) error {
groupName = strings.ToLower(groupName)
if _, ok := app.Groups.Get(groupName); ok {
return ErrAlreadyConnected
}
if isGroup, err := publicAPI.IsGroup(groupName); err != nil || !isGroup {
return ErrNotAGroup
}
group := Group{
App: app,
Name: groupName,
WsUrl: utils.GetServer(groupName),
AnonName: app.Config.AnonName,
NameColor: app.Config.NameColor,
TextColor: app.Config.TextColor,
TextFont: app.Config.TextFont,
TextSize: app.Config.TextSize,
SessionID: app.Config.SessionID,
LoggedIn: app.Config.Password != "",
}
if err := group.Connect(app.context); err != nil {
return err
}
app.Groups.Set(groupName, &group)
return nil
}
// LeaveGroup leaves a group in the application.
//
// Args:
// - groupName: The name of the group to leave.
//
// Returns:
// - error: An error if the group cannot be left.
func (app *Application) LeaveGroup(groupName string) error {
groupName = strings.ToLower(groupName)
if group, ok := app.Groups.Get(groupName); ok {
// app.Groups.Del(groupName) // Group deletion is handled by the [Group.wsOnError].
group.Disconnect()
return nil
}
return ErrNotConnected
}
// ConnectPM connects to private messages.
//
// Returns:
// - error: An error if the connection to private messages fails.
func (app *Application) ConnectPM() error {
app.Private.App = app
app.Private.Name = "Private"
app.Private.WsUrl = PM_SERVER
app.Private.NameColor = app.Config.NameColor
app.Private.TextColor = app.Config.TextColor
app.Private.TextFont = app.Config.TextFont
app.Private.TextSize = app.Config.TextSize
app.Private.SessionID = app.Config.SessionID
return app.Private.Connect(app.context)
}
// DisconnectPM disconnects from private messages.
func (app *Application) DisconnectPM() {
app.Private.Disconnect()
}
// GetContext returns the [context.Context] of the application.
//
// Returns:
// - context.Context: The context of the application.
func (app *Application) GetContext() context.Context {
return app.context
}
// PrivateAPI returns the [PrivateAPI] used in the application.
//
// Returns:
// - *PrivateAPI: The private API used in the application.
func (app *Application) PrivateAPI() *PrivateAPI {
return privateAPI
}
// PublicAPI returns the [PublicAPI] used in the application.
//
// Returns:
// - *PublicAPI: The public API used in the application.
func (app *Application) PublicAPI() *PublicAPI {
return publicAPI
}
// New creates a new instance of the [Application] with the provided configuration.
//
// Args:
// - config: The configuration for the application.
//
// Returns:
// - *Application: A new instance of the [Application].
func New(config *Config) *Application {
return &Application{
eventHandlers: []Handler{},
errorHandlers: []Handler{},
Config: config,
}
}