forked from johntynan/changinglives
/
public_app.py
executable file
·189 lines (150 loc) · 6.26 KB
/
public_app.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
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
#!/usr/bin/env python
import datetime
import logging
import os
import re
import shlex
import subprocess
import time
from flask import Flask, redirect, render_template
from jinja2.filters import do_mark_safe
from tumblpy import Tumblpy
from tumblpy import TumblpyError
from werkzeug import secure_filename
import app_config
from zazzle import zazzlify_png
app = Flask(app_config.PROJECT_NAME)
app.config['PROPAGATE_EXCEPTIONS'] = True
os.environ['TZ'] = 'US/Eastern'
time.tzset()
logger = logging.getLogger('tumblr')
file_handler = logging.FileHandler('/var/log/%s.log' % app_config.PROJECT_SLUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(logging.INFO)
@app.route('/%s/errors/' % app_config.PROJECT_SLUG, methods=['GET'])
def _errors():
"""
Parses the log for errors.
Returns them to the page.
"""
context = {}
context['errors'] = []
with open('/var/log/%s.log' % app_config.PROJECT_SLUG) as logfile:
for line in logfile:
if 'ERROR' in line:
line_dict = {}
try:
total_items = len(line.split())
line_dict['date'] = line.split()[0]
line_dict['time'] = line.split()[1]
line_dict['type'] = '%s %s' % (line.split()[2], line.split()[3])
line_dict['message'] = ''
current_item = 4
for item in line.split():
if current_item <= total_items:
line_dict['message'] += '%s ' % item
current_item += 1
line_dict['message'] = line_dict['message'].strip()
context['errors'].append(line_dict)
except:
pass
context['errors'] = sorted(context['errors'], key=lambda item: item['date'], reverse=True)
return render_template('error.html', **context)
@app.route('/%s/test/' % app_config.PROJECT_SLUG, methods=['GET'])
def _test():
"""
Returns the time. Proves the app server is running.
"""
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
@app.route('/%s/' % app_config.PROJECT_SLUG, methods=['POST'])
def _post_to_tumblr():
"""
Handles the POST to Tumblr.
"""
def strip_html(value):
"""
Strips HTML from a string.
"""
try:
return re.compile(r'</?\S([^=]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE).sub('', value)
except TypeError:
return None
def strip_breaks(value):
"""
Converts newlines, returns and other breaks to <br/>.
"""
value = re.sub(r'\r\n|\r|\n', '\n', value)
return value.replace('\n', do_mark_safe('<br/>'))
# Request is a global. Import it down here where we need it.
from flask import request
name = strip_html(request.form.get('signed_name', None))
location = strip_html(request.form.get('location', None))
svg = request.form.get('image', None)
svg = re.sub('(height|width)=\"[0-9]+\"', '', svg, 2)
# Fix for duplicate namespaces in IE...
if svg.count('xmlns="http://www.w3.org/2000/svg"') > 1:
svg = svg.replace('xmlns="http://www.w3.org/2000/svg"', '', 1)
file_path = '/uploads/%s/%s_%s' % (
app_config.PROJECT_SLUG,
str(time.mktime(datetime.datetime.now().timetuple())).replace('.', ''),
secure_filename(name.replace(' ', '-'))
)
svg_path = file_path + '.svg'
png_path = file_path + '.png'
with open('/var/www%s' % svg_path, 'wb') as f:
f.write(svg.encode('utf-8'))
if app_config.DEPLOYMENT_TARGET == 'development':
command = 'cairosvg /var/www/%s -f png -o /var/www%s' % (svg_path, png_path)
else:
command = '/home/ubuntu/apps/changing-lives/virtualenv/bin/cairosvg /var/www%s -f png -o /var/www%s' % (svg_path, png_path)
args = shlex.split(command)
try:
# When used with check_output(), subprocess will return errors to a "CalledProcessError."
# This is nice. I'm also piping stderr to stdout so we can see a trace if we want.
# I am not logging the trace because we need the log to be single lines for continuity.
subprocess.check_output(args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError, e:
# If we encounter a CalledProcessError, log the output.
logger.error('%s %s %s http://%s%s reader(%s) (times in EST)' % (
'ERROR', '500', e, app_config.SERVERS[0], svg_path, name))
# These bits build a nicer error page that has the real stack trace on it.
context = {}
context['title'] = 'CairoSVG is unhappy.'
context['message'] = e.output
return render_template('500.html', **context)
context = {
'name': name,
'location': location,
}
caption = render_template('caption.html', **context)
secrets = app_config.get_secrets()
t = Tumblpy(
app_key=secrets['TUMBLR_APP_KEY'],
app_secret=secrets['TUMBLR_APP_SECRET'],
oauth_token=secrets['TUMBLR_OAUTH_TOKEN'],
oauth_token_secret=secrets['TUMBLR_OAUTH_TOKEN_SECRET'])
params = {
"type": "photo",
"caption": caption,
"tags": app_config.TUMBLR_TAGS,
"source": "http://%s%s" % (app_config.SERVERS[0], png_path)
}
try:
tumblr_post = t.post('post', blog_url=app_config.TUMBLR_URL, params=params)
tumblr_url = u"http://%s/%s" % (app_config.TUMBLR_URL, tumblr_post['id'])
logger.info('200 %s reader(%s) (times in EST)' % (tumblr_url, name))
if app_config.ZAZZLE_ENABLE:
zazzlify_png(png_path, tumblr_post['id'], name, location)
return redirect(tumblr_url, code=301)
except TumblpyError, e:
logger.error('%s %s http://%s%s reader(%s) (times in EST)' % (
e.error_code, e.msg, app_config.SERVERS[0], svg_path, name))
context = {}
context['title'] = 'Tumblr error'
context['message'] = '%s\n%s' % (e.error_code, e.msg)
return render_template('500.html', **context)
return redirect('%s#posts' % tumblr_url, code=301)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8001, debug=app_config.DEBUG)