order-confirmation-mail-parser 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # PYTHON_ARGCOMPLETE_OK
  4. import re
  5. import os
  6. import sys
  7. import yaml
  8. import email
  9. import pprint
  10. import random
  11. import locale
  12. import argparse
  13. import datetime
  14. import traceback
  15. import subprocess
  16. import HTMLParser
  17. import argcomplete
  18. # strptime
  19. locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
  20. def parse_amazon(msg):
  21. order = {
  22. 'platform': 'amazon.de',
  23. }
  24. msg_text = msg.get_payload()[0].get_payload(decode = True)
  25. order['order_id'] = re.search(r'Bestellnummer #(.+)', msg_text).group(1)
  26. order_date = datetime.datetime.strptime(
  27. re.search(r'Aufgegeben am (.+)', msg_text).group(1),
  28. '%d. %B %Y'
  29. )
  30. order['order_date'] = order_date.strftime('%Y-%m-%d')
  31. order['articles'] = []
  32. articles_text = msg_text.split('Bestellte(r) Artikel:')[1].split('_' * 10)[0].strip()
  33. for article_text in articles_text.split('\n\n'):
  34. article_match = re.match(
  35. ur' *(?P<name>.*)\n'
  36. + ur'( *von (?P<authors>.*)\n)?'
  37. + ur' *(?P<price_brutto_currency>[A-Z]+) (?P<price_brutto>\d+,\d+)\n'
  38. + ur'( *Zustand: (?P<state>.*)\n)?'
  39. + ur' *Verkauft von: (?P<reseller>.*)'
  40. + ur'(\n *Versand durch (?P<shipper>.*))?',
  41. article_text,
  42. re.MULTILINE | re.UNICODE
  43. )
  44. if article_match is None:
  45. sys.stderr.write(repr(article_text) + '\n')
  46. raise Exception('could not match article')
  47. article = article_match.groupdict()
  48. if article['authors']:
  49. article['authors'] = article['authors'].split(',')
  50. else:
  51. del article['authors']
  52. article['price_brutto'] = float(article['price_brutto'].replace(',', '.'))
  53. order['articles'].append(article)
  54. return order
  55. def parse_oebb(msg):
  56. msg_text = msg.get_payload()[0].get_payload(decode = True).decode('utf8')
  57. # msg_text = re.sub(
  58. # r'<[^>]+>',
  59. # '',
  60. # HTMLParser.HTMLParser().unescape(msg.get_payload(decode = True).decode('utf8'))
  61. # )
  62. order_match = re.search(
  63. ur'Booking code:\s+(?P<order_id>[\d ]+)\s+'
  64. + ur'Customer number:\s+(?P<customer_id>PV\d+)\s+'
  65. + ur'Booking date:\s+(?P<order_date>.* \d{4})\s',
  66. msg_text,
  67. re.MULTILINE | re.UNICODE
  68. )
  69. order = order_match.groupdict()
  70. order['platform'] = 'oebb.at'
  71. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  72. order['order_date'] = datetime.datetime.strptime(
  73. order['order_date'],
  74. '%b %d, %Y'
  75. ).strftime('%Y-%m-%d')
  76. article_match = re.search(
  77. ur'(?P<price_brutto_currency>.)(?P<price_brutto>\d+\.\d+)'
  78. + ur'[\W\w]+'
  79. + ur'Your Booking\s+'
  80. + ur'(?P<departure_point>.*)\s+>\s+(?P<destination_point>.*)',
  81. msg_text,
  82. re.MULTILINE | re.UNICODE
  83. )
  84. article = article_match.groupdict()
  85. article['name'] = 'Train Ticket'
  86. article['price_brutto'] = float(article['price_brutto'])
  87. if article['price_brutto_currency'] == u'€':
  88. article['price_brutto_currency'] = 'EUR'
  89. else:
  90. raise Exception('currency %s is not supported' % article['price_brutto_currency'])
  91. order['articles'] = [article]
  92. return order
  93. def parse_mytaxi(msg):
  94. pdf_compressed = msg.get_payload()[1].get_payload(decode = True)
  95. pdftk = subprocess.Popen(
  96. ['pdftk - output - uncompress'],
  97. shell = True,
  98. stdin = subprocess.PIPE,
  99. stdout = subprocess.PIPE,
  100. )
  101. pdf_uncompressed = pdftk.communicate(
  102. input = pdf_compressed,
  103. )[0].decode('latin-1')
  104. assert type(pdf_uncompressed) is unicode
  105. order_match = re.search(
  106. ur'Rechnungsnummer:[^\(]+\((?P<order_id>\w+)\)',
  107. pdf_uncompressed,
  108. re.MULTILINE | re.UNICODE
  109. )
  110. order = order_match.groupdict()
  111. order['platform'] = 'mytaxi'
  112. article_match = re.search(
  113. ur'\(Bruttobetrag\)'
  114. + ur'[^\(]+'
  115. + ur'\((?P<price_brutto>\d+,\d+) (?P<price_brutto_currency>.+)\)'
  116. + ur'[\w\W]+'
  117. + ur'\((?P<driver>[^\(]+)\)'
  118. + ur'[^\(]+'
  119. + ur'\(\d+,\d+ .\)'
  120. + ur'[^\(]+'
  121. + ur'\((?P<name>Taxifahrt)'
  122. + ur'[^\(]+'
  123. + ur'\(von: (?P<departure_point>[^\)]+)'
  124. + ur'[^\(]+'
  125. + ur'\(nach: (?P<destination_point>[^\)]+)'
  126. + ur'[\w\W]+'
  127. + ur'Belegdatum \\\(Leistungszeitpunkt\\\):[^\(]+\((?P<arrival_time>\d\d.\d\d.\d\d \d\d:\d\d)\)',
  128. pdf_uncompressed,
  129. re.MULTILINE | re.UNICODE
  130. )
  131. article = article_match.groupdict()
  132. locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
  133. arrival_time = datetime.datetime.strptime(
  134. article['arrival_time'],
  135. '%d.%m.%y %H:%M'
  136. )
  137. article['arrival_time'] = arrival_time.strftime('%Y-%m-%d %H:%M')
  138. order['order_date'] = arrival_time.strftime('%Y-%m-%d')
  139. article['price_brutto'] = float(article['price_brutto'].replace(',', '.'))
  140. if article['price_brutto_currency'] in [u'€', u'\x80']:
  141. article['price_brutto_currency'] = 'EUR'
  142. else:
  143. raise exception('currency %s is not supported' % article['price_brutto_currency'])
  144. order['articles'] = [article]
  145. return order
  146. def parse(msg):
  147. tracebacks = {}
  148. try:
  149. return parse_amazon(msg)
  150. except:
  151. tracebacks['amazon'] = traceback.format_exc()
  152. try:
  153. return parse_oebb(msg)
  154. except:
  155. tracebacks['oebb'] = traceback.format_exc()
  156. try:
  157. return parse_mytaxi(msg)
  158. except:
  159. tracebacks['mytaxi'] = traceback.format_exc()
  160. for parser_name in tracebacks:
  161. print('%s parser: \n%s' % (parser_name, tracebacks[parser_name]))
  162. raise Exception('failed to parse')
  163. def compute():
  164. msg = email.message_from_string(sys.stdin.read())
  165. order = parse(msg)
  166. print(yaml.safe_dump(order, default_flow_style = False))
  167. def _init_argparser():
  168. argparser = argparse.ArgumentParser(description = None)
  169. return argparser
  170. def main(argv):
  171. argparser = _init_argparser()
  172. argcomplete.autocomplete(argparser)
  173. args = argparser.parse_args(argv)
  174. compute(**vars(args))
  175. return 0
  176. if __name__ == "__main__":
  177. sys.exit(main(sys.argv[1:]))