summaryrefslogtreecommitdiff
path: root/landscape
blob: 10e8ede722ef139517aaf6f0dab258dfc3480a72 (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#!/usr/bin/python2.7
import cgi
import sys
import os
import re
import time
import string
import urllib
from subprocess import Popen, PIPE
import sha
import simplejson as json

import mimetypes
import s3

import db
DB = db.db ()

import base64
import urlparse


AWS_ACCESS_KEY_ID = 'AKIAIR53VPBXKJMXZIBA'
AWS_SECRET_ACCESS_KEY = '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'
BUCKET_NAME = 'i.asdf.us'
BASE_PATH = "/var/www/asdf.us/httpdocs/imlandscape"
BASE_URL = "http://i.asdf.us/" 
PARAM_LIST = "heightmap texture name imgdata filename"
BIN_IDENTIFY = "/usr/bin/identify"

print "Content-type: text/plain"
print ""
def insert_cmd (dir, newfile, name, texture, dataobj):
  if texture == "":
    texture = "NULL"
  try:
    sql = "INSERT INTO im_cmd (date,remote_addr,name,url,dir,oldfile,newfile,cmd, dataobj, tag) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s, %s)"
    
    args = (now(), "NULL", name, texture, dir, "NULL", newfile, "NULL", dataobj, "imlandscape")
    DB.execute(sql, args)
  except ():
    return

def hash_dir (s):
  return sha.new(s).hexdigest()[:2]

def bin_identify (filename):
  ident = Popen([BIN_IDENTIFY, filename], stdout=PIPE).communicate()[0]
  partz = ident.split(" ")
  width,height = partz[2].split("x")
  return width, height

def get_params (paramlist):
  paramkeys = paramlist.split()
  form = cgi.FieldStorage()
  params = {}
  for key in paramkeys:
    if key in form:
      if key == 'heightmap':
        params[key] = form[key].value
      elif key == 'imgdata':
        params[key] = form[key].value
      elif key == 'texture':
        params[key] = form[key].value
      else:
        params[key] = sanitize(form[key].value)
    else:
      params[key] = None
  return params

def error (e):
  print "#@imlandscape"
  print "ERROR\t"+e
  sys.exit()

def now ():
  return int(time.mktime(time.localtime()))

def sanitize (str):
  return re.sub(r'\W+', '', str)

def filename_from_url (url, name=""):
  if "?" in url:
    url = url.split("?")[0]
  if "/" in url:
    url = urllib.unquote(url).replace(" ","")
    filename = url.split("/")[-1]
    filetype = "png" 
    filename = sanitize(filename[:-4])
  else:
    filename = "" 
  if name != "":
    name = name+"_"
  return "{}_{}{}_{}.{}".format("imlandscape", name, filename,now(), "png")

def saveImgData(url, filename):
  try:
    up = urlparse.urlparse(url)
    head, data = up.path.split(',', 1)
    bits = head.split(';')
    mime_type = bits[0] if bits[0] else 'text/plain'
    charset, b64 = 'ASCII', False
    for bit in bits[1]:
        if bit.startswith('charset='):
            charset = bit[8:]
        elif bit == 'base64':
            b64 = True

    # Do something smart with charset and b64 instead of assuming
    plaindata = base64.b64decode(data)

    with open(filename, 'wb') as f:
        f.write(plaindata)
  except Exception as e:
    error(str(e));

def file_size (file):
  return os.stat(file)[6]

def moveToS3(filename,objectname):
  conn = s3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
  sys.stderr.write( "Uploading %s" % filename)
  filedata = open(filename, 'rb').read()
  content_type = mimetypes.guess_type(filename)[0]
  if not content_type:
    content_type = 'text/plain'
  conn.put(BUCKET_NAME, objectname, s3.S3Object(filedata),
    {'x-amz-acl': 'public-read', 'Content-Type': content_type, 'x-amz-storage-class': 'REDUCED_REDUNDANCY'})

param = get_params(PARAM_LIST)
if param['imgdata'] is None:
  error("no imgdata")
url = param['imgdata']
if param['texture'] is None:
  param['texture'] = "";
if param['heightmap'] is None:
  param['heightmap'] = "";
if param['name'] is None:
  param['name'] = "";

dataobj = json.dumps({
  'texture' : param['texture'],
  'heightmap' : param['heightmap'],
  'name' : param['name']
})

dir = hash_dir(param['imgdata']);

filename = filename_from_url(param['texture'], param['name']);

tag = "imlandscape"
objectname = "im/"+dir+"/"+filename

saveImgData(param['imgdata'], filename);

print "#@imlandscape"
#print ", ".join([k+"="+str(v) for k,v in param.iteritems()])
print file_size (filename)
print bin_identify (filename)
print BASE_URL+objectname
insert_cmd(dir, filename, param['name'], param['texture'], dataobj);
moveToS3(filename, objectname);
os.remove(filename);