forked from adammck/plumpynut
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.py
executable file
·600 lines (436 loc) · 15.2 KB
/
backend.py
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
#!/usr/bin/env python
# vim: noet
import kannel
from smsapp import *
from datetime import date, datetime
from strings import ENGLISH as STR
# import the essentials of django
from django.core.management import setup_environ
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from webui import settings
setup_environ(settings)
# import the django models, which should be movd
# somewhere sensible at the earliest opportunity
from webui.inventory.models import *
class App(SmsApplication):
kw = SmsKeywords()
# non-standard regex chunks
ALIAS = '([a-z\.]+)'
def __get(self, model, **kwargs):
try:
# attempt to fetch the object
return model.objects.get(**kwargs)
# no objects or multiple objects found (in the latter case,
# something is probably broken, so perhaps we should warn)
except (ObjectDoesNotExist, MultipleObjectsReturned):
return None
def __identify(self, caller, task=None):
monitor = self.__get(Monitor, phone=caller)
# if the caller is not identified, then send
# them a message asking them to do so, and
# stop further processing
if not monitor:
msg = "Please register your mobile number"
if task: msg += " before %s" % (task)
msg += ", by replying: I AM <USERNAME>"
raise CallerError(msg)
return monitor
def __monitor(self, alias):
# some people like to include dots
# in the username (like "a.mckaig"),
# so we'll merrily ignore those
clean = alias.replace(".", "")
# attempt to fetch the monitor from db
# (for now, only by their ALIAS...
monitor = self.__get(Monitor, alias=clean)
# abort if nothing was found
if not monitor:
raise CallerError(
STR["unknown_alias"] % alias)
return monitor
def __guess(self, string, within):
try:
from Levenshtein import distance
import operator
d = []
# something went wrong (probably
# missing the Levenshtein library)
except:
self.log("Couldn't import Levenshtein library", "warn")
return None
# searches are case insensitive
string = string.upper()
# calculate the levenshtein distance
# between each object and the argument
for obj in within:
# some objects may have a variety of
# ways of being recognized (code or name)
if hasattr(obj, "guess"): tries = obj.guess()
else: tries = [str(obj)]
# calculate the intersection of
# all objects and their "tries"
for t in tries:
dist = distance(str(t).upper(), string)
d.append((t, obj, dist))
# sort it, and return the closest match
d.sort(None, operator.itemgetter(2))
if (len(d) > 0):# and (d[0][1] < 3):
return d[0]
# nothing was close enough
else: return None
def new_transaction(self, caller):
id = random.randint(11111111, 99999999)
# fetch the monitor, and increment their incoming
# message counter (so they can be payed for the sms)
mon = self.__get(Monitor, phone=caller)
if mon is not None:
mon.incoming_messages += 1
mon.save()
# when a new transaction is started, create an
# instance to bind the messages sent and received
return Transaction.objects.create(
identity=id,
phone=caller,
monitor=mon)
# I AM <ALIAS> ------------------------------------------------------------
kw.prefix = ["i am", "this is", "identify"]
@kw(ALIAS)
def identify(self, caller, alias):
monitor = self.__monitor(alias)
# if this monitor is already associated
# with this number, there's nothing to do
if monitor.phone == caller:
self.respond(STR["ident_again"] % (monitor))
# if anyone else is currently identified
# by this number, then disassociate them
prev = self.__get(Monitor, phone=caller)
if prev and (prev.pk != monitor.pk):
prev.phone = ""
prev.save()
# associate the monitor with this number
monitor.phone = caller
monitor.save()
# the monitor is now identified
self.respond(STR["ident"] % (monitor))
@kw.blank()
@kw.invalid()
def identify_fail(self, caller, *msg):
raise CallerError(STR["ident_help"])
# WHO AM I ----------------------------------------------------------------
kw.prefix = ["who am i", "whoami"]
@kw.blank()
def whoami(self, caller):
# attempt to find a monitor matching the
# caller's phone number, and remind them
monitor = self.__get(Monitor, phone=caller)
if monitor: self.respond(STR["whoami"] % (monitor.details))
else: raise CallerError(STR["whoami_unknown"])
@kw.invalid()
def whoami_help(self, caller, *msg):
raise CallerError(STR["whoami_help"])
# WHO IS <ALIAS> ----------------------------------------------------------
kw.prefix = ["who is", "whois"]
@kw(ALIAS)
def who(self, caller, alias):
monitor = self.__monitor(alias)
self.respond(STR["whois"] % (alias, monitor.details))
@kw.blank()
@kw.invalid()
def who_fail(self, caller, *msg):
raise CallerError(STR["whois_help"])
# ALERT <NOTICE> ----------------------------------------------------------
kw.prefix = "alert"
@kw("(whatever)")
def alert(self, caller, notice):
monitor = self.__identify(caller, "alerting")
Notification.objects.create(monitor=monitor, resolved=0, notice=notice)
self.respond(STR["alert_ok"] % (monitor.alias))
@kw.blank()
def alert_help(self, caller, *msg):
raise CallerError(STR["alert_help"])
# CANCEL ------------------------------------------------------------------
kw.prefix = ["cancel", "cancle"]
@kw("(letters)")
def cancel_code(self, caller, code):
monitor = self.__identify(caller, "cancelling")
try:
# attempt to find monitor's
# entry with this code
entry = Entry.objects.filter(
monitor=monitor,\
supply_place__location__code=code)\
.order_by('-time')[0]
# delete it and notify
entry.delete()
self.respond(STR["cancel_code_ok"] % (code))
except (ObjectDoesNotExist, IndexError):
try:
# try again for woreda code
entry = Entry.objects.filter(
monitor=monitor,\
supply_place__area__code=code)\
.order_by('-time')[0]
# delete it and notify
entry.delete()
self.respond(STR["cancel_code_ok"] % (code))
except (ObjectDoesNotExist, IndexError):
raise CallerError(STR["cancel_none"])
@kw.blank()
def cancel(self, caller):
monitor = self.__identify(caller, "cancelling")
try:
# attempt to find the monitor's
# most recent entry TODAY
latest = Entry.objects.filter(
time__gt=date.today(),
monitor=monitor)\
.order_by('-time')[0]
latest_desc = latest.supply_place
# delete it and notify
latest.delete()
self.respond(STR["cancel_ok"] % (monitor.alias, latest_desc))
except (ObjectDoesNotExist, IndexError):
raise CallerError(STR["cancel_none"] % (monitor.alias))
@kw.invalid()
def cancel_help(self, caller, *msg):
raise CallerError(STR["cancel_help"])
# SUPPLIES ----------------------------------------------------------------
kw.prefix = ["supplies", "supplys", "supply", "sups"]
@kw.blank()
def supplies(self, caller):
self.respond(["%s: %s" % (s.code, s.name)\
for s in Supply.objects.all()])
@kw.invalid()
def supplies_help(self, caller):
raise CallerError(STR["supplies_help"])
# HELP <QUERY> ------------------------------------------------------------
kw.prefix = ["help", "help me"]
@kw.blank()
def help_main(self, caller):
self.respond(STR["help_main"])
@kw("report", "format", "fields")
def help_report(self, caller):
self.respond(STR["help_report"])
@kw("register", "identify")
def help_report(self, caller):
self.respond(STR["help_reg"])
@kw("alert")
def help_report(self, caller):
self.respond(STR["help_alert"])
@kw.invalid()
def help_help(self, caller, *msg):
self.respond(STR["help_help"])
# CONVERSATIONAL ------------------------------------------------------------
kw.prefix = ["ok", "thanks", "thank you"]
@kw.blank()
@kw("(whatever)")
@kw.invalid()
def conv_welc(self, caller):
monitor = self.__identify(caller, "thanking")
self.respond(STR["conv_welc"] % (monitor))
kw.prefix = ["hi", "hello", "howdy", "whats up"]
@kw.blank()
@kw("(whatever)")
@kw.invalid()
def conv_greet(self, caller, whatever=None):
monitor = self.__get(Monitor, phone=caller)
if monitor.phone == caller:
self.respond(STR["ident"] % (monitor))
self.respond(STR["conv_greet"])
kw.prefix = ["fuck", "damn", "shit", "bitch"]
@kw.blank()
@kw("(whatever)")
@kw.invalid()
def conv_swear(self, caller, whatever=None):
monitor = self.__get(Monitor, phone=caller)
if monitor.phone == caller:
self.respond(STR["conv_swear"] % (monitor))
self.respond(STR["conv_greet"])
# <SUPPLY> <PLACE> <BENEFICIERIES> <QUANTITY> <CONSUMPTION> <BALANCE> --
kw.prefix = ""
@kw("[\"'\s]*(letters)[,\.\s]*(letters)[,\.\s]*(\d+)(?:[,\.\s]*(\d+))?(?:[,\.\s]*(\d+))?(?:[,\.\s]*(\d+))?[\.,\"'\s]*")
def report(self, caller, sup_code, place_code, ben="", qty="", con="", bal=""):
# ensure that the caller is known
monitor = self.__identify(caller, "reporting")
# validate + fetch the supply
scu = sup_code.upper()
sup = self.__get(Supply, code=scu)
if sup is None:
# invalid supply code, so
# search for a close match
all_sup = Supply.objects.all()
sug = self.__guess(scu, all_sup)
if sug is not None:
str, obj, dist = sug
# found a close match, so
# error with a suggestion
if dist < 5:
raise CallerError(STR["suggest"]\
% ("supply code", scu, obj.code, obj.name))
# no close matches (or spellcheck isn't
# working), so just return error
raise CallerError(STR["unknown"]\
% ("supply code", scu))
# init variables to avoid
# pythonic complaints
loc = None
area = None
pcu = place_code.upper()
# ...and the "place", which could
# be either a location or area
loc = self.__get(Location, code=pcu)
if loc is None:
# not a valid location, so try area
area = self.__get(Area, code=pcu)
if area is None:
# the code was neither a location
# no area, so search for a close match
sug = self.__guess(pcu,
list(Location.objects.all()) +
list(Area.objects.all()))
if sug is not None:
str, obj, dist = sug
# found a close match, so
# error with a suggestion
if dist < 5:
raise CallerError(STR["suggest"]\
% ("OTP or Woreda code", pcu, obj.code, obj.name))
# no close matches (or spellcheck isn't
# working), so just return error
raise CallerError(STR["unknown"]\
% ("OTP or Woreda code", pcu))
# fetch the supplylocation object, to update the current stock
# levels. if it doesn't already exist, just create it, because
# the administrators probably won't want to add them all...
sp, created = SupplyPlace.objects.get_or_create(supply=sup, location=loc, area=area)
# create the entry object,
# unless its a recent duplicate
try:
Entry.objects.filter(
monitor=monitor,
supply_place=sp,
time__gt=date.today())\
.order_by('-time')[0]
except (ObjectDoesNotExist, IndexError):
Entry.objects.create(
monitor=monitor,
supply_place=sp,
beneficiaries=ben,
quantity=qty,
consumption=con,
balance=bal)
# collate all of the information submitted, to
# be sent back and checked by the caller
info = [
"ben=%s" % (ben or "??"),
"qty=%s" % (qty or "??"),
"con=%s" % (con or "??"),
"bal=%s" % (bal or "??")]
# notify the caller of their new entry
# this doesn't seem to be localizable
if loc is None:
self.respond(
"Received %s report for %s %s by %s: %s.\nIf this is not correct, reply with CANCEL %s" %\
(sup.name, sp.type, sp.place, monitor, ", ".join(info), area))
if area is None:
self.respond(
"Received %s report for %s %s by %s: %s.\nIf this is not correct, reply with CANCEL %s" %\
(sup.name, sp.type, sp.place, monitor, ", ".join(info), loc))
# NO IDEA WHAT THE CALLER WANTS -------------------------------------------
def incoming_sms(self, caller, msg):
self.log("No match by regex", "warn")
# we will only attempt to guess if
# it looks like the caller is trying
# to use these functions
guess_funcs = (
self.identify,
self.report,
self.alert)
while(len(msg) > 0):
found = False
# iterate each guessable function, and each
# of its regexen without their tailing DOLLAR.
# since we couldn't find a real match, we're
# looking for a matching prefix (in case the
# sender has appended junk to their message,
# or concatenated multiple messages without
# proper delimitors)
for func in guess_funcs:
for regex in getattr(func, "regexen"):
pattern = regex.pattern.rstrip("$")
new_regex = re.compile(pattern, re.IGNORECASE)
# does the message START with
# the applied pattern?
match = new_regex.match(msg)
if match:
# hack: since we're about to recurse via d_i_sms,
# the chopped up message will be entered into the
# database as if it were a real message, which will
# confuse the log. this flag instructs before_incoming
# to mark the following messages as virtual
self.processing_virtual = True
# log and dispatch the matching part, as if
# it were a regular incoming message
self.log("Prefix matches function: %s" % (func.func_name), "info")
self.dispatch_incoming_sms(caller, match.group(0))
# revert to normal behavior
self.processing_virtual = False
# drop the part of the message
# that we just dealt with, and
# continue with the next iteration
msg = new_regex.sub("", msg, 1).strip()
found = True
break
# nothing matched in this iteration,
# so it won't ever. abort :(
if not found:
self.log("No match for: %r" % (msg), "warn")
raise CallerError(STR["error"])
# LOGGING -----------------------------------------------------------------
# always called by smsapp, to log
# without interfereing with dispatch
def before_incoming(self, caller, msg):
# we will log the monitor, if we can identify
# them by their number. otherwise, log the number
mon = self.__get(Monitor, phone=caller)
if mon is None: ph = caller
else: ph = None
# don't log if the details are the
# same as the transaction itself
if mon == self.transaction.monitor: mon = None
if ph == self.transaction.phone: ph = None
# see above (hack) for explanation
# of t his 'virtual' flag
virt = False
if hasattr(self, "processing_virtual"):
virt = self.processing_virtual
# create a new log entry
Message.objects.create(
transaction=self.transaction,
is_outgoing=False,
phone=caller,
monitor=mon,
message=msg,
is_virtual=virt)
# as above...
def before_outgoing(self, recipient, msg):
# we will log the monitor, if we can identify
# them by their number. otherwise, log the number
mon = self.__get(Monitor, phone=recipient)
if mon is None: ph = recipient
else: ph = None
# don't log if the details are the
# same as the transaction itself
if mon == self.transaction.monitor: mon = None
if ph == self.transaction.phone: ph = None
# create a new log entry
Message.objects.create(
transaction=self.transaction,
is_outgoing=True,
phone=recipient,
monitor=mon,
message=msg)
app = App(backend=kannel, sender_args=["user", "pass"])
app.run()
# wait for interrupt
while True: time.sleep(1)