-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.py
1522 lines (1388 loc) · 58 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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from flask import Flask
from flask import request
from flask import Response
from flask import render_template
from flask import make_response, current_app
from flask_bootstrap import Bootstrap
from flask import jsonify
from flask.json import JSONEncoder
from functools import update_wrapper
from db_def import db
from db_def import app
from db_def import Account
from db_def import WebAccount
from db_def import Note
from db_def import Context
from db_def import Media
from db_def import Feedback
from db_def import Site
from db_def import InteractionLog
import notification
import trello_api
import re
from sqlalchemy import or_
from sqlalchemy import and_
from sqlalchemy import func
from sqlalchemy import distinct
import traceback
from datetime import datetime
from datetime import timedelta
import calendar
import cloudinary
import cloudinary.api
import cloudinary.uploader
from cloudinary.utils import cloudinary_url
cloudinary.config(
cloud_name = 'university-of-colorado',
api_key = '893246586645466',
api_secret = '8Liy-YcDCvHZpokYZ8z3cUxCtyk'
)
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
import json
import psycopg2
Bootstrap(app)
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
try:
if isinstance(obj, datetime):
if obj.utcoffset() is not None:
obj = obj - obj.utcoffset()
millis = int(
calendar.timegm(obj.timetuple()) * 1000 +
obj.microsecond / 1000
)
return millis
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, obj)
app.json_encoder = CustomJSONEncoder
def success(data):
return jsonify({"status_code": 200, "status_txt": "OK",
"data": data})
def error(msg):
return jsonify({"status_code": 400, "status_txt": msg}), 400
def auth_error():
return jsonify({"status_code": 403, "status_txt": "You are not allowed to perform this action"}), 403
def validate_credentials(args):
username = args.get('username')
password = args.get('password')
if username is not None and password is not None:
account = Account.query.filter_by(username=username).first()
if account is not None and account.password == password:
return account
return None
@app.route('/api')
def api():
return render_template('apis.html')
#
# Account
#
@app.route('/api/accounts/count')
@crossdomain(origin='*')
def api_accounts_count():
n = Account.query.count()
return jsonify({'success' : True, 'data' : n})
@app.route('/api/account/delete/<username>', methods = ['GET'])
@crossdomain(origin='*')
def api_account_delete(username):
requesting_user = validate_credentials(request.args)
if requesting_user is not None:
account = Account.query.filter_by(username=username).first()
if account is not None and account.username == requesting_user.username:
print "deleting %s " % account.to_hash()
db.session.delete(account)
db.session.commit()
return success({})
return auth_error()
@app.route('/api/account/update/<username>', methods = ['POST','GET'])
@crossdomain(origin='*')
def api_account_update(username):
account = Account.query.filter_by(username=username).first()
if account is None:
return error("User: %s does not exists" % username)
if request.method == 'POST':
requesting_user = validate_credentials(request.form)
if requesting_user is not None and account.username == requesting_user.username:
f = request.form
if 'email' in f:
account.email = f['email']
if 'icon_url' in f:
account.icon_url = f['icon_url']
if 'password' in f:
account.password = f['password']
if 'consent' in f:
account.consent = f['consent']
if 'affiliation' in f:
account.affiliation = f['affiliation']
account.modified_at = datetime.now()
db.session.commit()
return success(account.to_hash())
else:
return auth_error()
else:
return error("the request to update [%s] must be done through a post" % username)
@app.route('/api/account/new/<username>', methods = ['POST','GET'])
@crossdomain(origin='*')
def api_account_new(username):
if request.method == 'POST':
f = request.form
if username and 'email' in f and 'name' in f and 'consent' in f and 'password' in f:
account = Account.query.filter_by(username=username).first()
if not account:
newAccount = Account(username)
newAccount.name = f['name']
newAccount.email = f['email']
newAccount.consent = f['consent']
newAccount.password = f['password']
newAccount.created_at = datetime.now()
if 'icon_url' in f:
newAccount.icon_url = f['icon_url']
else:
newAccount.icon_url = f.get('icon_url', newAccount.icon_url)
if 'affiliation' in f:
newAccount.affiliation = f['affiliation']
else:
newAccount.affiliation = ''
db.session.add(newAccount)
db.session.commit()
return success(newAccount.to_hash())
return error("Username %s is already taken" % username)
return error("Username is not specified")
else:
return error("the request to add [%s] must be done through a post" % username)
@app.route('/api/account/login', methods=['POST'])
@crossdomain(origin='*')
def api_account_login():
f = request.form
if 'username' in f and 'password' in f:
requesting_user = validate_credentials(request.form)
if requesting_user is not None:
#login successful
return success(requesting_user.to_hash_short())
return error('Invalid username or password')
else:
return error('Username or password is not specified')
@app.route('/api/account/<query>')
@crossdomain(origin='*')
def api_account_get(query):
field = request.args.get("field","username")
if field == 'username':
account = Account.query.filter_by(username=query).first()
else:
account = Account.query.get(query)
if account:
return success(account.to_hash())
else:
return error("user does not exist")
@app.route('/api/account/<username>/notes')
@crossdomain(origin='*')
def api_account_get_notes(username):
account = Account.query.filter_by(username=username).first()
return success([x.to_hash() for x in account.notes])
@app.route('/api/account/<username>/feedbacks')
@crossdomain(origin='*')
def api_account_get_feedbacks(username):
account = Account.query.filter_by(username=username).first()
return success([x.to_hash() for x in account.feedbacks])
@app.route('/api/accounts')
@crossdomain(origin='*')
def api_accounts_list():
accounts = Account.query.all()
return success([x.to_hash() for x in accounts])
@app.route('/api/account/<username>/activity/<activityname>/countstats')
@crossdomain(origin='*')
def api_account_activity_countstats(username, activityname):
account = Account.query.filter_by(username=username).first()
activity = Context.query.filter_by(name=activityname).first()
h = {}
if not account:
return error("account does not exists.")
if not activity:
return error("activity does not exists.")
h = find_latest_counts(account, activity, h)
h = find_latest_seasonal_counts(activity, h)
return success(h)
#
# WebAccount
#
'''
@app.route('/api/webaccounts/count')
@crossdomain(origin='*')
def api_webaccounts_count():
n = WebAccount.query.count()
return jsonify({'success' : True, 'data' : n})
@app.route('/api/webaccounts')
@crossdomain(origin='*')
def api_webaccounts_list():
accounts = WebAccount.query.all()
return success([x.to_hash() for x in accounts])
@app.route('/api/webaccount/update/<username>', methods = ['POST','GET'])
@crossdomain(origin='*')
def api_webaccount_update(username):
account = WebAccount.query.filter_by(username=username).first()
if not account:
return error("User: %s does not exists" % username)
if request.method == 'POST':
f = request.form
if 'email' in f:
account.email = f['email']
if 'icon_url' in f:
account.icon_url = f['icon_url']
if 'password' in f:
account.password = f['password']
if 'consent' in f:
account.consent = f['consent']
if 'affiliation' in f:
account.affiliation = f['affiliation']
account.modified_at = datetime.now()
db.session.commit()
return success(account.to_hash())
else:
return error("the request to update [%s] must be done through a post" % username)
@app.route('/api/webaccount/new/<username>', methods = ['POST','GET'])
@crossdomain(origin='*')
def api_webaccount_new(username):
if request.method == 'POST':
f = request.form
if username and 'email' in f and 'name' in f and 'consent' in f and 'password' in f:
account = WebAccount.query.filter_by(username=username).first()
if not account:
newAccount = WebAccount(username)
newAccount.name = f['name']
newAccount.email = f['email']
newAccount.consent = f['consent']
newAccount.password = f['password']
newAccount.created_at = datetime.now()
if 'icon_url' in f:
newAccount.icon_url = f['icon_url']
else:
newAccount.icon_url = f.get('icon_url', newAccount.icon_url)
if 'affiliation' in f:
newAccount.affiliation = f['affiliation']
else:
newAccount.affiliation = ''
newAccount.account_id = get_default_user_id()
db.session.add(newAccount)
db.session.commit()
return success(newAccount.to_hash())
return error("Username %s is already taken" % username)
return error("Username is not specified")
else:
return error("the request to add [%s] must be done through a post" % username)
@app.route('/api/webaccount/delete/<username>', methods = ['GET'])
@crossdomain(origin='*')
def api_webaccount_delete(username):
account = WebAccount.query.filter_by(username=username).first()
if account:
print "deleting %s " % account.to_hash()
db.session.delete(account)
db.session.commit()
return success({})
else:
return error("account does not exist")
@app.route('/api/webaccount/<webusername>/relatesto/<username>', methods = ['GET'])
@crossdomain(origin='*')
def api_webaccount_relation(webusername, username):
account = Account.query.filter_by(username=username).first()
webaccount = WebAccount.query.filter_by(username=webusername).first()
if account and webaccount:
webaccount.account_id = account.id
webaccount.modified_at = datetime.now()
db.session.commit()
return success(webaccount.to_hash())
return error("cannot find the account or webaccount.")
'''
#
# Note
#
trello_api.setup()
@app.route('/api/note/<id>')
@crossdomain(origin='*')
def api_note_get(id):
note = Note.query.get(id)
return success(note.to_hash())
@app.route('/api/note/<id>/delete', methods = ['GET'])
@crossdomain(origin='*')
def api_note_delete(id):
note = Note.query.get(id)
if note is not None:
requesting_user = validate_credentials(request.args)
if requesting_user is not None and note.account.username == requesting_user.username:
print "deleting %s " % note.to_hash()
trello_api.delete_card(note.id)
note.status = "deleted"
db.session.commit()
return success({})
else:
return auth_error()
else:
return error("note does not exist")
@app.route('/api/notes')
@crossdomain(origin='*')
def api_note_list():
format = request.args.get('format', 'full')
n = request.args.get('n',1000)
notes = Note.query.limit(n)
return success([x.to_hash(format) for x in notes])
@app.route('/api/designideas/at/<site>')
@crossdomain(origin='*')
def api_designidea_list_at_site(site):
format = request.args.get('format', 'full')
the_site = Site.query.filter_by(name=site).first()
if not the_site:
return error("site does not exist")
notes = Note.query.filter(Note.kind.ilike('designidea')).order_by(Note.modified_at.asc()).all()
context_ids = [c.id for c in the_site.contexts]
notes = [x for x in notes if x.context_id in context_ids]
return success([x.to_hash(format) for x in notes])
@app.route('/api/notes/at/<site>')
@crossdomain(origin='*')
def api_notes_list_at_site(site):
format = request.args.get('format', 'full')
the_site = Site.query.filter_by(name=site).first()
if not the_site:
return error("site does not exist")
notes = Note.query.filter(Note.kind.ilike('fieldnote')).order_by(Note.modified_at.asc()).all()
context_ids = [c.id for c in the_site.contexts]
notes = [x for x in notes if x.context_id in context_ids]
return success([x.to_hash(format) for x in notes])
@app.route('/api/notes/all')
@crossdomain(origin='*')
def api_note_list_all():
notes = Note.query.all()
return success([x.to_hash() for x in notes])
@app.route('/api/note/<id>/feedbacks')
@crossdomain(origin='*')
def api_note_get_feedbacks(id):
note = Note.query.filter_by(id=id).first()
feedbacks = Feedback.query.filter(Feedback.table_name.ilike('note'), Feedback.row_id == id).all()
return success([x.to_hash() for x in feedbacks])
@app.route('/api/note/<id>/update', methods = ['POST'])
@crossdomain(origin='*')
def api_note_update(id):
obj = request.form
note = Note.query.get(id)
if note:
requesting_user = validate_credentials(request.form)
if requesting_user is not None and note.account.username == requesting_user.username:
note.content = obj.get('content', note.content)
note.kind = obj.get('kind', note.kind)
note.status = obj.get('status', note.status)
if 'context' in obj:
c = Context.query.filter_by(name=obj['context']).first()
if c == None:
return error("context %s does not exist" % obj['context'])
note.context = c
note.modified_at = datetime.now()
db.session.commit()
#if note.kind == 'DesignIdea':
feedbacks_comment = Feedback.query.filter(Feedback.table_name.ilike('note'), Feedback.row_id==id, Feedback.kind=='commnet').all()
feedbacks_like = Feedback.query.filter(Feedback.table_name.ilike('note'), Feedback.row_id==id, Feedback.kind=='like').all()
new_desc = find_location_for_note(note)
if len(new_desc) > 0:
new_desc = "location: " + new_desc + "\r\n"
new_desc = new_desc + note.to_trello_desc() + "\r\n#likes: " + str(len(feedbacks_like))# + "\r\n#comments: " + str(len(feedbacks_comment))
trello_api.update_card(note.id, note.content, new_desc)
trello_api.move_card(note.id, note.status)
return success(note.to_hash())
else:
return auth_error()
return error("some parameters are missing")
@app.route('/api/note/new/<username>', methods = ['POST', 'GET'])
@crossdomain(origin='*')
def api_note_create(username):
if request.method == 'POST':
obj = request.form
requesting_user = validate_credentials(obj)
if requesting_user is not None and username == requesting_user.username:
if username and obj and 'content' in obj and 'context' in obj and 'kind' in obj:
content = obj['content']
context = obj['context']
kind = obj['kind']
a = Account.query.filter_by(username=username).first()
c = Context.query.filter_by(name=context).first()
if a and c:
note = Note(a.id, c.id, kind, content)
a.modified_at = datetime.now()
if 'longitude' in obj and 'latitude' in obj:
note.longitude = obj['longitude']
note.latitude = obj['latitude']
if 'status' in obj:
note.status = obj['status']
else:
note.status = ''
db.session.add(note)
db.session.commit()
if kind == 'DesignIdea' and is_note_in_aces(note):
print "adding a design idea card to trello."
card = trello_api.add_card(note.id, content, note.to_trello_desc(), note.status, use_default_list=True)
if card:
note.trello_card_id = card.id
db.session.commit()
else:
print "could not create design idea card in trello."
return success(note.to_hash())
return error("some parameters are missing")
return auth_error()
else:
return error("the request must be a post")
#
# Media
#
@app.route('/api/medias')
@crossdomain(origin='*')
def api_media_list():
medias = Media.query.all()
return success([x.to_hash() for x in medias])
@app.route('/api/media/<id>')
@crossdomain(origin='*')
def api_media_get(id):
media = Media.query.get(id)
if media:
return success(media.to_hash())
else:
return error("media object does not exist")
@app.route('/api/media/<id>/feedbacks')
@crossdomain(origin='*')
def api_media_get_feedbacks(id):
feedbacks = Feedback.query.filter(Feedback.table_name.ilike('media'), Feedback.row_id==id).all()
return success([x.to_hash() for x in feedbacks])
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/api/note/<id>/new/photo', methods = ['POST','GET'])
@crossdomain(origin='*')
def api_media_create(id):
try:
if request.method == 'POST':
link = request.form.get("link","")#["link"] or request.form["link"] or ""
title = request.form.get("title","")#files["title"] or request.form["title"] or ""
kind = "Photo"
note = Note.query.get(id)
if note is not None:
requesting_user = validate_credentials(request.form)
if requesting_user is not None and note.account.username == requesting_user.username:
media = Media(note.id, kind, title, link)
file = request.files.get("file",None)
if not file:
print "No file provided."
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
#file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# #print "saving locally to " + filename
response = cloudinary.uploader.upload(file, public_id = media.id)
# print "uploading to cloudinary .."
if response:
# print response['url']
media.link = response['url']
db.session.add(media)
note.status = str(note.created_at.date())
note.modified_at = datetime.now()
db.session.commit()
if is_note_in_aces(note):
# send notification
notification.send_new_note_notification_email(note, media, True)
print "Adding card to trello... link: ", media.link
feedbacks_like = Feedback.query.filter(Feedback.table_name.ilike('note'), Feedback.row_id==id, Feedback.kind=='like').all()
new_desc = find_location_for_note(note)
if len(new_desc) > 0:
new_desc = "location: " + new_desc + "\r\n"
new_desc = new_desc + note.to_trello_desc() + "\r\n#likes: " + str(len(feedbacks_like))# + "\r\n#comments: " + str(len(feedbacks_comment))
if len(note.content) == 0:
card = trello_api.add_card_with_attachment(note.id, "[no description]", new_desc, note.status, media.get_url())
else:
card = trello_api.add_card_with_attachment(note.id, note.content, new_desc, note.status, media.get_url())
if card:
note.trello_card_id = card.id
db.session.commit()
return success(media.to_hash())
else:
return auth_error()
else:
return error("note id %d is invalid" % id)
else:
return error("adding a media object to note {%s}, this request must be a post." % id)
except:
print traceback.format_exc()
#
# Context
#
@app.route('/api/contexts')
@crossdomain(origin='*')
def api_context_list_all():
contexts = Context.query.all()
return success([x.to_hash() for x in contexts])
@app.route('/api/context/<id>')
@crossdomain(origin='*')
def api_context_get(id):
context = Context.query.get(id)
return success(context.to_hash())
@app.route('/api/context/<id>/notes')
@crossdomain(origin='*')
def api_context_get_all_notes(id):
context = Context.query.get(id)
if context:
items = context.notes
return success([x.to_hash() for x in items])
@app.route('/api/context/activities')
@crossdomain(origin='*')
def api_context_get_all_activities():
items = Context.query.filter(Context.kind.ilike('activity')).all()
return success([x.to_hash() for x in items])
@app.route('/api/context/landmarks')
@crossdomain(origin='*')
def api_context_get_all_landmarks():
items = Context.query.filter(Context.kind.ilike('landmark')).all()
return success([x.to_hash() for x in items])
'''
@app.route('/api/context/<id>/update', methods = ['POST'])
@crossdomain(origin='*')
def api_context_update(id):
obj = request.form
context = Context.query.get(id)
if context:
context.title = obj.get('title', context.title)
context.description = obj.get('description', context.description)
if 'icon' in obj:
context.extras = obj.get('icon', context.extras)
context.modified_at = datetime.now()
db.session.commit()
return success(context.to_hash())
return error("some parameters are missing")
'''
'''
@app.route('/api/context/<id>/delete', methods = ['GET'])
@crossdomain(origin='*')
def api_context_delete(id):
# id = request.form.get('id','')
context = Context.query.get(id)
if context:
print "deleting %s " % context.to_hash()
db.session.delete(context)
db.session.commit()
return success({})
else:
return error("context does not exist")
'''
'''
@app.route('/api/context/new/activity/at/<site_name>', methods = ['POST'])
@crossdomain(origin='*')
def api_context_add_activity(site_name):
site = Site.query.filter_by(name=site_name).first()
if not site:
return error("site does not exists.")
obj = request.form
if 'title' in obj and 'description' in obj:
title = obj['title']
desc = obj['description']
new_context = Context("Activity", site.name + "_" + title, title, desc)
new_context.site_id = site.id
if 'icon' in obj:
icon = obj['icon']
new_context.extras = icon
new_context.site = site
db.session.add(new_context)
db.session.commit()
return success(new_context.to_hash())
else:
return error("title or description for the activity not provided.")
'''
@app.route('/api/context/active/activities/at/<site_name>', methods = ['GET'])
@crossdomain(origin='*')
def api_context_active_activities_at_site(site_name):
site = Site.query.filter_by(name=site_name).first()
if not site:
return error("site does not exists.")
active_activities = get_active_contexts(site.id, 'activity')
return success([x.to_hash() for x in active_activities])
@app.route('/api/context/active/designideas/at/<site_name>', methods = ['GET'])
@crossdomain(origin='*')
def api_context_active_designideas_at_site(site_name):
site = Site.query.filter_by(name=site_name).first()
if not site:
return error("site does not exists.")
active_designideas = get_active_contexts(site.id, 'design')
return success([x.to_hash() for x in active_designideas])
#
# Feedback
#
@app.route('/api/feedbacks')
@crossdomain(origin='*')
def api_feedbacks_list_all():
feedbacks = Feedback.query.all()
return success([x.to_hash() for x in feedbacks])
@app.route('/api/feedback/<id>')
@crossdomain(origin='*')
def api_feedback_get(id):
feedback = Feedback.query.get(id)
return success(feedback.to_hash())
@app.route('/api/feedback/<id>/update', methods = ['POST'])
@crossdomain(origin='*')
def api_feedback_update(id):
obj = request.form
requesting_user = validate_credentials(request.form)
feedback = Feedback.query.get(id)
if feedback is not None and requesting_user is not None and feedback.account.username == requesting_user.username:
feedback.content = obj.get('content', feedback.content)
feedback.kind = obj.get('kind', feedback.kind)
feedback.modified_at = datetime.now()
db.session.commit()
return success(feedback.to_hash())
return error("some parameters are missing")
@app.route('/api/feedback/new/<kind>/for/<model>/<id>/by/<username>',methods = ['POST', 'GET'])
@crossdomain(origin='*')
def api_feedback_add_to_note(kind,model,id,username):
if request.method == 'POST':
account = Account.query.filter_by(username=username).first()
target = Feedback.resolve_target(model,id)
requesting_user = validate_credentials(request.form)
if requesting_user is not None and account.username == requesting_user.username:
print "adding feedback [%s] about [%s] by user [%s]" % (kind, target, username)
try:
if target and account:
content = request.form.get('content','')
#print "content: ", content
if content == '':
return error("Content cannot be empty.")
parent_id = request.form.get('parent_id',0)
table_name = target.__class__.__name__
row_id = id
feedback = Feedback(account.id, kind, content, table_name, row_id, parent_id)
db.session.add(feedback)
db.session.commit()
if model.lower() == 'note':
#if target.kind == 'DesignIdea':
feedbacks_comment = Feedback.query.filter(Feedback.table_name.ilike('note'), Feedback.row_id==id, Feedback.kind=='comment').all()
feedbacks_like = Feedback.query.filter(Feedback.table_name.ilike('note'), Feedback.row_id==id, Feedback.kind=='like').all()
new_desc = find_location_for_note(target)
if len(new_desc) > 0:
new_desc = "location: " + new_desc + "\r\n"
trello_api.update_card(target.id, target.content, new_desc + target.to_trello_desc() + "\r\n#likes: " + \
str(len(feedbacks_like)))# + "\r\n#comments: " + str(len(feedbacks_comment)))
if kind.lower() == 'comment':
account_username = "The Design Team"
if account.username != 'default':
account_username = account.username
trello_api.add_comment_card(target.id, target.content, content)
return success(feedback.to_hash())
return error("something wrong")
except:
print traceback.format_exc()
else:
return auth_error()
else:
return error("add feedback to note [%s] by [%s], this operation must be done through a post" %
(id, username))
@app.route('/api/media/<id>/feedback/<username>/new/comment',methods = ['POST','GET'])
@crossdomain(origin='*')
def api_feedback_add_to_media(id,username):
if request.method == 'POST':
media = Media.query.get(id)
account = Account.query.filter_by(username=username).first()
requesting_user = validate_credentials(request.form)
if requesting_user is not None and account.username == requesting_user.username:
if media is not None and account and 'content' in request.form:
kind = "comment"
content = request.form['content']
table_name = "media"
row_id = id
parent_id = request.form.get('parent_id',0)
feedback = Feedback(account.id, kind, content, table_name, row_id, parent_id)
db.session.add(feedback)
db.session.commit()
return success(feedback.to_hash())
else:
return success({'success': False})
else:
return auth_error()
else:
return error("add feedback to media [%s] by [%s], this operation must be done through a post" %
(id, username))
#
# Site
#
@app.route('/api/site/<name>')
@crossdomain(origin='*')
def api_site_get(name):
site = Site.query.filter_by(name=name).first()
if site:
return success(site.to_hash())
else:
return error("site does not exist")
@app.route('/api/site/<name>/long')
@crossdomain(origin='*')
def api_site_get_long(name):
site = Site.query.filter_by(name=name).first()
if site:
h = site.to_hash()
h['contexts'] = [c.to_hash() for c in site.contexts]
return success(h)
else:
return error("site does not exist")
@app.route('/api/site/<name>/active/activities')
@crossdomain(origin='*')
def api_site_get_active_activities(name):
site = Site.query.filter_by(name=name).first()
if site:
h = site.to_hash()
activities = get_active_contexts(site.id, 'activity')
h['contexts'] = [c.to_hash() for c in activities]
return success(h)
else:
return error("site does not exist")
@app.route('/api/site/<name>/active/designideas')
@crossdomain(origin='*')
def api_site_get_active_designideas(name):
site = Site.query.filter_by(name=name).first()
if site:
h = site.to_hash()
designideas = get_active_contexts(site.id, 'design')
h['contexts'] = [c.to_hash() for c in designideas]
return success(h)
else:
return error("site does not exist")
@app.route('/api/site/<name>/notes')
@crossdomain(origin='*')
def api_site_get_notes(name):
site = Site.query.filter_by(name=name).first()
if site:
notes = []
for c in site.contexts:
notes += c.notes
return success([x.to_hash() for x in notes])
else:
return error("site does not exist")
@app.route('/api/site/<name>/notes/<username>')
@crossdomain(origin='*')
def api_site_get_notes_user(name,username):
site = Site.query.filter_by(name=name).first()
account = Account.query.filter_by(username=username).first()
if site and account:
all_notes = []
for c in site.contexts:
notes = Note.query.filter_by(account_id=account.id, context_id=c.id).all()
all_notes += notes
return success([x.to_hash() for x in all_notes])
else:
return error("site does not exist")
@app.route('/api/sites')
@crossdomain(origin='*')
def api_site_list():
sites = Site.query.all()
return success([x.to_hash() for x in sites])
@app.route('/api/site/<name>/contexts')
@crossdomain(origin='*')
def api_site_list_contexts(name):
site = Site.query.filter_by(name=name).first()
if site:
ordered_list = []
for c in site.contexts:
idx = 0
if c.title == "Free Observation":
ordered_list.insert(0,c)
idx = 1
else:
ordered_list.insert(idx,c)
#print [x.title for x in ordered_list]
return success([x.to_hash() for x in ordered_list])
else:
return error("site does not exist")
#
# Sync
#
'''
@app.route('/api/sync/accounts/created/since/<year>/<month>/<date>/<hour>/<minute>')
@crossdomain(origin='*')
def api_sync_account_since_minute(year,month,date,hour,minute):
since_date = datetime(int(year),int(month),int(date),int(hour),int(minute))
accounts = Account.query.filter(Account.created_at >= since_date).all()
return sync_success([x.to_hash() for x in accounts])
@app.route('/api/sync/webaccounts/created/since/<year>/<month>/<date>/<hour>/<minute>')
@crossdomain(origin='*')
def api_sync_webaccount_since_minute(year,month,date,hour,minute):
since_date = datetime(int(year),int(month),int(date),int(hour),int(minute))
accounts = WebAccount.query.filter(WebAccount.created_at >= since_date).all()
return sync_success([x.to_hash() for x in accounts])
@app.route('/api/sync/accounts/created/since/<year>/<month>/<date>/<hour>/<minute>/at/<site>')
@crossdomain(origin='*')
def api_sync_site_account_since_minute(site,year,month,date,hour,minute):
since_date = datetime(int(year),int(month),int(date),int(hour),int(minute))
accounts = Account.query.filter(Account.modified_at >= since_date).order_by(Account.modified_at.asc()).all()
the_site = Site.query.filter_by(name=site).first()
site_accounts = []
potential_accounts = []
if not the_site:
return error("site does not exist")
for a in accounts:
if any(n.context.site.id == the_site.id for n in a.notes):
site_accounts.append(a)
else:
potential_accounts.append(a)
for a in potential_accounts:
if is_account_related_to_site(a, the_site, True):
site_accounts.append(a)
return sync_success([x.to_hash() for x in site_accounts])
@app.route('/api/sync/notes/created/since/<year>/<month>/<date>/<hour>/<minute>')
@crossdomain(origin='*')
def api_sync_notes_since_minute(year,month,date,hour,minute):
since_date = datetime(int(year),int(month),int(date),int(hour),int(minute))
notes = Note.query.filter(Note.created_at >= since_date).all()
return sync_success([x.to_hash() for x in notes])
@app.route('/api/sync/notes/created/since/<year>/<month>/<date>/<hour>/<minute>/at/<site>')
@crossdomain(origin='*')
def api_sync_site_notes_since_minute(year,month,date,hour,minute,site):
since_date = datetime(int(year),int(month),int(date),int(hour),int(minute))
notes = Note.query.filter(Note.modified_at >= since_date).order_by(Note.modified_at.asc()).all()
the_site = Site.query.filter_by(name=site).first()
if not the_site:
return error("site does not exist")
context_ids = [c.id for c in the_site.contexts]
notes = [x for x in notes if x.context_id in context_ids]
return sync_success([x.to_hash() for x in notes])
@app.route('/api/sync/notes/within/<year>/<month>/at/<site>', methods=['GET'])
@crossdomain(origin='*')
def api_sync_notes_within_year_month(year, month, site):
try:
month_int = int(month)
year_int = int(year)
since_date = datetime(year_int, month_int, 1)
month_int = month_int + 1
if month_int == 13:
month_int = 1
year_int = year_int + 1
since_date_plus_one = datetime(year_int, month_int, 1)
notes = Note.query.filter(and_(Note.status != "deleted", and_(Note.modified_at >= since_date, Note.modified_at < since_date_plus_one))).order_by(Note.modified_at.asc()).all()
the_site = Site.query.filter_by(name=site).first()
if not the_site:
return error("site does not exist")
context_ids = [c.id for c in the_site.contexts]
notes = [x for x in notes if x.context_id in context_ids]