This repository has been archived by the owner on Feb 13, 2018. It is now read-only.
/
__init__.py
95 lines (76 loc) · 2.81 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import email, time, urllib
from datetime import datetime
from cStringIO import StringIO
from django.contrib.auth.models import User
from gonzo.hunt.models import Hunt,Submission
from gonzo.utils import assign_image_to_model
class InvalidAddress(Exception):
pass
class HuntDoesNotExist(Hunt.DoesNotExist):
pass
class HuntNotCurrent(Exception):
pass
class NoImage(Exception):
pass
def submit_from_file(environ, fp):
return submit_message(environ, email.message_from_file(fp))
#def submit_from_string(environ, s):
# return submit(environ, email.message_from_string(s))
def submit_message(environ, message):
if not message.is_multipart():
raise NoImage()
email_to = environ.get('RECIPIENT')
email_from = message.get('from', environ.get('SENDER'))
if not email_to:
raise InvalidAddress("Missing recipient")
# For the time being, ignore the actual 'to' and focus on the
# local extension
try:
(realname,addr) = email.utils.parseaddr(email_to)
(user,local) = addr.split('@')[0].split('+')
except ValueError:
raise InvalidAddress("Invalid hunt address: " + email_to)
try:
hunt = Hunt.objects.get(tag=local)
except Hunt.DoesNotExist:
raise HuntDoesNotExist()
date = email.utils.parsedate(message.get('date'))
if not date:
date = datetime.utcnow()
else:
date = datetime(*date[:6])
if date < hunt.start_time:
raise HuntNotCurrent("Hunt hasn't started yet")
if date >= hunt.end_time:
raise HuntNotCurrent("Hunt has ended")
submission = Submission(hunt=hunt,
time=date,
via='email',
ip_address=environ.get('CLIENT_ADDRESS',''))
# photo
# description?
# user
# anon_source
# Find the image by walking the payload
for part in message.walk():
if part.get_content_maintype() == 'image' and not part.is_multipart():
image_data = part.get_payload(decode=True)
assign_image_to_model(submission,
'photo',
StringIO(image_data),
part.get_filename(addr+"."+part.get_content_subtype()),
part.get_content_type())
break
if not submission.photo:
raise NoImage()
# Get the sender and see if it's a user
(realname,addr) = email.utils.parseaddr(email_from)
try:
user = User.objects.get(email=addr)
submission.user = user
except User.DoesNotExist:
# Override the addr with what we get from postfix
addr = environ.get('SENDER', addr)
submission.anon_source = 'email:'+urllib.urlencode({'name':realname, 'addr':addr})
submission.save()
return submission