forked from cole-gillespie/StoryMapJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
886 lines (738 loc) · 26.8 KB
/
api.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
from __future__ import division
from flask import Flask, request, session, redirect, url_for, \
render_template, jsonify, abort
from collections import defaultdict
import math
import os
import sys
import importlib
import traceback
import time
import datetime
import re
import json
from functools import wraps
import urllib
from urlparse import urlparse
# Import settings module
if __name__ == "__main__":
if not os.environ.get('FLASK_SETTINGS_MODULE', ''):
os.environ['FLASK_SETTINGS_MODULE'] = 'core.settings.loc'
settings_module = os.environ.get('FLASK_SETTINGS_MODULE')
try:
importlib.import_module(settings_module)
except ImportError, e:
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (settings_module, e))
import hashlib
import requests
import slugify
import bson
from oauth2client.client import OAuth2WebServerFlow
from storymap import storage, google
from storymap.connection import _user
app = Flask(__name__)
app.config.from_envvar('FLASK_CONFIG_MODULE')
settings = sys.modules[settings_module]
_GOOGLE_OAUTH_SCOPES = [
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/userinfo.profile'
];
@app.context_processor
def inject_urls():
"""
Inject urls into the templates.
Template variable will always have a trailing slash.
"""
static_url = settings.STATIC_URL or app.static_url_path
if not static_url.endswith('/'):
static_url += '/'
storage_url = settings.AWS_STORAGE_BUCKET_URL
if not storage_url.endswith('/'):
storage_url += '/'
storage_url += settings.AWS_STORAGE_BUCKET_KEY
if not storage_url.endswith('/'):
storage_url += '/'
cdn_url = settings.CDN_URL
if not cdn_url.endswith('/'):
cdn_url += '/'
return dict(
STATIC_URL=static_url, static_url=static_url,
STORAGE_URL=storage_url, storage_url=storage_url,
CDN_URL=cdn_url, cdn_url=cdn_url)
class APIEncoder(json.JSONEncoder):
def default(self, obj):
"""Format obj as json."""
if isinstance(obj, datetime.datetime):
return obj.isoformat()
if isinstance(obj, bson.objectid.ObjectId):
return str(obj)
return json.JSONEncoder.default(self, obj)
def _str2bool(s):
"""Convert string to boolean."""
return s.lower() in ("true", "t", "yes", "y", "1")
def _request_wants_json():
"""Determine response type."""
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'application/json' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['text/html']
def _jsonify(*args, **kwargs):
"""Convert to JSON"""
return app.response_class(json.dumps(dict(*args, **kwargs), cls=APIEncoder),
mimetype='application/json')
def _format_err(err_type, err_msg):
return "%s: %s" % (err_type, err_msg)
def _get_uid(user_string):
"""Generate a unique identifer for user string"""
return hashlib.md5(user_string).hexdigest()
def _utc_now():
return datetime.datetime.utcnow().isoformat()+'Z'
#
# request/session
#
def _request_get(*keys):
"""Get request data and return values"""
if request.method == 'POST':
obj = request.form
else:
obj = request.args
values = []
for k in keys:
v = obj.get(k)
values.append(v)
if len(values) > 1:
return values
return values[0]
def _request_get_required(*keys):
"""Verify existence of request data and return values"""
if request.method == 'POST':
obj = request.form
else:
obj = request.args
values = []
for k in keys:
v = obj.get(k)
if not v:
raise Exception('Expected "%s" parameter' % k)
values.append(v)
if len(values) > 1:
return values
return values[0]
def _session_get(*keys):
"""Verify existence of session data and return value"""
values = []
for k in keys:
v = session.get(key)
if not v:
raise Exception('Expected "%s" in session' % key)
values.append(v)
if len(values) > 1:
return values
return values[0]
def _session_pop(*keys):
"""Remove list of keys from session"""
for k in keys:
if k in session:
session.pop(k)
#
# auth
# https://developers.google.com/drive/web/quickstart/quickstart-python
#
@app.route("/google/auth/start/", methods=['GET', 'POST'])
def google_auth_start():
"""Initiate google authorization"""
flow = OAuth2WebServerFlow(
settings.GOOGLE_CLIENT_ID,
settings.GOOGLE_CLIENT_SECRET,
_GOOGLE_OAUTH_SCOPES,
redirect_uri='https://'+request.host+url_for('google_auth_verify')
)
authorize_url = flow.step1_get_authorize_url()
return redirect(authorize_url)
@app.route("/google/auth/verify/", methods=['GET', 'POST'])
def google_auth_verify():
"""Finalize google authorization"""
try:
if 'error' in request.args:
raise Exception(_format_err(
'Error getting authorization', request.args.get('error')))
code = _request_get_required('code')
flow = OAuth2WebServerFlow(
settings.GOOGLE_CLIENT_ID,
settings.GOOGLE_CLIENT_SECRET,
_GOOGLE_OAUTH_SCOPES,
redirect_uri='https://'+request.host+url_for('google_auth_verify')
)
credentials = flow.step2_exchange(code)
# ^ this is an oauth2client.client.OAuth2Credentials object
# Get user info
userinfo = google.get_userinfo(
google.get_userinfo_service(credentials))
if not userinfo:
raise Exception('Could not get Google user info')
info = {
'id': userinfo.get('id'),
'name': userinfo.get('name'),
'credentials': credentials.to_json()
}
if not info['id']:
raise Exception('Could not get Google user ID')
# Upsert user record
uid = _get_uid('google:'+info['id'])
user = _user.find_one({'uid': uid})
if user:
user['google'] = info
else:
user = {
'uid': uid,
'migrated': 0,
'storymaps': {},
'google': info
}
user['uname'] = info['name']
_user.save(user)
# Update session
session['uid'] = uid
return redirect(url_for('select'))
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
#
# Misc
#
def _user_get():
"""Enforce authenticated user"""
uid = session.get('uid')
if not uid:
return redirect(url_for('select'))
user = _user.find_one({'uid': uid})
if not user:
session.pop('uid')
return redirect(url_for('select'))
return user
def require_user(f):
"""
Decorator to enforce authenticated user
Adds user to request and kwargs
"""
@wraps(f)
def decorated_function(*args, **kwargs):
user = _user_get()
request.user = user
kwargs['user'] = user
return f(*args, **kwargs)
return decorated_function
def require_user_id(template=None):
"""
Decorator to enfore storymap access for authenticated user
Adds user to request and kwargs, adds id to kwargs
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
user = _user_get()
id = _request_get_required('id')
if id not in user['storymaps']:
error = 'You do not have permission to access to this StoryMap'
if template:
del user['_id'] # for serialization
return render_template('edit.html', user=user, error=error)
else:
return jsonify({'error': error})
request.user = user
kwargs['user'] = user
kwargs['id'] = id
return f(*args, **kwargs)
return decorated_function
return decorator
def _make_storymap_id(user, title):
"""Get unique storymap id from slugified title"""
id_set = set(user['storymaps'].keys())
# Add keys from S3 (in case of db issues)
user_key_prefix = storage.key_prefix(user['uid'])
regex = re.compile(r'^%s([^/]+).*' % user_key_prefix)
name_list, more = storage.list_key_names(user_key_prefix, 999, '')
for name in name_list:
m = regex.match(name)
if m:
id_set.add(m.group(1))
id_base = slugify.slugify(title)
id = id_base
n = 0
while id in id_set:
n += 1
id = '%s-%d' % (id_base, n)
return id
def _parse_url(url):
"""Parse url into (scheme, netloc, path, filename)"""
r = urlparse(url)
parts = r.path.split('/')
return {
'scheme': r.scheme or 'http',
'netloc': r.netloc,
'path': '/'.join(parts[:-1]),
'file': parts[-1]
}
def _write_embed(embed_key_name, json_key_name, meta):
"""Write embed page"""
# NOTE: facebook needs the protocol on embed_url for og tag
image_url = meta.get('image_url', settings.STATIC_URL+'img/logos/logo_storymap.png')
parts = _parse_url(image_url)
parts['path'] = urllib.quote(parts['path'])
image_url = '%(scheme)s://%(netloc)s%(path)s/%(file)s' % parts
content = render_template('_embed.html',
embed_url='http:'+urllib.quote(settings.AWS_STORAGE_BUCKET_URL+embed_key_name),
json_url=urllib.quote(settings.AWS_STORAGE_BUCKET_URL+json_key_name),
title=meta.get('title', ''),
description=meta.get('description', ''),
image_url=image_url
)
storage.save_from_data(embed_key_name, 'text/html', content)
def _write_embed_draft(key_prefix, meta):
"""Write embed page for draft storymap """
_write_embed(key_prefix+'draft.html', key_prefix+'draft.json', meta)
def _write_embed_published(key_prefix, meta):
"""Write embed for published storymap"""
_write_embed(key_prefix+'index.html', key_prefix+'published.json', meta)
#
# API views
# (called from the select page)
#
@app.route('/storymap/update/meta/', methods=['GET', 'POST'])
@require_user_id()
def storymap_update_meta(user, id):
"""Update storymap meta value"""
try:
key, value = _request_get_required('key', 'value')
user['storymaps'][id][key] = value
_user.save(user)
key_prefix = storage.key_prefix(user['uid'], id)
if key in ['title', 'description', 'image_url']:
_write_embed_draft(key_prefix, user['storymaps'][id])
if user['storymaps'][id].get('published_on'):
_write_embed_published(key_prefix, user['storymaps'][id])
return jsonify(user['storymaps'][id])
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/copy/', methods=['GET', 'POST'])
@require_user_id()
def storymap_copy(user, id):
"""
Copy storymap
@id = storymap to copy
@title = name of new copy
"""
try:
title = _request_get_required('title')
dst_id = _make_storymap_id(user, title)
src_key_prefix = storage.key_prefix(user['uid'], id)
dst_key_prefix = storage.key_prefix(user['uid'], dst_id)
src_re = re.compile(r'%s' % src_key_prefix)
src_key_list, more = storage.list_keys(src_key_prefix, 999, '')
for src_key in src_key_list:
file_name = src_key.name.split(src_key_prefix)[-1]
dst_key_name = "%s%s" % (dst_key_prefix, file_name)
if file_name.endswith('.json'):
json_string = src_key.get_contents_as_string()
storage.save_json(dst_key_name,
src_re.sub(dst_key_prefix, json_string))
else:
storage.copy_key(src_key.name, dst_key_name)
# Update meta
user['storymaps'][dst_id] = {
'id': dst_id,
'title': title,
'draft_on': user['storymaps'][id]['draft_on'],
'published_on': user['storymaps'][id]['published_on']
}
_user.save(user)
# Write new embed pages
_write_embed_draft(dst_key_prefix, user['storymaps'][dst_id])
if user['storymaps'][dst_id].get('published_on'):
_write_embed_published(dst_key_prefix, user['storymaps'][dst_id])
return jsonify(user['storymaps'][dst_id])
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/delete/')
@require_user_id()
def storymap_delete(user, id):
"""Delete storymap"""
try:
key_name = storage.key_name(user['uid'], id)
key_list, marker = storage.list_keys(key_name, 50)
for key in key_list:
storage.delete(key.name);
del user['storymaps'][id]
_user.save(user)
return jsonify({})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/create/', methods=['POST'])
@require_user
def storymap_create(user):
"""Create a storymap"""
try:
title, data = _request_get_required('title', 'd')
id = _make_storymap_id(user, title)
key_prefix = storage.key_prefix(user['uid'], id)
content = json.loads(data)
storage.save_json(key_prefix+'draft.json', content)
user['storymaps'][id] = {
'id': id,
'title': title,
'draft_on': _utc_now(),
'published_on': ''
}
_user.save(user)
_write_embed_draft(key_prefix, user['storymaps'][id])
return jsonify({'id': id})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/migrate/done/', methods=['GET'])
@require_user
def storymap_migrate_done(user):
"""Flag user as migrated"""
try:
user['migrated'] = 1
_user.save(user)
return jsonify({})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/migrate/list/', methods=['GET', 'POST'])
@require_user
def storymap_migrate_list(user):
"""Get list of storymaps that still need to be migrated"""
try:
credentials = google.get_credentials(user['google']['credentials'])
drive_service = google.get_drive_service(credentials)
existing = [d['title'] for (k, d) in user['storymaps'].items()]
temp_list = google.drive_get_migrate_list(drive_service)
migrate_list = [r for r in temp_list if r['title'] not in existing]
return jsonify({'migrate_list': migrate_list})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/migrate/', methods=['POST'])
@require_user
def storymap_migrate(user):
"""
Migrate a storymap
@title = storymap title
@url = storymap base url
@draft_on = ...
@published_on = ...
@file_list = json encoded list of file names
"""
try:
title, src_url, draft_on, file_list_json = _request_get_required(
'title', 'url', 'draft_on', 'file_list')
published_on = _request_get('published_on')
file_list = json.loads(file_list_json)
dst_id = _make_storymap_id(user, title)
dst_key_prefix = storage.key_prefix(user['uid'], dst_id)
dst_url = settings.AWS_STORAGE_BUCKET_URL+dst_key_prefix
dst_img_url = dst_url+'_images/'
re_img = re.compile(r'.*\.(png|gif|jpg|jpeg)$', re.I)
re_src = re.compile(r'%s' % src_url)
for file_name in file_list:
file_url = "%s%s" % (src_url, file_name)
if file_name.endswith('.json'):
key_name = storage.key_name(user['uid'], dst_id, file_name)
r = requests.get(file_url)
storage.save_json(key_name, re_src.sub(dst_img_url, r.text))
elif re_img.match(file_name):
key_name = storage.key_name(user['uid'], dst_id, '_images', file_name)
storage.save_from_url(key_name, file_url)
else:
continue # skip
user['storymaps'][dst_id] = {
'id': dst_id,
'title': title,
'draft_on': draft_on,
'published_on': published_on
}
_user.save(user)
_write_embed_draft(dst_key_prefix, user['storymaps'][dst_id])
if published_on:
_write_embed_published(dst_key_prefix, user['storymaps'][dst_id])
return jsonify(user['storymaps'][dst_id])
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
#
# API views
# (called from the edit page)
#
@app.route('/storymap/')
@require_user_id()
def storymap_get(user, id):
"""Get storymap"""
try:
key_name = storage.key_name(user['uid'], id, 'draft.json')
data = storage.load_json(key_name)
return jsonify({'meta': user['storymaps'][id], 'data': data})
except storage.StorageException, e:
traceback.print_exc()
return jsonify({'error': str(e), 'error_detail': e.detail})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/save/', methods=['POST'])
@require_user_id()
def storymap_save(user, id):
"""Save draft storymap"""
try:
data = _request_get_required('d')
key_name = storage.key_name(user['uid'], id, 'draft.json')
content = json.loads(data)
storage.save_json(key_name, content)
user['storymaps'][id]['draft_on'] = _utc_now()
_user.save(user)
return jsonify({'meta': user['storymaps'][id]})
except storage.StorageException, e:
traceback.print_exc()
return jsonify({'error': str(e), 'error_detail': e.detail})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/publish/', methods=['POST'])
@require_user_id()
def storymap_publish(user, id):
"""Save published storymap"""
try:
data = _request_get_required('d')
key_prefix = storage.key_prefix(user['uid'], id)
content = json.loads(data)
storage.save_json(key_prefix+'published.json', content)
user['storymaps'][id]['published_on'] = _utc_now()
_user.save(user)
_write_embed_published(key_prefix, user['storymaps'][id])
return jsonify({'meta': user['storymaps'][id]})
except storage.StorageException, e:
traceback.print_exc()
return jsonify({'error': str(e), 'error_detail': e.detail})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/image/list/', methods=['GET', 'POST'])
@require_user_id()
def storymap_image_list(user, id):
"""List storymap images """
try:
key_prefix = storage.key_prefix(user['uid'], id, '_images')
key_list, more = storage.list_key_names(key_prefix, 999, '')
image_list = [n.split('/')[-1] for n in key_list]
return jsonify({'image_list': image_list})
except storage.StorageException, e:
traceback.print_exc()
return jsonify({'error': str(e), 'error_detail': e.detail})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
@app.route('/storymap/image/save/', methods=['POST'])
@require_user_id()
def storymap_image_save(user, id):
"""
Save storymap image
@id = storymap id
@name = file name
@content = data:URL representing the file's data as base64 encoded string
"""
try:
name, content = _request_get_required('name', 'content')
m = re.match('data:(.+);base64,(.+)', content)
if m:
content_type = m.group(1)
content = m.group(2).decode('base64')
else:
raise Exception('Expected content as data-url')
key_name = storage.key_name(user['uid'], id, '_images', name)
storage.save_from_data(key_name, content_type, content)
return jsonify({'url': settings.AWS_STORAGE_BUCKET_URL+key_name})
except storage.StorageException, e:
traceback.print_exc()
return jsonify({'error': str(e), 'error_detail': e.detail})
except Exception, e:
traceback.print_exc()
return jsonify({'error': str(e)})
#
# Views
#
@app.route("/")
def index():
return render_template('index.html')
@app.route("/gigapixel/")
def gigapixel():
return render_template('gigapixel.html')
@app.route("/advanced/")
def advanced():
return render_template('advanced.html')
@app.route("/examples/<name>/")
def examples(name):
return render_template('examples/%s.html' % name)
@app.route("/logout/")
def logout():
_session_pop('uid')
return redirect('https://www.google.com/accounts/Logout')
@app.route("/userinfo/")
def userinfo():
import pprint
uid = session.get('uid')
user = None
if uid:
user = _user.find_one({'uid': uid})
if user:
del user['_id']
user = pprint.pformat(user, indent=4)
return render_template('userinfo.html',
uid=uid, user=user)
@app.route("/select.html/", methods=['GET', 'POST'])
@app.route("/edit.html/", methods=['GET', 'POST'])
def legacy_redirect():
"""Legacy redirect"""
return redirect(url_for('select'))
@app.route("/select/", methods=['GET', 'POST'])
def select():
try:
uid = session.get('uid')
if not uid:
return render_template('select.html')
user = _user.find_one({'uid': uid})
if not user:
_session_pop('uid')
return render_template('select.html')
del user['_id']
return render_template('select.html', user=user)
except Exception, e:
traceback.print_exc()
return render_template('select.html', error=str(e))
@app.route("/edit/", methods=['GET', 'POST'])
@require_user_id('edit.html')
def edit(user, id):
try:
del user['_id'] # for serialization
return render_template('edit.html',
user=user, meta=user['storymaps'][id])
except Exception, e:
traceback.print_exc()
return render_template('edit.html', error=str(e))
@app.route('/admin/')
@require_user
def admin(user):
if not user['uid'] in settings.ADMINS:
abort(401)
return render_template('/admin/index.html')
@app.route('/admin/users/')
@require_user
def admin_users(user):
if not user['uid'] in settings.ADMINS:
abort(401)
args = request.args.copy()
page = int(args.pop('page', 1))
rpp = int(request.args.get('rpp', 100))
skip = (page - 1) * rpp
files = defaultdict(list)
users = []
query = {}
if args.get('uname'):
if args.get('unamesearch') == 'is':
query.update({ 'uname': args['uname'] })
else:
query.update({ 'uname':{'$regex': args['uname'], '$options': 'i'}})
if args.get('uid'):
query.update({ 'uid': args['uid'] })
migrated = args.get('migrated')
if migrated == 'migrated':
query.update({ 'migrated': 1 })
elif migrated == 'unmigrated':
query.update({ 'migrated': 0 })
for k in storage.all_keys():
uid = k.split('/')[1]
files[uid].append(k)
pages = 0
if query:
for u in _user.find(query, skip=skip, limit=rpp):
u.update({ 'files': files[u['uid']] })
users.append(u)
pages = int(math.ceil(_user.find(query).count() / rpp))
return render_template('admin/users.html', **{
'users': users,
'page': page,
'pages': pages,
'args': args,
'querystring': urllib.urlencode(args.items()),
'storage_root': settings.AWS_STORAGE_BUCKET_URL
})
@app.route('/admin/unmatched-files')
@require_user
def admin_unmatched_files(user):
if not user['uid'] in settings.ADMINS:
abort(401)
files = defaultdict(list)
users = []
for k in storage.all_keys():
uid = k.split('/')[1]
files[uid].append(k)
for u in _user.find():
try:
del files[u['uid']]
except KeyError:
pass
return _jsonify(files)
@app.route("/qunit/", methods=['GET'])
def qunit():
return render_template('qunit.html')
#
# FOR DEVELOPMENT
# SERVE URLS FROM DIRECTORIES
#
from flask import send_from_directory
build_dir = os.path.join(settings.PROJECT_ROOT, 'build')
compiled_dir = os.path.join(settings.PROJECT_ROOT, 'compiled')
templates_dir = os.path.join(settings.PROJECT_ROOT, 'compiled/templates')
@app.route('/build/<path:path>')
def catch_build(path):
return send_from_directory(build_dir, path)
@app.route('/compiled/<path:path>')
def catch_compiled(path):
return send_from_directory(compiled_dir, path)
@app.route('/editor/templates/<path:path>')
def catch_compiled_templates(path):
return send_from_directory(templates_dir, path)
# redirect old documentation URLs
@app.route('/<path:path>')
def redirect_old_urls(path):
if path.endswith('.html'):
return redirect(url_for(path.split('.')[0]))
abort(404)
if __name__ == '__main__':
import getopt
# Add current directory to sys.path
site_dir = os.path.dirname(os.path.abspath(__file__))
if site_dir not in sys.path:
sys.path.append(site_dir)
ssl_context = None
port = 5000
try:
opts, args = getopt.getopt(sys.argv[1:], "sp:", ["port="])
for opt, arg in opts:
if opt == '-s':
from OpenSSL import SSL
ssl_context = SSL.Context(SSL.SSLv23_METHOD)
ssl_context.use_privatekey_file(os.path.join(site_dir, 'website', 'website.key'))
ssl_context.use_certificate_file(os.path.join(site_dir, 'website', 'website.crt'))
elif opt in ('-p', '--port'):
port = int(arg)
else:
print 'Usage: app.py [-s]'
sys.exit(1)
except getopt.GetoptError:
print 'Usage: app.py [-s] [-p port]'
sys.exit(1)
app.run(host='0.0.0.0', port=port, debug=True, ssl_context=ssl_context)