Full location support with partial match smartitty
[ottawa-travel-planner.git] / mailPlanner.py
blob773250bab1d75850a8991e1d547eb410d74a20c4
1 #!/usr/bin/python
2 # vi: set softtabstop=4 shiftwidth=4 tabstop=8 expandtab:
4 import email.FeedParser
5 from email.MIMEText import MIMEText
6 from email.Utils import parseaddr
7 import smtplib
8 import sys
9 import traceback
11 import Planner
12 import PlanTime
13 import time
14 import CommandParser
15 import ShortFormatter
17 FROM_ADDRESS = "tp@hurts.ca"
18 LOG_FILE = "/home/tp/planner.log"
20 def logIt(string):
21 fp = open(LOG_FILE, "a")
22 print >> fp, string
24 def sendMessage(msg, to):
25 msg['From'] = FROM_ADDRESS
26 msg['To'] = to
28 s = smtplib.SMTP("10.42.42.1")
29 s.sendmail(parseaddr(FROM_ADDRESS)[1], [parseaddr(msg['To'])[1]],
30 msg.as_string())
31 s.close()
33 def sendError(e, replyto):
34 sendMessage(MIMEText(e.args[0]), replyto)
36 def handleMessage(msg, replyto):
37 try:
38 if msg.is_multipart():
39 raise Exception("Sorry, fancy multipart messages aren't supported.")
41 for line in msg.get_payload().splitlines():
42 s = line.strip()
43 if len(s) != 0:
44 logIt(s)
45 cmd = CommandParser.CommandParser(s).cmd
46 break
47 else:
48 # No command.
49 return 0
51 # Leave in 3 minutes if time is unspecified.
52 if cmd.time is None:
53 cmd.time = PlanTime.PlanTime(time.time() + 180,
54 PlanTime.MUST_LEAVE_AFTER)
56 itin = Planner.plan(cmd.start, cmd.end, cmd.time)
57 sf = ShortFormatter.ShortFormatter(itin.entries)
59 sendMessage(MIMEText("\n".join(sf.lines)), replyto)
60 except Exception, e:
61 traceback.print_exc()
62 sendError(e, replyto)
64 # Always return success. Otherwise Postfix will send a bounce message.
65 return 0
67 def main(argv=None):
68 if argv is None:
69 argv = sys.argv
71 fp = email.FeedParser.FeedParser()
72 for line in sys.stdin:
73 fp.feed(line)
74 msg = fp.close()
76 # if these headers are here, we can reply semi-intelligently with errors
77 replyto = msg["reply-to"] or msg["from"]
78 return handleMessage(msg, replyto)
80 if __name__ == '__main__':
81 sys.exit(main())