-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathphotos.py
272 lines (240 loc) · 9.57 KB
/
photos.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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# -*- coding: utf-8 -*-
import os
import sys
import math
from eve import Eve
from PIL import Image
from eve.auth import TokenAuth
from bson.objectid import ObjectId
from alerts import rainbow_spotted_alert
from settings import *
from utils import logger
from users import slightly_delayed_synch_users
from flask import request, Response, current_app as app
from functools import wraps
class SimpleTokenAuth(TokenAuth):
"""
This uses the username from HTTP basic authentication as its token
The token that needs to be passed is the ID of the user in the database
If it finds the user ID in the database, the picture is allowed
FIXME: the big inconvenience is that the canonical base of users is not stored in
this database: it is stored in Appcelerator Cloud Services.
The file users.py serves to synchronise these two databases.
It would be better if user management would be only through this server.
`curl -i -d {"key":"value","key","value",etc...} -H 'Content-Type: application/json' --user 436641f6e1etceteara: http://127.0.0.1:5000/photos`
"""
def check_auth(self, token, allowed_roles, resource, method):
"""
resource='photos'
method='GET|POST|DELETE'
If the user is not found, synchronise the database first
"""
if app.data.driver.db.users.find_one({'id': token }):
return True
else:
try_get_users = slightly_delayed_synch_users()
if not try_get_users:
return False
if app.data.driver.db.users.find_one({'id': token }):
return True
return False
# Uploaded photo info needs to correspond to this schema, or it will be rejected.
# Full example:
# curl -i -d '{"content_type":"image/jpeg","created_at":"2014-04-12T18:52:05+0000","custom_fields":{"coordinates":[[41.36667,56.85]],"name_en":"Shuya","name_ru":"\u0428\u0443\u044f"},"exif":{"create_date":"2005-07-20T20:08:38+0000","height":1600,"make":"Canon","model":"CanonPowerShotA60","shutter_speed":"1/800","width":1200},"filename":"upload_test_photo.jpg","md5":"0bfa85371e2d64f771b9209426827c74","processed":true,"size":203267,"updated_at":"2014-04-12T18:52:05+0000","urls":{"large_1024":"http://storage.cloud.appcelerator.com/X3Eaph9KUC6Z1Lga4YOq8lRY1DWESOZD/photos/7c/74/53498b54ed8cdc76d900019e/upload_test_photo_large_1024.jpg","medium_500":"http://storage.cloud.appcelerator.com/X3Eaph9KUC6Z1Lga4YOq8lRY1DWESOZD/photos/7c/74/53498b54ed8cdc76d900019e/upload_test_photo_medium_500.jpg","medium_640":"http://storage.cloud.appcelerator.com/X3Eaph9KUC6Z1Lga4YOq8lRY1DWESOZD/photos/7c/74/53498b54ed8cdc76d900019e/upload_test_photo_medium_640.jpg","original":"http://storage.cloud.appcelerator.com/X3Eaph9KUC6Z1Lga4YOq8lRY1DWESOZD/photos/7c/74/53498b54ed8cdc76d900019e/upload_test_photo_original.jpg","small_240":"http://storage.cloud.appcelerator.com/X3Eaph9KUC6Z1Lga4YOq8lRY1DWESOZD/photos/7c/74/53498b54ed8cdc76d900019e/upload_test_photo_small_240.jpg","square_75":"http://storage.cloud.appcelerator.com/X3Eaph9KUC6Z1Lga4YOq8lRY1DWESOZD/photos/7c/74/53498b54ed8cdc76d900019e/upload_test_photo_square_75.jpg","thumb_100":"http://storage.cloud.appcelerator.com/X3Eaph9KUC6Z1Lga4YOq8lRY1DWESOZD/photos/7c/74/53498b54ed8cdc76d900019e/upload_test_photo_thumb_100.jpg"},"user":{"username":"test_user"}}' --user 436641f6e1someusertokenandthenthecolon: -H 'Content-Type: application/json' http://127.0.0.1:5000/photos'
photos_schema = {
"content_type": {
"type": "string"
},
"created_at": {
"type": "string"
},
"custom_fields": {
"type": "dict",
"schema": {
"coordinates": {
"type": "list",
"schema": {
"type": "list",
"schema": {
"type": "number"
}
}
},
"name_en": {
"type": "string"
},
"name_ru": {
"type": "string"
}
}
},
"exif": {
"type": "dict",
"schema": {
"create_date": {
"type": "string",
"required": False
},
"width": {
"type": "integer",
"required": False
},
"height": {
"type": "integer",
"required": False
},
"make": {
"type": "string",
"required": False
},
"model": {
"type": "string",
"required": False
},
"shutter_speed": {
"type": "string",
"required": False
}
},
"required": False
},
"filename": {
"type": "string"
},
"id": {
"type": "string",
"required": False
},
"md5": {
"type": "string",
"required": False
},
"processed": {
"type": "boolean"
},
"size": {
"type": "integer"
},
"updated_at": {
"type": "string"
},
"image": {
"type": "media",
"default": ""
},
"urls": {
"type": "dict",
"schema": {
"large_1024": {
"type": "string",
"required": False
},
"medium_640": {
"type": "string",
"required": False
},
"medium_500": {
"type": "string",
"required": False
},
"small_320": {
"type": "string",
"required": False
},
"small_240": {
"type": "string",
"required": False
},
"thumb_100": {
"type": "string",
"required": False
},
"square_75": {
"type": "string",
"required": False
},
"original": {
"type": "string",
"required": False
}
},
"required": False
},
"user": {
"type": "dict",
"schema": {
"username" : {
"type": "string"
},
"id" : {
"type": "string",
"required": False
}
}
}
}
eve_settings = {
'SERVER_NAME': SERVER_NAME,
'URL_PROTOCOL': 'http',
'DOMAIN': {
'photos': {
'schema': photos_schema,
'datasource': {
"default_sort": [("created_at",-1)]
},
'cache_control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0',
'cache_expires': -1,
},
},
'MONGO_DBNAME': 'raduga',
'RESOURCE_METHODS': ['GET', 'POST'],
'ITEM_METHODS': ['GET', 'PATCH', 'DELETE'],
'PUBLIC_METHODS': ['GET'],
'IF_MATCH': False,
}
def write_photo_versions(id):
"""
After the photo is uploaded, we create several sizes thumbnails of the photo to be used in the app
FIXME: For now the photo is uploaded to the GridFS file system first, because this was
the easiest to implement. It is then saved to disk, and the reduced versions are generated.
Of course it would be more clean if it got saved to disk in the first place and the
GridFS step was skipped.
"""
def bounds(width):
"""
The photos are viewed primarily in a scroll, on portrait devices.
If the device is 240px wide, both landscape and portrait pictures will have a width of 240px
The maximum height is then calculated given that 9:16 is probably the tallest format.
"""
return (width, math.ceil(( width / 9.0 ) * 16))
logger.debug("writing newly uploaded photo %s to disk" % str(id))
photo = app.data.driver.db.photos.find_one(ObjectId(id))
os.mkdir(os.path.join(PHOTO_FOLDER, id))
im = Image.open(app.media.get(photo['image']))
im.save(os.path.join(PHOTO_FOLDER, id, photo['filename']))
basename, extension = os.path.splitext(photo['filename'])
update = {"urls": {}}
logger.debug("writing thumbnails of %s to disk" % str(id))
for size, slug in [(320, "small_320"), (640, "medium_640"), (1024, "large_1024")]:
im_small = im.copy()
im_small.thumbnail(bounds(size), Image.ANTIALIAS)
filename = "%s_%s%s" % (basename, slug, extension)
im_small.save(os.path.join(PHOTO_FOLDER, id, filename ))
update['urls'][slug] = 'http://' + SERVER_NAME + '/static/photos/' + id + '/' + filename
update['urls']['original'] = 'http://' + SERVER_NAME + '/static/photos/' + id + '/' + photo['filename']
update['processed'] = True
# set the `url` fields for this photo in the database, so the app can display the photo
app.data.driver.db.photos.update({"id": id}, { "$set": update})
# Send out a push message to all users in the vicinity of the spotted photo
# (as defined in alerts.py)
rainbow_spotted_alert(photo)
def after_update_photos(request, payload):
"""
Right now the photo is uploaded in two parts: first the metadata, then the photo itself.
The latter request is an `update` request. After this request, we want to create the thumbnails
"""
write_photo_versions(request.form['id'])
app = Eve(settings=eve_settings, auth=SimpleTokenAuth, static_folder=STATIC_FOLDER)
app.on_post_PATCH_photos += after_update_photos
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')