-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEmailSender.py
319 lines (295 loc) · 16.1 KB
/
EmailSender.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
import json
import pyrebase
import sendgrid
from Utils import supported_categories, get_current_pst_format_timestamp, flag_for_country, log_info
class EmailSender:
def __init__(self):
with open('credentials/firebase_credentials.json', 'r') as f:
firebase_credentials = json.load(f)
self.firebase = pyrebase.initialize_app(firebase_credentials)
self.database = self.firebase.database()
with open('credentials/sendgrid_credentials.json', 'r') as f:
sendgrid_credentials = json.load(f)
self.sg = sendgrid.SendGridAPIClient(sendgrid_credentials['apiKey'])
def item_added_html_string(self, locale_code, category_code, sku):
try:
added_time = self.database.child(
'{}/product_updates/{}/ADDED/{}/{}'.format(locale_code, category_code, sku, 'time_added')).get().val()
return '<p>Available from: {}</p>'.format(added_time[:8] + " " + added_time[9:14].replace("_", ":"))
except Exception:
return ""
def item_added_time_html_string(self, locale_code, category_code, sku):
try:
added_time = self.database.child(
'{}/product_updates/{}/ADDED/{}/{}'.format(locale_code, category_code, sku, 'time_added')).get().val()
formatted_added_time = added_time[:8] + " " + added_time[9:14].replace("_", ":")
return '<p>Available from: {}</p>'.format(formatted_added_time)
except Exception:
return '<p>Available from: N/A</p>'
def item_removed_time_html_string(self, locale_code, category_code, sku):
ret = ""
try:
added_time = self.database.child(
'{}/product_updates/{}/REMOVED/{}/{}'.format(locale_code, category_code, sku, 'time_added')).get().val()
formatted_added_time = added_time[:8] + " " + added_time[9:14].replace("_", ":")
ret += '<p>Available from: {}</p>'.format(formatted_added_time)
except Exception:
ret += '<p>Available from: N/A</p>'
try:
removed_time = self.database.child(
'{}/product_updates/{}/REMOVED/{}/{}'.format(locale_code, category_code, sku,
'time_removed')).get().val()
available_time_hours = self.database.child(
'{}/product_updates/{}/REMOVED/{}/{}'.format(locale_code, category_code, sku,
'time_available_hours')).get().val()
formatted_removed_time = removed_time[:8] + " " + removed_time[9:14].replace("_", ":")
ret += '<p>Sold out at: {} ({} hours after release)</p>'.format(formatted_removed_time,
"{:.2f}".format(available_time_hours))
except Exception:
ret += '<p>Sold out at: N/A (N/A hours after release)</p>'
return ret
def send_realtime_update(self, locale_code, last_update_stamp=None):
def image_html(item):
template = '''<img src="{}" height="150" />'''
html = ''
for url in item['assets']:
html += template.format('https:' + url['url'])
return html
def added_products_html(locale_code, realtime_delta_data):
added_item_html = '<h2>New Items ({} in total):</h2>'
added_product_template = '''
<hr />
<p>{}</p>
<p>{} - <a href="{}">{}</a></p>
<p>Price: {}</p>
{}
<p>Category: {}</p>
'''
added_item_count = 0
visited = set()
for category_code in supported_categories():
if category_code not in realtime_delta_data:
log_info('{} not in realtime_delta_data'.format(category_code))
continue
if "ADDED" in realtime_delta_data[category_code]:
for sku in realtime_delta_data[category_code]['ADDED']:
if sku in visited:
continue
visited.add(sku)
added_item_count += 1
item = realtime_delta_data[category_code]['ADDED'][sku]
item_html = added_product_template.format(image_html(item), added_item_count,
'https://www.hermes.com/{}'.format(locale_code.replace("_", "/")) + item['url'],
item['title'],
item['price'],
self.item_added_time_html_string(locale_code,
category_code, sku),
category_code)
added_item_html += item_html
if added_item_count > 0:
log_info("Detected {} realtime added items".format(added_item_count))
return added_item_html.format(added_item_count)
else:
return ""
def removed_products_html(locale_code, daily_delta_data):
removed_item_html = '<h2>Sold out Items ({} in total):</h2>'
removed_product_template = '''
<hr />
<p>{}</p>
<p><span style="text-decoration: line-through;">{} - <a href="{}">{}</a></span></p>
<p><span style="text-decoration: line-through;">Price: {} </span>(SOLD OUT)</p>
{}
<p>Category: {}</p>
'''
removed_item_count = 0
visited = set()
for category_code in supported_categories():
if category_code not in daily_delta_data:
log_info('{} not in daily_delta_data'.format(category_code))
continue
if "REMOVED" in daily_delta_data[category_code]:
for sku in daily_delta_data[category_code]['REMOVED']:
if sku in visited:
continue
visited.add(sku)
removed_item_count += 1
item = daily_delta_data[category_code]['REMOVED'][sku]
item_html = removed_product_template.format(image_html(item), removed_item_count,
'https://www.hermes.com/{}'.format(locale_code.replace("_", "/")) + item['url'],
item['title'],
item['price'],
self.item_removed_time_html_string(locale_code,
category_code,
sku),
category_code)
removed_item_html += item_html
if removed_item_count > 0:
return removed_item_html.format(removed_item_count)
else:
return ""
if not last_update_stamp:
last_update_stamp = self.database.child("{}/delta_realtime/last_update".format(locale_code)).get().val()
delta_realtime_path = "{}/delta_realtime/{}/{}".format(locale_code, last_update_stamp[:6], last_update_stamp)
log_info('sending email for {} real time update'.format(delta_realtime_path))
realtime_delta_data = self.database.child(delta_realtime_path).get().val()
if not realtime_delta_data:
log_info("realtime delta not exists: {}".format(delta_realtime_path))
return
added_products_html_string = added_products_html(locale_code, realtime_delta_data)
removed_products_html_string = removed_products_html(locale_code, realtime_delta_data)
if not added_products_html_string:
log_info("no added product update detected")
return
html_content = '''
<h1>Realtime Update {}</h1>
{}
{}
<p><strong><br />Thanks for staying updated with us!</strong></p>
'''.format(flag_for_country(locale_code), added_products_html_string, removed_products_html_string)
log_info(realtime_delta_data)
update_stamp = last_update_stamp.split('_to_')[-1]
message = sendgrid.Mail(
from_email='',
to_emails=[
'',
],
subject='📢 Hermes realtime update {} {}'.format(flag_for_country(locale_code), update_stamp),
html_content=html_content
)
response = self.sg.send(message)
log_info(response.status_code)
log_info(response.body)
log_info(response.headers)
def send_daily_update(self, date_string, locale_code):
def image_html(item):
template = '''<img src="{}" height="150" />'''
html = ''
for url in item['assets']:
html += template.format('https:' + url['url'])
return html
def added_products_html(locale_code, daily_delta_data):
added_item_html = '<h2>New Items ({} in total):</h2>'
added_product_template = '''
<hr />
<p>{}</p>
<p>{} - <a href="{}">{}</a></p>
<p>Price: {}</p>
{}
<p>Category: {}</p>
'''
added_item_count = 0
visited = set()
for category_code in supported_categories():
if category_code not in daily_delta_data:
log_info('{} not in daily_delta_data'.format(category_code))
continue
if "ADDED" in daily_delta_data[category_code]:
for sku in daily_delta_data[category_code]['ADDED']:
if sku in visited:
continue
visited.add(sku)
added_item_count += 1
item = daily_delta_data[category_code]['ADDED'][sku]
item_html = added_product_template.format(image_html(item), added_item_count,
'https://www.hermes.com/{}'.format(locale_code.replace("_", "/")) + item['url'],
item['title'],
item['price'],
self.item_added_time_html_string(locale_code,
category_code, sku),
category_code)
added_item_html += item_html
if added_item_count > 0:
log_info("Detected {} added items on daily update".format(added_item_count))
return added_item_html.format(added_item_count)
else:
return ""
def removed_products_html(locale_code, daily_delta_data):
removed_item_html = '<h2>Sold out Items ({} in total):</h2>'
removed_product_template = '''
<hr />
<p>{}</p>
<p><span style="text-decoration: line-through;">{} - <a href="{}">{}</a></span></p>
<p><span style="text-decoration: line-through;">Price: {} </span>(SOLD OUT)</p>
{}
<p>Category: {}</p>
'''
removed_item_count = 0
visited = set()
for category_code in supported_categories():
if category_code not in daily_delta_data:
log_info('{} not in daily_delta_data'.format(category_code))
continue
if "REMOVED" in daily_delta_data[category_code]:
for sku in daily_delta_data[category_code]['REMOVED']:
if sku in visited:
continue
visited.add(sku)
removed_item_count += 1
item = daily_delta_data[category_code]['REMOVED'][sku]
item_html = removed_product_template.format(image_html(item), removed_item_count,
'https://www.hermes.com/{}'.format(locale_code.replace("_", "/")) + item['url'],
item['title'],
item['price'],
self.item_removed_time_html_string(locale_code,
category_code,
sku),
category_code)
removed_item_html += item_html
if removed_item_count > 0:
return removed_item_html.format(removed_item_count)
else:
return ""
daily_delta_db_path = "{}/delta_daily/{}/{}".format(locale_code, date_string[:-2], date_string)
log_info('sending email for {} update'.format(daily_delta_db_path))
daily_delta_data = self.database.child(daily_delta_db_path).get().val()
if not daily_delta_data:
log_info("daily delta not exists: {}".format(daily_delta_db_path))
return
added_products_html_string = added_products_html(locale_code, daily_delta_data)
removed_products_html_string = removed_products_html(locale_code, daily_delta_data)
if not added_products_html_string and not removed_products_html_string:
log_info("no product update detected")
return
html_content = '''
<h1>Update on {} {}</h1>
{}
{}
<p><strong><br />Thanks for staying updated with us!</strong></p>
'''.format(date_string, flag_for_country(locale_code), added_products_html_string, removed_products_html_string)
log_info(daily_delta_data)
message = sendgrid.Mail(
from_email='',
to_emails=[
],
subject='📢 {} Hermes daily update {}'.format(date_string, flag_for_country(locale_code)),
html_content=html_content
)
response = self.sg.send(message)
log_info(response.status_code)
log_info(response.body)
log_info(response.headers)
def notice_admins_on_exception(self, exception, local_code, job_type):
message = sendgrid.Mail(
from_email='',
to_emails=[
],
subject='Hermes scraper exception {}'.format(get_current_pst_format_timestamp()),
html_content='''
<h1>Exception: {}</h1>
<h2>local_code: {}</h2>
<h2>job_type: {}</h2>
'''.format(exception, local_code, job_type)
)
response = self.sg.send(message)
log_info(response.status_code)
log_info(response.body)
log_info(response.headers)
# sender = EmailSender()
# sender.send_realtime_update('us_en', "20210617_09_46_53_to_20210617_10_28_55")
# sender.send_realtime_update("us_en", "20210615_14_27_28_to_20210615_15_45_30")
# sender.send_realtime_update("us_en", "20210607_23_09_00_to_20210607_23_54_01")
# sender.send_daily_update('20210618', 'us_en')
# response = sg.send(message)
# log_info(response.status_code)
# log_info(response.body)
# log_info(response.headers)