wienerlinien.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import dingguo
  4. import email
  5. import email.utils
  6. import ioex
  7. import re
  8. class UtcOffsetTimezone(datetime.tzinfo):
  9. def __init__(self, seconds):
  10. assert type(seconds) is int
  11. self.seconds = seconds
  12. def utcoffset(self, dt):
  13. return datetime.timedelta(seconds = self.seconds)
  14. def dst(self, dt):
  15. return None
  16. def tzname(self, dt):
  17. return self.__class__.__name__ + '(seconds = %d)' % self.seconds
  18. def parse_order_confirmation_mail(mail):
  19. assert isinstance(mail, email.message.Message)
  20. msg_text = mail.get_payload(decode = True).decode('utf8')
  21. if not 'Wiener Linien' in msg_text:
  22. raise Exception()
  23. order_match = re.search(
  24. r'(?P<name>Single-Ticket)\s+'
  25. + r'Valid from: (?P<valid_from>\d{1,2} \w+ \d{4} \d{1,2}:\d{2})\s+'
  26. + r'Type: (?P<type>Mobile ticket)\s+'
  27. + r'For\:\s+'
  28. + r'(?P<passenger_first_name>Fabian Peter)\s+'
  29. + r'(?P<passenger_last_name>Hammerle)\s+'
  30. + ur'Price: (?P<currency>€)(?P<price>2.80)\s+'
  31. + r'Quantity: (?P<quantity>1)\s+'
  32. ,
  33. msg_text,
  34. re.MULTILINE | re.UNICODE
  35. )
  36. if not order_match:
  37. print(repr(msg_text))
  38. order_match_groups = order_match.groupdict()
  39. email_recipient_address = mail['delivered-to'].decode('utf8')
  40. email_date = datetime.datetime.utcfromtimestamp(
  41. # seconds since the Epoch in UTC
  42. email.utils.mktime_tz(email.utils.parsedate_tz(mail['date']))
  43. )
  44. order = dingguo.Order(
  45. platform = u'wiener_linien',
  46. order_id = '%s-%s' % (email_recipient_address, email_date.isoformat()),
  47. order_date = email_date,
  48. customer_id = email_recipient_address,
  49. )
  50. assert int(order_match_groups['quantity']) == 1
  51. with ioex.setlocale('en_US.UTF-8'):
  52. import pytz
  53. order.items.append(dingguo.Transportation(
  54. name = order_match_groups['name'],
  55. price_brutto = dingguo.Sum(
  56. float(order_match_groups['price']),
  57. order_match_groups['currency'],
  58. ),
  59. passenger = dingguo.Person(
  60. first_name = order_match_groups['passenger_first_name'],
  61. last_name = order_match_groups['passenger_last_name'],
  62. ),
  63. valid_from = datetime.datetime.strptime(order_match_groups['valid_from'], '%d %B %Y %H:%M')
  64. .replace(tzinfo = UtcOffsetTimezone(email.utils.parsedate_tz(mail['date'])[9]))
  65. ))
  66. return [order]