order-confirmation-mail-parser 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # PYTHON_ARGCOMPLETE_OK
  4. import dingguo.parser
  5. import email
  6. import os
  7. import shutil
  8. import sys
  9. import yaml
  10. def compute(mail_path, catalogue, register_path):
  11. orders = []
  12. if mail_path:
  13. for p in mail_path:
  14. with open(p, 'r') as mail:
  15. mail_orders = dingguo.parser.parse_order_confirmation_mail(
  16. email.message_from_file(mail)
  17. )
  18. orders += mail_orders
  19. if catalogue:
  20. for order in mail_orders:
  21. order_dir_path = os.path.join(order.platform, order.order_id)
  22. if not os.path.isdir(order_dir_path):
  23. os.makedirs(order_dir_path)
  24. shutil.copyfile(p, os.path.join(order_dir_path, os.path.basename(p)))
  25. os.remove(p)
  26. else:
  27. msg = email.message_from_string(sys.stdin.read())
  28. orders += dingguo.parser.parse_order_confirmation_mail(msg)
  29. if register_path:
  30. if os.path.exists(register_path):
  31. with open(register_path, 'r') as register_file:
  32. registry = yaml.load(register_file.read().decode('utf-8'))
  33. else:
  34. registry = dingguo.OrderRegistry()
  35. for order in orders:
  36. registry.register(order)
  37. with open(register_path, 'w') as register:
  38. register.write(yaml.dump(registry, default_flow_style = False, allow_unicode = True))
  39. print(yaml.dump(orders, default_flow_style = False, allow_unicode = True))
  40. def _init_argparser():
  41. import argparse
  42. argparser = argparse.ArgumentParser(description = None)
  43. argparser.add_argument('--register', metavar = 'path', dest = 'register_path')
  44. argparser.add_argument('--catalogue', action='store_true')
  45. argparser.add_argument('mail_path', nargs = '*')
  46. return argparser
  47. def main(argv):
  48. argparser = _init_argparser()
  49. try:
  50. import argcomplete
  51. argcomplete.autocomplete(argparser)
  52. except ImportError:
  53. pass
  54. args = argparser.parse_args(argv)
  55. compute(**vars(args))
  56. return 0
  57. if __name__ == "__main__":
  58. sys.exit(main(sys.argv[1:]))