-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
375 lines (331 loc) · 9.04 KB
/
main.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
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"github.com/fabien-chebel/pegass-cli/whatsapp"
_ "github.com/glebarez/go-sqlite"
log "github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow/types"
"gopkg.in/urfave/cli.v1"
"os"
"strconv"
"strings"
"time"
)
const APP_VERSION = "1.9.0"
var pegassClient PegassClient
func initClient() (Config, error) {
configData := parseConfig()
pegassClient = PegassClient{
Username: configData.Username,
Password: configData.Password,
TotpSecretKey: configData.TotpSecretKey,
}
return configData, pegassClient.Authenticate()
}
func initLogs(verbose bool) {
log.SetOutput(os.Stdout)
if verbose {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
}
func main() {
initLogs(os.Getenv("VERBOSE") != "")
app := cli.NewApp()
app.Name = "Pegass CLI"
app.Usage = "Interact with Red Cross's Pegass web app through the CLI"
app.Version = APP_VERSION
app.Commands = []cli.Command{
{
Name: "login",
Usage: "Authenticate to Pegass",
Action: func(c *cli.Context) error {
_, err := initClient()
if err != nil {
return nil
}
err = pegassClient.Authenticate()
if err != nil {
return err
}
return nil
},
},
{
Name: "whoami",
Usage: "Get current user information",
Action: func(c *cli.Context) error {
_, err := initClient()
if err != nil {
return err
}
user, err := pegassClient.GetCurrentUser()
if err != nil {
return err
}
log.Infof("Bonjour %s %s (NIVOL: %s) !", user.Utilisateur.Prenom, user.Utilisateur.Nom, user.Utilisateur.ID)
return nil
},
},
{
Name: "dispatchers",
Usage: "Get list of current dispatchers",
Action: func(c *cli.Context) error {
err := pegassClient.ReAuthenticate()
if err != nil {
return err
}
_, err = pegassClient.GetDispatchers()
if err != nil {
return err
}
return nil
},
},
{
Name: "dispatcherstats",
Usage: "Get dispatcher stats",
Action: func(c *cli.Context) error {
err := pegassClient.ReAuthenticate()
if err != nil {
return err
}
dispatchers, err := pegassClient.GetDispatchers()
if err != nil {
return err
}
for _, dispatcher := range dispatchers {
stats, err := pegassClient.GetStatsForUser(dispatcher.ID)
if err != nil {
return err
}
reguleCount := 0
for _, statistique := range stats.Statistiques {
if statistique.StatistiquesGroupeAction.Label == "Urgence et Secourisme" {
for _, activite := range statistique.StatistiquesActivites {
if activite.Label == "Régulation" {
reguleCount = activite.Nombre
break
}
}
break
}
}
log.Infof("Utilisateur: %s %s : %d régulations", dispatcher.Nom, dispatcher.Prenom, reguleCount)
}
return nil
},
},
{
Name: "regulationstats",
Usage: "Export regulation stats",
Action: func(c *cli.Context) error {
err := pegassClient.ReAuthenticate()
if err != nil {
return err
}
statsByUser, err := pegassClient.GetActivityStats()
if err != nil {
return err
}
f, err := os.Create("stats-regulation.csv")
defer f.Close()
if err != nil {
return err
}
w := csv.NewWriter(f)
defer w.Flush()
err = w.Write([]string{"nom,prenom,regule,eval,opr"})
if err != nil {
return err
}
for nivol, stats := range statsByUser {
details, err := pegassClient.GetUserDetails(nivol)
if err != nil {
log.Printf("failed to fetch user details for user '%s' ; %s", nivol, err)
}
log.Printf("Utilisateur %s %s ; %d regulations, %d eval, %d OPR", details.Nom, details.Prenom, stats.Regul, stats.Eval, stats.OPR)
record := []string{details.Nom, details.Prenom, strconv.Itoa(stats.Regul), strconv.Itoa(stats.Eval), strconv.Itoa(stats.OPR)}
err = w.Write(record)
if err != nil {
return err
}
}
return nil
},
},
{
Name: "find-users-for-role",
Usage: "Export a list of users matching a given pegass role",
Action: func(c *cli.Context) error {
roleName := c.Args().Get(0)
err := pegassClient.ReAuthenticate()
if err != nil {
return err
}
role, err := pegassClient.FindRoleByName(roleName)
if err != nil {
return err
}
log.Printf("Found role {id: '%s', type: '%s', name: '%s'} for role name '%s'", role.ID, role.Type, role.Libelle, roleName)
users, err := pegassClient.GetUsersForRole(role)
f, err := os.Create(fmt.Sprintf("user-export-92-%s-%s.csv", role.Type, role.ID))
defer f.Close()
if err != nil {
return err
}
w := csv.NewWriter(f)
defer w.Flush()
err = w.Write([]string{"nom", "prenom", "UL", "nivol", "phone-number", "role"})
if err != nil {
return err
}
for _, user := range users {
phoneNumber := ""
for _, coordonnee := range user.Coordonnees {
if coordonnee.MoyenComID == "POR" {
phoneNumber = coordonnee.Libelle
break
}
}
record := []string{user.Nom, user.Prenom, user.Structure.Libelle, user.ID, phoneNumber, roleName}
err = w.Write(record)
if err != nil {
return err
}
}
return nil
},
},
{
Name: "summarize-samu-activities",
Usage: "Fetch tomorrow's SAMU-related activities and send their status to WhatsApp",
Action: func(c *cli.Context) error {
conf, err := initClient()
if err != nil {
return err
}
day := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
var shouldCensorData = true
if isGroupOwnedByCRF(conf.WhatsAppBotGroups, conf.WhatsAppNotificationGroup) {
shouldCensorData = false
}
log.Info("Fetching activity summary for day ", day)
summary, err := pegassClient.FindActivitiesOnDay(day, SAMU, shouldCensorData)
if err != nil {
return err
}
summary = fmt.Sprintf("Etat du réseau de secours de demain (%s):\n%s", day, summary)
log.Info(summary)
if conf.WhatsAppNotificationGroup == "" {
return fmt.Errorf("no WhatsApp group Id provided. Skipping WhatsApp notification")
}
jid, err := types.ParseJID(conf.WhatsAppNotificationGroup)
whatsAppClient := whatsapp.NewClient()
if err != nil {
return err
}
err = whatsAppClient.SendMessage(
summary,
jid,
)
return err
},
},
{
Name: "register-chat-device",
Usage: "Register whats app device locally",
Action: func(c *cli.Context) error {
log.Infof("Starting what's app client")
whatsAppClient := whatsapp.NewClient()
log.Infof("Registering device")
err := whatsAppClient.RegisterDevice()
if err != nil {
log.Infof("Failed to register device: %s", err.Error())
return err
}
return nil
},
},
{
Name: "list-chat-groups",
Action: func(c *cli.Context) error {
whatsAppClient := whatsapp.NewClient()
return whatsAppClient.PrintGroupList()
},
},
{
Name: "start-bot",
Action: func(c *cli.Context) error {
config, err := initClient()
if err != nil {
return err
}
whatsAppClient := whatsapp.NewClient()
var botService = BotService{
pegassClient: &pegassClient,
chatClient: &whatsAppClient,
}
whatsAppClient.SetMessageCallback(func(senderName string, senderId types.JID, chatId types.JID, content string, timestamp time.Time) {
if !isGroupOwnedByCRF(config.WhatsAppBotGroups, chatId.String()) {
// Security: only whitelisted groups are able to use bot features
return
}
log.Infof("Received message from '%s': %s", senderName, content)
if time.Since(timestamp) > 2*time.Minute {
log.Infof("ignoring message, as it was sent more than 2 minutes ago.")
return
}
var recipient = chatId
lowerMessage := strings.ToLower(content)
err = pegassClient.AuthenticateIfNecessary()
if err != nil {
log.Errorf("failed to authenticate to pegass: '%s'", err.Error())
return
}
if strings.HasPrefix(lowerMessage, "!psr") {
botService.SendActivitySummary(recipient, SAMU, 3)
} else if strings.HasPrefix(lowerMessage, "!bspp") {
botService.SendActivitySummary(recipient, BSPP, 3)
} else if strings.HasPrefix(lowerMessage, "!today") {
botService.SendActivitySummary(recipient, SAMU, 1)
botService.SendActivitySummary(recipient, BSPP, 1)
}
})
err = whatsAppClient.StartBot()
if err != nil {
return err
}
return nil
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func parseConfig() Config {
configFile, err := os.Open("config.json")
if err != nil {
log.Fatal("Failed to open application configuration file 'config.json'", err)
}
defer configFile.Close()
var configData = Config{}
err = json.NewDecoder(configFile).Decode(&configData)
if err != nil {
log.Fatal("Failed to parse application configuration file", err)
}
return configData
}
func isGroupOwnedByCRF(allowedGroups []string, groupId string) bool {
for _, allowedId := range allowedGroups {
if allowedId == groupId {
return true
}
}
return false
}