-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrest.py
More file actions
571 lines (475 loc) · 16.6 KB
/
Copy pathrest.py
File metadata and controls
571 lines (475 loc) · 16.6 KB
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
import datetime
from flask import (
Response,
abort,
jsonify,
render_template,
redirect,
make_response,
url_for,
)
from typing import Any, Dict, List, Optional, Union
from werkzeug.datastructures import Authorization
from app import app, config, request
from data import Data
from events import (
Event,
StartStreamingEvent,
StopStreamingEvent,
SetDescriptionEvent,
SetViewerPasswordEvent,
SendBroadcastEvent,
SendMessageEvent,
SendActionEvent,
get_events,
insert_event,
)
from presence import stream_count, users_in_room
from helpers import (
PICTOCHAT_IMAGE_WIDTH,
PICTOCHAT_IMAGE_HEIGHT,
clean_symlinks,
emotes,
fetch_m3u8,
fetch_ts,
first_quality,
get_emoji_unicode_dict,
get_aliases_unicode_dict,
mysql,
now,
stream_live,
symlink,
)
# Allow cache-busting of entire frontend for stream page and chat updates.
FRONTEND_CACHE_BUST: str = "site.1.2.3"
@app.context_processor
def provide_globals() -> Dict[str, Any]:
return {
"cache_bust": f"v={FRONTEND_CACHE_BUST}",
}
@app.route('/')
def index() -> str:
cursor = mysql().execute(
"SELECT `username`, `key`, `description`, `streampass` FROM streamersettings",
)
streamers = [
{
'username': result['username'],
'live': stream_live(result['key'], first_quality()), 'count': stream_count(result['username'].lower()),
'description': emotes(result['description']) if result['description'] else '',
'locked': result['streampass'] is not None,
}
for result in cursor
]
return render_template('index.html', streamers=streamers)
@app.route('/<streamer>/')
def stream(streamer: str) -> Response:
data = mysql()
cursor = data.execute(
"SELECT username, streampass, mastodon, chat FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
result = cursor.fetchone()
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
return make_response(
render_template(
'password.html',
streamer=result["username"],
),
403
)
# The stream is either not password protected, or the user has already authenticated.
qualities = config.get('video_qualities', None)
if not qualities:
playlists = [{"src": url_for('streamplaylist', streamer=streamer), "label": "live", "type": "application/x-mpegURL"}]
else:
playlists = [{"src": url_for('streamplaylistwithquality', streamer=streamer, quality=quality), "label": quality, "type": "application/x-mpegURL"} for quality in qualities]
emojis = {
**get_emoji_unicode_dict('en'),
**get_aliases_unicode_dict(),
}
emojis = {key: emojis[key] for key in emojis if "__" not in key}
cursor = data.execute(
"SELECT alias, uri FROM emotes ORDER BY alias",
)
emotes = {f":{result['alias']}:": result['uri'] for result in cursor}
# Support themes drop-down and default theme.
themes = config.get('themes', [])
if not themes:
themes = ['default']
default = themes[0]
if len(themes) == 1:
themes = []
return make_response(
render_template(
'stream.html',
streamer=result["username"],
mastodon=result["mastodon"],
chat=result["chat"] or "enabled",
playlists=playlists,
emojis=emojis,
emotes=emotes,
icons=['admin', 'moderator'],
themes=themes,
default=default,
pictochat_image_width=PICTOCHAT_IMAGE_WIDTH,
pictochat_image_height=PICTOCHAT_IMAGE_HEIGHT,
)
)
@app.route('/<streamer>/password', methods=["POST"])
def password(streamer: str) -> Response:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
# Verify the password.
result = cursor.fetchone()
streampass = result['streampass']
if request.form.get('streampass') == streampass:
expire_date = datetime.datetime.now()
expire_date = expire_date + datetime.timedelta(days=1)
response = make_response(redirect(url_for("stream", streamer=result["username"])))
response.set_cookie("streampass", streampass, expires=expire_date)
return response
# Wrong password bucko!
return make_response(
render_template(
'password.html',
streamer=result["username"],
password_invalid=True,
),
403
)
@app.route('/<streamer>/info')
def streaminfo(streamer: str) -> Response:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass`, `key`, `description` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
# Doesn't cost us much, so let's clean up on the fly.
clean_symlinks()
result = cursor.fetchone()
# First, verify they're even allowed to see this stream.
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
abort(403)
# The stream is either not password protected, or the user has already authenticated.
live = stream_live(result['key'], first_quality())
return make_response(jsonify({
'live': live,
'count': stream_count(streamer) if live else 0,
'description': emotes(result['description']) if result['description'] else '',
}))
@app.route('/<streamer>/playlist.m3u8')
def streamplaylist(streamer: str) -> str:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass`, `key` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
result = cursor.fetchone()
# First ensure they're even allowed to see this stream.
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
abort(403)
# The stream is either not password protected, or the user has already authenticated.
key = result['key']
if not stream_live(key):
abort(404)
m3u8 = fetch_m3u8(key)
if m3u8 is None:
abort(404)
lines = m3u8.splitlines()
for i in range(len(lines)):
if lines[i].startswith(key) and lines[i][-3:] == ".ts":
# We need to rewrite this
oldname = lines[i]
newname = f"{streamer}" + lines[i][len(key):]
symlink(oldname, newname)
lines[i] = "/hls/" + newname
if key in lines[i]:
raise Exception("Possible stream key leak!")
# Doesn't cost us much, so let's clean up on the fly.
clean_symlinks()
m3u8 = "\n".join(lines)
return m3u8
@app.route('/<streamer>/playlist/<quality>.m3u8')
def streamplaylistwithquality(streamer: str, quality: str) -> str:
streamer = streamer.lower()
cursor = mysql().execute(
"SELECT `username`, `streampass`, `key` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
abort(404)
result = cursor.fetchone()
# First ensure they're even allowed to see this stream.
streampass = result['streampass']
if streampass is not None and request.cookies.get('streampass') != streampass:
# This stream is password protected!
abort(403)
# The stream is either not password protected, or the user has already authenticated.
key = result['key']
if not stream_live(key, quality):
abort(404)
m3u8 = fetch_m3u8(key, quality)
if m3u8 is None:
abort(404)
lines = m3u8.splitlines()
for i in range(len(lines)):
if lines[i].startswith(key + '_' + quality) and lines[i][-3:] == ".ts":
# We need to rewrite this
oldname = lines[i]
newname = f"{streamer}_{quality}" + lines[i][(len(key) + len(quality) + 1):]
symlink(oldname, newname)
lines[i] = "/hls/" + newname
if key in lines[i]:
raise Exception("Possible stream key leak!")
# Doesn't cost us much, so let's clean up on the fly.
clean_symlinks()
m3u8 = "\n".join(lines)
return m3u8
@app.route('/hls/<filename>')
def streamts(filename: str) -> Response:
# This is a debugging endpoint only, your production nginx setup should handle this.
ts = fetch_ts(filename)
if ts is None:
abort(404)
response = make_response(ts)
response.headers.set('Content-Type', 'video/mp2t')
return response
@app.route('/auth/on_publish', methods=["GET", "POST"])
def publishcheck() -> Response:
key = request.values.get('name')
if key is None:
# We don't have a stream key, deny it.
abort(404)
data = mysql()
cursor = data.execute(
"SELECT `username`, `description`, `streampass` FROM streamersettings WHERE `key` = :key",
{"key": key},
)
if cursor.rowcount != 1:
# We didn't find a registered streamer with this key, deny it.
abort(404)
# Log that we started streaming.
result = cursor.fetchone()
insert_event(
data,
StartStreamingEvent(
now(),
result["username"].lower(),
result["description"],
result["streampass"],
)
)
# This is fine, allow it
return make_response("Stream ok!", 200)
@app.route('/auth/on_publish_done', methods=["GET", "POST"])
def donepublishcheck() -> Response:
key = request.values.get('name')
if key is None:
# We don't have a stream key, can't link to an event.
return make_response("Stream ok!", 200)
data = mysql()
cursor = data.execute(
"SELECT `username` FROM streamersettings WHERE `key` = :key",
{"key": key},
)
if cursor.rowcount != 1:
# We didn't find a registered streamer with this key, can't link to an event.
return make_response("Stream ok!", 200)
# Log that we stopped streaming.
result = cursor.fetchone()
insert_event(
data,
StopStreamingEvent(
now(),
result["username"].lower(),
)
)
return make_response("Stream ok!", 200)
def get_auth(data: Data, auth: Optional[Authorization]) -> Optional[str]:
if not auth:
return None
if auth.type != "basic":
return None
if not auth.username or not auth.password:
return None
cursor = data.execute(
"SELECT `username`, `key` FROM streamersettings WHERE username = :username",
{"username": auth.username},
)
if cursor.rowcount != 1:
return None
result = cursor.fetchone()
if auth.password == result["key"]:
return auth.username.lower()
return None
def __info(data: Data, streamer: str) -> Response:
cursor = data.execute(
"SELECT `username`, `key`, `streampass`, `description` FROM streamersettings WHERE username = :username",
{"username": streamer},
)
if cursor.rowcount != 1:
# Shouldn't happen due to auth check, but let's be sure.
abort(404)
result = cursor.fetchone()
# First, verify they're even allowed to see this stream.
streampass = result['streampass'] or None
username = result['username']
description = result['description'] or ''
# Figure out if the stream itself is live.
live = stream_live(result['key'], first_quality())
# Grab viewer count, active chatters.
users = [u["username"] for u in users_in_room(streamer)]
viewers = stream_count(streamer) if live else 0
# Return all that info!
return make_response(jsonify({
'username': username,
'description': emotes(description),
'streampass': streampass,
'live': live,
'viewers': viewers,
'members': users,
}))
@app.route('/api/info', methods=["GET"])
def fetchinfo() -> Response:
data = mysql()
streamer = get_auth(data, request.authorization)
if not streamer:
abort(401)
return __info(data, streamer)
@app.route('/api/info', methods=["PATCH"])
def updateinfo() -> Response:
data = mysql()
streamer = get_auth(data, request.authorization)
if not streamer:
abort(401)
content = request.json
if isinstance(content, dict):
if 'description' in content:
description = str(content["description"] or "")
data.execute(
"UPDATE streamersettings SET description = :description WHERE username = :username LIMIT 1",
{"username": streamer, "description": description},
)
insert_event(
data,
SetDescriptionEvent(
now(),
streamer,
description,
)
)
if 'streampass' in content:
password = content["streampass"]
if not password:
password = None
else:
password = str(password)
data.execute(
"UPDATE streamersettings SET streampass = :password WHERE username = :username LIMIT 1",
{'username': streamer, 'password': password},
)
insert_event(
data,
SetViewerPasswordEvent(
now(),
streamer,
password,
)
)
return __info(data, streamer)
@app.route('/api/messages', methods=["GET"])
def getmessages() -> Response:
data = mysql()
streamer = get_auth(data, request.authorization)
if not streamer:
abort(401)
# Offer ability to limit to number of messages.
limitStr = request.args.get('limit', '')
if limitStr:
limit = int(limitStr)
else:
limit = None
# Offer ability to limit to only the last active stream.
lastStreamOnly = request.args.get('lastStreamOnly', '')
startEvent: Optional[Event] = None
if lastStreamOnly.lower() == "true":
startEvents = get_events(data, streamer=streamer, types=[StartStreamingEvent], limit=1)
if startEvents:
startEvent = startEvents[0]
else:
# No active stream, so no events to return.
return make_response(jsonify([]))
all_events = get_events(
data,
streamer=streamer,
types=[SendBroadcastEvent, SendMessageEvent, SendActionEvent],
after=startEvent,
limit=limit
)
# Now, serialize these out.
output: List[Dict[str, Union[str, int]]] = []
for event in all_events:
if isinstance(event, SendBroadcastEvent):
output.append({
"type": "broadcast",
"timestamp": event.timestamp,
"message": event.broadcast,
})
elif isinstance(event, SendMessageEvent):
output.append({
"type": "message",
"timestamp": event.timestamp,
"name": event.name,
"message": event.message,
})
elif isinstance(event, SendActionEvent):
output.append({
"type": "action",
"timestamp": event.timestamp,
"name": event.name,
"message": event.action,
})
return make_response(jsonify(output))
@app.route('/api/messages', methods=["POST"])
def sendmessage() -> Response:
data = mysql()
streamer = get_auth(data, request.authorization)
if not streamer:
abort(401)
content = request.json
if isinstance(content, dict):
messagetype: Optional[str] = None
message: Optional[str] = None
if "type" in content:
messagetype = str(content["type"])
if not messagetype:
messagetype = "normal"
if "message" in content:
message = str(content["message"])
if messagetype is None or message is None:
abort(400)
if messagetype not in {"normal", "action", "server"}:
abort(400)
data.execute(
"INSERT INTO pendingmessages (`username`, `type`, `message`) VALUES (:username, :type, :message)",
{'username': streamer, 'type': messagetype, 'message': message},
)
return make_response(jsonify({}))