summaryrefslogtreecommitdiffstats
path: root/npc.py
blob: 833ccb2e9645fc23e15b56a9464b973098f141a3 (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
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
#!/usr/bin/python3
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 tw=80 expandtab :

# Copyright (C) 2012 Florian Bruhin <me@the-compiler.org>

# npc.py is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# npc.py is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with npc.py.  If not, see <http://www.gnu.org/licenses/>.

import sys
import bottle
import pygments
import pygments.util
import pygments.lexers
import pygments.formatters
import sqlalchemy
import sqlalchemy.ext.declarative
import urllib.parse
import os.path
from bottle import route, put, post, request, static_file, redirect, response
from bottle.ext.sqlalchemy import SQLAlchemyPlugin
from sqlalchemy import (Integer, Column, Sequence, String, Boolean,
                        ForeignKey, Text, UniqueConstraint)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError

if sys.argv[0].startswith(os.sep):
    __PATH__ = os.path.dirname(sys.argv[0])
else:
    __PATH__ = os.getcwd() + os.sep + os.path.dirname(sys.argv[0])

HTML_HEADER="""
<!DOCTYPE html>
<html>
<head>
<title>Nerd pissing contest</title>
<link rel="stylesheet" type="text/css" href="static/npc.css" />
<link rel="stylesheet" href="codemirror/lib/codemirror.css">
<link rel="stylesheet" href="codemirror/theme/monokai.css">
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; \
minimum-scale=1.0; maximum-scale=1.0;"/>
</head>
<body>
"""
HTML_FOOTER="""
</body>
</html>
"""

Base = sqlalchemy.ext.declarative.declarative_base()
engine = sqlalchemy.create_engine(
    'mysql+oursql://npc:rK3fzEuZ9p55X2Tm@localhost/npc',
    echo=False, pool_recycle=3600
)
create_session = sessionmaker(bind=engine)

class Votes(Base):
    __tablename__ = 'votes'
    vote_id = Column(Integer, Sequence('vote_id_seq'),  primary_key=True)
    ip = Column(String(45))
    task_id = Column(Integer)
    lang_id = Column(Integer)
    __table_args__ = (UniqueConstraint('ip', 'task_id', name='unique_vote'),)

class Tasks(Base):
    __tablename__ = 'tasks'
    task_id = Column(Integer, Sequence('task_id_seq'),  primary_key=True)
    name = Column(String(255))
    desc = Column(Text)
    show = Column(Boolean, default=0)
    vote_done = Column(Boolean, default=0)

class Langs(Base):
    __tablename__ = 'langs'
    lang_id = Column(Integer, Sequence('lang_id_seq'), primary_key=True)
    name = Column(String(255))
    lexer = Column(String(255))
    codemirror = Column(String(255))
    codemirror_deps = Column(String(255))

class Pastes(Base):
    __tablename__ = 'pastes'
    paste_id = Column(Integer, Sequence('paste_id_seq'), primary_key=True)
    lang_id = Column(Integer)
    task_id = Column(Integer)
    paste = Column(Text)
    __table_args__ = (UniqueConstraint('lang_id', 'task_id',
                      name='unique_paste'),)

class Users(Base):
    __tablename__ = 'users'
    user_id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    ip = Column(String(45), primary_key=True)
    lang_id = Column(Integer)

@route('/vote')
def vote(db):
    ip = request.environ.get('REMOTE_ADDR')
    task_id = request.query.task_id
    lang_id = request.query.lang_id
    html = HTML_HEADER
    if (not task_id) or (not lang_id):
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: task_id/lang_id not given!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if db.query(Users).filter_by(ip=ip).all():
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: You may not vote!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    try:
        db.query(Langs).filter_by(lang_id=lang_id).one()
        task_db = db.query(Tasks).filter_by(task_id=task_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: Task or language does not exist!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if not task_db.show:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: This task is still hidden!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if task_db.vote_done:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: You can not vote for this anymore!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    for lang in db.query(Langs):
        if not db.query(Pastes).filter_by(task_id=task_id,
                                          lang_id=lang.lang_id).all():
            # Someone has not submitted code yet
            html += '<span class="task">\n'
            html += '<span class="desc">\n'
            html += '<p>Error: Vote is not open yet!</p>\n'
            html += '<a href="/">Go back</a>\n'
            html += '</span>\n' # desc
            html += '</span>\n' # task
            html += HTML_FOOTER
            return html
    newvote = Votes(ip=ip, lang_id=lang_id, task_id=task_id)
    session = create_session()
    try:
        session.add(newvote)
        session.commit()
    except sqlalchemy.exc.IntegrityError:
        session.rollback()
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: You already voted for this task!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    else: 
        redirect('/')
    finally:
        session.close()

@route('/getvotes')
def getvotes(db):
    langs = db.query(Langs)
    task_id = request.query.task_id
    html = HTML_HEADER
    if not task_id:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: task_id is not given!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    try:
        task = db.query(Tasks).filter_by(task_id=task_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: task does not exist!</p>\n'
        html += '<a href="/">go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if not task.show:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: This task is still hidden!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if not task.vote_done:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: votes for this task are not done yet!</p>\n'
        html += '<a href="/">go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    html += '<span class="tasklist voteresult">\n'
    html += '<span class="task">\n'
    html += '<span class="taskname">{}</span>\n'.format(task.name)
    total = db.query(Votes).filter_by(task_id=task_id).count()
    counts = {}
    for lang in langs:
        count = db.query(Votes).filter_by(
            task_id=task_id, lang_id=lang.lang_id).count()
        if count != 0:
            counts[lang.name] = count
    chd = 't:' + ','.join([ str(val) for val in counts.values() ]) 
    chl = '|'.join(counts.keys())
    data = {
        'cht': 'p3',
        'chs': '375x150',
        'chd': chd,
        'chl': chl,
    }
    urlstring = urllib.parse.urlencode(data)
    html += ('<img src="http://chart.apis.google.com/chart?{}" '
             'alt="pie chart" />\n'.format(urlstring))
    html += '<span class="desc">\n'
    cntstr = 'vote' if total == 1 else 'votes'
    html += '<p>Total {} {}.</p>\n'.format(total, cntstr)
    html += '<ul>\n'
    for lang in counts.keys():
        val = counts[lang]
        cntstr = 'vote' if val == 1 else 'votes'
        html += '<li>{} - {} {} ({}%)</li>\n'.format(
            lang, val, cntstr, round(100/total*val))
    html += '</ul>\n'
    html += '<span class="taskbottom"><a href="/">Go back</a></span>\n'
    html += '</span>\n' # task
    html += '</span>\n' # tasklist
    html += HTML_FOOTER
    return html

@route('/submit')
def submit_get(db):
    task_id = request.query.task_id
    lang_id = request.query.lang_id
    html = HTML_HEADER
    if (not task_id) or (not lang_id):
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: task_id/lang_id not given!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    try:
        lang_db = db.query(Langs).filter_by(lang_id=lang_id).one()
        task_db = db.query(Tasks).filter_by(task_id=task_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: This language or task does not exist!</p>\n'
        html += '<a href="/">go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    lang_cm = lang_db.codemirror
    cm_deps = lang_db.codemirror_deps
    html += '<div class="tasklist">\n'
    html += '<span class="task">'
    html += '<span class="taskname">{}</span>\n'.format(task_db.name)
    html += '<span class="desc">\n'
    html += '<p>\n'
    html += '<form action="" method="post">\n'
    html += ('<textarea name="paste" id="paste" cols="80" rows="25">'
             '</textarea><br />\n')
    html += ('<input name="task_id" value="{}" type="hidden" />\n'
             .format(task_id))
    html += ('<input name="lang_id" value="{}" type="hidden" />\n'
             .format(lang_id))
    html += '<input type="submit" value="Submit" />\n'
    html += '</form>\n'
    html += '<script src="codemirror/lib/codemirror.js"></script>\n'
    langs = []
    langs += cm_deps.split(',')
    langs.append(lang_cm)
    for lang in langs:
        if lang:
            html += ('<script src="codemirror/mode/{}/{}.js">'
                     '</script>\n'.format(lang, lang))
    html += '<script type="text/javascript">\n'
    html += 'var textfield = document.getElementById("paste");\n'
    cmconfig = ('{{ lineNumbers: true, mode: "{}", theme: "monokai", '
                'indentUnit: 4 }}'.format(lang_cm))
    html += ('var myCodeMirror = CodeMirror.fromTextArea('
             'textfield, {});\n'.format(cmconfig))
    html += '</script>\n'
    html += '</p>\n'
    html += '</span>\n'
    html += '<span class="taskbottom">\n'
    html += '<a href="/">Go back</a>\n'
    html += '</span>\n' # taskbottom
    html += '</span>\n' # task
    html += '</div>\n' # tasklist
    html += HTML_FOOTER
    return html

@post('/submit')
def submit_post(db):
    ip = request.environ.get('REMOTE_ADDR')
    text = request.forms.paste
    lang_id = request.forms.lang_id
    task_id = request.forms.task_id
    session = create_session()
    html = HTML_HEADER
    try:
        user = db.query(Users).filter_by(ip=ip).one()
    except sqlalchemy.orm.exc.NoResultFound:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: You are not a valid user!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if str(user.lang_id) != lang_id:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += ('<p>Error: You are not allowed to submit code for this '
                 'language!</p>\n')
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    try:
        db.query(Langs).filter_by(lang_id=lang_id).one()
        task_db = db.query(Tasks).filter_by(task_id=task_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: Task or language does not exist!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if not task_db.show:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: This task is still hidden!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    paste = Pastes(lang_id=lang_id, task_id=task_id, paste=text)
    try:
        session.add(paste)
        session.commit()
    except sqlalchemy.exc.IntegrityError:
        session.rollback()
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: there is already a paste for that!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    else: 
        redirect('/')
    finally:
        session.close()

@route('/source')
def get_source(db):
    task_id = request.query.task_id
    lang_id = request.query.lang_id
    raw = request.query.raw
    download = request.query.download
    taskname = db.query(Tasks).filter_by(task_id=task_id).one().name
    html = ''
    text = db.query(Pastes).filter_by(lang_id=lang_id,
                                      task_id=task_id).all()
    html += HTML_HEADER
    if (not task_id) or (not lang_id):
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: task_id/lang_id not given!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    try:
        lang_db = db.query(Langs).filter_by(lang_id=lang_id).one()
        task_db = db.query(Tasks).filter_by(task_id=task_id).one()
    except sqlalchemy.orm.exc.NoResultFound:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: Task or language does not exist!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if not task_db.show:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: This task is still hidden!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if text:
        text = text[0].paste
    else:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: There is no paste for that!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    if raw:
        response.content_type = 'text/plain'
        return text
    if download:
        response.content_type = 'text/plain'
        response.set_header('Content-Disposition', 'attachment; '
                            'filename={}_{}.txt'.format(task_id, lang_id))
        return text
    lexer_name = lang_db.lexer
    try:
        lexer = pygments.lexers.get_lexer_by_name(lexer_name)
    except pygments.util.ClassNotFound:
        lexer = pygments.lexers.TextLexer
    formatter = pygments.formatters.HtmlFormatter(linenos='inline',
                                                  style='monokai')
    html += '<div class="tasklist">\n'
    html += '<span class="task">\n'
    html += '<span class="taskname">{}</span>\n'.format(taskname)
    html += '<span class="raw">'
    html += '<a href="?task_id={}&lang_id={}&raw=1">raw</a> / \n'.format(
        task_id, lang_id)
    html += ('<a href="?task_id={}&lang_id={}&download=1">download</a> /'
             '\n'.format(task_id, lang_id))
    html += '<a href="/">Go back</a>\n'
    html += '</span>' # raw
    html += '<span class="desc"><p>\n'
    html += pygments.highlight(text, lexer, formatter)
    html += '</p></span>\n'
    html += '<span class="taskbottom">\n'
    html += '<a href="/">Go back</a>\n'
    html += '</span>\n' # taskbottom
    html += '</span>\n' # task
    html += '</div>\n' # tasklist
    html += HTML_FOOTER
    return html

@route('/signup')
def signup(db):
    langs = db.query(Langs)
    signup_lang = request.query.lang
    ip = request.environ.get('REMOTE_ADDR')
    html = HTML_HEADER
    langcnt = 0
    if signup_lang:
        if not langs.filter_by(lang_id=signup_lang).all():
            html += '<span class="task">\n'
            html += '<span class="desc">\n'
            html += '<p>Error: This language does not exist!</p>\n'
            html += '<a href="/">go back</a>\n'
            html += HTML_FOOTER
            return html
        session = create_session()
        user = Users(ip=ip, lang_id=signup_lang)
        try:
            session.add(user)
            session.commit()
        except sqlalchemy.exc.IntegrityError:
            pass
        except sqlalchemy.SQLAlchemyError:
            html += 'wtf'
        else:
            redirect('/')
        finally:
            session.close()
    if db.query(Users).filter_by(ip=ip).all(): # already signed up
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>You did already sign up!</p>\n'
        html += '<a href="/">go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    for lang in langs:
        if not db.query(Users).filter_by(lang_id=lang.lang_id).all():
            # nobody signed up yet
            html += '<p><div class="vote">\n'
            html += ('<a href="?lang={}">Sign up for {}</a>\n'
                     .format(lang.lang_id, lang.name))
            html += '</div></p>\n'
            langcnt += 1
    if not langcnt:
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>There are no more languages to sign up for! :(</p>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
    html += HTML_FOOTER
    return html

@route('/')
def main(db):
    tasks = db.query(Tasks).filter_by(show=1)
    langs = db.query(Langs)
    ip = request.environ.get('REMOTE_ADDR')
    acc = db.query(Users).filter_by(ip=ip).all() # Signed in
    html = ''
    html += HTML_HEADER
    html += '<div class="tasklist">\n'
    if not tasks.all():
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += 'There are no tasks yet! :('
        html += '</span>'
        html += '</span>'
    for task in tasks: # task box
        html += '<span class="task">\n'
        html += '<span class="taskname">{}</span>\n'.format(task.name)
        html += '<span class="desc"><p>{}</p></span>\n'.format(task.desc)
        votes_open = True
        code = []
        for lang in langs: # code: box
            if db.query(Pastes).filter_by(task_id=task.task_id,
                                          lang_id=lang.lang_id).all():
                code.append('<a href="/source?task_id={}&lang_id={}">{}'
                            '</a>\n'.format(task.task_id, lang.lang_id,
                            lang.name))
            else:
                votes_open = False # votes are closed as long as any group did
                                   # not paste yet
        if code:
            html += '<span class="taskbottom">\n'
            html += 'Code: '
            html += ', '.join(code)
            html += '</span>\n'
        if acc: # Submit code
            html += '<span class="vote">\n'
            html += ('<a href="/submit?lang_id={}&task_id={}">'
                     'Submit code</a>\n'.format(acc[0].lang_id, task.task_id))
            html += '</span>\n'
        elif votes_open and not task.vote_done: # Vote buttons
            voted = False
            for lang in langs:
                vote = db.query(Votes).filter_by(task_id=task.task_id,
                                                 lang_id=lang.lang_id,
                                                 ip=ip)
                if vote.all():
                    html += ('<span class="votetext">You voted for {}</span>\n'
                             .format(lang.name))
                    voted = True
            if not voted:
                html += '<span class="votetext">Vote: </span>'
                for lang in langs:
                    html += ('<a class="vote" href="/vote?lang_id={}'
                             '&amp;task_id={}">{}</a> \n'.format(lang.lang_id,
                             task.task_id, lang.name))
        elif task.vote_done: # Votes done
            html += ('<a class="vote" href="/getvotes?task_id={}">Show '
                     'results</a>\n'.format(task.task_id))
        else: # Cannot vote yet
            html += ('<span class="votetext">Can\'t vote for this task '
                     'yet!</span>\n')
        html+='</span>\n' # task
    html += '</div>\n' # tasklist
    html += HTML_FOOTER
    return html

@route('/new')
def new_get(db):
    html = HTML_HEADER
    html += '<div class="tasklist">\n'
    html += '<span class="task">\n'
    html += '<form action="" method="post">\n'
    html += '<span class="taskname">\n'
    html += 'Title: <input type="text" name="title" />\n'
    html += '</span>\n' # taskname
    html += '<span class="desc">\n'
    html += 'Description:<br />\n'
    html += '<textarea name="desc" cols="50" rows="10"></textarea><br />\n'
    html += '<input type="submit" value="Submit" />\n'
    html += '</span>\n' # desc
    html += '</span>\n' # task
    html += '</div>\n' # tasklist
    html += '</form>\n'
    html += HTML_FOOTER
    return html

@post('/new')
def new_post(db):
    title = request.forms.title
    desc = request.forms.desc
    html = HTML_HEADER
    if (not title) or (not desc):
        html += '<span class="task">\n'
        html += '<span class="desc">\n'
        html += '<p>Error: Either title or description are missing!</p>\n'
        html += '<a href="/">Go back</a>\n'
        html += '</span>\n' # desc
        html += '</span>\n' # task
        html += HTML_FOOTER
        return html
    task = Tasks(name=title, desc=desc, show=0, vote_done=0)
    db.add(task)
    html += '<span class="task">\n'
    html += '<span class="desc">\n'
    html += '<p>Thanks, your task has been added!</p>\n'
    html += '<a href="/">Go back</a>\n'
    html += '</span>\n' # desc
    html += '</span>\n' # task
    html += HTML_FOOTER
    return html

@route('/static/<filename>')
def serve_static(filename):
    return static_file(filename, root=(__PATH__ + '/static'))

@route('/codemirror/<path:path>')
def serve_codemirror(path):
    return static_file(path, root=(__PATH__ + '/codemirror'))

bottle.install(SQLAlchemyPlugin(engine, Base.metadata, create=True))

if __name__ == '__main__':
    if 'cherry' in sys.argv:
        bottle.run(server='cherrypy', host='0.0.0.0')
    elif 'flup' in sys.argv:
        from bottle import FlupFCGIServer
        bottle.run(
            server=FlupFCGIServer,
            bindAddress='/run/lighttpd/npc.sock'
        )
    else:
        bottle.debug(True)
        bottle.run(reloader=True, host='0.0.0.0')