order-confirmation-mail-parser 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # PYTHON_ARGCOMPLETE_OK
  4. import dingguo
  5. import re
  6. import os
  7. import sys
  8. import yaml
  9. import email
  10. import shutil
  11. import pprint
  12. import random
  13. import locale
  14. import argparse
  15. import datetime
  16. import traceback
  17. import subprocess
  18. import HTMLParser
  19. import argcomplete
  20. import BeautifulSoup
  21. def parse_amazon(msg):
  22. msg_text = msg.get_payload()[0].get_payload(decode = True).decode('utf-8')
  23. if not u'Amazon.de Bestellbestätigung' in msg_text:
  24. raise Exception('no amazon order confirmation')
  25. orders = []
  26. for order_text in re.split(ur'={32,}', msg_text)[1:-1]:
  27. order_id = re.search(r'Bestellnummer #(.+)', order_text).group(1)
  28. order_date_formatted = re.search(ur'Aufgegeben am (.+)', order_text, re.UNICODE).group(1)
  29. locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
  30. order_date = datetime.datetime.strptime(order_date_formatted.encode('utf-8'), '%d. %B %Y')
  31. order = dingguo.Order(
  32. u'amazon.de',
  33. order_id,
  34. order_date
  35. )
  36. articles_text = order_text.split('Bestellte(r) Artikel:')[1].split('_' * 10)[0].strip()
  37. for article_text in re.split(ur'\n\t*\n', articles_text):
  38. article_match = re.match(
  39. ur' *((?P<quantity>\d+) x )?(?P<name>.*)\n'
  40. + ur'( *von (?P<authors>.*)\n)?'
  41. + ur' *(?P<price_brutto_currency>[A-Z]+) (?P<price_brutto>\d+,\d+)\n'
  42. + ur'( *Zustand: (?P<state>.*)\n)?'
  43. + ur' *Verkauft von: (?P<reseller>.*)'
  44. + ur'(\n *Versand durch (?P<shipper>.*))?',
  45. article_text,
  46. re.MULTILINE | re.UNICODE
  47. )
  48. if article_match is None:
  49. sys.stderr.write(repr(article_text) + '\n')
  50. raise Exception('could not match article')
  51. article = article_match.groupdict()
  52. order.items.append(dingguo.Article(
  53. name = article['name'],
  54. price_brutto = dingguo.Sum(
  55. float(article['price_brutto'].replace(',', '.')),
  56. article['price_brutto_currency']
  57. ),
  58. quantity = int(article['quantity']) if article['quantity'] else 1,
  59. authors = article['authors'].split(',') if article['authors'] else [],
  60. state = article['state'],
  61. reseller = article['reseller'],
  62. shipper = article['shipper'],
  63. ))
  64. orders.append(order)
  65. return orders
  66. def parse_oebb(msg):
  67. msg = msg.get_payload()[0]
  68. if type(msg.get_payload()) is list:
  69. msg = msg.get_payload()[0]
  70. msg_text = msg.get_payload(decode = True).decode('utf8')
  71. # msg_text = re.sub(
  72. # r'<[^>]+>',
  73. # '',
  74. # HTMLParser.HTMLParser().unescape(msg.get_payload(decode = True).decode('utf8'))
  75. # )
  76. order_match = re.search(
  77. ur'Booking code:\s+(?P<order_id>[\d ]+)\s+'
  78. + ur'Customer number:\s+(?P<customer_id>PV\d+)\s+'
  79. + ur'Booking date:\s+(?P<order_date>.* \d{4})\s',
  80. msg_text,
  81. re.MULTILINE | re.UNICODE
  82. )
  83. order_match_groups = order_match.groupdict()
  84. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  85. order_date = datetime.datetime.strptime(
  86. order_match_groups['order_date'],
  87. '%b %d, %Y'
  88. )
  89. order = dingguo.Order(
  90. u'oebb',
  91. order_match_groups['order_id'],
  92. order_date,
  93. customer_id = order_match_groups['customer_id'],
  94. )
  95. item_match = re.search(
  96. ur'(?P<price_brutto_currency>.)(?P<price_brutto>\d+\.\d+)'
  97. + ur'[\W\w]+'
  98. + ur'Your Booking\s+'
  99. + ur'(?P<departure_point>.*)\s+>\s+(?P<destination_point>.*)',
  100. msg_text,
  101. re.MULTILINE | re.UNICODE
  102. )
  103. item = item_match.groupdict()
  104. order.items.append(dingguo.Transportation(
  105. name = u'Train Ticket',
  106. price_brutto = dingguo.Sum(
  107. float(item['price_brutto']),
  108. item['price_brutto_currency'],
  109. ),
  110. departure_point = item['departure_point'],
  111. destination_point = item['destination_point'],
  112. ))
  113. return [order]
  114. def parse_mytaxi(msg):
  115. if not 'mytaxi' in msg.get_payload()[0].get_payload()[0].get_payload(decode = True):
  116. raise Exception('no mytaxi mail')
  117. pdf_compressed = msg.get_payload()[1].get_payload(decode = True)
  118. pdftk = subprocess.Popen(
  119. ['pdftk - output - uncompress'],
  120. shell = True,
  121. stdin = subprocess.PIPE,
  122. stdout = subprocess.PIPE,
  123. )
  124. pdf_uncompressed = pdftk.communicate(
  125. input = pdf_compressed,
  126. )[0].decode('latin-1')
  127. assert type(pdf_uncompressed) is unicode
  128. order_match = re.search(
  129. ur'Rechnungsnummer:[^\(]+\((?P<order_id>\w+)\)',
  130. pdf_uncompressed,
  131. re.MULTILINE | re.UNICODE
  132. )
  133. order_id = order_match.groupdict()['order_id']
  134. ride_match_groups = re.search(
  135. ur'\(Bruttobetrag\)'
  136. + ur'[^\(]+'
  137. + ur'\((?P<price_brutto>\d+,\d+) (?P<price_brutto_currency>.+)\)'
  138. + ur'[\w\W]+'
  139. + ur'\((?P<driver>[^\(]+)\)'
  140. + ur'[^\(]+'
  141. + ur'\(\d+,\d+ .\)'
  142. + ur'[^\(]+'
  143. + ur'\((?P<name>Taxifahrt)'
  144. + ur'[^\(]+'
  145. + ur'\(von: (?P<departure_point>[^\)]+)'
  146. + ur'[^\(]+'
  147. + ur'\(nach: (?P<destination_point>[^\)]+)'
  148. + ur'[\w\W]+'
  149. + ur'Belegdatum \\\(Leistungszeitpunkt\\\):[^\(]+\((?P<arrival_time>\d\d.\d\d.\d\d \d\d:\d\d)\)',
  150. pdf_uncompressed,
  151. re.MULTILINE | re.UNICODE
  152. ).groupdict()
  153. arrival_time = datetime.datetime.strptime(
  154. ride_match_groups['arrival_time'],
  155. '%d.%m.%y %H:%M'
  156. )
  157. order = dingguo.Order(
  158. u'mytaxi',
  159. order_id,
  160. arrival_time,
  161. )
  162. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  163. order.items.append(dingguo.TaxiRide(
  164. price_brutto = dingguo.Sum(
  165. float(ride_match_groups['price_brutto'].replace(',', '.')),
  166. # why 0x80 ?
  167. u'EUR' if (ride_match_groups['price_brutto_currency'] == u'\x80')
  168. else ride_match_groups['price_brutto_currency'],
  169. ),
  170. departure_point = ride_match_groups['departure_point'],
  171. destination_point = ride_match_groups['destination_point'],
  172. driver = ride_match_groups['driver'],
  173. arrival_time = arrival_time,
  174. ))
  175. return [order]
  176. def parse_uber(msg):
  177. html = msg.get_payload()[0].get_payload(decode = True)
  178. """ document in html2 has the same structure as the one in html.
  179. only difference is that hyperlink urls in html2 have been
  180. replaced by 'email.uber.com/wf/click?upn=.*' urls.
  181. """
  182. html2 = msg.get_payload()[1].get_payload()[0].get_payload(decode = True)
  183. route_map = msg.get_payload()[1].get_payload()[1].get_payload(decode = True)
  184. doc = BeautifulSoup.BeautifulSoup(
  185. html,
  186. convertEntities = BeautifulSoup.BeautifulSoup.HTML_ENTITIES,
  187. )
  188. # strptime
  189. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  190. trip_id = re.search(
  191. ur'[\da-f\-]{36}',
  192. doc.find(text = 'Visit the trip page').parent['href'],
  193. ).group(0)
  194. order = dingguo.Order(
  195. u'uber',
  196. trip_id,
  197. datetime.datetime.strptime(
  198. doc.find(attrs = {'class': 'date'}).text,
  199. '%B %d, %Y',
  200. ),
  201. )
  202. departure_time_tag = doc.find(attrs = {'class': 'from time'})
  203. departure_time = datetime.datetime.strptime(
  204. departure_time_tag.text,
  205. '%I:%M%p',
  206. ).time()
  207. arrival_time_tag = doc.find(attrs = {'class': 'to time'})
  208. arrival_time = datetime.datetime.strptime(
  209. arrival_time_tag.text,
  210. '%I:%M%p',
  211. ).time()
  212. distance = dingguo.Distance(
  213. float(doc.find(text = 'kilometers').parent.parent.find(attrs = {'class': 'data'}).text),
  214. u'km',
  215. )
  216. fare = doc.find(attrs = {'class': 'header-price'}).find(attrs = {'class': 'header-fare text-pad'}).text
  217. order.items.append(dingguo.TaxiRide(
  218. name = doc.find(text = 'CAR').parent.parent.find(attrs = {'class': 'data'}).text + ' Ride',
  219. price_brutto = dingguo.Sum(float(fare[1:]), fare[0]),
  220. arrival_time = datetime.datetime.combine(order.order_date, arrival_time),
  221. departure_time = datetime.datetime.combine(order.order_date, departure_time),
  222. departure_point = departure_time_tag.parent.find(attrs = {'class': 'address'}).text,
  223. destination_point = arrival_time_tag.parent.find(attrs = {'class': 'address'}).text,
  224. distance = distance,
  225. driver = doc.find(attrs = {'class': 'driver-info'}).text[len('You rode with '):],
  226. route_map = route_map,
  227. ))
  228. return [order]
  229. def parse_yipbee(msg):
  230. text = msg.get_payload()[0].get_payload()[0].get_payload(decode = True).decode('utf-8')
  231. if not u'Vielen Dank für deine Bestellung bei yipbee' in text:
  232. raise Exception('no yipbee confirmation')
  233. order_match_groups = re.search(
  234. ur'[\W\w]+'
  235. + ur'BESTELLUNG: (?P<order_id>\w+) vom (?P<order_time>\d\d.\d\d.\d{4} \d\d:\d\d:\d\d)'
  236. + ur'[\W\w]+'
  237. + ur'GESAMTPREIS\s+'
  238. + ur'(?P<articles_and_discount_text>[\W\w]+)'
  239. + ur'(?P<summary_text>ARTIKEL [\W\w]+)',
  240. text,
  241. re.UNICODE
  242. ).groupdict()
  243. order = dingguo.Order(
  244. u'yipbee',
  245. order_match_groups['order_id'],
  246. datetime.datetime.strptime(order_match_groups['order_time'], '%d.%m.%Y %H:%M:%S'),
  247. )
  248. for article_match in re.finditer(
  249. ur'(?P<name>[\w\-\.\:,%\(\) ]+ (Klasse \d|[\w\-\. ]+[^\d ]))'
  250. + ur'(?P<total_price>\d+,\d\d) €(?P<quantity>\d)(?P<total_price_2>\d+,\d\d) €',
  251. order_match_groups['articles_and_discount_text'].replace('\n', ' '),
  252. re.UNICODE,
  253. ):
  254. article_match_groups = article_match.groupdict()
  255. total_price = float(article_match_groups['total_price'].replace(',', '.'))
  256. total_price_2 = float(article_match_groups['total_price_2'].replace(',', '.'))
  257. assert abs(total_price - total_price_2) < 0.01, 'expected %f, received %f' % (total_price, total_price_2)
  258. quantity = int(article_match_groups['quantity'])
  259. order.items.append(dingguo.Article(
  260. name = article_match_groups['name'],
  261. price_brutto = dingguo.Sum(round(total_price / quantity, 2), u'EUR'),
  262. quantity = quantity,
  263. reseller = u'yipbee',
  264. shipper = u'yipbee',
  265. ))
  266. articles_price = float(text.split('RABATTE')[0].split('ARTIKEL')[-1].strip().split(' ')[0].replace(',', '.'))
  267. assert abs(articles_price - sum([a.price_brutto.value * a.quantity for a in order.items])) < 0.01
  268. discount_tag = BeautifulSoup.BeautifulSoup(
  269. order_match_groups['articles_and_discount_text'],
  270. convertEntities = BeautifulSoup.BeautifulSoup.HTML_ENTITIES,
  271. ).find('tr')
  272. if discount_tag:
  273. name_tag, value_tag = discount_tag.findAll('td', recursive = False)
  274. value, currency = value_tag.text.split(' ')
  275. order.discounts.append(dingguo.Discount(
  276. name = name_tag.text,
  277. amount = dingguo.Sum(float(value.replace(',', '.')) * -1, currency),
  278. ))
  279. delivery_price = order_match_groups['summary_text'].split('VERSAND')[1].split('STEUERN')[0].strip()
  280. delivery_price_value, delivery_price_currency = delivery_price.split(' ')
  281. order.items.append(dingguo.Item(
  282. name = u'Delivery',
  283. price_brutto = dingguo.Sum(float(delivery_price_value.replace(',', '.')), delivery_price_currency),
  284. ))
  285. return [order]
  286. def parse_yipbee_html(msg):
  287. html = msg.get_payload()[0].get_payload()[1].get_payload(decode = True)
  288. if not 'yipbee' in html:
  289. raise Exception('no yipbee confirmation')
  290. doc = BeautifulSoup.BeautifulSoup(html, convertEntities = BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
  291. content_table = doc.find('table')
  292. order_match_groups = re.search(
  293. ur'Bestellung:(?P<order_id>\w+) vom (?P<order_time>\d\d.\d\d.\d{4} \d\d:\d\d:\d\d)',
  294. content_table.find('table').findAll('tr')[3].text,
  295. re.UNICODE
  296. ).groupdict()
  297. order = dingguo.Order(
  298. u'yipbee',
  299. order_match_groups['order_id'],
  300. datetime.datetime.strptime(order_match_groups['order_time'], '%d.%m.%Y %H:%M:%S'),
  301. )
  302. articles_table = content_table.find('table').find('tbody').findAll('tr', recursive = False)[4].find('table')
  303. for article_row in articles_table.find('tbody').findAll('tr', recursive = False)[1:]:
  304. article_columns = article_row.findAll('td', recursive = False)
  305. (price, currency) = re.sub(ur'\s+', ' ', article_columns[2].text.replace(u',', u'.')).split(' ')
  306. order.items.append(dingguo.Article(
  307. name = article_columns[1].text,
  308. price_brutto = dingguo.Sum(float(price), currency),
  309. quantity = int(article_columns[3].text),
  310. reseller = u'yipbee',
  311. shipper = u'yipbee',
  312. ))
  313. discount_row = content_table.find('table').find('tbody').findAll('tr', recursive = False)[6]
  314. (discount_name, discount_value_with_currency) = [c.text for c in discount_row.findAll('td', recursive = False)]
  315. (discount_value, discount_currency) = discount_value_with_currency.split(' ')
  316. order.discounts.append(dingguo.Discount(
  317. name = discount_name,
  318. amount = dingguo.Sum(float(discount_value.replace(',', '.')) * -1, discount_currency)
  319. ))
  320. shipping_costs_table = content_table.find('tbody').findAll('tr', recursive = False)[3].findAll('table')[1]
  321. (shipping_price, shipping_currency) = shipping_costs_table.text.replace(',', '.').split(' ')
  322. order.items.append(dingguo.Item(
  323. name = u'Delivery',
  324. price_brutto = dingguo.Sum(float(shipping_price), shipping_currency),
  325. ))
  326. return [order]
  327. def parse_lieferservice(msg):
  328. text = msg.get_payload()[0].get_payload(decode = True).decode('utf-8').replace('\r\n', '\n')
  329. assert type(text) is unicode
  330. if not 'Lieferservice.at' in text:
  331. raise Exception('no lieferservice.at confirmation')
  332. order_match = re.search(
  333. ur'(Your order|Ihre Bestellung) \(.+\) (at|bei) (?P<restaurant>.*)\s+'
  334. + ur'(Your order reference is|Ihre Bestellnummer lautet): (?P<order_id>.*)\s+'
  335. + ur'[\W\w]+'
  336. + ur'(Your order|Ihre Bestellung)\s+'
  337. + ur'(?P<orders_text>[\W\w]+)'
  338. + ur'(Delivery costs|Lieferung):\s+(?P<delivery_costs>.*)\s+',
  339. text,
  340. re.UNICODE,
  341. )
  342. order_match_groups = order_match.groupdict()
  343. import time
  344. import email.utils
  345. order_date = datetime.datetime.fromtimestamp(
  346. time.mktime(email.utils.parsedate(msg['Date']))
  347. )
  348. order = dingguo.Order(
  349. u'lieferservice.at',
  350. order_match_groups['order_id'].strip(),
  351. order_date
  352. )
  353. restaurant = order_match_groups['restaurant'].strip('"')
  354. for article_match in re.finditer(
  355. ur'(?P<quantity>\d+)x\s'
  356. + ur'(?P<name>.*)\s'
  357. + ur'(?P<currency>.) (?P<price>-?\d+,\d+)\s',
  358. order_match_groups['orders_text'],
  359. re.UNICODE,
  360. ):
  361. article_match_groups = article_match.groupdict()
  362. quantity = int(article_match_groups['quantity'])
  363. assert quantity == 1
  364. name = re.sub(ur' +', ' ', article_match_groups['name'])
  365. price = dingguo.Sum(
  366. float(article_match_groups['price'].replace(',', '.')),
  367. article_match_groups['currency'],
  368. )
  369. if price.value < 0:
  370. price.value *= -1
  371. order.discounts.append(dingguo.Discount(
  372. name = name,
  373. amount = price,
  374. ))
  375. else:
  376. order.items.append(dingguo.Article(
  377. name = name,
  378. quantity = 1,
  379. price_brutto = price,
  380. reseller = restaurant,
  381. shipper = restaurant,
  382. ))
  383. delivery_costs = order_match_groups['delivery_costs'].strip()
  384. if delivery_costs in ['FREE', 'GRATIS']:
  385. order.items.append(dingguo.Item(
  386. name = u'Delivery',
  387. price_brutto = dingguo.Sum(0.0, u'EUR'),
  388. ))
  389. else:
  390. unit, value = delivery_costs.split(' ')
  391. order.items.append(dingguo.Item(
  392. name = u'Delivery',
  393. price_brutto = dingguo.Sum(float(value.replace(',', '.')), unit),
  394. ))
  395. return [order]
  396. def parse(msg):
  397. tracebacks = {}
  398. try:
  399. return parse_amazon(msg)
  400. except:
  401. tracebacks['amazon'] = traceback.format_exc()
  402. try:
  403. return parse_oebb(msg)
  404. except:
  405. tracebacks['oebb'] = traceback.format_exc()
  406. try:
  407. return parse_lieferservice(msg)
  408. except:
  409. tracebacks['lieferservice'] = traceback.format_exc()
  410. try:
  411. return parse_mytaxi(msg)
  412. except:
  413. tracebacks['mytaxi'] = traceback.format_exc()
  414. try:
  415. return parse_uber(msg)
  416. except:
  417. tracebacks['uber'] = traceback.format_exc()
  418. try:
  419. return parse_yipbee(msg)
  420. except:
  421. tracebacks['yipbee'] = traceback.format_exc()
  422. for parser_name in tracebacks:
  423. sys.stderr.write('%s parser: \n%s\n' % (parser_name, tracebacks[parser_name]))
  424. raise Exception('failed to parse')
  425. def compute(mail_path, catalogue, register_path):
  426. orders = []
  427. if mail_path:
  428. for p in mail_path:
  429. with open(p, 'r') as mail:
  430. mail_orders = parse(email.message_from_file(mail))
  431. orders += mail_orders
  432. if catalogue:
  433. for order in mail_orders:
  434. order_dir_path = os.path.join(order.platform, order.order_id)
  435. if not os.path.isdir(order_dir_path):
  436. os.makedirs(order_dir_path)
  437. shutil.copyfile(p, os.path.join(order_dir_path, os.path.basename(p)))
  438. os.remove(p)
  439. else:
  440. msg = email.message_from_string(sys.stdin.read())
  441. orders += parse(msg)
  442. if register_path:
  443. with open(register_path, 'r') as register:
  444. registered_orders = yaml.load(register.read().decode('utf-8'))
  445. if not registered_orders:
  446. registered_orders = {}
  447. for order in orders:
  448. if order.platform not in registered_orders:
  449. registered_orders[order.platform] = {}
  450. if order.order_id in registered_orders[order.platform]:
  451. raise Exception('already registered')
  452. registered_orders[order.platform][order.order_id] = order
  453. with open(register_path, 'w') as register:
  454. register.write(yaml.safe_dump(registered_orders, default_flow_style = False))
  455. else:
  456. print(yaml.safe_dump(orders, default_flow_style = False))
  457. def _init_argparser():
  458. argparser = argparse.ArgumentParser(description = None)
  459. argparser.add_argument('--register', metavar = 'path', dest = 'register_path')
  460. argparser.add_argument('--catalogue', action='store_true')
  461. argparser.add_argument('mail_path', nargs = '*')
  462. return argparser
  463. def main(argv):
  464. argparser = _init_argparser()
  465. argcomplete.autocomplete(argparser)
  466. args = argparser.parse_args(argv)
  467. compute(**vars(args))
  468. return 0
  469. if __name__ == "__main__":
  470. sys.exit(main(sys.argv[1:]))