-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.py
73 lines (61 loc) · 2.12 KB
/
upload.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
#!/usr/bin/python
from database_tables import DrawingHistory
from webserver_utils import verify_id, get_dir_for_artist
from pencilbox_config import TMP_FILE_URL
import cgi, os
import cgitb
import urllib2
import time
def createUniqueFilename(filename):
# TODO what if it's not a png -- use file extension of original
# filename if present?
# TODO include some info in here like the title of the
# image it belongs to?
return "%d.png" % time.time()
def uploadFromClient(fileitem):
# Test if the file was uploaded
if fileitem.filename:
# Don't care about original filename; make a new one up
# that way we don't have to worry about spaces, collisions, etc
filename = createUniqueFilename(fileitem.filename)
tmp_dir = get_dir_for_artist(artist, "tmp")
file = open(os.path.join(tmp_dir, filename), "wb")
file.write(fileitem.file.read())
file.close()
url = TMP_FILE_URL % (str(artist.id), filename)
return url
else:
return False
def sideloadFromWeb(url):
# TODO need to think about security - can someone fuck up my server
# by using the url import to force it into downloading some bad
# juju?
response = urllib2.urlopen(url)
data = response.read()
# TODO how big a file will this work on? might we need to stream
# it for larger files?
response.close()
filename = createUniqueFilename(url.split("/")[-1])
tmp_dir = get_dir_for_artist(artist, "tmp")
file = open(os.path.join(tmp_dir, filename), "wb")
file.write(data)
file.close()
url = TMP_FILE_URL % (str(artist.id), filename)
return url
# TODO error handling - return false if urlopen fails or whatever
if __name__ == "__main__":
cgitb.enable()
q = cgi.FieldStorage()
artist = verify_id()
url = False
src_type = q.getfirst("src_type", "")
if src_type == "file":
url = uploadFromClient(q["file"])
elif src_type == "url":
url = sideloadFromWeb(q.getfirst("url", ""))
print "Content-Type: text/html"
print
if url == False:
print "Failed"
else:
print url