summaryrefslogtreecommitdiff
path: root/pbserver.py
blob: 530e54f9df0b10fe90bde6fb6e13302b74905734 (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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/python2.7
from bottle import route, run, post, request, static_file

from Pb.Gradient import Gradient
from Pb.Imgrid import Imgrid
from Pb.Breaker import Breaker
from Pb.Pattern import Pattern
from Pb.Generate import Generate
from Pb.Imlandscape import Imlandscape

from Config import AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, BUCKET_NAME, BIN_IDENTIFY
from Pb import Pb
from Db import Db

import os
import sys

import sha
from subprocess import call, Popen, PIPE
import simplejson as json

from boto.s3.connection import S3Connection
from boto.s3.key import Key
#
try:
    db = Db(); 
except Exception as e:
    sys.stderr.write("Could not connect to db:\n{}".format(e))
    sys.exit(1);
BASE_URL = "http://i.asdf.us"

def hashdir(filename):
    return  sha.new(filename).hexdigest()[:2]

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

def cleanup(filepath):
    try:
        call(['rm', filepath])
    except Exception as e:
        sys.stderr.write(str(e))
        raise 

def s3move(filename,objectname):
    try:
        conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, is_secure=False)
        b = conn.get_bucket(BUCKET_NAME)
        k = Key(b)
        k.key = objectname
        k.set_contents_from_filename(filename)
        k.set_acl('public-read')
        k.storage_class = 'REDUCED_REDUNDANCY'
    except Exception as e:
        sys.stderr.write(str(e));
        raise(e)

def format_im_data(im, insert_url="NULL"):
    directory = hashdir(im.filename)
    dimensions = bin_identify(im.filepath)
    size = Pb.file_size(im.filepath)
    objectname = "im/{}/{}".format(directory, im.filename)
    try:
        s3move(im.filepath, objectname)
        cleanup(im.filepath)
        db.insert_cmd(
            date=im._now, 
            remote_addr=request.environ.get('REMOTE_ADDR', "NULL"),
            username=im.params.username or "NULL",
            url=insert_url,
            directory=directory,
            oldfile="NULL",
            newfile=im.filename, 
            dataobj=";".join(im.commands),
            cmd=json.dumps(dict(im.params)),
            tag=im.__class__.__name__,
        )
        return json.dumps({
            'url' : "{}/{}".format(BASE_URL, objectname),
            'size' : size,
            'width' : "{}px".format(dimensions[0]),
            'height' : "{}px".format(dimensions[1]),
        })
    except Exception as e:
        sys.stderr.write("Problem sending to database or s3\n")
        sys.stderr.write(str(e))
        raise;


def return_image(im, insert_url="NULL"):
  return format_im_data(im, insert_url)


def return_jsonp(im, insert_url="NULL"):    
  return "{}({})".format(im.get("callback"), format_im_data(im, insert_url))


@post('/im/api/imgradient')
def gradient():
    try:
        im = Gradient(**(dict(request.forms)))
        im.create();
        return return_image(im)
    except Exception as e:
        sys.stderr.write("imgradient failure\n")
        sys.stderr.write("params:\n")
        for i in request.forms:
            sys.stderr.write("{}:{}\n".format(i, request.forms[i]))
        raise;
        return json.dumps({ 'error' : 'Request could not be processed' })

@post('/im/api/imgrid')
def imgrid():
    try:
        im = Imgrid(**(dict(request.forms)))
        im.create();
        url= "NULL"
        for elem in [ im.params.imageinstead , im.params.bgimage, im.params.planebgimage ]:
            if elem:
                url = elem['url']
                break
        return return_image(im, url)
    except Exception as e:
        sys.stderr.write(str(e))
        return json.dumps({ 'error' : 'Request could not be processed' })

@post('/im/api/generate')
def generate():
    try:
        im = Generate(**(dict(request.forms)))
        im.create();
        return return_image(im)
    except Exception as e:
        sys.stderr.write(str(e))
        return json.dumps({ 'error' : 'Request could not be processed' })

@post('/im/api/imbreak')
def breaker():
    try:
        im = Breaker(**(dict(request.forms)))
        im.create();
        return return_image(im, im.params.url)
    except Exception as e:
        sys.stderr.write(str(e))
        return json.dumps({ 'error' : 'Request could not be processed' })

@post('/im/api/impattern')
def pattern():
    try:
        im = Pattern(**(dict(request.forms)))
        im.create();
        return return_image(im, im.params['image_url'])
    except Exception as e:
        sys.stderr.write(str(e)+"\n")
        for i in request.forms:
            sys.stderr.write("{}:{}\n".format(i, request.forms[i]))
        raise;
        return json.dumps({ 'error' : 'Request could not be processed' })

@post('/im/api/imlandscape')
def imlandscape():
    sys.stderr.write(str(dict(request.forms)))
    try:
        im = Imlandscape(**(dict(request.forms)))
        im.create();
        sys.stderr.write(str(im.params))
        return return_image(im, im.params['texture'])
    except Exception as e:
        sys.stderr.write(str(e))
        return json.dumps({ 'error' : 'Request could not be processed' })



#static routes
@route('/im/<filename>')
def server_static(filename):
    return static_file(filename, root='frontend/im/')
@route('/im')
def server_static():
    return static_file("index.html", root='frontend/im/')
@route('/imgrid')
def server_static():
    return static_file("index.html", root='frontend/imgrid/')
@route('/imgradient')
def server_static():
    return static_file("index.html", root='frontend/imgradient/')
@route('/imlandscape')
def server_static():
    return static_file("index.html", root='frontend/imlandscape/')
@route('/impattern')
def server_static():
    return static_file("index.html", root='frontend/impattern/')
@route('/imbreak')
def server_static():
    return static_file("index.html", root='frontend/imbreak/')
@route('/')
def server_static():
    return static_file("index.html", root='frontend/im/')
@route('/css/<filename>')
def server_static(filename):
    return static_file(filename, root='frontend/css/')
@route('/js/<filename>')
def server_static(filename):
    return static_file(filename, root='frontend/js/')
@route('/img/<filename>')
def server_static(filename):
    return static_file(filename, root='frontend/img/')


run(host='0.0.0.0', server='flup', port=8999, debug=True)
#run(host='0.0.0.0',  port=8999, debug=True)