-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathasternic_email.py
222 lines (193 loc) · 7.05 KB
/
asternic_email.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
"""
Asternic Call Static Email Script
Copyright 2016 SF/Software t/a PEBBLE
"""
try:
import local_settings
except ImportError:
raise RuntimeError('local_settings.py does not exist or cannot be imported')
from bs4 import BeautifulSoup
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import CommonMark
import requests
import arrow
class CallStats(object):
ARROW_FORMAT = 'YYYY-MM-DD HH:MM:ss'
def __init__(self, extensions):
self.stats = extensions
self.session = requests.Session()
if local_settings.PBX_LOGIN_PAGE:
print ">> Login to PBX..."
self.session.post(
"{}/admin/config.php".format(
local_settings.PBX_URL),
data={
'username': local_settings.PBX_USERNAME,
'password': local_settings.PBX_PASSWORD
})
def connect_smtp(self, server, username, password):
print ">>> Connecting to SMTP"
self.smtp = smtplib.SMTP_SSL(server, 465)
self.smtp.login(username, password)
def stats_markdown(self, stats):
return u"""
<table>
<tr>
<th style="text-align:left">Total Calls</th>
<td>{total}</td>
</tr>
<tr>
<th style="text-align:left">Completed Calls</th>
<td>{completed}</td>
</tr>
<tr>
<th style="text-align:left">Missed Calls</th>
<td>{missed}</td>
</tr>
<tr>
<th style="text-align:left">Missed Percentage To You</th>
<td>{missedPercentage}</td>
</tr>
<tr>
<th style="text-align:left">Total time on phone</th>
<td>{duration}</td>
</tr>
<tr>
<th style="text-align:left">Average time per call</th>
<td>{avgDuration}</td>
</tr>
<tr>
<th style="text-align:left">Total Ring Time</th>
<td>{totalRingTime}</td>
</tr>
<tr>
<th style="text-align:left">Average Ring Time</th>
<td>{avgRingTime}</td>
</tr>
</table>
""".format(**stats)
def generate_email(self, data, tagline):
email = u"""
Hi {name},
{tagline}
## Outgoing Calls
{outgoing}
## Incoming Calls
{incoming}
Thanks,
The Call Stats Robot
""".format(
name=data['name'],
outgoing=self.stats_markdown(data['outgoing']),
incoming=self.stats_markdown(data['incoming']),
tagline=tagline)
html_email = CommonMark.commonmark(email)
# Send HTML email
html_part = MIMEText(html_email, 'html', 'utf-8')
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Your Call Stats'
msg['From'] = local_settings.SMTP_FROM
if isinstance(data['email'], basestring):
data['email'] = [data['email']]
for email in data['email']:
msg['To'] = email
msg.attach(html_part)
self.smtp.sendmail(
local_settings.SMTP_FROM,
email, msg.as_string())
def generate_emails(self, tagline):
for extension, data in self.stats.items():
self.generate_email(data, tagline)
print ">>> Sent Emails"
def fetch_stats(self):
self.get_callstats('incoming')
self.get_callstats('outgoing')
def set_day(self):
# Set to start of day
self.start = arrow.get().replace(hour=0, minute=0, second=0)
# Roll to end of day
self.end = arrow.get().replace(hour=23, minute=59, second=59)
def roll_to_weekday(self, date, weekday):
while date.weekday() != weekday:
if date.weekday() > weekday:
date = date.replace(days=-1)
else:
date = date.replace(days=1)
return date
def set_week(self, day_in_week=None):
# Set to start of day
self.start = self.roll_to_weekday(
arrow.get(day_in_week).replace(hour=0, minute=0, second=0), 0)
# Roll to end of day
self.end = self.roll_to_weekday(
arrow.get(day_in_week).replace(hour=23, minute=59, second=59), 6)
def set_month(self):
# Set to start of month
self.start = arrow.get().replace(day=1, hour=0, minute=0, second=0)
# Roll to next month's first day, then back to last second of month
self.end = arrow.get().replace(day=1, months=+1).replace(
days=-1, hour=23, minute=59, second=59)
def set_times(self, start, end):
self.start = arrow.get(start)
self.end = arrow.get(end)
def get_callstats(self, tab):
print '>>> Requesting {} stats'.format(tab)
print '>>> Report for period {} - {}'.format(self.start, self.end)
# Asternic requires a post
page = self.session.post(
"{}/admin/config.php?type=tool&display=asternic_cdr&tab={}".format(
local_settings.PBX_URL, tab),
auth=(local_settings.PBX_USERNAME, local_settings.PBX_PASSWORD),
data={
'start': self.start.format(self.ARROW_FORMAT),
'end': self.end.format(self.ARROW_FORMAT),
'List_Extensions[]': [
"'{}'".format(k) for k, v in
self.stats.items()
],
'tab': tab
})
# Then requesting the report
# (idk what it's doing)
page = self.session.get(
"{}/admin/config.php?type=tool&display=asternic_cdr&tab={}".format(
local_settings.PBX_URL, tab),
auth=(local_settings.PBX_USERNAME, local_settings.PBX_PASSWORD))
print '>>> Asternic responded with {}'.format(page.status_code)
soup = BeautifulSoup(page.text, 'html.parser')
for extension, data in self.stats.items():
# Asternic produces a <tr> straight after what we want labeled
# with an ID
try:
wrong_row = soup.select("#{}".format(extension))[0]
# So we need to get the row just before it
row = wrong_row.previous_sibling.previous_sibling
items = row.find_all('td')
# Now we have the partial call stats for this person
# so we fill the array
self.stats[extension][tab] = {
'total': items[1].string,
'completed': items[2].string,
'missed': items[3].string,
'missedPercentage': items[4].string,
'duration': items[5].string,
'durationPercentage': items[6].string,
'avgDuration': items[7].string,
'totalRingTime': items[8].string,
'avgRingTime': items[9].string
}
except IndexError:
print '>>>> {} did no calls during this period'.format(data['name'])
self.stats[extension][tab] = {
'total': 0,
'completed': 0,
'missed': 0,
'missedPercentage': 'null',
'duration': '0s',
'durationPercentage': 'null',
'avgDuration': '0s',
'totalRingTime': 'null',
'avgRingTime': 'null'
}