This repository has been archived by the owner on Jul 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
288 lines (236 loc) · 7.26 KB
/
main.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
from flask import Flask, request, render_template, abort, send_from_directory, send_file
from media import MediaFile, VideoFile, ImageFile, MediaDirectory
from ffmpeg import canHEVC, isImageSubtitle
import os, time, threading, sys
app = Flask(__name__)
app.config.from_json("config.json")
print(app.config["SETTINGS"])
res = MediaDirectory(
app.config["SETTINGS"]["media_folders"],
app.config["SETTINGS"]["temporary_folder"],
app.config["SETTINGS"]["thumbnail_height"],
app.config["SETTINGS"]["preprobe"],
app.config["SETTINGS"]["accel_table"][app.config["SETTINGS"]["avc_accel"]],
app.config["SETTINGS"]["accel_table"][app.config["SETTINGS"]["hevc_accel"]],
)
def app_basepath():
if "X-Url-Base" in request.headers:
return request.headers["X-Url-Base"]
return "/"
def redirect(where):
return "<script>window.location.replace('" + app_basepath() + where + "');</script>"
@app.route("/scan", methods=["POST"])
def scandir():
res.scan()
return "OK", 200
@app.route("/")
def first():
print()
return redirect("browse/")
@app.route("/browse/")
def browseaux():
return browse("")
@app.route("/browse/<path:path>")
def browse(path):
folders = []
videos = []
images = []
brow = res.file_browser
name = "Index"
fpath =""
for i in path.split("/"):
if i != "":
fpath = i + "/"
name = i
if (not i in brow):
return abort(403)
brow = brow[i]
for i in brow:
if (isinstance(brow[i], dict)):
folders.append({
"name": i,
"link": i + "/",
})
else:
#TODO: Move this
hash = brow[i]
if (hash in res.video_files): #Video
t = {
"cover": hash,
"name": i
}
#TODO: Allow video as "popup" in frame instead
#TODO: Implement gifv support (inline video)
data = res.getMedia(hash)
width = data.getSize()[0]
height = data.getSize()[1]
t["width"] = width
t["height"] = height
t["link"] = "select/" + hash
t["has_handy"] = data.isHandy()
videos.append(t)
else: #Image
#TODO: Implement youtube-dl and ripme support
#TODO: Implement scrolller like interface, maybe
data = res.getMedia(hash)
width = data.getSize()[0]
height = data.getSize()[1]
images.append({
"hash": hash,
"name": i,
"width": width,
"height": height
})
#Get client information
browser = request.user_agent.browser
version = request.user_agent.version and int(request.user_agent.version.split(".")[0])
platform = request.user_agent.platform
uas = request.user_agent.string
print(browser)
print(version)
print(platform)
print(uas)
print(request.user_agent)
return render_template("index.html",
folder_name=name,
folders=folders,
videos=videos,
images=images,
basepath=app_basepath()
)
@app.route("/select/<string:hash>")
def selection(hash):
global res
if hash in videos:
return redirect("media/{}".format(hash))
#TODO: Modulize this better
media = res.getMedia(hash)
if not media:
return abort(418)
subtitletracks = []
subfix = 0 #Yeah ffmpeg is wierd
codec_type=""
media.scan()
for i in media.data["streams"]:
if (i["codec_type"] == "video"):
codec_type=i["codec_name"]
if (i["codec_type"] == "subtitle" and isImageSubtitle(i["codec_name"])):
subtitletracks.append((i["index"],subfix))
subfix = subfix + 1
#Get client information
browser = request.user_agent.browser
version = request.user_agent.version and int(request.user_agent.version.split(".")[0])
platform = request.user_agent.platform
uas = request.user_agent.string
print(browser)
print(version)
print(platform)
print(uas)
#print(request.headers.get("User-Agent"))
#https://unix.stackexchange.com/a/284808
subs = []
for (sub, idx) in subtitletracks:
subs.append({
"id": idx,
"url": "hardsub-track=" + str(idx),
"text": "Subtitle: {} ({})".format(
media.data["streams"][sub]["tags"]["title"] if "title" in media.data["streams"][sub]["tags"] else "Unknown",
media.data["streams"][sub]["tags"]["language"] if "language" in media.data["streams"][sub]["tags"] else "Unknown",
)
})
return render_template("select.html", basepath=app_basepath(), videoid=hash, subs=subs, canHEVC=str(canHEVC(request.user_agent)), codec_type=codec_type)
videos = {}
@app.route("/media/<hash>")
def media_content_mp4(hash):
video = res.getMedia(hash)
if (video == None):
return abort(400)
if (not hash in videos): #TODO: This should be media sided
process = video.start(request)
videos[hash] = {
"time": time.time(),
"video": video,
"process": process
}
else:
process = videos[hash]["process"]
#TODO: Bring back custom videopath, as this would help workload offloading
#as this is single threaded.
#or just enable multithreading :)
return render_template(
"play.html",
basepath=app_basepath(),
videopath=app_basepath() + "video/",
videoid=hash,
subs=process.data["subs"],
vrtype=process.data["VRType"],
script_url=process.data["script_url"],
should_handy=process.data["script_url"] != None #TODO: Not needed
)
@app.route("/poll/<string:hash>", methods=["POST"])
def poll(hash):
if hash in videos:
videos[hash]["time"] = time.time()
return "OK"
else:
return abort(400)
#Force clients to request files (streams are temporary)
#TODO: Is this needed?
@app.after_request
def add_header(response):
response.headers["X-UA-Compatible"] = "IE=Edge,chrome=1"
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
#Serve video
@app.route("/video/<path:filename>")
def serve_videos(filename):
return send_from_directory(directory=os.path.join(app.config["SETTINGS"]["temporary_folder"], "encodes"), filename=filename, conditional=True)
#Serve static files like js and css
@app.route("/serve/<path:filename>")
def req(filename):
return send_from_directory(directory="static/", filename=filename)
#Serve image
@app.route("/image/<string:hash>")
def serve_image(hash):
#Wait this will serve literally any media
#Also videos
#LOL
return send_file(res.getMedia(hash).getPath(), conditional=True)
#Serve thumbnails
@app.route("/thumbnail/<string:hash>.jpeg")
def serve_thumbnail(hash):
#TODO: Sometimes FileNotFoundError
#Do we care?
return send_file(res.getMedia(hash).getThumbnailPath(), conditional=True)
should_stop = False
keepalive_thread = None
def check_old():
while(not should_stop):
for key in list(videos.keys()):
try:
i = videos[key]
if (i["time"] + app.config["SETTINGS"]["ttl"] < time.time()):
print("Removing inactive media {}".format(key))
i["process"].stop()
del videos[key]
except:
print("Removal of {} failed!".format(key))
time.sleep(5)
def savecounter():
global should_stop
print("Builtin Exiting...")
should_stop = True
for key in list(videos.keys()):
i = videos[key]
i["process"].stop()
del videos[key]
keepalive_thread.join(10)
sys.exit(0)
import atexit
atexit.register(savecounter)
keepalive_thread = threading.Thread(target=check_old)
keepalive_thread.start()
if __name__ == "__main__":
app.run(host="0.0.0.0", threaded=True)