forked from phynfo/LiquidDemocracy-XXS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliquidDemocracyLight.py
More file actions
907 lines (822 loc) · 36.4 KB
/
liquidDemocracyLight.py
File metadata and controls
907 lines (822 loc) · 36.4 KB
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
from flask import Flask, session, render_template, request, redirect, url_for, escape, flash, g, abort, jsonify
from model import Graph
from datetime import datetime
from utils import date_diff
from collections import deque
import werkzeug
import thread
import re
import operator
import time
import math
# configuration
DATABASE = 'graphdatabase'
DEBUG = True
SECRET_KEY = 'blubber'
USERNAME = 'tobias'
PASSWORD = 'bla'
ADMIN = 'admin'
app = Flask(__name__)
app.config.from_object(__name__)
db = Graph()
@app.template_filter('parlamentTitle')
def parlamentTitle(eid):
return db.parlaments.get(eid).title
@app.template_filter('getParlaments')
def getParlaments(eid):
v = db.vertices.get(eid)
if v.element_type == 'instance':
ps = [p for p in v.outV('instanceHasParlament')]
elif v.element_type == 'proposal':
ps = [p for p in v.outV('proposalHasParlament')]
#TODO eid in die dicts mit einfuegen!
ds = []
for p in ps:
d = p.data()
d['eid'] = p.eid
ds.append(d)
return ds
@app.template_filter('getPeople')
def getPeople(eid):
''' returns all people of the Instance eid '''
q = '''START i=node({i_eid})
MATCH i-[:hasPeople]->p
RETURN ID(p), p.username
'''
people = db.cypher.table(q,dict(i_eid=eid))[1] # Fetch the people from neo4j ...
peopleDict = [dict(p_eid = p[0],
username = p[1])
for p in people]
return peopleDict
@app.template_filter('getProposals')
def getProposals(eid):
''' returns all proposals of the Instance eid'''
q = '''START i=node({i_eid})
MATCH i-[:hasProposal]->pr
RETURN ID(pr), pr.title
'''
proposals = db.cypher.table(q,dict(i_eid=eid))[1] # Fetch the propsals from neo4j ...
proposalDict = [dict(p_eid = p[0],
title = p[1])
for p in proposals]
return proposalDict
@app.template_filter('getGrantedDelegations')
def getGrantedDelegations(eid):
q='''START i=node({userID}) MATCH i - [:personDelegation] -> hyperEdge ,
hyperEdge-[:delegationPerson]->person,hyperEdge -[r?:delegationProposal|delegationParlament]->type,
instance -[:instanceHasDelegation] -> hyperEdge
WHERE ID(instance) ={i_eid}
RETURN ID(hyperEdge),hyperEdge.datetime_created,ID(person), person.username,TYPE(r),ID(type),type.title'''
delegations = db.cypher.table(q,dict(i_eid=eid, userID=session['userId']))[1]
delegationsDict = [dict(delegationID=p[0],
delegationCreated = date_diff(datetime.utcfromtimestamp(p[1]), datetime.today()),
username = p[3],
p_eid = p[2],
delegationtype=p[4],
typeID=p[5],
title=p[6]
)
for p in delegations]
return delegationsDict
@app.template_filter('getReceivedDelegations')
def getReceivedDelegations(eid):
q='''START i=node({userID}) MATCH i <- [:delegationPerson] - hyperEdge ,
hyperEdge<-[:personDelegation]-person,hyperEdge -[r?:delegationProposal|delegationParlament]->type,
instance -[:instanceHasDelegation] -> hyperEdge
WHERE ID(instance) ={i_eid}
RETURN ID(hyperEdge),hyperEdge.datetime_created,ID(person), person.username,TYPE(r),ID(type),type.title'''
delegations = db.cypher.table(q,dict(i_eid=eid, userID=session['userId']))[1]
delegationsDict = [dict(delegationID=p[0],
delegationCreated = date_diff(datetime.utcfromtimestamp(p[1]), datetime.today()),
username = p[3],
p_eid = p[2],
delegationtype=p[4],
typeID=p[5],
title=p[6]
)
for p in delegations]
return delegationsDict
@app.template_filter('person2proposals')
def person2proposals(p_eid):
''' all proposals of a given person p_eid in a given instance g.i_eid in descending
order, i.e. props[1] contains the newest proposal, props[-1] contains the oldest proposal.
'''
q = '''START p=node({peid}), inst=node({ieid})
MATCH p-[i:issued]->pr<-[:hasProposal]-inst
WHERE pr.element_type="proposal"
RETURN ID(pr), pr.title, pr.datetime_created ORDER BY pr.datetime_created DESC
'''
props = db.cypher.table(q,dict(peid=p_eid, ieid=g.i_eid))[1] # Fetch the proposals from neo4j ...
propsDict = [dict(created = date_diff(datetime.utcfromtimestamp(p[2]), datetime.today()),
title = p[1],
p_eid = p[0])
for p in props] # ... and create a dict-object ...
return propsDict # ... and return it.
@app.template_filter('person2comments')
def person2comments(p_eid):
''' all comments of a given person p_eid in a given instance g.i_eid in descending
order, i.e. comments[1] contains the newest comment, comments[-1] contains the oldest comment.
'''
q = '''START p=node({peid}), inst=node({ieid})
MATCH p-[i:issuesComment]->co<-[:hasComment]-pr<-[:hasProposal]-inst
WHERE co.element_type="comment"
RETURN ID(co), co.title, co.datetime_created, ID(pr) ORDER BY co.datetime_created DESC
'''
comments = db.cypher.table(q,dict(peid=p_eid, ieid=g.i_eid))[1] # Fetch the comments from neo4j ...
commentsDict = [dict(created = date_diff(datetime.utcfromtimestamp(c[2]), datetime.today()),
title = c[1],
c_eid = c[0],
p_eid = c[3])
for c in comments] # ... and create a dict-object ...
return commentsDict # ... and return it.
@app.template_filter('person2votesProposals')
def person2votesProposals(p_eid):
''' all proposals votings of a given person p_eid in a given instance g.i_eid in temporal descending
order, i.e. propVotes[0] contains the latest vote, propVotes[-1] contains the oldest vote.
'''
q = '''START p=node({peid}), inst=node({ieid})
MATCH p-[v:votes]->pr<-[:hasProposal]-inst
WHERE pr.element_type="proposal"
RETURN v.created, v.pro, pr.title, ID(pr) ORDER BY v.created DESC '''
propVotes = db.cypher.table(q,dict(peid=p_eid, ieid=g.i_eid))[1] # Fetch the votes from neo4j ...
propVotesDict = [dict(created = date_diff(datetime.utcfromtimestamp(p[0]), datetime.today()),
pro = p[1],
title = p[2],
p_eid = p[3])
for p in propVotes] # ... and create a dict-object ...
return propVotesDict # ... and return it.
@app.template_filter('person2votesComments')
def person2votesComments(p_eid):
''' all comments votings of a given person p_eid in a given instance g.i_eid in temporal descending
order, i.e. coVotes[0] contains the latest vote, copVotes[-1] contains the oldest vote.
'''
q = '''START p=node({peid}), inst=node({ieid})
MATCH p-[v:votes]->co<-[:hasComment]-pr<-[:hasProposal]-inst
WHERE co.element_type="comment"
RETURN v.created, v.pro, co.title, ID(co), ID(pr) ORDER BY v.created DESC '''
coVotes = db.cypher.table(q,dict(peid=p_eid, ieid=g.i_eid))[1] # Fetch the votes from neo4j ...
coVotesDict = [dict(created = date_diff(datetime.utcfromtimestamp(c[0]), datetime.today()),
pro = c[1],
title = c[2],
c_eid = c[3],
p_eid = c[4])
for c in coVotes] # ... and create a dict-object ...
return coVotesDict # ... and return it.
@app.template_filter('iconize')
def compact(s):
''' return the first few words of the text s in order to produce
a short description of an entry's or comment's text '''
if len(s)<=200: return s
s=s[:200]
s2 = filter(lambda c: c!='\n', s)
m = re.match(r".*\s", s2)
return s2 if not m else s2[:m.end()] + ' ... '
@app.template_filter('i_eid2title')
def eid2title(i_eid):
instance = db.instances.get(i_eid)
return instance.title
@app.url_defaults
def add_i_eid(endpoint, values):
if 'i_eid' in values or not g.i_eid:
return
if app.url_map.is_endpoint_expecting(endpoint, 'i_eid'):
values['i_eid'] = g.i_eid
@app.url_value_preprocessor
def pull_i_eid(endpoint, values):
if values:
g.i_eid = values.pop('i_eid', None)
else:
g.i_eid = None
def data(p):
d = p.data()
d['eid'] = p.eid
return d
def issuer(eid):
''' Returns the User(s) which issued the Proposal with eid "eId" '''
if db.vertices.get(eid).element_type=='proposal':
return [e.outV() for e in db.vertices.get(eid).inE('issued') ]
elif db.vertices.get(eid).element_type=='comment':
return [e.outV() for e in db.vertices.get(eid).inE('issuesComment')]
def countVotes(propId):
''' Calculates the votes count '''
return countVotesUp(propId) - countVotesDown(propId)
def countVotesDown(eid):
''' Calculates the votes "down" '''
v = db.vertices.get(eid)
return sum([ -1 for voteRel in v.inE('votes') if voteRel.pro==0])
def countVotesUp(eid):
''' Calculates the votes "up" '''
v = db.vertices.get(eid)
return sum([1 for voteRel in v.inE('votes') if voteRel.pro==1])
def proposalsByVotes(i_eid):
''' Sorts proposals of a specific instance by vote-count '''
instance = db.instances.get(i_eid)
proposals = instance.outV('hasProposal')
return sorted(proposals, key=lambda p:len(list(p.inE('votes'))), reverse=True)
def commentsByVotes(prop_id):
''' Sorts proposals by vote-count '''
comments = db.comments.get(prop_id).outV('hasComment')
return sorted(comments, key=lambda c:len(list(c.inE('votesComment'))), reverse=True)
def v2Dict(eid, loggedUserEid=None):
''' v = proposal OR comment
The resulting dict-Object d collects
- the person which issued the proposal/comment,
- the vote-counts
- the creation date '''
v = db.vertices.get(eid)
d = dict(title = v.title, body=v.body, eid=eid, ups=v.ups, downs=v.downs)
users = issuer(eid)
d['username'] = users[0].username if users else None
d['userid'] = users[0].eid if users else None
d['voteCountUp'] = countVotesUp(eid)
d['voteCountDown'] = countVotesDown(eid)
d['created'] = date_diff(v.datetime_created, datetime.today())
if loggedUserEid:
loggedUser = db.people.get(loggedUserEid)
votes = [voteEdge for voteEdge in loggedUser.outE('votes') if voteEdge.inV() == v]
if votes:
d['upvoted'] = (votes[0].pro == 1)
d['downvoted'] = (votes[0].pro == 0)
return d
def i2Dict(i_eid, loggedUserEid=None):
''' i_eid = instance
Collects information about an instance:
title, body, created, numberUsers, numberVotes, numberProposals, numberComments'''
instance = db.instances.get(i_eid)
d = dict(title=instance.title, body=instance.body, eid=i_eid)
d['created'] = date_diff(instance.datetime_created, datetime.today())
d['numberUsers'] = len(list(instance.outV('hasPeople')))
proposals = list(instance.outV('hasProposal'))
d['numberProposals'] = len(proposals)
d['numberVotes'] = sum([len(list(p.inE('votes'))) for p in proposals])
d['numberComments'] = sum([len(list(p.outE('hasComment'))) for p in proposals])
# Alternatively, the following Cypher-Query could be used:
# q = '''START i=node({i_eid})
# MATCH i-[:hasProposal]->p-[:hasComment]->c
# RETURN count(c)'''
# d['numberComments'] = db.cypher.table(q,dict(i_eid=i_eid))[1][0][0]
return d
def person2Dict(person):
p = person.data()
p['eid'] = person.eid
return p
#delegationProposal -> priorltaet 1
#delegationParlament -> prioritaet 2
#nur delegationPerson -> prioritaet 3
def countVotingWeight(personID,proposalID,i_eid,commentid=None):
'''Zaehlt das Stimmgewicht der uebergebenen Person bei dem uerbegebenen Vorschlag.
Die child_list enthaelt am schluss alle ids der gezaehlten Stimmen.
'''
db=Graph()
#Liste welche die eid jeder gueltigen Person(Stimme) enthaelt
child_list=[personID]
#Alle eids welche beim uebergebenen proposalID bereits selbst gevotet haben(pfad der delegation endet dann)
if commentid is not None:
votes=[p.eid for p in db.proposals.get(commentid).inV('votes')]
else:
votes=[p.eid for p in db.proposals.get(proposalID).inV('votes')]
#Stack der zu zu durchlaufenden nodes, wird erweitert in der Schleife
to_crawl=deque(list(db.vertices.get(personID).inV("delegationPerson")))
while to_crawl:
node = to_crawl.popleft()
if node.element_type=='delegation' and node.inV('instanceHasDelegation').next().eid==i_eid:
#Wenn delegation zu einem Proposal zeigt und dieses auch noch passende Id hat.
#In meiner ueberlegung die hoechste Prioritaet.
valid=False
delegatorID=node.inV('personDelegation').next()
if node.delegation_type=='proposal' and node.outV('delegationProposal').next().eid == proposalID:
valid=True
#Hat ein andere User eine delegation bekommen welche direkt zum Proposal geht?
elif not hasPropopsalDelegation(delegatorID.eid,proposalID):
#Handelt es sich um eine Delegation fuer ein Parlament?
if node.delegation_type=='parlament':
#Hat das Proposal mehrere Delegationen(Parlament) vom Benutzer?Dann gilt die zuletzt angelegte.
parlamentDelegations=[d for d in node.inV('personDelegation').next().outV('personDelegation') for i in d.outV('delegationParlament') if i in db.proposals.get(proposalID).outV('proposalHasParlament')]
parlamentDelegations.sort(key=lambda r: r.datetime_created,reverse=True)
if not parlamentDelegations==[] and node == parlamentDelegations[0]:
valid=True
elif node.delegation_type=='all' and not hasParlamentDelegation(delegatorID.eid,proposalID):
valid=True
if valid:
if not delegatorID.eid in votes:
if not delegatorID.eid in child_list:
child_list.append(delegatorID.eid)
to_crawl.extend(list(delegatorID.inV('delegationPerson')))
return child_list
def hasPropopsalDelegation(user,proposal):
db=Graph()
q='''START i=node({userid}) MATCH i-[:personDelegation] ->d-[:delegationProposal]->p
RETURN ID(p)'''
dele=db.cypher.table(q,dict(userid=user,proposalid=proposal))[1]
if any(p[0] == proposal for p in dele):
return True
else:
return False
def hasParlamentDelegation(user,proposal):
db=Graph()
q='''START i=node({proposalid}),u=node({userid})
MATCH i-[:proposalHasParlament]->p<-[:delegationParlament|personDelegation*2]-u
RETURN ID(p)'''
dele=db.cypher.table(q,dict(userid=user,proposalid=proposal))[1]
if any(p for p in dele):
return True
else:
return False
def affectedVotes():
'''ueberprueft bei welchen Proposals das Voting neu berechent werden muss beim anlegen oder loeschen einer delegation.
Beim erstellen:delegation erst erstellen dann Voting neu berechnen'''
db=Graph()
q= '''START i=node({userid})
MATCH i-[:personDelegation*]->x-[:delegationPerson|personDelegation|votes*] ->p
WHERE (p.element_type="proposal" or p.element_type="comment") RETURN distinct ID(p)
'''
affected = db.cypher.table(q,dict(userid=session['userId']))[1]
if affected != []:
return reduce(operator.add, affected )#TODO Crahs wenn keine delegation bestehen??
else:
return []
def recalculateAffectedProposals(result,i_eid):
'''Berechnet die uebergebenden Proposals neu'''
db=Graph()
for p in result:
qHasDelegation='''START i=node({proposalid}) MATCH p-[r:votes]->i ,d-[?:delegationPerson]->p WHERE NOT(ID(d) is null) RETURN distinct ID(p) AS voterID,r.pro as pro'''
qVoteOnly='''START i=node({proposalid}) MATCH p-[r:votes]->i ,d-[?:delegationPerson]->p WHERE (ID(d) is null) RETURN count(distinct ID(p)) AS voterCount,r.pro AS pro'''
q='''START i=node({proposalid}) MATCH p-[r:votes]->i RETURN ID(p) AS voterID,r.pro AS pro'''
delegatedVotes=db.cypher.table(qHasDelegation,dict(proposalid=p))[1]
singleVotes=db.cypher.table(qVoteOnly,dict(proposalid=p))[1]
downs=0
ups=0
commentID = None
if db.proposals.get(p).element_type == 'comment':
commentID = db.proposals.get(p).eid
countId=db.proposals.get(p).inV('hasComment').next().eid
else:
countId=p
for v in delegatedVotes:
if v[1]==1:
ups+=len(countVotingWeight(v[0],countId,i_eid,commentID))
elif v[1]==0:
downs+=len(countVotingWeight(v[0],countId,i_eid,commentID))
for v in singleVotes:
if v[1]==1:
ups+=v[0]
elif v[1]==0:
downs+=v[0]
c_p=db.vertices.get(p)
c_p.ups=ups
c_p.downs=downs
c_p.save()
return result
#-------------------- The view functions ----------------------------------------
# * Instances
# - show_instances, add_instance
# * Proposals
# - show_proposal , show_single_proposal, add_proposal, delete_proposal
# * Comments
# - add_comment
# * Votes
# - vote
# * People
# - login, logout, signin, login_instance
# - show_person, show_people
# -------------------------------------------------------------------------------
@app.route('/')
def show_instances():
user = db.people.get(session['userId']) if session.get('logged_in') else None
if user and not session['isAdmin']:
instances = [i2Dict(i.eid, user) for i in db.instances.get_all() if user in i.outV('hasPeople')]
else:
instances = [i2Dict(i.eid) for i in db.instances.get_all()]
return render_template('show_instances.html', instances=instances)
@app.route('/addinstance', methods=['POST'])
def add_instance():
if not (session.get('logged_in') and session['isAdmin']):
abort(401)
instance = db.instances.create(title=request.form['title'], body=request.form['body'])
flash('Neue Instanz haette angelegt werden muessen')
return redirect(url_for('show_instances'))
@app.route('/<int:i_eid>/proposals')
def show_proposals():
page=request.args.get('page',1,type=int)
orderP=request.args.get('sort',"upsdesc",type=str)
filterP=request.args.get('filter',"all",type=str)
searchP=request.args.get('search',"",type=str)
userEid = db.people.get(session['userId']).eid if session.get('logged_in') else None
propPerPage = 10.
proposalCount = float(countProposals(filterP,g.i_eid,userEid))
pagesCount = int(math.ceil(proposalCount/propPerPage))
limit = propPerPage*page
skip = propPerPage*page - propPerPage
proposals = []
instance = db.instances.get(g.i_eid)
for proposal in orderedProposals(orderP,filterP,g.i_eid,userEid,searchP,int(skip),int(limit)):
p = v2Dict(proposal.eid, loggedUserEid=userEid)
proposals.append(p)
return render_template('show_proposals.html', entries=proposals,navigation=dict(currentPage=page,pagessum=pagesCount,sort=orderP,filter=filterP,search=searchP))
def countProposals(filterP,instanceID,userEid):
if userEid is not None:
if filterP == 'all':
match = 'MATCH i-[:hasProposal]->p'
elif filterP == 'ownprop':
match = 'MATCH i-[:hasProposal]->p<-[:issued]-u'
elif filterP == 'votedprop':
match = 'MATCH i-[:hasProposal]->p<-[:votes]-u'
q = '''START i=node({ieid}),u=node({user}) '''+match+''' RETURN count(p)'''
else:
q = '''START i=node({ieid}) MATCH i-[:hasProposal]->p RETURN count(p)'''
numProposals=db.cypher.table(q,dict(ieid=instanceID,user=userEid))[1]
if len(numProposals) == 1:
return numProposals[0][0]
else:
return 0
def orderedProposals(orderP,filterP,instanceID,userEid,searchstring,lower=None,upper=None):
if userEid is not None:
start='''START i=node({ieid}),u=node({user}) '''
else:
filterP='all'
start='''START i=node({ieid}) '''
if filterP == 'all':
match = 'MATCH i-[:hasProposal]->p'
elif filterP == 'ownprop':
match = 'MATCH i-[:hasProposal]->p<-[:issued]-u'
elif filterP == 'votedprop':
match = 'MATCH i-[:hasProposal]->p<-[:votes]-u'
if searchstring != '':
searchstring="(?i).*"+searchstring+".*"
where= ' WHERE p.title =~ {search} OR p.body =~ {search}'
else:
where=''
if orderP == 'upsdesc':
ret=''' RETURN p ORDER BY p.ups DESC'''
elif orderP == 'upsasc':
ret=''' RETURN p ORDER BY p.ups'''
elif orderP == 'downsdesc':
ret=''' RETURN p ORDER BY p.downs DESC'''
elif orderP == 'downsasc':
ret=''' RETURN p ORDER BY p.downs'''
elif orderP == 'newest':
ret=''' RETURN p ORDER BY p.datetime_created DESC'''
elif orderP == 'oldest':
ret=''' RETURN p ORDER BY p.datetime_created'''
q=start+match+where+ret
if not lower is None and not upper is None:
q = q + ' SKIP {lower} LIMIT {upper}'
proposals=db.cypher.query(q,dict(lower=lower,upper=upper,ieid=instanceID,user=userEid,search=searchstring))
return proposals
@app.route('/<int:i_eid>/proposal/<int:prop_id>')
def show_single_proposal(prop_id):
userEid = db.people.get(session['userId']).eid if session.get('logged_in') else None
proposal = v2Dict(prop_id, loggedUserEid=userEid)
comments = []
for comment in commentsByVotes(prop_id):
c = v2Dict(comment.eid, loggedUserEid=userEid)
comments.append(c)
return render_template('show_single_proposal.html', proposal=proposal, comments=comments)
@app.route('/<int:i_eid>/addproposal',methods=['POST'])
def add_proposal():
if not session.get('logged_in'):
abort(401)
prop = db.proposals.create(title=request.form['title'], body=request.form['body'], ups=0, downs=0)
if 'parlament' in request.form:
for parl in request.form.getlist('parlament'):
p = list(db.parlaments.index.lookup(title=parl))
if p:
db.proposalHasParlament.create(prop,p[0])
instance = db.instances.get(g.i_eid)
user = db.people.get(session['userId'])
db.issued.create(user,prop) # Edge1: User issues Proposal
db.hasProposal.create(instance, prop) # Edge2: Proposal belongs to current Instance
flash('Neuer Eintrag erfolgreich erstellt')
return redirect(url_for('show_proposals'))
@app.route('/<int:i_eid>/deleteproposal/<int:prop_id>')
def delete_proposal(prop_id):
proposal = db.proposals.get(prop_id)
if not session.get('logged_in') or session['userId'] != proposal.inV('issued').next().eid :
abort(401)
#Delete proposal delegations
for d in proposal.inV('delegationProposal'):
db.delegations.delete(d.eid)
resp = db.proposals.delete(prop_id)
flash('Eintrag geloescht')
return redirect(url_for('show_proposals'))
@app.route('/<int:i_eid>/addcomment/<int:prop_id>',methods=['POST'])
def add_comment(prop_id):
if not session.get('logged_in'):
abort(401)
comment = db.comments.create(title=request.form['title'], body=request.form['body'], ups=0, downs=0)
user = db.people.get(session['userId'])
db.issuesComment.create(user,comment)
db.hasComment.create(db.proposals.get(prop_id), comment)
flash('Neuer Kommentar erfolgreich erstellt')
return redirect(url_for('show_single_proposal', prop_id=prop_id))
@app.route('/_vote')
def vote():
''' Voting a proposoal or comment with Id eid. Upvote means pro==1, Downvote means pro==0'''
if not session.get('logged_in'):
abort(401)
pro=request.args.get('pro',0,type=int)
eid=request.args.get('eid',0,type=int)
voted=0
loggedUser = db.people.get(session['userId'])
c_p = db.vertices.get(eid) # c_p is a comment or a proposal
voteRels = [rel for rel in loggedUser.outE('votes') if rel.inV() == c_p]
if voteRels and voteRels[0].pro!=pro: # i.e.: user undoes vote => delete Edge
db.votes.delete(voteRels[0].eid)
votingAction=0
if voteRels and voteRels[0].pro==pro: # i.e.: Voting up/down a second time is not allowed.
abort(401)
if not voteRels: # i.e.: No "votes"-edge exists => create new "votes"-Edge
db.votes.create(loggedUser,c_p, pro=pro)
voted=1
votingAction = -1 if pro == 0 else 1
#Komplettes Voting nur dann neu berechnen wenn andere Votings betroffen sind oder Delegationen bestehen.
q='''START i=node({userid})
MATCH i-[:personDelegation|delegationPerson|votes*2..]->e
WHERE (ID(e)={proposalid})
RETURN distinct id(e)'''
outd = db.cypher.table(q,dict(userid=session['userId'],proposalid=eid))[1]
if len(outd) >=1 or len(list(loggedUser.inV('delegationPerson'))) >=1:
if c_p.element_type=='comment':
recalculateAffectedProposals([eid],c_p.inV('hasComment').next().inV('hasProposal').next().eid)
else:
recalculateAffectedProposals([eid],c_p.inV('hasProposal').next().eid)
c_p = db.vertices.get(eid)
else:
if pro==1:
if votingAction==0:
c_p.downs-=1
else:
c_p.ups+=1
elif pro==0:
if votingAction==0:
c_p.ups-=1
else:
c_p.downs+=1
c_p.save()
returnList = [
{'ups': c_p.ups, 'downs': c_p.downs,'voted':voted},
]
return jsonify(results = returnList)
@app.route('/<int:i_eid>/login',methods=['POST','GET'])
def login_instance():
error = None
if request.method == 'POST':
username = request.form['username'] ; password = request.form['password']
instance = db.instances.get(g.i_eid)
users = [u for u in db.people.index.lookup(username=username) if u in instance.outV('hasPeople')]
if users and users[0].password==password:
session['logged_in'] = True
session['userId'] = users[0].eid ; session['username'] = users[0].username
session['isAdmin'] = users[0].username==app.config['USERNAME']
s = "Du hast Dich in Instanz %s eingeloggt" % instance.title
flash(s)
return redirect(url_for('show_proposals'))
elif not users:
error = 'Ungueltiger Benutzername'
else:
error = 'Ungueltiges Passwort'
return render_template('login.html', instances=None, error=error)
@app.route('/login', methods=['POST','GET'])
def login():
error = None
if request.method == 'POST':
username = request.form['username'] ; password = request.form['password'] ; instancetitle = request.form['instancetitle']
instance = db.instances.index.lookup(title=instancetitle).next()
users = [u for u in db.people.index.lookup(username=username) if u in instance.outV('hasPeople')]
if users and users[0].password==password:
session['logged_in'] = True
session['userId'] = users[0].eid ; session['username'] = users[0].username
session['isAdmin'] = users[0].username==app.config['USERNAME']
s = "Du hast Dich in Instanz %s eingeloggt" % instancetitle
flash(s)
return redirect(url_for('show_proposals', i_eid=instance.eid))
elif not users:
error = 'Ungueltiger Benutzername fuer Instanz %s' % instancetitle
else:
error = 'Ungueltiges Passwort'
return render_template('login.html', i_eid=None, instances = [dict(title=i.title) for i in db.instances.get_all()], error=error)
@app.route('/<int:i_eid>/logout')
def logout():
''' Deletes the cookies and redirects to show_instances'''
session.pop('logged_in', None)
session.pop('userId',None)
session.pop('username',None)
session.pop('isAdmin',None)
flash('Du hast Dich ausgeloggt')
return redirect(url_for('show_instances'))
@app.route('/<int:i_eid>/signin', methods=['POST', 'GET'])
def signin():
''' There are two cases:
1. A new user is created in the current instance
2. An existing user is associated with the current instance '''
error = None
if request.method == 'POST':
if 'username' in request.form:
username = request.form['username'] ; pass1 = request.form['password1'] ; pass2 = request.form['password2']
email = request.form['email'] ; vorname = request.form['vorname'] ; nachname = request.form['nachname']
users = [p for p in db.people.index.lookup(username=username)]
if users: #Benutzername schon vorhanden?
error = 'Benutzername existiert schon'
elif pass1!=pass2:
error = 'Passwort nochmals eingeben!'
elif not (email and vorname and nachname and username):
error = 'Eingabedaten unvollstaendig!'
else:
instance = db.instances.get(g.i_eid)
user = db.people.create(firstname=vorname, secondname=nachname, username=username, password=pass1, email=email)
db.hasPeople.create(instance, user)
flash('Benutzer erfolgreich angelegt')
return redirect(url_for('login_instance'))
if 'username1' in request.form:
username = request.form['username1']
passw = request.form['password']
# does username alread exist?
users = list(db.people.index.lookup(username=username))
if not users:
flash('Der angegebene Benutzername existiert aber noch nicht')
return redirect(url_for('signin'))
else:
user = users[0]
if user.password != passw:
flash('Password war falsch')
return redirect(url_for('signin'))
else:
instance = db.instances.get(g.i_eid)
db.hasPeople.create(instance, user)
flash('Benutzer erfolgreich zur Instanz hinzugefgt')
return redirect(url_for('login_instance'))
return render_template('signin.html', error=error)
@app.route('/<int:i_eid>/logoutLogin/<int:p_eid>')
def logoutLogin(p_eid):
''' Wird ein User geklickt, so wird automatisch versucht, den aktuellen Benutzer auszuloggen und
mit dem neuen Benutzer einzuloggen '''
if session.get('logged_in'):
flash('Du hast Dich ausgeloggt')
session.pop('logged_in', None)
session.pop('userId',None)
session.pop('username',None)
session.pop('isAdmin',None)
session['userId']=p_eid
session['username']=db.people.get(p_eid).username
return redirect(url_for('login_instance'))
@app.route('/<int:i_eid>/person/<int:p_eid>')
def show_person(p_eid):
if not session.get('logged_in'):
abort(401)
person = db.people.get(p_eid)
return render_template('show_person.html', person=dict(p_eid=p_eid, firstname=person.firstname,\
secondname=person.secondname,\
username=person.username, email=person.email))
@app.route('/<int:i_eid>/persons')
def show_people():
instance = db.instances.get(g.i_eid)
people = [person2Dict(p) for p in instance.outV('hasPeople')]
return render_template('show_people.html', people = people,
instance = dict(title=instance.title,\
eid=instance.eid))
@app.route('/<int:i_eid>/parlaments')
def show_parlaments():
q_pa = '''START i=node({i_eid})
MATCH i-[:instanceHasParlament]->pa
RETURN pa'''
pa = db.cypher.query(q_pa, dict(i_eid=g.i_eid))
parlaments = [data(p) for p in pa]
q_numProp = '''START pa=node({pa_eid})
MATCH pa<-[:proposalHasParlament]-pr
RETURN COUNT(pr)'''
for p in parlaments:
erg = db.cypher.table(q_numProp, dict(pa_eid=p['eid']))[1]
p['numberProposals'] = 0 if not erg else erg[0][0]
return render_template('show_parlaments.html', parlaments=parlaments)
@app.route('/<int:i_eid>/addparlament', methods=['POST'])
def add_parlament():
if not (session.get('logged_in') and session['isAdmin']):
abort(401)
q = '''START i=node({i_eid})
MATCH i-[:instanceHasParlament]->pa
WHERE pa.title = {title}
RETURN pa'''
pa = list(db.cypher.query(q, dict(i_eid=g.i_eid, title=request.form['title'])))
if pa:
flash('Parlament wurde nicht angelegt! Es existiert schon in dieser Instanz')
else:
instance = db.instances.get(g.i_eid)
parlament = db.parlaments.create(title=request.form['title'], body=request.form['body'])
db.instanceHasParlament.create(instance, parlament)
flash('Neues Parlament wurde angelegt')
return redirect(url_for('show_parlaments'))
@app.route('/<int:i_eid>/delegate_overview')
def delegateOverview():
if not session.get('logged_in'):
abort(401)
return render_template('delegate.html', overview=True)
@app.route('/<int:i_eid>/delegate_parlament/<int:parl_eid>')
def delegateParlament(parl_eid):
if not session.get('logged_in'):
abort(401)
parlament = db.parlaments.get(parl_eid)
return render_template('delegate.html', parlament=parl_eid)
@app.route('/<int:i_eid>/delegate_proposal/<int:pr_eid>')
def delegateProposal(pr_eid):
if not session.get('logged_in'):
abort(401)
return render_template('delegate.html', proposal=pr_eid)
@app.route('/<int:i_eid>/delegate_person/<int:p_eid>')
def delegatePerson(p_eid):
if not session.get('logged_in'):
abort(401)
return render_template('delegate.html', person=p_eid)
@app.route('/<int:i_eid>/delegate',methods=['POST'])
def delegate():
if not session.get('logged_in'):
abort(401)
postData=werkzeug.urls.url_decode(request.form['param'],'utf-8')
overwrite=int(request.form['overwrite'])
q='''START i=node({userid})
MATCH i-[:personDelegation]->d-[?:delegationParlament|delegationProposal]->p,d-[:delegationPerson]->u
RETURN ID(p),p.element_type,ID(d),ID(u)'''
delete=None
result=db.cypher.table(q,dict(userid=session['userId']))[1]
if overwrite == 0:
if postData['span'] == 'proposal':
if any(p[0]==int(postData['proposal']) and p[1] == 'proposal' for p in result):
return jsonify(results=[{'exists': 1}])
elif postData['span']== 'parlament':
if any(p[0]==int(postData['parlament']) and p[1] == 'parlament' for p in result):
return jsonify(results=[{'exists': 1}])
else:
if any(p[1] == None for p in result):
return jsonify(results=[{'exists': 1}])
else:
if postData['span'] == 'proposal' or postData['span'] == 'parlament':
delete=[p for p in result if p[0]==int(postData[postData['span']])][0][2]
print delete
else:
delete=[p for p in result if p[1]==None][0][2]
print delete
person = int(postData['person']) if 'person' in postData else None
proposal = int(postData['proposal']) if 'proposal' in postData else None
parlament = int(postData['parlament']) if 'parlament' in postData else None
span = postData['span'] # span is one of 'parlament' / 'proposal' / 'all'
# Create edges:
delegation = db.delegations.create(delegation_type=span)
db.instanceHasDelegation.create(db.instances.get(g.i_eid),delegation)
personDelegationEdge = db.personDelegation.create(db.people.get(session['userId']), delegation)
delegationPersonEdge = db.delegationPerson.create(delegation, db.people.get(person))
if span=='parlament': # make edge from delegation object to parlament
delegationParlamentEdge = db.delegationParlament.create(delegation, db.parlaments.get(parlament))
elif span=='proposal': # make edge from delegaton object to proposal
delegationProposalEdge = db.delegationProposal.create(delegation, db.proposals.get(proposal))
# else: # here span=='all' should hold
# pass # no additonal edges!
affected=affectedVotes()
#Delete old delegation
if not delete is None:
db.client.delete_vertex(delete)
def bgrWorker(req,aff,i_eid):
with app.test_request_context():
from flask import request
request = req
recalculateAffectedProposals(aff,i_eid)
thread.start_new_thread(bgrWorker, (request,affected,g.i_eid))
list = [
{'exists': 0}
]
return jsonify(results = list)
@app.route('/<int:i_eid>/deleteDelegation/<int:eid>')
def deleteDelegation(eid):
delegation = db.proposals.get(eid)
if not session.get('logged_in') or session['userId'] != delegation.inV('personDelegation').next().eid:
abort(401)
affected=affectedVotes()
db.client.delete_vertex(eid)
flash('Delegation geloescht')
#recalculateAffectedProposals(affected)
def bgrWorker(req,aff,i_eid):
with app.test_request_context():
from flask import request
request = req
recalculateAffectedProposals(aff,i_eid)
thread.start_new_thread(bgrWorker, (request,affected,g.i_eid))
return redirect(url_for('delegateOverview'))
@app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a',0,type=int)
b = request.args.get('b',0,type=int)
#return jsonify(result=a+b)
list = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return jsonify(results = list)
def initdb():
users = [p for p in db.people.index.lookup(username=app.config['USERNAME'])]
if not users:
db.people.create(username=app.config['USERNAME'], \
firstname=app.config['USERNAME'], \
secondname=app.config['USERNAME'], \
password=app.config['PASSWORD'], \
email='email')
initdb()
if __name__ == '__main__':
app.run(host='0.0.0.0')