-
Notifications
You must be signed in to change notification settings - Fork 0
/
parceltracking.go
436 lines (381 loc) · 12 KB
/
parceltracking.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
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
package main
import (
"fmt"
"strings"
"github.com/osm/irc"
"github.com/osm/postnord"
)
// initParcelTrackingDefaults sets default values for all settings.
func (b *bot) initParcelTrackingDefaults() {
if b.IRC.ParcelTrackingLocale == "" {
b.IRC.ParcelTrackingLocale = "sv"
}
if b.IRC.ParcelTrackingMsgInfo == "" {
b.IRC.ParcelTrackingMsgInfo = "<consignor_name>, <event_date> <event_time>, <location_display_name>, <event_description> estimated time of arrival: <estimated_time_of_arrival_date> <estimated_time_of_arrival_time>"
}
if b.IRC.ParcelTrackingMsgAliasRemoved == "" {
b.IRC.ParcelTrackingMsgAliasRemoved = "<alias> removed"
}
if b.IRC.ParcelTrackingMsgAliasDoesNotExist == "" {
b.IRC.ParcelTrackingMsgAliasDoesNotExist = "<alias> does not exist"
}
if b.IRC.ParcelTrackingErrNoData == "" {
b.IRC.ParcelTrackingErrNoData = "no tracking data found"
}
if b.IRC.ParcelTrackingErrDuplicateAlias == "" {
b.IRC.ParcelTrackingErrDuplicateAlias = "<alias> is already in use for parcel <existing_id>"
}
if b.IRC.ParcelTrackingCmd == "" {
b.IRC.ParcelTrackingCmd = "!pt"
}
if b.IRC.ParcelTrackingCmdAdd == "" {
b.IRC.ParcelTrackingCmdAdd = "add"
}
if b.IRC.ParcelTrackingCmdRemove == "" {
b.IRC.ParcelTrackingCmdRemove = "remove"
}
if b.IRC.ParcelTrackingCmdInfo == "" {
b.IRC.ParcelTrackingCmdInfo = "info"
}
if b.IRC.ParcelTrackingCmdFull == "" {
b.IRC.ParcelTrackingCmdFull = "full"
}
if b.IRC.ParcelTrackingCmdList == "" {
b.IRC.ParcelTrackingCmdList = "list"
}
}
// parcelTrackingCommandHandler handles the commands issued from the IRC channel.
func (b *bot) parcelTrackingCommandHandler(m *irc.Message) {
a := b.parseAction(m).(*privmsgAction)
// Not our channel, return.
if !a.validChannel {
return
}
// Not a parcel tracking command, return.
if a.cmd != b.IRC.ParcelTrackingCmd {
return
}
// Use should be ignored, return.
if b.shouldIgnore(m) {
return
}
// Not enough args, return.
if len(a.args) < 1 {
return
}
// Determine which sub command to execute.
subCmd := a.args[0]
if subCmd == b.IRC.ParcelTrackingCmdAdd {
b.parcelTrackingAdd(a)
} else if subCmd == b.IRC.ParcelTrackingCmdRemove {
b.parcelTrackingRemove(a)
} else if subCmd == b.IRC.ParcelTrackingCmdInfo {
b.parcelTrackingInfo(a)
} else if subCmd == b.IRC.ParcelTrackingCmdFull {
b.parcelTrackingFull(a)
} else if subCmd == b.IRC.ParcelTrackingCmdList {
b.parcelTrackingList(a)
}
}
// parcelTrackingAdd adds the given id and alias to the database and returns
// the latest event data to the channel.
func (b *bot) parcelTrackingAdd(a *privmsgAction) {
// !pt add <id> <alias>
if len(a.args) != 3 {
return
}
// Store the arguments in convenient variable names.
id := a.args[1]
alias := a.args[2]
// Make sure that the alias isn't used already.
if existingID := b.parcelTrackingAliasExists(alias); existingID != "" {
b.privmsgph(b.IRC.ParcelTrackingErrDuplicateAlias, map[string]string{
"<alias>": alias,
"<existing_id>": existingID,
})
return
}
// Make sure that the requested id exists.
events := b.fetchPostNordInfo(id)
if events == nil {
b.privmsg(b.IRC.ParcelTrackingErrNoData)
return
}
// Store the id and alias.
b.insertParcelTracking(alias, id, a.nick)
// Print the latest info
b.sendParcelTrackingInfo(&events[len(events)-1])
}
// parcelTrackingRemove removes the alias from the database.
func (b *bot) parcelTrackingRemove(a *privmsgAction) {
// !pt remove <alias>
if len(a.args) != 2 {
return
}
// Store the arguments in convenient variable names.
alias := a.args[1]
// Make sure that the ID exists before we try to remove it.
if existingID := b.parcelTrackingAliasExists(alias); existingID == "" {
b.privmsgph(b.IRC.ParcelTrackingMsgAliasDoesNotExist, map[string]string{
"<alias>": alias,
})
return
}
// Delete it.
stmt, err := b.prepare("UPDATE parcel_tracking SET is_deleted = true WHERE alias = $1")
if err != nil {
b.logger.Printf("parcelTracking: %v", err)
b.privmsg(b.DB.Err)
return
}
defer stmt.Close()
_, err = stmt.Exec(alias)
if err != nil {
b.logger.Printf("parcelTracking: %v", err)
b.privmsg(b.DB.Err)
return
}
// Print it to the channel.
b.privmsgph(b.IRC.ParcelTrackingMsgAliasRemoved, map[string]string{
"<alias>": alias,
})
}
// parcelTrackingInfo returns the latest info for the given parcel id.
func (b *bot) parcelTrackingInfo(a *privmsgAction) {
events := b.fetchParcelTrackingInfo(a)
if events == nil {
return
}
b.sendParcelTrackingInfo(&events[len(events)-1])
}
// parcelTrackingFull fetches a full details info for the given parcel id.
func (b *bot) parcelTrackingFull(a *privmsgAction) {
events := b.fetchParcelTrackingInfo(a)
if events == nil {
return
}
// Compile a string of all events.
var fullMsg string
for _, e := range events {
data := map[string]string{
"<consignor_name>": e.consignorName,
"<event_date>": e.eventDate,
"<event_time>": e.eventTime,
"<location_display_name>": e.locationDisplayName,
"<event_description>": e.eventDescription,
"<estimated_time_of_arrival_date>": e.estimatedTimeOfArrivalDate,
"<estimated_time_of_arrival_time>": e.estimatedTimeOfArrivalTime,
"<drop_off_date>": e.dropOffDate,
"<drop_off_time>": e.dropOffTime,
"<estimation_or_drop_off_date>": e.estimationOrDropOffDate,
"<estimation_or_drop_off_time>": e.estimationOrDropOffTime,
}
msg := b.IRC.ParcelTrackingMsgInfo
for k, v := range data {
msg = strings.ReplaceAll(msg, k, v)
}
fullMsg = fmt.Sprintf("%s%s\n", fullMsg, msg)
}
// Remove the trailing new line.
fullMsg = fullMsg[0 : len(fullMsg)-1]
// Upload to pastebin.
b.newPaste(a.args[0], fullMsg)
}
// parcelTrackingList lists all stored aliases
func (b *bot) parcelTrackingList(a *privmsgAction) {
// Select all non deleted parcel trackings.
rows, err := b.query(`
SELECT alias, parcel_tracking_id, nick
FROM parcel_tracking
WHERE is_deleted = false
ORDER BY inserted_at DESC
`)
if err != nil {
b.logger.Printf("parcelTracking: %v", err)
return
}
defer rows.Close()
// Concat all aliases
var content string
for rows.Next() {
var alias, id, nick string
rows.Scan(&alias, &id, &nick)
if nick == "" {
content = fmt.Sprintf("%s%s -> %s\n", content, alias, id)
} else {
content = fmt.Sprintf("%s%s: %s -> %s\n", content, nick, alias, id)
}
}
// No parcels, return.
if len(content) == 0 {
return
}
// Trim traling new line.
content = content[0 : len(content)-1]
// Upload to pastebin.
b.newPaste("", content)
}
// parcelTrackingInfo fetches tracking info for the given id.
func (b *bot) fetchParcelTrackingInfo(a *privmsgAction) []postNordEvent {
// !pt info <id|alias> [alias]
if len(a.args) < 2 {
return nil
}
// Store the arguments in convenient variable names.
id := a.args[1]
// Check if the given ID is actually an alias that we have stored in
// the database.
existingID := b.parcelTrackingAliasExists(id)
if existingID != "" {
id = existingID
}
// Make sure that the requested id exists.
events := b.fetchPostNordInfo(id)
if events == nil {
b.privmsg(b.IRC.ParcelTrackingErrNoData)
return nil
}
// If the optional alias parameter is sent we'll also insert the
// parcel with an alias, as long as the alias isn't actually an alias
// already.
alias := ""
if len(a.args) >= 3 {
alias = a.args[2]
}
if alias != "" && existingID == "" && b.parcelTrackingAliasExists(alias) == "" {
// Store the id and alias.
b.insertParcelTracking(alias, id, a.nick)
}
return events
}
// parcelTrackingAliasExists checks whether or not the alias is used, if it is
// we'll return the parcel tracking ID, otherwise we'll return an empty
// string.
func (b *bot) parcelTrackingAliasExists(alias string) string {
var existingID string
b.queryRow("SELECT parcel_tracking_id FROM parcel_tracking WHERE alias = $1 AND is_deleted = false", alias).Scan(&existingID)
return existingID
}
// sendParcelTrackingInfo sends the given event to the channel.
func (b *bot) sendParcelTrackingInfo(e *postNordEvent) {
b.privmsgph(b.IRC.ParcelTrackingMsgInfo, map[string]string{
"<consignor_name>": e.consignorName,
"<event_date>": e.eventDate,
"<event_time>": e.eventTime,
"<location_display_name>": e.locationDisplayName,
"<event_description>": e.eventDescription,
"<estimated_time_of_arrival_date>": e.estimatedTimeOfArrivalDate,
"<estimated_time_of_arrival_time>": e.estimatedTimeOfArrivalTime,
"<drop_off_date>": e.dropOffDate,
"<drop_off_time>": e.dropOffTime,
"<estimation_or_drop_off_date>": e.estimationOrDropOffDate,
"<estimation_or_drop_off_time>": e.estimationOrDropOffTime,
})
}
// insertParcelTracking adds an entry to the parcel_tracking table.
func (b *bot) insertParcelTracking(alias, id, nick string) {
stmt, err := b.prepare(`INSERT INTO parcel_tracking (
id,
alias,
parcel_tracking_id,
nick,
inserted_at,
is_deleted
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6
);`)
if err != nil {
b.logger.Printf("parcelTracking: %v", err)
b.privmsg(b.DB.Err)
return
}
defer stmt.Close()
_, err = stmt.Exec(newUUID(), alias, id, nick, newTimestamp(), false)
if err != nil {
b.logger.Printf("parcelTracking: %v", err)
b.privmsg(b.DB.Err)
return
}
}
// fetchPostNordInfo fetches info from the PostNord API for the given id.
func (b *bot) fetchPostNordInfo(id string) []postNordEvent {
// Fetch the PostNord info.
pn := postnord.New(b.IRC.ParcelTrackingPostNordAPIKey, b.IRC.ParcelTrackingLocale)
tir, err := pn.FindByIdentifierV5(id)
if err != nil {
return nil
}
// PostNord does not return 404 if the id is incorrect, so we'll just
// assume it's incorrect if the response doesn't have any shipments.
if len(tir.TrackingInformationResponse.Shipments) == 0 {
return nil
}
// Convert the PostNord API data into our local data structure.
var events []postNordEvent
for _, s := range tir.TrackingInformationResponse.Shipments {
for _, i := range s.Items {
for _, e := range i.Events {
eventDate := ""
eventTime := ""
if len(e.EventTime) >= 16 {
eventDate = e.EventTime[0:10]
eventTime = e.EventTime[11:16]
}
estimatedTimeOfArrivalDate := ""
estimatedTimeOfArrivalTime := ""
if len(i.EstimatedTimeOfArrival) >= 16 {
estimatedTimeOfArrivalDate = i.EstimatedTimeOfArrival[0:10]
estimatedTimeOfArrivalTime = i.EstimatedTimeOfArrival[11:16]
}
dropOffDate := ""
dropOffTime := ""
if len(i.DropOffDate) >= 16 {
dropOffDate = i.DropOffDate[0:10]
dropOffTime = i.DropOffDate[11:16]
}
estimationOrDropOffDate := estimatedTimeOfArrivalDate
estimationOrDropOffTime := estimatedTimeOfArrivalTime
if estimationOrDropOffDate == "" {
estimationOrDropOffDate = dropOffDate
}
if estimationOrDropOffTime == "" {
estimationOrDropOffTime = dropOffTime
}
events = append(events, postNordEvent{
consignorName: s.Consignor.Name,
eventDate: eventDate,
eventTime: eventTime,
locationDisplayName: e.Location.DisplayName,
eventDescription: e.EventDescription,
estimatedTimeOfArrivalDate: estimatedTimeOfArrivalDate,
estimatedTimeOfArrivalTime: estimatedTimeOfArrivalTime,
dropOffDate: dropOffDate,
dropOffTime: dropOffTime,
estimationOrDropOffDate: estimationOrDropOffDate,
estimationOrDropOffTime: estimationOrDropOffTime,
})
}
}
}
return events
}
// postNordEvent simplified data structure for the "important" PostNord event
// data.
type postNordEvent struct {
consignorName string
eventDate string
eventTime string
locationDisplayName string
eventDescription string
estimatedTimeOfArrivalDate string
estimatedTimeOfArrivalTime string
dropOffDate string
dropOffTime string
estimationOrDropOffDate string
estimationOrDropOffTime string
}