This repository has been archived by the owner on Sep 6, 2018. It is now read-only.
forked from tfrce/call-congress
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy paththrottle.py
executable file
·91 lines (68 loc) · 3.14 KB
/
throttle.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
import os, psycopg2, hashlib
class Throttle():
conn = None
def __init__(self):
url = os.environ.get('HEROKU_POSTGRESQL_AMBER_URL')
self.conn = psycopg2.connect(url)
def throttle(self, campaign_id, from_phone_number, ip_address, override):
"""Records call info in the log"""
if from_phone_number == '' or len(from_phone_number) != 10:
print "THROTTLE TRIP! --- Bad from_phone_number!"
from_phone_number = format_phone_number(from_phone_number)
conn = self.conn
cur = conn.cursor()
flag_number = 0
flag_ip = 0
blacklist = 0
is_whitelisted = 0
hashed_ip_address = hashlib.sha256(ip_address).hexdigest()
qry = ("SELECT count(id) FROM _ms_call_throttle WHERE "
"create_date >= NOW() - '1 day'::INTERVAL "
" AND campaign_id=%s AND from_phone_number=%s")
cur.execute(qry, (campaign_id, from_phone_number))
recent_from_phone_number = cur.fetchone()
if recent_from_phone_number[0] > 1:
flag_number = 1
qry = ("SELECT count(id) FROM _ms_call_throttle WHERE "
"create_date >= NOW() - '1 day'::INTERVAL "
" AND campaign_id=%s AND (ip_address=%s OR ip_address=%s)")
cur.execute(qry, (campaign_id, ip_address, hashed_ip_address))
recent_ip_address = cur.fetchone()
if recent_ip_address[0] > 1:
flag_ip = 1
qry = "SELECT count(id) FROM _ms_call_blacklist WHERE phone_number=%s"
cur.execute(qry, (from_phone_number,))
is_blacklisted = cur.fetchone()
if is_blacklisted[0] > 0:
blacklist = 1
if override ==os.environ.get('THROTTLE_OVERRIDE_KEY') and not blacklist:
flag_ip = 0
flag_number = 0
is_whitelisted = 1
if flag_number == 0 and flag_ip == 0:
ip_address = hashed_ip_address
cur.execute(("INSERT INTO _ms_call_throttle "
" (campaign_id, from_phone_number, is_whitelisted, "
" is_blacklisted, ip_address, flag_number, flag_ip, "
" create_date) "
"VALUES "
" (%s, %s, %s, %s, %s, %s, %s, NOW())"),
(campaign_id, from_phone_number, is_whitelisted, blacklist,
ip_address, flag_number, flag_ip))
conn.commit()
cur.close()
if flag_number:
print "THROTTLE TRIP! --- from_phone_number %s / %s" % \
(from_phone_number, recent_from_phone_number[0])
return True
elif flag_ip:
print "THROTTLE TRIP! --- ip_address %s / %s" % \
(ip_address, recent_ip_address[0])
return True
elif blacklist:
print "THROTTLE TRIP! --- BLACKLISTED %s" % \
(from_phone_number,)
return True
return False
def format_phone_number(phone_number):
return phone_number[:3] + "-" + phone_number[3:6] + "-" + phone_number[6:10]