-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.py
83 lines (70 loc) · 2.49 KB
/
sync.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
import os
from datetime import datetime, timedelta
from urllib.parse import urljoin
import psycopg2
import requests
CHANNEL_ID = os.environ.get("CHANNEL_ID", "11")
HUB_URL = os.environ.get("HUB_URL")
HUB_TOKEN = os.environ.get("HUB_TOKEN")
QUERY_LIMIT = os.environ.get("QUERY_LIMIT", "99999")
DB_NAME = os.environ["DATABASE_NAME"]
DB_USER = os.environ["LOGIN"]
DB_PASSWORD = os.environ.get("PASSWORD")
DB_HOST = os.environ["HOST"]
DB_PORT = int(os.environ["DB_PORT"])
def get_send_errors(error_date):
cursor.execute(
"""
SELECT contacts_contacturn.path, MAX(channels_channellog.created_on)
FROM channels_channellog
INNER JOIN msgs_msg
ON channels_channellog.msg_id = msgs_msg.id
INNER JOIN contacts_contacturn
ON msgs_msg.contact_urn_id = contacts_contacturn.id
WHERE channels_channellog.created_on::date = %s
AND channels_channellog.channel_id = %s
AND channels_channellog.is_error = TRUE
AND channels_channellog.response LIKE '%%"code":1013%%'
GROUP BY contacts_contacturn.path
ORDER BY 2 desc
LIMIT %s
""",
(error_date, CHANNEL_ID, QUERY_LIMIT),
)
return [(urn, error_timestamp) for urn, error_timestamp in cursor]
def send_error_to_hub(contact_id, timestamp):
headers = {
"Authorization": "Token {}".format(HUB_TOKEN),
"Content-Type": "application/json",
}
response = requests.post(
urljoin(HUB_URL, f"/api/v2/deliveryfailure/{contact_id}/"),
headers=headers,
json={
"contact_id": contact_id,
"timestamp": timestamp.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
},
)
response.raise_for_status()
return response.status_code
if __name__ == "__main__":
conn = psycopg2.connect(
dbname=DB_NAME,
user=DB_USER,
password=DB_PASSWORD,
host=DB_HOST,
port=DB_PORT,
)
cursor = conn.cursor()
start_time = datetime.now()
yesterday = datetime.now() - timedelta(1)
send_errors = get_send_errors(datetime.strftime(yesterday, "%Y-%m-%d"))
for contact_id, error_timestamp in send_errors:
print(
f"{datetime.now()} [-] Sending *{contact_id[-4:]} - {error_timestamp}",
end=" ",
)
status_code = send_error_to_hub(contact_id, error_timestamp)
print(f"- Result: {status_code}")
print(f"Completed: {len(send_errors)}")
print(f"Duration: {str(datetime.now() - start_time)}")