forked from Chris230291/STB-Proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
458 lines (424 loc) · 14.7 KB
/
app.py
File metadata and controls
458 lines (424 loc) · 14.7 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
import stb
from flask import Flask, render_template, redirect, request, Response
from pathlib import Path
import os
import sys
import json
from urllib import parse
import subprocess
app = Flask(__name__)
basePath = Path(__file__).resolve().parent
if os.getenv("HOST"):
host = os.getenv("HOST")
else:
host = "localhost:8001"
if os.getenv("CONFIG"):
config_file = os.getenv("CONFIG")
else:
config_file = str(basePath) + "/config.json"
def getPortals():
try:
with open(config_file) as f:
data = json.load(f)
portals = data["portals"]
except:
print("Creating config file")
data = {}
data["portals"] = []
portals = []
savePortals(portals)
return portals
def savePortals(portals):
with open(config_file, "w") as f:
data = {}
data["portals"] = portals
json.dump(data, f, indent=4)
@app.route("/", methods=["GET"])
def home():
return redirect("/portals", code=302)
@app.route("/portals", methods=["GET"])
def portals():
names = []
masterBlacklist = "^((?=[a-zA-Z0-9_-]+).)*$"
blacklists = []
portals = getPortals()
if portals and len(portals) > 0:
for i in portals:
names.append(i["name"])
# ^((?!^word1$|^word2$)(?=[a-zA-Z0-9_-]+).)*$
masterBlacklist = "^((?!^" + ("$|^".join(names)) + "$)(?=[a-zA-Z0-9_-]+).)*$"
for i in portals:
inames = names.copy()
iname = i["name"]
inames.remove(iname)
blacklist = "^((?!^" + ("$|^".join(inames)) + "$)(?=[a-zA-Z0-9_-]+).)*$"
blacklists.append(blacklist)
return render_template(
"portals.html",
portals=portals,
masterBlacklist=masterBlacklist,
blacklists=blacklists,
)
@app.route("/portal/add", methods=["POST"])
def portalsAdd():
name = request.form["name"]
url = stb.getUrl(request.form["url"])
mac = request.form["mac"]
proxy = request.form["proxy"]
format = request.form["format"]
try:
portals = getPortals()
token = stb.getToken(url, mac)
expiry = stb.getExpires(url, mac, token)
portals.append(
{
"name": name,
"url": url,
"mac": mac,
"proxy": proxy,
"format": format,
"expires": expiry,
"enabled channels": [],
"custom channel names": {},
"custom genres": {},
}
)
savePortals(portals)
except:
print(sys.exc_info()[1])
pass
return redirect("/portals", code=302)
@app.route("/portal/update", methods=["POST"])
def portalUpdate():
name = request.form["name"]
oname = request.form["oname"]
url = stb.getUrl(request.form["url"])
mac = request.form["mac"]
proxy = request.form["proxy"]
format = request.form["format"]
try:
portals = getPortals()
token = stb.getToken(url, mac)
expiry = stb.getExpires(url, mac, token)
for i in range(len(portals)):
if portals[i]["name"] == oname:
portals[i]["name"] = name
portals[i]["url"] = url
portals[i]["mac"] = mac
portals[i]["proxy"] = proxy
portals[i]["format"] = format
portals[i]["expires"] = expiry
savePortals(portals)
break
except:
print(sys.exc_info()[1])
pass
return redirect("/portals", code=302)
@app.route("/portal/remove", methods=["POST"])
def portalRemove():
name = request.form["name"]
portals = getPortals()
for i in range(len(portals)):
if portals[i]["name"] == name:
portals.pop(i)
break
savePortals(portals)
return redirect("/portals", code=302)
@app.route("/editor", methods=["GET"])
def editor():
channels = []
portals = getPortals()
if len(portals) > 0:
for p in portals:
portalName = p["name"]
url = p["url"]
mac = p["mac"]
enabledChannels = p["enabled channels"]
customChannelNames = p["custom channel names"]
customGenres = p["custom genres"]
try:
token = stb.getToken(url, mac)
allChannels = stb.getAllChannels(url, mac, token)
genres = stb.getGenres(url, mac, token)
for i in allChannels:
channelId = i["id"]
channelName = i["name"]
genre = genres.get(i["tv_genre_id"])
if channelId in enabledChannels:
enabled = True
else:
enabled = False
customChannelName = customChannelNames.get(channelId)
if customChannelName == None:
customChannelName = ""
customGenre = customGenres.get(channelId)
if customGenre == None:
customGenre = ""
channels.append(
{
"enabled": enabled,
"channelName": channelName,
"customChannelName": customChannelName,
"genre": genre,
"customGenre": customGenre,
"channelId": channelId,
"portalName": portalName,
}
)
except:
print(sys.exc_info()[1])
pass
return render_template("editor.html", channels=channels)
@app.route("/editor/save", methods=["POST"])
def editorSave():
enabledEdits = json.loads(request.form["enabledEdits"])
nameEdits = json.loads(request.form["nameEdits"])
genreEdits = json.loads(request.form["genreEdits"])
portals = getPortals()
for e in enabledEdits:
portal = e["portal"]
chid = e["channel id"]
enabled = e["enabled"]
for i, p in enumerate(portals):
if p["name"] == portal:
enabledChannels = p["enabled channels"]
if enabled:
enabledChannels.append(chid)
else:
enabledChannels.remove(chid)
enabledChannels = list(set(enabledChannels))
portals[i]["enabled channels"] = enabledChannels
break
for n in nameEdits:
portal = n["portal"]
chid = n["channel id"]
customName = n["custom name"]
for i, p in enumerate(portals):
if p["name"] == portal:
customChannelNames = p["custom channel names"]
if customName:
customChannelNames.update({chid: customName})
else:
customChannelNames.pop(chid)
portals[i]["custom channel names"] = customChannelNames
break
for g in genreEdits:
portal = g["portal"]
chid = g["channel id"]
customGenre = g["custom genre"]
for i, p in enumerate(portals):
if p["name"] == portal:
customGenres = p["custom genres"]
if customGenre:
customGenres.update({chid: customGenre})
else:
customGenres.pop(chid)
portals[i]["custom genres"] = customGenres
break
savePortals(portals)
return redirect("/editor", code=302)
@app.route("/player", methods=["GET"])
def player():
channels = []
for p in getPortals():
portalName = p["name"]
url = p["url"]
mac = p["mac"]
proxy = p["proxy"]
enabledChannels = p["enabled channels"]
customChannelNames = p["custom channel names"]
customGenres = p["custom genres"]
if len(enabledChannels) != 0:
try:
token = stb.getToken(url, mac)
allChannels = stb.getAllChannels(url, mac, token)
genres = stb.getGenres(url, mac, token)
for i in allChannels:
channelId = i["id"]
if channelId in enabledChannels:
cmd = i["cmd"]
channelName = customChannelNames.get(channelId)
if channelName == None:
channelName = i["name"]
genre = customGenres.get(channelId)
if genre == None:
genre = genres.get(i["tv_genre_id"])
epg = stb.getShortEpg(channelId, url, mac, token)
try:
now = epg[0]["name"]
except:
now = "No data"
try:
nex = epg[1]["name"]
except:
nex = "No data"
query = parse.urlencode(
{
"portalName": portalName,
"url": url,
"mac": mac,
"cmd": cmd,
"proxy": proxy,
"format": "mp4",
}
)
link = "http://" + host + "/play?" + query
channels.append(
{
"name": channelName,
"genre": genre,
"link": link,
"now": now,
"next": nex,
}
)
channels.sort(key=lambda k: k["name"])
except:
print(sys.exc_info()[1])
pass
return render_template("player.html", channels=channels)
@app.route("/playlist", methods=["GET"])
def playlist():
channels = []
for p in getPortals():
portalName = p["name"]
url = p["url"]
mac = p["mac"]
proxy = p["proxy"]
format = p["format"]
enabledChannels = p["enabled channels"]
customChannelNames = p["custom channel names"]
customGenres = p["custom genres"]
if len(enabledChannels) != 0:
try:
token = stb.getToken(url, mac)
allChannels = stb.getAllChannels(url, mac, token)
genres = stb.getGenres(url, mac, token)
for i in allChannels:
channelId = i["id"]
if channelId in enabledChannels:
cmd = i["cmd"]
channelName = customChannelNames.get(channelId)
if channelName == None:
channelName = i["name"]
genre = customGenres.get(channelId)
if genre == None:
genre = genres.get(i["tv_genre_id"])
query = parse.urlencode(
{
"portalName": portalName,
"url": url,
"mac": mac,
"cmd": cmd,
"proxy": proxy,
"format": format,
}
)
channels.append(
'#EXTINF:-1 group-title="'
+ genre
+ '",'
+ channelName
+ "\n"
+ "http://"
+ host
+ "/play?"
+ query
)
except:
print(sys.exc_info()[1])
pass
channels.sort(key=lambda k: k.split(",")[1])
playlist = "#EXTM3U \n"
playlist = playlist + "\n".join(channels)
return Response(playlist, mimetype="text/plain")
@app.route("/play", methods=["GET"])
def channel():
def streamData(link, proxy, format):
if format == "mp4":
ffmpegcmd = [
"ffmpeg",
"-re",
"-loglevel",
"panic",
"-hide_banner",
"-i",
link,
"-vcodec",
"copy",
"-f",
"mp4",
"-movflags",
"frag_keyframe+empty_moov",
"pipe:",
]
elif format == "mpegts":
ffmpegcmd = [
"ffmpeg",
"-re",
"-loglevel",
"panic",
"-hide_banner",
"-i",
link,
"-c",
"copy",
"-f",
"mpegts",
"pipe:",
]
elif format == "hls":
ffmpegcmd = [
"ffmpeg",
"-re",
"-loglevel",
"panic",
"-hide_banner",
"-i",
link,
"-c",
"copy",
"-f",
"hls",
"pipe:",
]
if proxy:
ffmpegcmd.insert(5, "-http_proxy")
ffmpegcmd.insert(6, proxy)
try:
ffmpeg_sb = subprocess.Popen(
ffmpegcmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE
)
for stdout_line in iter(ffmpeg_sb.stdout.readline, ""):
yield stdout_line
finally:
ffmpeg_sb.terminate()
url = request.args.get("url")
mac = request.args.get("mac")
cmd = request.args.get("cmd")
proxy = request.args.get("proxy")
format = request.args.get("format")
if format == "redirect":
try:
token = stb.getToken(url, mac)
if "http://localhost/" in cmd:
link = stb.getLink(url, mac, token, cmd)
else:
link = cmd.split(" ")[1]
return redirect(link, code=302)
except:
print(sys.exc_info()[1])
pass
else:
try:
token = stb.getToken(url, mac)
if "http://localhost/" in cmd:
link = stb.getLink(url, mac, token, cmd)
else:
link = cmd.split(" ")[1]
return Response(streamData(link, proxy, format))
except:
print(sys.exc_info()[1])
pass
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8001, debug=True)