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
|
# -*- coding: utf-8 -*-
# Copyright (C) 2012, Sebastian Silva
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
import sys
import signal
import locale
from math import ceil
from string import join,split
import gevent
from urllib2 import urlopen
from flask import flash,Flask,request,url_for,abort,jsonify,Response,\
redirect,session,render_template,render_template_string,g,\
send_from_directory,Markup
from flaskext.babel import Babel, gettext as _, lazy_gettext as __, format_datetime
from werkzeug import Headers
import simplejson
from sugar_network import Client, sugar, ServerError
_BUFFER_SIZE = 1024 * 10
""" Initialization of local app """
app = Flask(__name__)
app.secret_key="ilovesugar" #necessary to initialize sessions
babel = Babel(app)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['BABEL_DEFAULT_TIMEZONE'] = 'America/Lima'
from cursors import *
mounts = network_mount.client.mounts()
@babel.localeselector
def get_locale():
# try to guess the language from the user accept
# header the browser transmits.
lang = request.accept_languages.best_match(['es', 'en'])
if not lang:
# otherwise we're probably embedded, get from env
lang = locale.getdefaultlocale()[0].split('_')[0]
return lang
@app.template_filter('special_str')
def special_str(arg):
if isinstance(arg, basestring): # Python 3: isinstance(arg, str)
return arg
else:
return(arg[0])
@app.template_filter('timedelta')
def timedelta(mtime):
return format_datetime(mtime, _('MMMM d, yyyy'))
def get_colors():
return sugar.color().split(',')
def mount_event(e):
if e.get('event')=='mount':
if not [True for m in mounts if m['mountpoint']==e['mountpoint']]:
mounts.append({'name':e['name'],
'mountpoint':e['mountpoint']})
elif e.get('event')=='unmount' and e.get('mountpoint')!='/':
mounts[:] = [m for m in mounts if m.get('mountpoint') != e.get('mountpoint')]
Client.connect(mount_event)
@app.context_processor
def inject_vars():
# Here we can inject variables into every template call
stroke,fill = get_colors()
connected = session.get('connected')
#TODO: Mark which mount is active
if connected==True:
mountpoint="/"
elif connected==False:
mountpoint="~"
else:
mountpoint=connected
kwvar = {
'userid': sugar.uid(),
'mounts': mounts,
'current_mount': mountpoint
}
return dict(stroke=stroke, fill=fill, **kwvar)
@app.before_request
def before_request():
if 'connected' not in session:
session['connected'] = network_mount.client.mounted
if session['connected']==True and not network_mount.client.mounted:
session['connected']=False
if session['connected']==False:
g.client = home_mount.client
g.Contexts = home_mount.Contexts
g.Activities= home_mount.Activities
g.Projects = home_mount.Projects
g.autocomplete_Contexts = home_mount.autocomplete_Contexts
g.Questions = home_mount.Questions
g.Ideas = home_mount.Ideas
g.Problems = home_mount.Problems
g.Solutions = home_mount.Solutions
g.Comments = home_mount.Comments
g.Reviews = home_mount.Reviews
g.Resources = home_mount.Resources
elif session['connected']==True:
g.client = network_mount.client
g.Contexts = network_mount.Contexts
g.Activities= network_mount.Activities
g.Projects = network_mount.Projects
g.autocomplete_Contexts = network_mount.autocomplete_Contexts
g.Questions = network_mount.Questions
g.Ideas = network_mount.Ideas
g.Problems = network_mount.Problems
g.Solutions = network_mount.Solutions
g.Comments = network_mount.Comments
g.Reviews = network_mount.Reviews
g.Resources = network_mount.Resources
else:
try:
cm = g.custom_mount
if cm.mountpoint!=session['connected']:
g.custom_mount = Mount(session['connected'])
except AttributeError:
g.custom_mount = Mount(session['connected'])
cm = g.custom_mount
g.client = cm.client
g.Contexts = cm.Contexts
g.Activities= cm.Activities
g.Projects = cm.Projects
g.autocomplete_Contexts = cm.autocomplete_Contexts
g.Questions = cm.Questions
g.Ideas = cm.Ideas
g.Problems = cm.Problems
g.Solutions = cm.Solutions
g.Comments = cm.Comments
g.Reviews = cm.Reviews
g.Resources = cm.Resources
@app.route('/')
def home():
return redirect(url_for('context_grid'))
@app.route('/_toggle_connect')
def toggle_connect():
if session.get('connected'):
session['connected'] = False
else:
session['connected'] = True
# Palette mount selector
if request.args.get('select')=='~':
session['connected'] = False
elif request.args.get('select')=='/':
session['connected'] = True
elif request.args.get('select'):
session['connected'] = request.args.get('select')
g.custom_mount = Mount(session['connected'])
return redirect(url_for('context_grid'))
@app.route('/context/icon/<context_guid>')
def gen_icon(context_guid):
type=request.args.get('type') or session['current_type']
offset=int(request.args.get('cursor_offset') or 0)
if offset and type:
if type in ['activity']:
context_cursor = g.Activities
elif type in ['project']:
context_cursor = g.Projects
else:
context_cursor = g.Contexts
context=context_cursor[offset]
else:
context=g.client.Context(context_guid)
def download(context):
with context.get_blob('icon') as icon:
if icon.closed:
icon=app.open_resource('static/icons/document-generic.png')
while True:
chunk = icon.read(_BUFFER_SIZE)
if not chunk:
break
yield chunk
header = Headers()
header.add("Content-Type", "image/png")
return Response(download(context), headers=header, direct_passthrough=True)
@app.route('/launch/<context_guid>')
def launch(context_guid):
g.client.launch(context_guid)
return redirect('/context/reviews/%s' % context_guid)
@app.route('/new/resource')
@app.route('/new/resource/<context_guid>')
def case_1(context_guid=None):
if not context_guid:
context_guid=session.get('last_context')
if not context_guid:
return redirect(url_for('context_grid'))
offset=int(request.args.get('cursor_offset') or 0)
if offset:
context=g.Contexts[offset]
else:
context=g.client.Context(context_guid, reply=['title', 'keep', 'keep_impl'])
return render_template('resource-form.html', context=context)
@app.route('/_report')
def report():
return render_template('report-form.html',
context=request.args.get('context') or '',
implementation=request.args.get('implementation') or '',
filename=request.args.get('filename') or '')
@app.route('/favorites')
def favorites():
if session.get('favorites-filter'):
session['favorites-filter']=False
else:
session['favorites-filter']=True
return redirect(url_for('context_grid'))
@app.route('/query')
def autocomplete_context():
query = "title:"+request.args.get('term')
r, total_pages, total, info = paginate(g.autocomplete_Contexts, query)
result = []
for item in r:
result.append( {'value':item['guid'],
'label':item['title']} )
return simplejson.dumps(result)
@app.route('/search/<query>')
def search(query=None):
return redirect(url_for('context_grid', query=query))
@app.route('/_tags/<tag>', methods=['DELETE'])
def del_tag(tag):
try:
session['tags'].pop(session['tags'].index(tag))
session.modified = True
except:
pass
return "True"
@app.route('/_tags', methods=['POST', 'GET'])
def tags():
hashtag = request.form['tag'][1:]
try:
session['tags'].append( hashtag )
session.modified = True
except KeyError:
session['tags'] = [hashtag, ]
return render_template_string(
"""{% for tag in tags %}
<span class="tag">{{tag}}</span>
{% endfor %}""",
tags=session['tags'])
@app.route('/_stars/<context>')
def stars(context=None):
if not context:
return jsonify()
guid = context[5:] #remove "stars-" from id
keep = request.args.get('keep')
context = g.client.Context(guid)
context['keep'] = (keep == 'true')
context.post()
# TODO Need to reset query object until supporting notifications
g.Contexts._reset()
return jsonify(keep=keep)
@app.route('/_moon/<context>')
def moon(context=None):
if not context:
return jsonify()
keep_impl = request.args.get('keep_impl', None)
guid = context[5:] #remove "moon-" from id
context = g.client.Context(guid)
context['keep_impl'] = 1 if keep_impl == 'true' else 0
context.post()
return jsonify(keep_impl=keep_impl)
def paginate(resource, full_query, _PAGE_SIZE=6, page=1, context=None):
""" This function attempts to query SN resources and
return a specific page of result items. """
r = []
resource.update_filter(full_query, context=context)
result=resource
page_offset = _PAGE_SIZE * (page - 1)
if page_offset>result.total:
raise KeyError
for i in range(page_offset, page_offset + _PAGE_SIZE):
try:
r.append(result[i])
except KeyError:
pass
total_pages = int(ceil(result.total / float(_PAGE_SIZE)))
if total_pages==0:
info = _(u'zero results')
else:
info = _(u'page %(page)s of %(total)s', page=page, total=total_pages)
if page > total_pages and total_pages > 0:
abort(404)
return r, total_pages, result.total, info
@app.route('/resource/search/')
@app.route('/resource/search/<query>')
@app.route('/resource/reviews')
@app.route('/resource/reviews/<query>')
@app.route('/resource/questions')
@app.route('/resource/questions/<query>')
@app.route('/resource/ideas')
@app.route('/resource/ideas/<query>')
@app.route('/resource/problems')
@app.route('/resource/problems/<query>')
@app.route('/resource')
def resource_list(query=None):
"""
Feedback Resource Browser (list)
"""
page=request.args.get('page')
if page:
page=int(page)
else:
return redirect(request.path + "?page=1")
if request.path=="/resource":
resource='all'
else:
resource=split(request.path, "/")[2]
if resource=='search':
resource = session.get('last_resource') or 'all'
if resource=='questions':
resource_object=g.Questions
resource_label=_("questions")
elif resource=='problems':
resource_object=g.Problems
resource_label=_("problems")
elif resource=='ideas':
resource_object=g.Ideas
resource_label=_("ideas")
elif resource=='reviews':
resource_object=g.Reviews
resource_label=_("reviews")
elif resource=='all':
resource_object=g.Resources
resource_label=_("resources")
resource='all_' # avoid chop
resource_type=resource[:-1]
session['last_resource']=resource
session.modified = True
try:
r, total_pages, total, info = paginate(resource_object,
query, page=page, _PAGE_SIZE=4)
except KeyError:
return redirect(url_for('resource_browser',
context_guid=context_guid, page=1))
meta=_("browsing %(total)s %(resource_label)s",
total=total, resource_label=resource_label)
if '_pjax' in request.args:
template='_resource-list.html'
else:
template='resource-list.html'
kwargs = {str(resource): 'button_selected'}
return render_template(template, query=query, resource=resource,
result=r, type='resource', page=page, info=info,
total_pages=total_pages, meta=meta, resource_view='true',
resource_type=resource_type, **kwargs)
@app.errorhandler(404)
def page_not_found(error):
template='browser-view.html'
return render_template(template, total=0, info=_('Error'), resource_type='context',
query='', total_pages=0, browser_view='true',
result=[], type='context', meta=_('Object not found.'), page=1)
@app.errorhandler(500)
def page_not_found(error):
template='browser-view.html'
return render_template(template, total=0, info=_('Error'), resource_type='context',
query='', total_pages=0, browser_view='true',
result=[], type='context', meta=_('Server error.'), page=1)
@app.route('/resource/contexts/<query>')
@app.route('/resource/contexts/')
@app.route('/context/search/')
@app.route('/context/search/<query>')
@app.route('/context')
def context_grid(query=None, page=None):
"""
Context Grid
"""
try:
page=int(request.args['page'])
session['page']=page
session.modified = True
except KeyError:
return redirect(url_for('context_grid',
type=request.args.get('type'),
query=query, page=session.get('page',1)))
#try:
# terms = session['tags'][:]
#except KeyError:
terms = []
type=request.args.get('type') or session.get('current_type')
if query:
terms.append(query)
type='all'
if type in ['activity']:
context_cursor = g.Activities
resource_label=_('activities')
elif type in ['project']:
context_cursor = g.Projects
resource_label=_('projects')
else: # type in [None, '', 'all']:
type='all'
context_cursor = g.Contexts
resource_label=_('contexts')
session['current_type']=type
full_query = join(terms, " AND ")
try:
r, total_pages, total, info = paginate(context_cursor, full_query, page=page)
except KeyError:
if '_pjax' in request.args:
return ''
else:
return redirect(url_for('context_grid',resource_type='context',
query=query, page=1))
meta = _("browsing %(total)s %(label)s", total=total, label=resource_label)
if '_pjax' in request.args:
template='_browser-grid.html'
else:
template='browser-view.html'
kwargs = {str(type): 'tab_selected button_selected'}
return render_template(template, total=total, meta=meta, resource_type='context',
query=query, total_pages=total_pages, browser_view='true',
result=r, type=type, info=info, page=page, **kwargs)
@app.route('/user/search/')
@app.route('/user/search/<query>')
@app.route('/user')
def users_grid(query=None):
"""
Users Grid
"""
result = g.client.User.cursor(query)
return render_template('users-grid.html',query=query,
result=result, type='user')
@app.route('/_comments/<resource_guid>', methods=['DELETE'])
def del_comment(resource_guid):
g.client.Comment.delete(resource_guid)
return "true"
@app.route('/_comments/<resource_guid>')
def comments_browser(resource_guid=None):
resource_type = request.args.get('resource_type')
g.Comments.filter(parent=resource_guid)
result = g.Comments
if not result:
result = []
return render_template('_context-comment-list.html',
result=result, resource_guid=resource_guid)
@app.route('/article/<context_guid>')
def project_browser(context_guid=None):
inner_template='_context-article-view.html'
if '_pjax' in request.args:
template=inner_template
context=None
else:
template='context-view.html'
context=g.client.Context(context_guid,
reply=['guid', 'title', 'description', 'author', 'summary', 'user', 'keep', 'keep_impl', 'type'])
try:
session['last_context_title']=context['title']
except RuntimeError:
abort(404)
session['last_context']=context['guid']
session.modified = True
return render_template(template, context=context,
inner_template=inner_template)
@app.route('/reload/<path:href>')
def reload(href=None):
g.Solutions._reset()
g.Comments._reset()
g.Contexts._reset()
g.Questions._reset()
g.Ideas._reset()
g.Resources._reset()
g.Reviews._reset()
return redirect(href)
@app.route('/context/reviews/<resource_guid>')
@app.route('/context/wikiwiki/<resource_guid>')
@app.route('/context/gallery/<resource_guid>')
@app.route('/review/<review_guid>')
def reviews_browser(resource_guid=None, review_guid=None):
if review_guid:
r = g.client.Review(guid=review_guid, reply=['context'])
resource_guid = r['context']
return redirect ('/context/reviews/'+resource_guid)
g.Reviews.filter(context=resource_guid, type='review')
inner_template='_context-review-list.html'
if '_pjax' in request.args:
template=inner_template
context=None
else:
template='context-view.html'
context=g.client.Context(resource_guid,
reply=['guid', 'title', 'description', 'author', 'summary', 'user', 'keep', 'keep_impl', 'type'])
try:
session['last_context_title']=context['title']
except RuntimeError:
abort(404)
session['last_context']=context['guid']
session.modified = True
kwargs = {'reviews':'button_selected'}
return render_template(template, context=context,
result=g.Reviews, inner_template=inner_template,
resource_label=_('reviews'),resource_type="review", **kwargs
)
@app.route('/question/<resource_guid>')
@app.route('/idea/<resource_guid>')
@app.route('/problem/<resource_guid>')
def solution_browser(resource_guid=None):
resource_type=split(request.path, "/")[1]
if resource_type=='question':
resource_cursor=g.Questions
resource_class=g.client.Question
elif resource_type=='problem':
resource_cursor=g.Problems
resource_class=g.client.Problem
elif resource_type=='idea':
resource_cursor=g.Ideas
resource_class=g.client.Idea
offset=int(request.args.get('cursor_offset') or 0)
if offset:
resource=resource_cursor[offset]
else:
resource=resource_class(resource_guid,
reply=['guid', 'title', 'content', 'author', 'user', 'context', 'tags', 'mtime', 'type'])
g.Solutions.filter(parent=resource['guid'])
inner_template='_context-solution-list.html'
if '_pjax' in request.args:
template=inner_template
context=None
else:
template='context-view.html'
context=g.client.Context(resource['context'],
reply=['guid', 'title', 'description', 'summary', 'author', 'keep', 'keep_impl', 'type'])
return render_template(template, context=context,
result=g.Solutions, inner_template=inner_template,
resource=resource, resource_type=resource_type,
cursor_offset=offset)
@app.route('/context/view/<context_guid>/<query>')
@app.route('/context/view/<context_guid>')
@app.route('/context/questions/<context_guid>')
@app.route('/context/ideas/<context_guid>')
@app.route('/context/problems/<context_guid>')
@app.route('/context/all/<context_guid>')
def resource_browser(context_guid=None, query=None):
"""
Context Resources View
"""
page=request.args.get('page')
if page:
page=int(page)
else:
return redirect(request.path + "?page=1")
resource_type=split(request.path, "/")[2][:-1]
if resource_type=='question':
resource_object = g.Questions
resource_label = _("questions")
elif resource_type=='problem':
resource_object = g.Problems
resource_label = _("problems")
elif resource_type=='idea':
resource_object = g.Ideas
resource_label = _("ideas")
elif resource_type=='al':
resource_object = g.Resources
resource_label = _("resources")
resource_type='all'
try:
r, total_pages, total, info = paginate(resource_object,
query, page=page, _PAGE_SIZE=4, context=context_guid)
except KeyError:
return redirect(url_for('resource_browser',
context_guid=context_guid, page=1))
meta=_("browsing %(total)s %(resource_label)s",
total=total, resource_label=resource_label)
offset=int(request.args.get('cursor_offset') or 0)
if offset:
context=resource_cursor[offset]
else:
context=g.client.Context(context_guid, reply=['guid', 'title', 'author', 'summary', 'description', 'keep', 'keep_impl', 'type'])
try:
session['last_context']=context['guid']
session['last_context_title']=context['title']
session.modified = True
except RuntimeError:
abort(404)
stroke, fill = get_colors()
if '_pjax' in request.args:
template='_context-resource-list.html'
_pjax=True
else:
template='context-view.html'
_pjax=False
kwargs = {str(resource_type) + 's': 'button_selected'}
return render_template(template, result=r,
total_pages=total_pages, info=info, meta=meta,
resource_label=resource_label, stroke=stroke,
resource_type=resource_type, context=context,
page=page, fill=fill, _pjax=_pjax, **kwargs)
@app.route('/submit_edit', methods=['POST'])
def edit_resource():
resource_type = request.form['resource_type']
resource_guid = request.form['edit_guid']
if resource_type=='question':
resource = g.client.Question(resource_guid)
resource_cursor = g.Questions
elif resource_type=='idea':
resource = g.client.Idea(resource_guid)
resource_cursor = g.Ideas
elif resource_type=='problem':
resource = g.client.Problem(resource_guid)
resource_cursor = g.Problems
elif resource_type=='review':
resource = g.client.Review(resource_guid)
resource_cursor = g.Reviews
elif resource_type=='solution':
resource = g.client.Solution(resource_guid)
resource_cursor = g.Solutions
if request.form.get('title'):
resource['title']=request.form['title']
if request.form.get('content'):
resource['content']=request.form['content']
try:
resource.post()
except NotFound:
abort(500)
resource_cursor._reset()
return redirect(request.form.get('href'))
@app.route('/submit_resource/<resource_type>', methods=['POST'])
def new_resource(resource_type):
if resource_type=='question':
resource = g.client.Question()
resource_cursor = g.Questions
elif resource_type=='idea':
resource = g.client.Idea()
resource_cursor = g.Ideas
elif resource_type=='problem':
resource = g.client.Problem()
resource_cursor = g.Problems
resource['content'] = request.form['content']
resource['title'] = request.form['title']
resource['context'] = request.form['guid']
resource['type'] = resource_type
if resource['title']:
resource.post()
resource_cursor._reset()
return redirect('/context/%ss/%s' % (resource_type, resource['context']))
@app.route('/update_context', methods=['POST'])
def update_context():
context=g.client.Context(request.form['edit_guid'])
context['title'] = request.form['title']
context['summary'] = request.form['summary']
context['description'] = request.form['content']
if context['title'] and context['description'] and context['summary']:
context.post()
return redirect('/article/%s' % request.form['edit_guid'])
@app.route('/submit_context', methods=['POST'])
def new_context():
context=g.client.Context()
context['type'] = ['project']
context['title'] = request.form['title']
context['summary'] = request.form['summary']
context['description'] = request.form['content']
if context['title'] and context['description'] and context['summary']:
context.post()
g.Contexts._reset()
return redirect(url_for('context_grid', page=1, type='project'))
@app.route('/submit_solution', methods=['POST'])
def new_solution():
solution=g.client.Solution()
solution['content'] = request.form['solution']
solution['parent'] = request.form['resource_guid']
solution['parent_resource'] = request.form['resource_type']
if solution['content']:
solution.post()
g.Solutions._reset()
return redirect('/%s/%s' % (solution['parent_resource'], solution['parent']))
@app.route('/submit_review', methods=['POST'])
def new_review():
review=g.client.Review()
review['content'] = request.form['review']
review['title'] = ''
review['type'] = 'review'
context = review['context'] = request.form['resource_guid']
if review['content']:
review.post()
g.Reviews._reset()
return redirect('/context/reviews/%s' % context)
@app.route('/submit_report', methods=['POST'])
def new_report():
report = g.client.Report()
report['context'] = request.form['context']
report['implementation'] = request.form['implementation']
report['description'] = request.form['content']
report.post()
filename = request.form.get('filename')
if filename:
report.upload_blob('data', filename)
return redirect('/resource/problems')
@app.route('/submit_comment', methods=['POST'])
def new_comment():
comment=g.client.Comment()
comment['message'] = request.form['comment']
comment['parent'] = request.form['resource_guid']
comment['parent_resource'] = request.form['resource_type']
if comment['message']:
comment.post()
g.Comments._reset()
return redirect('_comments/%s?resource_type=%s' %
(comment['parent'], comment['parent_resource']) )
@app.route('/_events/comment')
@app.route('/_events/solution')
def event_comment():
resource_type=split(request.path, "/")[2]
if resource_type=='comment':
cursor = g.Comments
elif resource_type=='solution':
cursor = g.Solutions
def feed():
for i in cursor.read_events():
yield 'data: %s\n\n' % i
return Response(feed(), mimetype='text/event-stream',
direct_passthrough=True)
@app.route('/_events/network')
def event_network():
def feed():
while True:
gevent.sleep(1)
for i in g.Solutions.read_events():
yield 'data: %s\n\n' % i
return Response(feed(), mimetype='text/event-stream',
direct_passthrough=True)
@app.route('/_shutdown')
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
return 'Goodbye'
@app.route('/_debug')
def debug():
raise Warning('All your base are belong to us.')
return 'Take off every Zig'
if __name__=="__main__":
host = '0.0.0.0' #'0.0.0.0' for all
try:
port=int(sys.argv[1])
except IndexError:
port=5000
app.debug = True
from gevent.wsgi import WSGIServer
http_server = WSGIServer((host, port), app)
http_server.serve_forever()
#app.run(host=host, port=port)
|