2 from flask import Flask
3 from flask import render_template, redirect
4 from flask import request
5 from functools import wraps
8 from flaskext.markdown import Markdown
9 from markdown.extensions import Extension
10 from datetime import date, time, datetime
13 db = getattr(g, '_database', 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
20 app.register_blueprint(filters.blueprint)
22 class EscapeHtml(Extension):
23 def extendMarkdown(self, md, md_globals):
24 del md.preprocessors['html_block']
25 del md.inlinePatterns['html']
27 md = Markdown(app, extensions=[EscapeHtml()])
29 class default_settings(object):
32 COPYRIGHTLINK="https://wpia.club"
33 IMPRINTLINK="https://documents.wpia.club/imprint.html"
34 DATAPROTECTIONLINK="https://documents.wpia.club/data_privacy_policy_html_pages_en.html"
38 app.config.from_object('motion.default_settings')
39 app.config.from_pyfile('config.py')
43 def __init__(self, name):
47 dict = app.config.get(self.name)
50 return dict.get(request.host)
52 prefix = ConfigProxy("GROUP_PREFIX")
53 times = ConfigProxy("DURATION")
54 debuguser = ConfigProxy("DEBUGUSER")
62 my_debuguser = debuguser.per_host
63 if my_debuguser is not None:
64 parts = my_debuguser.split("/", 1)
68 if "USER_ROLES" in env:
69 parts = env.get("USER_ROLES").split("/", 1)
73 if "USER" in env and "ROLES" in env:
74 user = env.get("USER")
75 roles = env.get("ROLES")
78 return "Server misconfigured", 500
79 roles = roles.split(" ")
81 if user == "<invalid>":
82 return "Access denied", 403;
86 rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
88 db.prepare("INSERT INTO voter(\"email\") VALUES($1)")(user)
89 rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
90 g.voter = rv[0].get("id");
98 if a[0] not in g.roles:
101 g.roles[a[0]] = [group for group in prefix.per_host]
103 g.roles[a[0]].append(val)
106 @app.context_processor
107 def init_footer_variables():
108 if int(app.config.get("COPYRIGHTSTART"))<datetime.now().year:
109 version_year = "%s - %s" % (app.config.get("COPYRIGHTSTART"), datetime.now().year)
111 version_year = datetime.now().year
114 footer = dict( version_year=version_year,
115 copyright_link=app.config.get("COPYRIGHTLINK"),
116 copyright_name=app.config.get("COPYRIGHTNAME"),
117 imprint_link=app.config.get("DATAPROTECTIONLINK"),
118 dataprotection_link=app.config.get("DATAPROTECTIONLINK")
123 def get_allowed_cats(action):
124 return g.roles.get(action, []);
126 def may(action, motion):
127 return motion in get_allowed_cats(action)
129 @app.teardown_appcontext
130 def close_connection(exception):
131 db = getattr(g, '_database', None)
136 with app.app_context():
139 ver = db.prepare("SELECT version FROM schema_version")()[0][0];
140 print("Database Schema version: ", ver)
141 except postgresql.exceptions.UndefinedTableError:
147 with app.open_resource('sql/schema.sql', mode='r') as f:
152 with app.open_resource('sql/from_1.sql', mode='r') as f:
155 for group in [group for group in prefix[app.config.get("DEFAULT_HOST")]]:
156 ct[group] = {"dt": "", "c": 0}
158 p = db.prepare("UPDATE \"motion\" SET \"identifier\"=$1 WHERE \"id\"=$2")
159 for row in db.prepare("SELECT id, \"type\", \"posed\" FROM \"motion\" ORDER BY \"id\" ASC"):
160 dt=row[2].strftime("%Y%m%d")
161 if ct[row[1]]["dt"] != dt:
162 ct[row[1]]["dt"] = dt
164 ct[row[1]]["c"] = ct[row[1]]["c"] + 1
165 name=prefix[app.config.get("DEFAULT_HOST")][row[1]]+"."+dt+"."+("%03d" % ct[row[1]]["c"])
167 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"identifier\" SET NOT NULL")()
168 db.prepare("UPDATE \"schema_version\" SET \"version\"=2")()
169 db.prepare("CREATE UNIQUE INDEX motion_ident ON motion (identifier)")()
172 with app.open_resource('sql/from_2.sql', mode='r') as f:
174 db.prepare("UPDATE \"motion\" SET \"host\"=$1")(app.config.get("DEFAULT_HOST"))
175 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"host\" SET NOT NULL")()
176 db.prepare("UPDATE \"schema_version\" SET \"version\"=3")()
182 start=int(request.args.get("start", "-1"));
183 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, "\
184 + "COUNT(CASE WHEN result='yes' THEN 'yes' ELSE NULL END) as yes, "\
185 + "COUNT(CASE WHEN result='no' THEN 'no' ELSE NULL END) as no, "\
186 + "COUNT(CASE WHEN result='abstain' THEN 'abstain' ELSE NULL END) as abstain "\
187 + "FROM vote GROUP BY motion_id) as votes ON votes.motion_id=motion.id "\
188 + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
189 + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
192 p = get_db().prepare(q + "WHERE motion.host = $1 ORDER BY motion.id DESC LIMIT 11")
195 p = get_db().prepare(q + "WHERE motion.host = $1 AND motion.id <= $2 ORDER BY motion.id DESC LIMIT 11")
196 rv = p(request.host, start)
197 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)
202 return render_template('index.html', motions=rv[:10], more=rv[10]["id"] if len(rv) == 11 else None, times=times.per_host, prev=prev,
203 categories=get_allowed_cats("create"), singlemotion=False)
205 def rel_redirect(loc):
207 r.autocorrect_location_header = False
210 @app.route("/motion", methods=['POST'])
212 cat=request.form.get("category", "")
213 if cat not in get_allowed_cats("create"):
214 return "Forbidden", 403
215 time = int(request.form.get("days", "3"));
216 if time not in times.per_host:
217 return "Error, invalid length", 400
218 title=request.form.get("title", "")
221 return "Error, missing title", 400
222 content=request.form.get("content", "")
223 content=content.strip()
225 return "Error, missing content", 400
229 t = db.prepare("SELECT CURRENT_TIMESTAMP")()[0][0];
230 s = db.prepare("SELECT MAX(\"identifier\") FROM \"motion\" WHERE \"type\"=$1 AND \"host\"=$2 AND DATE(\"posed\")=DATE(CURRENT_TIMESTAMP)")
231 sr = s(cat, request.host)
233 if len(sr) == 0 or sr[0][0] is None:
234 ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+".001"
236 ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+"."+("%03d" % (int(sr[0][0].split(".")[2])+1))
237 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)")
238 p(title, content, time, g.voter, cat, ident, request.host)
239 return rel_redirect("/")
241 def motion_edited(motion):
242 return rel_redirect("/?start=" + str(motion) + "#motion-" + str(motion))
244 def validate_motion_access(privilege):
246 def decorated_function(motion):
249 rv = db.prepare("SELECT id, type, deadline < CURRENT_TIMESTAMP AS expired, canceled FROM motion WHERE identifier=$1 AND host=$2")(motion, request.host);
251 return "Error, Not found", 404
253 if not may(privilege, rv[0].get("type")):
254 return "Forbidden", 403
255 if rv[0].get("canceled") is not None:
256 return "Error, motion was canceled", 403
257 if rv[0].get("expired"):
258 return "Error, out of time", 403
260 decorated_function.__name__ = f.__name__
261 return decorated_function
264 @app.route("/motion/<string:motion>/cancel", methods=['POST'])
265 @validate_motion_access('cancel')
266 def cancel_motion(motion, id):
267 if request.form.get("reason", "none") == "none":
268 return "Error, form requires reason", 500
269 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)
270 return motion_edited(id)
272 @app.route("/motion/<string:motion>/finish", methods=['POST'])
273 @validate_motion_access('finish')
274 def finish_motion(motion, id):
275 rv = get_db().prepare("UPDATE motion SET deadline=CURRENT_TIMESTAMP WHERE identifier=$1 AND host=$2 AND canceled is NULL")(motion, request.host)
276 return motion_edited(id)
278 @app.route("/motion/<string:motion>")
279 def show_motion(motion):
280 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 "\
281 + "LEFT JOIN vote on vote.motion_id=motion.id AND vote.voter_id=$2 "\
282 + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
283 + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
284 + "WHERE motion.identifier=$1 AND motion.host=$3")
285 rv = p(motion, g.voter, request.host)
287 return "Error, Not found", 404
289 if may("audit", rv[0].get("type")) and not rv[0].get("running") and not rv[0].get("canceled"):
290 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"));
291 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)
293 @app.route("/motion/<string:motion>/vote", methods=['POST'])
294 @validate_motion_access('vote')
295 def vote(motion, id):
296 v = request.form.get("vote", "abstain")
298 p = db.prepare("SELECT * FROM vote WHERE motion_id = $1 AND voter_id = $2")
301 db.prepare("INSERT INTO vote(motion_id, voter_id, result) VALUES($1,$2,$3)")(id, g.voter, v)
303 db.prepare("UPDATE vote SET result=$3, entered=CURRENT_TIMESTAMP WHERE motion_id=$1 AND voter_id = $2")(id, g.voter, v)
304 return motion_edited(id)