-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrevivetube.py
488 lines (378 loc) · 16.9 KB
/
revivetube.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
"""
(c) 2024 ReviveMii Project. All rights reserved. If you want to use this Code, give Credits to ReviveMii Project. https://revivemii.fr.to/
ReviveMii Project and TheErrorExe is the Developer of this Code. Modification, Network Use and Distribution is allowed if you leave this Comment in the beginning of the Code, and if a website exist, Credits on the Website.
This Code uses the Invidious API, Google API and yt-dlp. This Code is designed to run on Ubuntu 24.04.
Don't claim that this code is your code. Don't use it without Credits to the ReviveMii Project. Don't use it without this Comment. Don't modify this Comment.
ReviveMii's Server Code is provided "as-is" and "as available." We do not guarantee uninterrupted access, error-free performance, or compatibility with all Wii systems. ReviveMii project is not liable for any damage, loss of data, or other issues arising from the use of this service and code.
If you use this Code, you agree to https://revivemii.fr.to/revivetube/t-and-p.html, also available as http only Version: http://old.errexe.xyz/revivetube/t-and-p.html
ReviveMii Project: https://revivemii.fr.to/
"""
import os
import shutil
import subprocess
import tempfile
import threading
import time
from threading import Thread
import requests
import yt_dlp
from flask import Flask, request, render_template_string, send_file, Response, abort, jsonify
import helper
app = Flask(__name__)
def check_and_create_folder():
while True:
folder_path = './sigma/videos'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print(f"Folder {folder_path} got created.")
time.sleep(10)
def start_folder_check():
thread = Thread(target=check_and_create_folder)
thread.daemon = True
thread.start()
VIDEO_FOLDER = "sigma/videos"
API_BASE_URL = "https://y.com.sb/api/v1/"
YOUTUBE_API_URL = "https://www.googleapis.com/youtube/v3/videos"
video_status = {}
FILE_SEPARATOR = os.sep
LOADING_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}loading_template.html")
os.makedirs(VIDEO_FOLDER, exist_ok=True)
MAX_VIDEO_SIZE = 1 * 1024 * 1024 * 1024
MAX_FOLDER_SIZE = 5 * 1024 * 1024 * 1024
def get_folder_size(path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
file_path = os.path.join(dirpath, f)
total_size += os.path.getsize(file_path)
return total_size
"""
[UNUSED IN THE CURRENT VERSION]
def delete_videos_periodically():
while True:
time.sleep(86400)
for filename in os.listdir(VIDEO_FOLDER):
file_path = os.path.join(VIDEO_FOLDER, filename)
if os.path.isfile(file_path):
os.remove(file_path)
print(f"Deleted: {file_path}")
threading.Thread(target=delete_videos_periodically, daemon=True).start()
"""
INDEX_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}index_template.html")
WATCH_STANDARD_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}watch_standard_template.html")
WATCH_WII_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}watch_wii_template.html")
@app.route("/thumbnail/<video_id>")
def get_thumbnail(video_id):
thumbnail_url = f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"
try:
response = requests.get(thumbnail_url, stream=True, timeout=1)
if response.status_code == 200:
return send_file(
response.raw,
mimetype=response.headers.get("Content-Type", "image/jpeg"),
as_attachment=False,
)
else:
return f"Failed to fetch thumbnail. Status: {response.status_code}", 500
except requests.exceptions.RequestException as e:
return f"Error fetching thumbnail: {str(e)}", 500
def get_video_comments(video_id, max_results=20):
api_key = helper.get_api_key()
params = {
"part": "snippet",
"videoId": video_id,
"key": api_key,
"maxResults": max_results,
"order": "relevance"
}
try:
response = requests.get("https://www.googleapis.com/youtube/v3/commentThreads", params=params, timeout=3)
response.raise_for_status()
data = response.json()
comments = []
if "items" in data:
for item in data["items"]:
snippet = item["snippet"]["topLevelComment"]["snippet"]
comments.append({
"author": snippet["authorDisplayName"],
"text": snippet["textDisplay"],
"likeCount": snippet.get("likeCount", 0),
"publishedAt": snippet["publishedAt"]
})
return comments
except requests.exceptions.RequestException as e:
print(f"Fehler beim Abrufen der Kommentare: {str(e)}")
return []
@app.route("/switch_wii", methods=["GET"])
def switch_wii():
video_id = request.args.get("video_id")
if not video_id:
return "Missing Video-ID.", 400
headers = {
"User-Agent": "Mozilla/5.0 (Nintendo Wii; U; ; en) Opera/9.30 (Nintendo Wii)"
}
response = requests.get(f"http://localhost:5000/watch?video_id={video_id}", headers=headers, timeout=2)
if response.status_code == 200:
return response.text
else:
return "Can't start DEBUG Mode.", 500
@app.route("/switch_n", methods=["GET"])
def switch_n():
video_id = request.args.get("video_id")
if not video_id:
return "Missing Video-ID.", 400
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(f"http://localhost:5000/watch?video_id={video_id}", headers=headers, timeout=2)
if response.status_code == 200:
return response.text
else:
return "Can't start DEBUG Mode.", 500
@app.route("/", methods=["GET"])
def index():
query = request.args.get("query")
results = None
if query:
response = requests.get(f"https://y.com.sb/api/v1/search?q={query}", timeout=3)
try:
data = response.json()
except ValueError:
return "Can't parse Data. If this Issue persist, report it in the Discord Server.", 500
if response.status_code == 200 and isinstance(data, list):
results = [
{
"id": entry.get("videoId"),
"title": entry.get("title"),
"uploader": entry.get("author", "Unbekannt"),
"thumbnail": f"/thumbnail/{entry['videoId']}",
"viewCount": entry.get("viewCountText", "Unbekannt"),
"published": entry.get("publishedText", "Unbekannt"),
"duration": helper.format_duration(entry.get("lengthSeconds", 0)) # Video Dauer formatiert
}
for entry in data
if entry.get("videoId")
]
else:
return "No Results or Error in the API.", 404
return render_template_string(INDEX_TEMPLATE, results=results)
@app.route("/watch", methods=["GET"])
def watch():
video_id = request.args.get("video_id")
if not video_id:
return "Missing Video-ID.", 400
video_mp4_path = os.path.join(VIDEO_FOLDER, f"{video_id}.mp4")
video_flv_path = os.path.join(VIDEO_FOLDER, f"{video_id}.flv")
if video_id not in video_status:
video_status[video_id] = {"status": "processing"}
user_agent = request.headers.get("User-Agent", "").lower()
is_wii = "wii" in user_agent and "wiiu" not in user_agent
try:
response = requests.get(f"http://localhost:5000/video_metadata/{video_id}", timeout=20)
if response.status_code == 200:
metadata = response.json()
else:
return f"Metadata API Error for Video-ID {video_id}.", 500
except requests.exceptions.RequestException as e:
return f"Can't connect to Metadata-API: {str(e)}", 500
comments = []
try:
comments = get_video_comments(video_id)
except Exception as e:
print(f"Video-Comments Error: {str(e)}")
comments = []
if os.path.exists(video_mp4_path):
video_duration = helper.get_video_duration_from_file(video_flv_path)
alert_script = ""
if video_duration > 420:
alert_script = """
<script type="text/javascript">
alert("This Video is long. There is a chance that the Wii will not play the Video. Try a Video under 7 minutes or something like that.");
</script>
"""
if is_wii and os.path.exists(video_flv_path):
return render_template_string(WATCH_WII_TEMPLATE + alert_script,
title=metadata['title'],
uploader=metadata['uploader'],
channelId=metadata['channelId'],
description=metadata['description'].replace("\n", "<br>"),
viewCount=metadata['viewCount'],
likeCount=metadata['likeCount'],
publishedAt=metadata['publishedAt'],
comments=comments,
video_id=video_id,
video_flv=f"/sigma/videos/{video_id}.flv",
alert_message="")
return render_template_string(WATCH_WII_TEMPLATE,
title=metadata['title'],
uploader=metadata['uploader'],
channelId=metadata['channelId'],
description=metadata['description'].replace("\n", "<br>"),
viewCount=metadata['viewCount'],
likeCount=metadata['likeCount'],
publishedAt=metadata['publishedAt'],
comments=comments,
video_id=video_id,
video_flv=f"/sigma/videos/{video_id}.flv",
alert_message="")
if not os.path.exists(video_mp4_path):
if video_status[video_id]["status"] == "processing":
threading.Thread(target=process_video, args=(video_id,)).start()
return render_template_string(LOADING_TEMPLATE, video_id=video_id)
def process_video(video_id):
video_mp4_path = os.path.join(VIDEO_FOLDER, f"{video_id}.mp4")
video_flv_path = os.path.join(VIDEO_FOLDER, f"{video_id}.flv")
try:
video_status[video_id] = {"status": "downloading"}
with tempfile.TemporaryDirectory() as temp_dir:
temp_video_path = os.path.join(temp_dir, f"{video_id}.%(ext)s")
command = [
"yt-dlp",
"-f worstvideo+worstaudio",
"--proxy", "http://localhost:4000",
"-o", temp_video_path,
f"https://m.youtube.com/watch?v={video_id}"
]
subprocess.run(command, check=True)
downloaded_files = [f for f in os.listdir(temp_dir) if video_id in f]
if not downloaded_files:
video_status[video_id] = {"status": "error", "message": "Error downloading."}
return
downloaded_file = os.path.join(temp_dir, downloaded_files[0])
if not downloaded_file.endswith(".mp4"):
video_status[video_id] = {"status": "converting"}
subprocess.run(
[
"ffmpeg",
"-y",
"-i", downloaded_file,
"-c:v", "libx264",
"-crf", "51",
"-c:a", "aac",
"-strict", "experimental",
"-preset", "ultrafast",
"b:a", "64k",
"-movflags", "+faststart",
"-vf", "scale=854:480",
video_mp4_path
],
check=True
)
else:
shutil.copy(downloaded_file, video_mp4_path)
if not os.path.exists(video_flv_path):
video_status[video_id] = {"status": "converting for Wii"}
subprocess.run(
[
"ffmpeg",
"-y",
"-i", video_mp4_path,
"-ar", "22050",
"-f", "flv",
"-s", "320x240",
"-ab", "32k",
"-preset", "ultrafast",
"-crf", "51",
"-filter:v", "fps=fps=15",
video_flv_path
],
check=True)
video_status[video_id] = {"status": "complete", "url": f"/sigma/videos/{video_id}.mp4"}
except Exception as e:
video_status[video_id] = {"status": "error", "message": str(e)}
@app.route("/status/<video_id>")
def check_status(video_id):
return jsonify(video_status.get(video_id, {"status": "pending"}))
@app.route("/video_metadata/<video_id>")
def video_metadata(video_id):
api_key = helper.get_api_key()
params = {
"part": "snippet,statistics",
"id": video_id,
"key": api_key
}
try:
response = requests.get(YOUTUBE_API_URL, params=params, timeout=1)
response.raise_for_status()
data = response.json()
if "items" not in data or len(data["items"]) == 0:
return f"Video mit ID {video_id} wurde nicht gefunden.", 404
video_data = data["items"][0]
title = video_data["snippet"]["title"]
description = video_data["snippet"]["description"]
uploader = video_data["snippet"]["channelTitle"]
channel_id = video_data["snippet"]["channelId"]
view_count = video_data["statistics"].get("viewCount", "Unknown")
like_count = video_data["statistics"].get("likeCount", "Unknown")
dislike_count = video_data["statistics"].get("dislikeCount", "Unknown")
published_at = video_data["snippet"].get("publishedAt", "Unknown")
return {
"title": title,
"uploader": uploader,
"channelId": channel_id,
"description": description,
"viewCount": view_count,
"likeCount": like_count,
"dislikeCount": dislike_count,
"publishedAt": published_at
}
except requests.exceptions.RequestException as e:
return f"Fehler bei der API-Anfrage: {str(e)}", 500
@app.route("/<path:filename>")
def serve_video(filename):
file_path = os.path.join(filename)
if not os.path.exists(file_path):
return "File not found.", 404
file_size = helper.get_file_size(file_path)
range_header = request.headers.get('Range', None)
if range_header:
byte_range = range_header.strip().split('=')[1]
start_byte, end_byte = byte_range.split('-')
start_byte = int(start_byte)
end_byte = int(end_byte) if end_byte else file_size - 1
if start_byte >= file_size or end_byte >= file_size:
abort(416)
data = helper.get_range(file_path, (start_byte, end_byte))
content_range = f"bytes {start_byte}-{end_byte}/{file_size}"
response = Response(
data,
status=206,
mimetype="video/mp4",
content_type="video/mp4",
direct_passthrough=True
)
response.headers["Content-Range"] = content_range
response.headers["Content-Length"] = str(len(data))
return response
return send_file(file_path)
@app.route('/channel', methods=['GET'])
def channel_m():
channel_id = request.args.get('channel_id', None)
if not channel_id:
return "Channel ID is required.", 400
ydl_opts = {
'quiet': True,
'extract_flat': True,
'playlistend': 20,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
url = f"https://www.youtube.com/channel/{channel_id}/videos"
info = ydl.extract_info(url, download=False)
if 'entries' not in info:
return "No videos found.", 404
results = [
{
'id': video['id'],
'duration': 'Duration not available on Channel View',
'title': video['title'],
'uploader': info.get('uploader', 'Unknown'),
'thumbnail': f"http://yt.old.errexe.xyz/thumbnail/{video['id']}"
}
for video in info['entries']
]
return render_template_string(INDEX_TEMPLATE, results=results)
except Exception as e:
return f"An error occurred: {str(e)}", 500
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True, port=5000)