forked from ox-it/vacancy-emailer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vacancy-emailer.py
executable file
·251 lines (212 loc) · 9.32 KB
/
vacancy-emailer.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
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import datetime
import email.mime.multipart
import email.mime.text
import email.utils
import logging
import json
import os
import pytz
import smtplib
import sys
import textwrap
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
import dateutil.parser
from inlinestyler.utils import inline_css
from lxml import etree
from lxml.builder import E
import requests
logger = logging.getLogger(__name__)
class VacancyEmailer(object):
def __init__(self, seen_before):
self._seen_before = os.path.expanduser(seen_before) if seen_before else None
@property
def feed_url(self):
return os.environ['FEED_URL']
@property
def email_from(self):
return os.environ['EMAIL_FROM']
@property
def email_to(self):
return os.environ['EMAIL_TO']
@property
def email_cc(self):
return os.environ.get('EMAIL_CC')
@property
def email_bcc(self):
return os.environ.get('EMAIL_BCC')
@property
def email_subject(self):
return os.environ['EMAIL_SUBJECT']
@property
def smtp_server(self):
return os.environ['SMTP_SERVER']
@property
def html_preamble(self):
return etree.parse(open(os.environ['HTML_PREAMBLE_FILE'], 'rb')).getroot()
@property
def html_css(self):
return open(os.environ['HTML_CSS_FILE'], 'rb').read().decode('utf-8')
@property
def text_preamble(self):
return open(os.environ['TEXT_PREAMBLE_FILE'], 'rb').read().decode('utf-8')
def __call__(self):
vacancies = self.get_vacancies()
current_vacancies = set(vacancies.xpath('/vacancies/vacancy/@id'))
if self._seen_before and os.path.exists(self._seen_before):
seen_vacancies = set(open(self._seen_before, 'r').read().split())
new_vacancies = current_vacancies - seen_vacancies
else:
new_vacancies = set()
html, text = self.generate_email_bodies(vacancies, new_vacancies)
msg = self.compose_email(html, text)
self.send_email(msg)
if self._seen_before:
with open(self._seen_before, 'w') as f:
for vacancy_id in sorted(current_vacancies):
f.write('{}\n'.format(vacancy_id))
def get_vacancies(self):
return etree.parse(urlopen(self.feed_url))
def generate_email_bodies(self, vacancies, new_vacancies):
html_vacancies = E('div')
html = E('html',
E('head', E('style', self.html_css, type='text/css')),
E('body', self.html_preamble, html_vacancies))
text_body = [self.text_preamble]
if len(vacancies.xpath('/vacancies/vacancy')) == 0:
raise SystemExit(0)
for i, vacancy in enumerate(vacancies.xpath('/vacancies/vacancy')):
vacancy_id = vacancy.attrib['id']
html_description = etree.fromstring(vacancy.xpath("description[@media_type='text/html']")[0].text,
parser=etree.HTMLParser())[0][0]
first_para = html_description.xpath(".//text()[normalize-space(.) and not(contains(., 'INTERNAL') or contains(., 'ADVERTISEMENT'))]")[0].strip()
html_first_para = E('div', first_para, **{'class': 'description'})
tags = []
if 'INTERNAL' in html_description.text:
tags.append('internal applicants only')
if 'ADVERTISEMENT' in html_description.text:
tags.append('re-advertisement')
tags = ' ({0})'.format(', '.join(tags)) if tags else ''
try:
closes = dateutil.parser.parse(vacancy.find('closes').text)
except Exception:
closes, closes_soon = 'unknown', False
else:
closes_soon = (closes - datetime.datetime.now(pytz.utc)).total_seconds() < 3600 * 24 * 2
closes = closes.strftime('%a, %d %b %Y, %I:%M %p')
html_vacancy = E('div',
E('h1', vacancy.find('label').text),
E('div',
E('span', vacancy.find('salary').find('label').text, **{'class': 'salary'}),
'; closes: ',
E('span', closes, **{'class': 'closes' + (' closes-soon' if closes_soon else '')}),
tags,
**{'class': 'byline'}
),
html_first_para,
E('div',
E('a', 'More details\N{HORIZONTAL ELLIPSIS}', href=vacancy.find('webpage').text)),
**{'class': 'vacancy'}
)
if vacancy_id in new_vacancies:
html_vacancy[0].text += " "
html_vacancy[0].append(E('span', '\N{BLACK STAR} new', **{'class': 'new'}))
html_vacancies.append(html_vacancy)
text_body.extend([
'_' * 70,
'\n\n',
textwrap.fill(vacancy.find('label').text),
' *NEW*' if vacancy_id in new_vacancies else '',
'\n\n',
vacancy.find('salary').find('label').text,
'\nCloses: ',
closes,
tags,
'\n\n',
textwrap.fill(first_para),
'\n\n'
'More details: https://data.ox.ac.uk/v/',
vacancy.attrib['id'],
'\n'
])
html_body = inline_css(etree.tostring(html, method='html'))
text_body = ''.join(text_body).encode('utf-8')
return html_body, text_body
def compose_email(self, html_body, text_body):
msg = email.mime.multipart.MIMEMultipart('alternative')
msg['Subject'] = self.email_subject
msg['From'] = self.email_from
msg['To'] = self.email_to
if self.email_cc:
msg['CC'] = self.email_cc
msg.attach(email.mime.text.MIMEText(text_body, 'plain', 'utf-8'))
msg.attach(email.mime.text.MIMEText(html_body, 'html', 'utf-8'))
return msg
def send_email(self, msg):
s = smtplib.SMTP(self.smtp_server)
recipients = self.email_to.split(',') + (self.email_cc or '').split(',') + (self.email_bcc or '').split(',')
recipients = [email.utils.parseaddr(r.strip())[1] for r in recipients if r.strip()]
s.sendmail(email.utils.parseaddr(self.email_from)[1],
recipients,
msg.as_string())
s.quit()
class OnlyFirstWorkingDayOfWeekMixin(object):
bank_holidays_json_url = 'https://www.gov.uk/bank-holidays.json'
def __call__(self, *arg, **kwargs):
bank_holidays = json.loads(requests.get(self.bank_holidays_json_url).text)
bank_holidays = set(datetime.datetime.strptime(d['date'], "%Y-%m-%d").date()
for d in bank_holidays['england-and-wales']['events'])
today = datetime.date.today()
def working_day(d):
return (d.weekday() < 5 # Not a weekend
and d not in bank_holidays # Not a bank holiday
and not (d.month == 12 and 25 <= d.day <= 31)) # Not in Christmas closedown
# Only send if today is actually a working day, and...
if not working_day(today):
logger.info("Today is not a working day; not continuing")
return
# Look back through the week. If any of those days was also a working day, stop now.
for i in range(today.weekday(), 0, -1):
previous_date = today - datetime.timedelta(i)
if working_day(previous_date):
logger.info("%s was a working day; not continuing", previous_date)
return
super(OnlyFirstWorkingDayOfWeekMixin, self).__call__(*arg, **kwargs)
class PrintEmailInsteadMixin(object):
def send_email(self, msg):
print(msg.as_string())
if __name__ == '__main__':
argparser = argparse.ArgumentParser(
description="Send emails about vacancies")
argparser.add_argument('-l', '--log-level',
dest='loglevel', action='store',
help="Python logging level")
argparser.add_argument('-d', '--dry-run',
dest='dry_run', action='store_true',
help="Print email instead of emailing it")
argparser.add_argument('-w', '--only-first-working-day',
dest='first_working_day', action='store_true',
help="Only send if today is the first working day of the week")
argparser.add_argument('-s', '--seen-before',
dest='seen_before', action='store',
help='File containing vacancies seen before')
args = argparser.parse_args()
if args.loglevel:
try:
logging.basicConfig(level=getattr(logging, args.loglevel.upper()))
except AttributeError:
sys.stderr.write("{0} is not a valid log level".format(args.loglevel.upper()))
sys.exit(1)
bases = (VacancyEmailer,)
if args.first_working_day:
bases = (OnlyFirstWorkingDayOfWeekMixin,) + bases
if args.dry_run:
bases = (PrintEmailInsteadMixin,) + bases
# wrap in str to force to non-unicode in Py2; no-op in Py3
cls = type(str('VacancyEmailer'), bases, {})
cls(seen_before=args.seen_before)()