forked from pajbot/pajbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·797 lines (675 loc) · 28.1 KB
/
app.py
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
#!/usr/bin/env python3
import sys
import argparse
import os
import configparser
import json
import math
import logging
import subprocess
import datetime
import urllib
from pajbot.bot import Bot
from pajbot.web.routes import api
from pajbot.web.routes import admin
from pajbot.web.models import errors
from pajbot.models.db import DBManager
from pajbot.tbutil import load_config, init_logging, time_nonclass_method
from pajbot.models.deck import Deck
from pajbot.models.command import CommandExample
from pajbot.models.user import User
from pajbot.models.duel import UserDuelStats
from pajbot.models.stream import Stream, StreamChunk, StreamChunkHighlight
from pajbot.models.webcontent import WebContent
from pajbot.models.time import TimeManager
from pajbot.models.pleblist import PleblistSong
from pajbot.models.sock import SocketClientManager
from pajbot.models.module import ModuleManager
from pajbot.apiwrappers import TwitchAPI
from pajbot.tbutil import time_since
from pajbot.tbutil import find
import markdown
from flask import Flask
from flask import request
from flask import render_template
from flask import Markup
from flask import redirect
from flask import url_for
from flask import session
from flask import jsonify
from flask.ext.scrypt import generate_random_salt
from flask.ext.assets import Environment, Bundle
from flask_oauthlib.client import OAuth
from flask_oauthlib.client import OAuthException
# from flask import make_response
# from flask import jsonify
from sqlalchemy import func, cast, Date
init_logging('pajbot')
log = logging.getLogger('pajbot')
app = Flask(__name__)
app._static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
app.register_blueprint(api.page)
app.register_blueprint(admin.page)
assets = Environment(app)
# Basic CSS and Javascript:
# Available under: base_css, semantic_css, base_js
base_css = Bundle('css/base.min.css',
output='css/base.gen.%(version)s.css')
semantic_css = Bundle('semantic/semantic.min.css',
output='semantic/semantic.gen.%(version)s.css')
base_js = Bundle('scripts/base.js', filters='jsmin',
output='scripts/base.gen.%(version)s.js')
semantic_js = Bundle('semantic/semantic.min.js',
output='semantic/semantic.gen.%(version)s.js')
assets.register('base_css', base_css)
assets.register('base_js', base_js)
assets.register('semantic_css', semantic_css)
assets.register('semantic_js', semantic_js)
# Pleblist-related javascript
# Available undeer the following assets: pleblist_shared, pleblist_host, pleblist_client
pleblist_client = Bundle('scripts/pleblist.js', filters='jsmin',
output='scripts/pleblist.gen.%(version)s.js')
pleblist_shared = Bundle('scripts/pleblist.shared.js', filters='jsmin',
output='scripts/pleblist.gen.shared.%(version)s.js')
pleblist_host = Bundle('scripts/pleblist.host.js', filters='jsmin',
output='scripts/pleblist.gen.host.%(version)s.js')
assets.register('pleblist_shared', pleblist_shared)
assets.register('pleblist_client', pleblist_client)
assets.register('pleblist_host', pleblist_host)
# CLR Overlay
# Availabe under: clr_overlay
clr_overlay = Bundle('scripts/clr.overlay.js', filters='jsmin',
output='scripts/clr.gen.overlay.%(version)s.js')
assets.register('clr_overlay', clr_overlay)
# Admin site
# Availabe under: admin_create_banphrase, admin_create_command,
# admin_create_row, admin_edit_command
admin_create_banphrase = Bundle('scripts/admin/create_banphrase.js', filters='jsmin',
output='scripts/admin/create_banphrase.gen.%(version)s.js')
admin_create_command = Bundle('scripts/admin/create_command.js', filters='jsmin',
output='scripts/admin/create_command.gen.%(version)s.js')
admin_create_row = Bundle('scripts/admin/create_row.js', filters='jsmin',
output='scripts/admin/create_row.gen.%(version)s.js')
admin_edit_command = Bundle('scripts/admin/edit_command.js', filters='jsmin',
output='scripts/admin/edit_command.gen.%(version)s.js')
assets.register('admin_create_banphrase', admin_create_banphrase)
assets.register('admin_create_command', admin_create_command)
assets.register('admin_create_row', admin_create_row)
assets.register('admin_edit_command', admin_edit_command)
config = configparser.ConfigParser()
parser = argparse.ArgumentParser(description='start the web app')
parser.add_argument('--config', default='config.ini')
parser.add_argument('--host', default='0.0.0.0')
parser.add_argument('--port', type=int, default=2325)
parser.add_argument('--debug', dest='debug', action='store_true')
parser.add_argument('--no-debug', dest='debug', action='store_false')
parser.set_defaults(debug=False)
args = parser.parse_args()
config = load_config(args.config)
if 'web' not in config:
log.error('Missing [web] section in config.ini')
sys.exit(1)
if 'pleblist_password_salt' not in config['web']:
salt = generate_random_salt()
config.set('web', 'pleblist_password_salt', salt.decode('utf-8'))
if 'secret_key' not in config['web']:
salt = generate_random_salt()
config.set('web', 'secret_key', salt.decode('utf-8'))
if 'logo' not in config['web']:
twitchapi = TwitchAPI()
try:
data = twitchapi.get(['users', config['main']['streamer']], base='https://api.twitch.tv/kraken/')
log.info(data)
if data:
logo_raw = 'static/images/logo_{}.png'.format(config['main']['streamer'])
logo_tn = 'static/images/logo_{}_tn.png'.format(config['main']['streamer'])
with urllib.request.urlopen(data['logo']) as response, open(logo_raw, 'wb') as out_file:
data = response.read()
out_file.write(data)
try:
from PIL import Image
im = Image.open(logo_raw)
im.thumbnail((64, 64), Image.ANTIALIAS)
im.save(logo_tn, 'png')
except:
pass
config.set('web', 'logo', 'set')
log.info('set logo')
except:
pass
with open(args.config, 'w') as configfile:
config.write(configfile)
app.secret_key = config['web']['secret_key']
oauth = OAuth(app)
if 'sock' in config and 'sock_file' in config['sock']:
SocketClientManager.init(config['sock']['sock_file'])
twitch = oauth.remote_app(
'twitch',
consumer_key=config['webtwitchapi']['client_id'],
consumer_secret=config['webtwitchapi']['client_secret'],
request_token_params={'scope': 'user_read'},
base_url='https://api.twitch.tv/kraken/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://api.twitch.tv/kraken/oauth2/token',
authorize_url='https://api.twitch.tv/kraken/oauth2/authorize',
)
DBManager.init(config['main']['db'])
TimeManager.init_timezone(config['main'].get('timezone', 'UTC'))
with DBManager.create_session_scope() as db_session:
custom_web_content = {}
for web_content in db_session.query(WebContent).filter(WebContent.content is not None):
custom_web_content[web_content.page] = web_content.content
errors.init(app)
api.config = config
modules = config['web'].get('modules', '').split()
bot_commands_list = []
from flask import make_response
from functools import wraps, update_wrapper
def nocache(view):
@wraps(view)
def no_cache(*args, **kwargs):
response = make_response(view(*args, **kwargs))
response.headers['Last-Modified'] = datetime.datetime.now()
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
return update_wrapper(no_cache, view)
def update_commands(signal_id):
global bot_commands_list
from pajbot.models.command import CommandManager
bot_commands = CommandManager(
socket_manager=None,
module_manager=ModuleManager(None).load(),
bot=None).load(load_examples=True)
bot_commands_list = bot_commands.parse_for_web()
bot_commands_list = sorted(bot_commands_list, key=lambda x: (x.id or -1, x.main_alias))
del bot_commands
update_commands(26)
try:
import uwsgi
from uwsgidecorators import thread, timer
uwsgi.register_signal(26, "worker", update_commands)
uwsgi.add_timer(26, 60 * 10)
@thread
@timer(5)
def get_highlight_thumbnails(no_clue_what_this_does):
from pajbot.web.models.thumbnail import StreamThumbnailWriter
with DBManager.create_session_scope() as db_session:
highlights = db_session.query(StreamChunkHighlight).filter_by(thumbnail=None).all()
if len(highlights) > 0:
log.info('Writing {} thumbnails...'.format(len(highlights)))
StreamThumbnailWriter(config['main']['streamer'], [h.id for h in highlights])
log.info('Done!')
for highlight in highlights:
highlight.thumbnail = True
except ImportError:
pass
@app.route('/')
def index():
custom_content = custom_web_content.get('home', '')
try:
custom_content = Markup(markdown.markdown(custom_content))
except:
log.exception('Unhandled exception in def index')
return render_template('index.html',
custom_content=custom_content)
@app.route('/commands/')
def commands():
custom_commands = []
point_commands = []
moderator_commands = []
for command in bot_commands_list:
if command.level > 100 or command.mod_only:
moderator_commands.append(command)
elif command.cost > 0:
point_commands.append(command)
else:
custom_commands.append(command)
return render_template('commands.html',
custom_commands=sorted(custom_commands, key=lambda f: f.command),
point_commands=sorted(point_commands, key=lambda a: (a.cost, a.command)),
moderator_commands=sorted(moderator_commands, key=lambda c: (c.level if c.mod_only is False else 500, c.command)))
@app.route('/commands/<raw_command_string>')
def command_detailed(raw_command_string):
command_string_parts = raw_command_string.split('-')
command_string = command_string_parts[0]
command_id = None
try:
command_id = int(command_string)
except ValueError:
pass
if command_id is not None:
command = find(lambda c: c.id == command_id, bot_commands_list)
else:
command = find(lambda c: c.resolve_string == command_string, bot_commands_list)
if command is None:
# XXX: Is it proper to have it return a 404 code as well?
return render_template('command_404.html')
examples = command.autogenerate_examples()
return render_template('command_detailed.html', command=command, examples=examples)
@app.route('/decks/')
def decks():
session = DBManager.create_session()
top_decks = []
for deck in session.query(Deck).order_by(Deck.last_used.desc(), Deck.first_used.desc())[:25]:
top_decks.append(deck)
session.close()
return render_template('decks/all.html',
top_decks=top_decks,
deck_class=None)
@app.route('/decks/druid/')
def decks_druid():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='druid').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Druid')
@app.route('/decks/hunter/')
def decks_hunter():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='hunter').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Hunter')
@app.route('/decks/mage/')
def decks_mage():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='mage').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Mage')
@app.route('/decks/paladin/')
def decks_paladin():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='paladin').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Paladin')
@app.route('/decks/priest/')
def decks_priest():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='priest').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Priest')
@app.route('/decks/rogue/')
def decks_rogue():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='rogue').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Rogue')
@app.route('/decks/shaman/')
def decks_shaman():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='shaman').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Shaman')
@app.route('/decks/warlock/')
def decks_warlock():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='warlock').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Warlock')
@app.route('/decks/warrior/')
def decks_warrior():
session = DBManager.create_session()
decks = session.query(Deck).filter_by(deck_class='warrior').order_by(Deck.last_used.desc(), Deck.first_used.desc()).all()
session.close()
return render_template('decks/by_class.html',
decks=decks,
deck_class='Warrior')
@app.route('/user/<username>')
def user_profile(username):
session = DBManager.create_session()
user = session.query(User).filter_by(username=username).one_or_none()
if user is None:
return render_template('no_user.html'), 404
rank = session.query(func.Count(User.id)).filter(User.points > user.points).one()
rank = rank[0] + 1
user.rank = rank
user_duel_stats = session.query(UserDuelStats).filter_by(user_id=user.id).one_or_none()
try:
return render_template('user.html',
user=user,
user_duel_stats=user_duel_stats)
finally:
session.close()
@app.route('/points/')
def points():
custom_content = custom_web_content.get('points', '')
try:
custom_content = Markup(markdown.markdown(custom_content))
except:
log.exception('Unhandled exception in def index')
session = DBManager.create_session()
top_30_users = []
for user in session.query(User).order_by(User.points.desc())[:30]:
top_30_users.append(user)
session.close()
return render_template('points.html',
top_30_users=top_30_users,
custom_content=custom_content)
@app.route('/debug')
def debug():
return render_template('debug.html')
@app.route('/stats/')
def stats():
top_5_commands = sorted(bot_commands_list, key=lambda c: c.data.num_uses if c.data is not None else -1, reverse=True)[:5]
if 'linefarming' in modules:
session = DBManager.create_session()
top_5_line_farmers = session.query(User).order_by(User.num_lines.desc())[:5]
session.close()
else:
top_5_line_farmers = []
return render_template('stats.html',
top_5_commands=top_5_commands,
top_5_line_farmers=top_5_line_farmers)
@app.route('/stats/duels/')
def stats_duels():
session = DBManager.create_session()
data = {
'top_5_winners': session.query(UserDuelStats).order_by(UserDuelStats.duels_won.desc())[:5],
'top_5_points_won': session.query(UserDuelStats).order_by(UserDuelStats.profit.desc())[:5],
'top_5_points_lost': session.query(UserDuelStats).order_by(UserDuelStats.profit.asc())[:5],
'top_5_losers': session.query(UserDuelStats).order_by(UserDuelStats.duels_lost.desc())[:5],
'top_5_winrate': session.query(UserDuelStats).filter(UserDuelStats.duels_won >= 5).order_by(UserDuelStats.winrate.desc())[:5],
'bottom_5_winrate': session.query(UserDuelStats).filter(UserDuelStats.duels_lost >= 5).order_by(UserDuelStats.winrate.asc())[:5],
}
try:
return render_template('stats_duels.html', **data)
finally:
session.close()
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/highlights/<date>/')
def highlight_list_date(date):
# Make sure we were passed a valid date
try:
parsed_date = datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
# Invalid date
return redirect('/highlights/', 303)
session = DBManager.create_session()
dates_with_highlights = []
highlights = session.query(StreamChunkHighlight).filter(cast(StreamChunkHighlight.created_at, Date) == parsed_date).order_by(StreamChunkHighlight.created_at.desc()).all()
for highlight in session.query(StreamChunkHighlight):
dates_with_highlights.append(datetime.datetime(
year=highlight.created_at.year,
month=highlight.created_at.month,
day=highlight.created_at.day))
try:
return render_template('highlights_date.html',
highlights=highlights,
date=parsed_date,
dates_with_highlights=set(dates_with_highlights))
finally:
session.close()
@app.route('/highlights/<date>/<highlight_id>', defaults={'highlight_title': None})
@app.route('/highlights/<date>/<highlight_id>-<highlight_title>')
def highlight_id(date, highlight_id, highlight_title=None):
session = DBManager.create_session()
highlight = session.query(StreamChunkHighlight).filter_by(id=highlight_id).first()
if highlight is None:
session.close()
return render_template('highlight_404.html'), 404
else:
stream_chunk = highlight.stream_chunk
stream = stream_chunk.stream
session.close()
return render_template('highlight.html',
highlight=highlight,
stream_chunk=stream_chunk,
stream=stream)
@app.route('/highlights/')
def highlights():
session = DBManager.create_session()
dates_with_highlights = []
highlights = session.query(StreamChunkHighlight).order_by(StreamChunkHighlight.created_at_with_offset.desc()).all()
for highlight in highlights:
dates_with_highlights.append(datetime.datetime(
year=highlight.created_at.year,
month=highlight.created_at.month,
day=highlight.created_at.day))
try:
return render_template('highlights.html',
highlights=highlights[:10],
dates_with_highlights=set(dates_with_highlights))
finally:
session.close()
@app.route('/pleblist/')
def pleblist():
return render_template('pleblist.html')
@app.route('/pleblist/host/')
def pleblist_host():
return render_template('pleblist_host.html')
@app.route('/pleblist/history/')
def pleblist_history_redirect():
with DBManager.create_session_scope() as session:
current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start.desc()).first()
if current_stream is not None:
return redirect('/pleblist/history/{}/'.format(current_stream.id), 303)
last_stream = session.query(Stream).filter_by(ended=True).order_by(Stream.stream_start.desc()).first()
if last_stream is not None:
return redirect('/pleblist/history/{}/'.format(last_stream.id), 303)
return render_template('pleblist_history_no_stream.html'), 404
@app.route('/pleblist/history/<stream_id>/')
def pleblist_history_stream(stream_id):
with DBManager.create_session_scope() as session:
stream = session.query(Stream).filter_by(id=stream_id).one_or_none()
if stream is None:
return render_template('pleblist_history_404.html'), 404
songs = session.query(PleblistSong).filter(PleblistSong.stream_id == stream.id).order_by(PleblistSong.date_added.asc(), PleblistSong.date_played.asc()).all()
total_length_left = sum([song.song_info.duration if song.date_played is None and song.song_info is not None else 0 for song in songs])
first_unplayed_song = find(lambda song: song.date_played is None, songs)
stream_chunks = session.query(StreamChunk).filter(StreamChunk.stream_id == stream.id).all()
return render_template('pleblist_history.html',
stream=stream,
songs=songs,
total_length_left=total_length_left,
first_unplayed_song=first_unplayed_song,
stream_chunks=stream_chunks)
@app.route('/discord')
def discord():
return render_template('discord.html')
@app.route('/test/')
def test():
return render_template('test.html')
@app.route('/clr/overlay/<widget_id>')
@nocache
def clr_overlay(widget_id):
if widget_id == config['web']['clr_widget_id'] or True:
return render_template('clr/overlay.html',
widget={})
else:
return render_template('errors/404.html'), 404
@app.route('/login')
def login():
return twitch.authorize(callback=config['webtwitchapi']['redirect_uri'] if 'redirect_uri' in config['webtwitchapi'] else url_for('authorized', _external=True))
@app.route('/login/error')
def login_error():
return render_template('login_error.html')
@app.route('/login/authorized')
def authorized():
try:
resp = twitch.authorized_response()
except OAuthException:
log.exception('An exception was caught while authorizing')
return redirect(url_for('index'))
print(resp)
if resp is None:
log.warn('Access denied: reason={}, error={}'.format(request.args['error'], request.args['error_description']))
return redirect(url_for('index'))
elif type(resp) is OAuthException:
log.warn(resp.message)
log.warn(resp.data)
log.warn(resp.type)
return redirect(url_for('login_error'))
session['twitch_token'] = (resp['access_token'], )
me = twitch.get('user')
session['user'] = {
'username': me.data['name'],
'username_raw': me.data['display_name'],
}
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('twitch_token', None)
session.pop('user', None)
return redirect(url_for('index'))
@twitch.tokengetter
def get_twitch_oauth_token():
return session.get('twitch_token')
def change_twitch_header(uri, headers, body):
auth = headers.get('Authorization')
if auth:
auth = auth.replace('Bearer', 'OAuth')
headers['Authorization'] = auth
return uri, headers, body
twitch.pre_request = change_twitch_header
@app.template_filter()
def date_format(value, format='full'):
if format == 'full':
date_format = '%Y-%m-%d %H:%M:%S'
return value.strftime(date_format)
@app.template_filter('strftime')
def time_strftime(value, format):
return value.strftime(format)
@app.template_filter('localize')
def time_localize(value):
return TimeManager.localize(value)
@app.template_filter('unix_timestamp')
def time_unix_timestamp(value):
return value.timestamp()
@app.template_filter()
def number_format(value, tsep=',', dsep='.'):
s = str(value)
cnt = 0
numchars = dsep + '0123456789'
ls = len(s)
while cnt < ls and s[cnt] not in numchars:
cnt += 1
lhs = s[:cnt]
s = s[cnt:]
if not dsep:
cnt = -1
else:
cnt = s.rfind(dsep)
if cnt > 0:
rhs = dsep + s[cnt + 1:]
s = s[:cnt]
else:
rhs = ''
splt = ''
while s != '':
splt = s[-3:] + tsep + splt
s = s[:-3]
return lhs + splt[:-1] + rhs
module_manager = ModuleManager(None).load()
nav_bar_header = []
nav_bar_header.append(('/', 'home', 'Home'))
nav_bar_header.append(('/commands/', 'commands', 'Commands'))
if 'deck' in module_manager:
nav_bar_header.append(('/decks/', 'decks', 'Decks'))
if config['main']['nickname'] not in ['scamazbot']:
nav_bar_header.append(('/points/', 'points', 'Points'))
nav_bar_header.append(('/stats/', 'stats', 'Stats'))
nav_bar_header.append(('/highlights/', 'highlights', 'Highlights'))
if 'pleblist' in modules:
nav_bar_header.append(('/pleblist/history/', 'pleblist', 'Pleblist'))
nav_bar_admin_header = []
nav_bar_admin_header.append(('/', 'home', 'Home'))
nav_bar_admin_header.append(('/admin/', 'admin_home', 'Admin Home'))
nav_bar_admin_header.append(([
('/admin/banphrases/', 'admin_banphrases', 'Banphrases'),
('/admin/links/blacklist/', 'admin_links_blacklist', 'Blacklisted links'),
('/admin/links/whitelist/', 'admin_links_whitelist', 'Whitelisted links'),
], None, 'Filters'))
nav_bar_admin_header.append(('/admin/commands/', 'admin_commands', 'Commands'))
nav_bar_admin_header.append(('/admin/timers/', 'admin_timers', 'Timers'))
nav_bar_admin_header.append(('/admin/moderators/', 'admin_moderators', 'Moderators'))
nav_bar_admin_header.append(('/admin/modules/', 'admin_modules', 'Modules'))
if 'predict' in module_manager:
nav_bar_admin_header.append(('/admin/predictions/', 'admin_predictions', 'Predictions'))
version = Bot.version
last_commit = ''
commit_number = 0
try:
current_branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).decode('utf8').strip()
latest_commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf8').strip()[:8]
commit_number = subprocess.check_output(['git', 'rev-list', 'HEAD', '--count']).decode('utf8').strip()
last_commit = subprocess.check_output(['git', 'log', '-1', '--format=%cd']).decode('utf8').strip()
version = '{0} DEV ({1}, {2}, commit {3})'.format(version, current_branch, latest_commit, commit_number)
except:
pass
default_variables = {
'version': version,
'last_commit': last_commit,
'commit_number': commit_number,
'bot': {
'name': config['main']['nickname'],
},
'site': {
'domain': config['web']['domain'],
'deck_tab_images': config.getboolean('web', 'deck_tab_images'),
'websocket': {
'host': config['websocket'].get('host', config['web']['domain']),
'port': config['websocket']['port'],
'ssl': config.getboolean('websocket', 'ssl')
}
},
'streamer': {
'name': config['web']['streamer_name'],
'full_name': config['main']['streamer']
},
'nav_bar_header': nav_bar_header,
'nav_bar_admin_header': nav_bar_admin_header,
'modules': modules,
'request': request,
'session': session,
}
if 'streamtip' in config:
default_variables['streamtip_data'] = {
'client_id': config['streamtip']['client_id'],
'redirect_uri': config['streamtip']['redirect_uri'],
}
@app.context_processor
def current_time():
current_time = {}
current_time['current_time'] = datetime.datetime.now()
return current_time
@app.context_processor
def inject_default_variables():
return default_variables
@app.template_filter('time_ago')
def time_ago(t, format='long'):
return time_since(datetime.datetime.now().timestamp(), t.timestamp(), format)
@app.template_filter('time_diff')
def time_diff(t1, t2, format='long'):
return time_since(t1.timestamp(), t2.timestamp(), format)
@app.template_filter('time_ago_timespan_seconds')
def time_ago_timespan_seconds(t, format='long'):
v = time_since(t, 0, format)
return 'None' if len(v) == 0 else v
@app.template_filter('seconds_to_vodtime')
def seconds_to_vodtime(t):
s = int(t)
h = s / 3600
m = s % 3600 / 60
s = s % 60
return '%dh%02dm%02ds' % (h, m, s)
if __name__ == '__main__':
app.run(debug=args.debug, host=args.host, port=args.port)