summaryrefslogtreecommitdiff
path: root/rater.py
blob: 8fb3233ec496231ab70439ed46dd144b213088ad (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
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
#!venv/bin/python

from flask import Flask, render_template, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from lxml import etree
from argparse import ArgumentParser
import requests
import json

# Use this on FreeBSD when you've compiled pyopenssl with openssl from ports
# import urllib3.contrib.pyopenssl
# urllib3.contrib.pyopenssl.inject_into_urllib3()

parser = ArgumentParser(description="C3 rating helper")
parser.add_argument("-i", action="store_true", dest="pretalx_import", default=False, help="import events from pretalx")
parser.add_argument("-c", "--config", help="Config file location", default="./config.json")
args = parser.parse_args()

with open(args.config, mode="r", encoding="utf-8") as json_file:
    config = json.load(json_file)

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + config['pretalx-conference'] + '-' + config['track'] + '.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'Silence is golden. Gerd Eist.'
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

db = SQLAlchemy(app)

config['pretalx-conf-url'] = config['pretalx-url'] + 'orga/event/' + config['pretalx-conference']
config['pretalx-api-url'] = config['pretalx-url'] + 'api/events/' + config['pretalx-conference'] + '/submissions?track_id' + str(config['track-id'])

class Event(db.Model):
    """An event as dumped from pretalx"""
    pretalx_id = db.Column(db.String(64), primary_key=True)
    title = db.Column(db.String(1024))
    subtitle = db.Column(db.String(1024))
    abstract = db.Column(db.Text())
    description = db.Column(db.Text())
    state = db.Column(db.String(64))
    event_type = db.Column(db.String(64))
    speakers = db.Column(db.String(1024))
    coordinator = db.Column(db.String(1024))
    notes = db.Column(db.Text())
    duration = db.Column(db.Integer())

class EventRating(db.Model):
    """A rating as given by a logged in user"""
    id = db.Column(db.Integer, primary_key=True)
    submitter = db.Column(db.String(1024))
    pretalx_id = db.Column(db.String(64), db.ForeignKey('event.pretalx_id'))
    event = db.relationship('Event', backref=db.backref('ratings', lazy='dynamic'))
    comment = db.Column(db.Text())
    rating_dict = db.Column(db.String(1024), server_default="{}")

@app.route("/")
def root():
    events = Event.query.all()
    return render_template('index.html', events=events, json=json, config=config)

@app.route('/api/ratings')
def get_ratings():
    return jsonify(EventRating.query.all())

@app.route('/api/set_event_state/<eventid>', methods=['POST'])
def set_sevent_state(eventid):
    content = request.json
    dbevent = db.session.get(Event, eventid)
    dbevent.state = content.get('state', 'new')
    db.session.commit()
    return jsonify({"result":"ok"})

@app.route('/api/set_event_coordinator/<eventid>', methods=['POST'])
def set_sevent_coordinator(eventid):
    content = request.json
    dbevent = db.session.get(Event, eventid)
    dbevent.coordinator = content['coordinator']
    db.session.commit()
    return jsonify({"result":"ok"})

@app.route('/api/remove_event/<eventid>', methods=['POST'])
def remove_event(eventid):
    dbevent = db.session.get(Event, eventid)
    if dbevent.state == 'gone':
        db.session.delete(dbevent)
    db.session.commit()
    return jsonify({"result":"ok"})

@app.route('/api/remove_rating/<eventid>', methods=['POST'])
def remove_rating(eventid):
    content = request.json
    rating = EventRating.query.filter_by(pretalx_id = eventid, submitter = content['author']).first()
    if rating:
        db.session.delete(rating)
        db.session.commit()
    return jsonify({"result":"ok"})

@app.route('/api/add_rating/<eventid>', methods=['POST'])
def add_rating(eventid):
    content = request.json
    print ( str(eventid) + " " + str(content))
    r = content.get('ratings', '{}');

    rating = EventRating.query.filter_by(pretalx_id = eventid, submitter = content['author']).first()

    rd = json.dumps({ k: r.get(k,'0') for k in ['category1', 'category2', 'category3', 'category4'] })
    if rating:
        if 'comment' in content:
            rating.comment = content['comment']
        rating.rating_dict = rd
    else:
        db.session.add( EventRating( submitter = content.get('author','anonymous'), pretalx_id = eventid, comment = content['comment'], rating_dict = rd))

    db.session.commit()
    return jsonify({"result":"ok"})

def fetch_talks():
    sess = requests.Session()

    response = sess.get(config['pretalx-api-url'] + '&format=json&limit=20000' , verify=False, stream=True, headers={'Authorization': "Token " + config['pretalx-token']})

    talks_json = json.loads(response.text)

    # with open('dump.txt', mode='wb') as localfile:
    #    localfile.write(response.content)

    submissions = [s for s in talks_json['results'] if s['track_id'] == config['track-id'] ]

    imported = 0
    for json_event in submissions:
        # print (json_event)

        dbevent = db.session.get(Event, json_event['code'])
        speakers = { speaker['code']: speaker['name'] for speaker in json_event['speakers'] }
        submission_type = json_event['submission_type'].get('de') or json_event['submission_type'].get('en')
        if dbevent:
            dbevent.title = json_event['title']
            dbevent.abstract = json_event['abstract']
            dbevent.description = json_event['description']
            dbevent.event_type = submission_type
            dbevent.notes = json_event.get('notes')
            dbevent.duration = int(json_event['duration'])
            if 'state' in json_event:
                if json_event['state'] != 'submitted' or dbevent.state == 'gone':
                    dbevent.state = json_event['state']
            dbevent.speakers = json.dumps(speakers)
        else:
            db.session.add( Event( pretalx_id = json_event['code'], title = json_event['title'], abstract = json_event['abstract'], description = json_event['description'], speakers = json.dumps(speakers), state = json_event.get('state', 'submitted'), event_type = submission_type, notes = json_event.get('notes'), duration = int(json_event['duration'])) )
            imported += 1

    for goner in Event.query.filter( Event.pretalx_id.notin_([ ev['code'] for ev in submissions ])).all():
        goner.state = 'gone'

    db.session.commit()
    print ('Conference: ' + config['track'] + ', track: ' + config['track'] + ', imported ' + str(len(submissions)) + ' events, ' + str(imported) + ' new.')


if __name__ == "__main__":
    with app.app_context():
        db.create_all()
        if args.pretalx_import:
            fetch_talks()
        else:
            app.run(host=config.get('host', '127.0.0.1'), port=int(config.get('port', '8080')))