]> WPIA git - motion.git/blob - motion.py
upd: make sure that database is populated with tables
[motion.git] / motion.py
1 from flask import g
2 from flask import Flask
3 from flask import render_template, redirect
4 from flask import request
5 from functools import wraps
6 import postgresql
7 import filters
8 from flaskext.markdown import Markdown
9 from markdown.extensions import Extension
10 from datetime import date, time, datetime
11
12 def get_db():
13     db = getattr(g, '_database', None)
14     if db is None:
15         db = g._database = postgresql.open(app.config.get("DATABASE"), user=app.config.get("USER"), password=app.config.get("PASSWORD"))
16     #db.row_factory = sqlite3.Row
17     return db
18
19 app = Flask(__name__)
20 app.register_blueprint(filters.blueprint)
21
22 class EscapeHtml(Extension):
23     def extendMarkdown(self, md, md_globals):
24         del md.preprocessors['html_block']
25         del md.inlinePatterns['html']
26
27 md = Markdown(app, extensions=[EscapeHtml()])
28
29 # Load config
30 app.config.from_pyfile('config.py')
31
32
33 class ConfigProxy:
34     def __init__(self, name):
35         self.name = name
36     @property
37     def per_host(self):
38         dict = app.config.get(self.name)
39         if dict is None:
40             return None
41         return dict.get(request.host)
42
43 prefix = ConfigProxy("GROUP_PREFIX")
44 times = ConfigProxy("DURATION")
45 debuguser = ConfigProxy("DEBUGUSER")
46
47 @app.before_request
48 def lookup_user():
49     global prefix
50
51     env = request.environ
52     user = None
53     my_debuguser = debuguser.per_host
54     if my_debuguser is not None:
55         parts = my_debuguser.split("/", 1)
56         user = parts[0]
57         roles = parts[1]
58
59     if "USER_ROLES" in env:
60         parts = env.get("USER_ROLES").split("/", 1)
61         user = parts[0]
62         roles = parts[1]
63
64     if "USER" in env and "ROLES" in env:
65         user = env.get("USER")
66         roles = env.get("ROLES")
67
68     if user is None:
69         return "Server misconfigured", 500
70     roles = roles.split(" ")
71
72     if user == "<invalid>":
73         return "Access denied", 403;
74
75     db = get_db()
76     with db.xact():
77         rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
78         if len(rv) == 0:
79             db.prepare("INSERT INTO voter(\"email\") VALUES($1)")(user)
80             rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
81         g.voter = rv[0].get("id");
82     g.user = user
83     g.roles = {}
84
85     for r in roles:
86         a = r.split(":", 1)
87         if len(r)!=0:
88             val = a[1]
89             if a[0] not in g.roles:
90                 g.roles[a[0]] = []
91             if val == "*":
92                 g.roles[a[0]] = [group for group in prefix.per_host]
93             else:
94                 g.roles[a[0]].append(val)
95     return None
96
97 def get_allowed_cats(action):
98     return g.roles.get(action, []);
99
100 def may(action, motion):
101     return motion in get_allowed_cats(action)
102
103 @app.teardown_appcontext
104 def close_connection(exception):
105     db = getattr(g, '_database', None)
106     if db is not None:
107         db.close()
108
109 def init_db():
110     with app.app_context():
111         db = get_db()
112         try:
113             ver = db.prepare("SELECT version FROM schema_version")()[0][0];
114             print("Database Schema version: ", ver)
115         except postgresql.exceptions.UndefinedTableError:
116             g._database = None
117             db = get_db()
118             ver = 0
119
120         if ver < 1:
121             with app.open_resource('sql/schema.sql', mode='r') as f:
122                 db.execute(f.read())
123             return
124
125         if ver < 2:
126             with app.open_resource('sql/from_1.sql', mode='r') as f:
127                 db.execute(f.read())
128                 ct={}
129                 for group in [group for group in prefix[app.config.get("DEFAULT_HOST")]]:
130                     ct[group] = {"dt": "", "c": 0}
131
132                 p = db.prepare("UPDATE \"motion\" SET \"identifier\"=$1 WHERE \"id\"=$2")
133                 for row in db.prepare("SELECT id, \"type\", \"posed\" FROM \"motion\" ORDER BY \"id\" ASC"):
134                     dt=row[2].strftime("%Y%m%d")
135                     if ct[row[1]]["dt"] != dt:
136                         ct[row[1]]["dt"] = dt
137                         ct[row[1]]["c"] = 0
138                     ct[row[1]]["c"] = ct[row[1]]["c"] + 1
139                     name=prefix[app.config.get("DEFAULT_HOST")][row[1]]+"."+dt+"."+("%03d" % ct[row[1]]["c"])
140                     p(name, row[0])
141                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"identifier\" SET NOT NULL")()
142                 db.prepare("UPDATE \"schema_version\" SET \"version\"=2")()
143                 db.prepare("CREATE UNIQUE INDEX motion_ident ON motion (identifier)")()
144
145         if ver < 3:
146             with app.open_resource('sql/from_2.sql', mode='r') as f:
147                 db.execute(f.read())
148                 db.prepare("UPDATE \"motion\" SET \"host\"=$1")(app.config.get("DEFAULT_HOST"))
149                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"host\" SET NOT NULL")()
150                 db.prepare("UPDATE \"schema_version\" SET \"version\"=3")()
151
152
153 init_db()
154
155 @app.route("/")
156 def main():
157     start=int(request.args.get("start", "-1"));
158     q = "SELECT motion.*, votes.*, poser.email AS poser, canceler.email AS canceler, (motion.deadline > CURRENT_TIMESTAMP AND canceled is NULL) AS running FROM motion LEFT JOIN (SELECT motion_id, "\
159                              + "COUNT(CASE WHEN result='yes' THEN 'yes' ELSE NULL END) as yes, "\
160                              + "COUNT(CASE WHEN result='no' THEN 'no' ELSE NULL END) as no, "\
161                              + "COUNT(CASE WHEN result='abstain' THEN 'abstain' ELSE NULL END) as abstain "\
162                              + "FROM vote GROUP BY motion_id) as votes ON votes.motion_id=motion.id "\
163                              + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
164                              + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
165     prev=None
166     if start == -1:
167         p = get_db().prepare(q + "WHERE motion.host = $1 ORDER BY motion.id DESC LIMIT 11")
168         rv = p(request.host)
169     else:
170         p = get_db().prepare(q + "WHERE motion.host = $1 AND motion.id <= $2 ORDER BY motion.id DESC LIMIT 11")
171         rv = p(request.host, start)
172         rs = get_db().prepare("SELECT id FROM motion WHERE motion.host = $1 AND motion.id > $2 ORDER BY id ASC LIMIT 10")(request.host, start)
173         if len(rs) == 10:
174             prev = rs[9][0]
175         else:
176             prev = -1
177     return render_template('index.html', motions=rv[:10], more=rv[10]["id"] if len(rv) == 11 else None, times=times.per_host, prev=prev,
178                            categories=get_allowed_cats("create"), singlemotion=False)
179
180 def rel_redirect(loc):
181     r = redirect(loc)
182     r.autocorrect_location_header = False
183     return r
184
185 @app.route("/motion", methods=['POST'])
186 def put_motion():
187     cat=request.form.get("category", "")
188     if cat not in get_allowed_cats("create"):
189         return "Forbidden", 403
190     time = int(request.form.get("days", "3"));
191     if time not in times.per_host:
192         return "Error, invalid length", 400
193     title=request.form.get("title", "")
194     title=title.strip()
195     if title =='':
196         return "Error, missing title", 400
197     content=request.form.get("content", "")
198     content=content.strip()
199     if content =='':
200         return "Error, missing content", 400
201
202     db = get_db()
203     with db.xact():
204         t = db.prepare("SELECT CURRENT_TIMESTAMP")()[0][0];
205         s = db.prepare("SELECT MAX(\"identifier\") FROM \"motion\" WHERE \"type\"=$1 AND \"host\"=$2 AND DATE(\"posed\")=DATE(CURRENT_TIMESTAMP)")
206         sr = s(cat, request.host)
207         ident=""
208         if len(sr) == 0 or sr[0][0] is None:
209             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+".001"
210         else:
211             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+"."+("%03d" % (int(sr[0][0].split(".")[2])+1))
212         p = db.prepare("INSERT INTO motion(\"name\", \"content\", \"deadline\", \"posed_by\", \"type\", \"identifier\", \"host\") VALUES($1, $2, CURRENT_TIMESTAMP + $3 * interval '1 days', $4, $5, $6, $7)")
213         p(title, content, time, g.voter, cat, ident, request.host)
214     return rel_redirect("/")
215
216 def motion_edited(motion):
217     return rel_redirect("/?start=" + str(motion) + "#motion-" + str(motion))
218
219 def validate_motion_access(privilege):
220     def decorator(f):
221         def decorated_function(motion):
222             db = get_db()
223             with db.xact():
224                 rv = db.prepare("SELECT id, type, deadline < CURRENT_TIMESTAMP AS expired, canceled FROM motion WHERE identifier=$1 AND host=$2")(motion, request.host);
225                 if len(rv) == 0:
226                     return "Error, Not found", 404
227                 id = rv[0].get("id")
228                 if not may(privilege, rv[0].get("type")):
229                     return "Forbidden", 403
230                 if rv[0].get("canceled") is not None:
231                     return "Error, motion was canceled", 403
232                 if rv[0].get("expired"):
233                     return "Error, out of time", 403
234             return f(motion, id)
235         decorated_function.__name__ = f.__name__
236         return decorated_function
237     return decorator
238     
239 @app.route("/motion/<string:motion>/cancel", methods=['POST'])
240 @validate_motion_access('cancel')
241 def cancel_motion(motion, id):
242     if request.form.get("reason", "none") == "none":
243         return "Error, form requires reason", 500
244     rv = get_db().prepare("UPDATE motion SET canceled=CURRENT_TIMESTAMP, cancelation_reason=$1, canceled_by=$2 WHERE identifier=$3 AND host=$4 AND canceled is NULL")(request.form.get("reason", ""), g.voter, motion, request.host)
245     return motion_edited(id)
246
247 @app.route("/motion/<string:motion>/finish", methods=['POST'])
248 @validate_motion_access('finish')
249 def finish_motion(motion, id):
250     rv = get_db().prepare("UPDATE motion SET deadline=CURRENT_TIMESTAMP WHERE identifier=$1 AND host=$2 AND canceled is NULL")(motion, request.host)
251     return motion_edited(id)
252
253 @app.route("/motion/<string:motion>")
254 def show_motion(motion):
255     p = get_db().prepare("SELECT motion.*, poser.email AS poser, canceler.email AS canceler, (motion.deadline > CURRENT_TIMESTAMP AND canceled is NULL) AS running, vote.result FROM motion "\
256                          + "LEFT JOIN vote on vote.motion_id=motion.id AND vote.voter_id=$2 "\
257                          + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
258                          + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
259                          + "WHERE motion.identifier=$1 AND motion.host=$3")
260     rv = p(motion, g.voter, request.host)
261     if len(rv) == 0:
262         return "Error, Not found", 404
263     votes = None
264     if may("audit", rv[0].get("type")) and not rv[0].get("running") and not rv[0].get("canceled"):
265         votes = get_db().prepare("SELECT vote.result, voter.email FROM vote INNER JOIN voter ON voter.id = vote.voter_id WHERE vote.motion_id=$1")(rv[0].get("id"));
266     return render_template('single_motion.html', motion=rv[0], may_vote=may("vote", rv[0].get("type")), may_cancel=may("cancel", rv[0].get("type")), may_finish=may("finish", rv[0].get("type")), votes=votes, singlemotion=True)
267
268 @app.route("/motion/<string:motion>/vote", methods=['POST'])
269 @validate_motion_access('vote')
270 def vote(motion, id):
271     v = request.form.get("vote", "abstain")
272     db = get_db()
273     p = db.prepare("SELECT * FROM vote WHERE motion_id = $1 AND voter_id = $2")
274     rv = p(id, g.voter)
275     if len(rv) == 0:
276         db.prepare("INSERT INTO vote(motion_id, voter_id, result) VALUES($1,$2,$3)")(id, g.voter, v)
277     else:
278         db.prepare("UPDATE vote SET result=$3, entered=CURRENT_TIMESTAMP WHERE motion_id=$1 AND voter_id = $2")(id, g.voter, v)
279     return motion_edited(id)