summaryrefslogtreecommitdiffstats
path: root/main.py
blob: 667a97cc7e7a314eac4f1f378fbfae4a179c10e3 (plain)
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
# -*- coding: utf-8 -*-

import feedparser
import requests
import string
import random
from flask import Flask, render_template, request, flash, session, abort
from time import mktime
from datetime import datetime

app = Flask('main')
app.config.from_pyfile('main.cfg')

def pull_feed_entries():
    all_entries = []
    for tag, url in app.config['FEEDS']:
        entries = feedparser.parse(url).entries
        for e in entries:
            e.tag = tag
            dt = datetime.fromtimestamp(mktime(e.updated_parsed))
            e.updated_display = dt.strftime(app.config['DATE_FORMAT'])
        all_entries.extend(entries)
    all_entries.sort(key=lambda e: e.updated_parsed, reverse=True)
    return all_entries[:app.config['MAX_ENTRIES']]

def mailman_subscribe(email, mailing_list):
    password = "".join(random.choice(string.letters) for _ in range(8))
    post = {"email": email, "fullname": "", "pw": password, "pw-conf": password, "email-button": "Zapisz", "digest": 0}
    headers = {"X-Forwarded-For": request.remote_addr}
    r = requests.post("https://lists.hackerspace.pl/subscribe/" + mailing_list, post, headers=headers)
    if r.status_code != 200:
       return False
    return True

def parse_subscribe_requests():
    if "email" in request.form:
        email = request.form["email"].strip()
        if len(email) > 0:
            if "@" in email:
                lists = []
                if "mail-waw" in request.form:
                    lists.append("waw")
                if "mail-proj" in request.form:
                    lists.append("waw-proj")
                if "mail-offtopic" in request.form:
                    lists.append("waw-ot")
                subscribed = []
                failed = []
                for maillist in lists:
                    if mailman_subscribe(email, maillist):
                        subscribed.append(maillist)
                    else:
                        failed.append(maillist)
                if len(subscribed) == 1:
                    flash(u"Pomyślnie zasubskrybowano na listę %s@lists.hackerspace.pl.\
    W celu aktywacji subskrypcji odwiedź odnośnik wysłany mailem na adres %s." % (subscribed[0], email))
                elif len(subscribed) > 1:
                    flash(u"Pomyślnie zasubskrybowano na listy %s. \
    W celu aktywacji subskrypcji odwiedź odnośniki wysłane mailem na adres %s." % \
                        (", ".join(l + "@lists.hackerspace.pl" for l in subscribed), email))
                if len(failed) > 0:
                    flash(u"Wystąpił problem z zapisaniem na następujące listy: %s. Ups! Napisz na bofh@hackerspace.pl, spróbujemy to naprawić." % ", ".join(failed), "error")
            else:
                flash(u"Podano nieprawidłowy adres email.", "error")
        else:
            flash(u"Nie podano adresu email.", "error")

@app.route('/', methods=["GET", "POST"])
def main():
    if request.method == "POST":
        parse_subscribe_requests()
    return render_template('main.html', entries=pull_feed_entries())

@app.route('/about', methods=["GET", "POST"])
def about():
    if request.method == "POST":
        parse_subscribe_requests()
    return render_template('about.html', entries=pull_feed_entries())
@app.before_request
def csrf_protect():
    if request.method == "POST":
        token = session.pop('_csrf_token', None)
        if not token or token != request.form.get('_csrf_token'):
            abort(403)
        generate_csrf_token()

def generate_csrf_token():
    if '_csrf_token' not in session:
        session['_csrf_token'] = "".join(random.choice(string.letters) for _ in range(32))
    return session['_csrf_token']

app.jinja_env.globals['csrf_token'] = generate_csrf_token 

if __name__ == '__main__':
    app.run('0.0.0.0', 8080, debug=True)