Update revivetube.py

This commit is contained in:
TheErrorExe 2025-04-01 21:20:55 +02:00 committed by GitHub
parent ad2d786099
commit c9d7518c84
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -5,7 +5,7 @@ ReviveMii Project and TheErrorExe is the Developer of this Code. Modification, N
This Code uses the Invidious API, Google API and yt-dlp. This Code is designed to run on Ubuntu 24.04. This Code uses the Invidious API, Google API and yt-dlp. This Code is designed to run on Ubuntu 24.04.
Dont 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. You need to make your modified Code Open Source with this exact License. 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. You need to make your modified Code Open Source with this exact License.
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. 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.
@ -18,35 +18,15 @@ import os
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
import threading
import time import time
from threading import Thread import aiofiles
import aiohttp
from bs4 import BeautifulSoup import asyncio
import requests
import yt_dlp import yt_dlp
from flask import Flask, request, render_template_string, send_file, Response, abort, jsonify from bs4 import BeautifulSoup
import json from quart import Quart, 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()
app = Quart(__name__)
VIDEO_FOLDER = "sigma/videos" VIDEO_FOLDER = "sigma/videos"
YOUTUBE_API_URL = "https://www.googleapis.com/youtube/v3/videos" YOUTUBE_API_URL = "https://www.googleapis.com/youtube/v3/videos"
@ -54,17 +34,41 @@ video_status = {}
FILE_SEPARATOR = os.sep FILE_SEPARATOR = os.sep
LOADING_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}loading_template.html") async def read_file(file_path):
CHANNEL_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}channel_template.html") async with aiofiles.open(file_path, mode='r') as f:
SEARCH_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}search_template.html") return await f.read()
async 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.")
await asyncio.sleep(10)
app.before_serving(lambda: asyncio.create_task(check_and_create_folder()))
LOADING_TEMPLATE = None
CHANNEL_TEMPLATE = None
SEARCH_TEMPLATE = None
INDEX_TEMPLATE = None
WATCH_WII_TEMPLATE = None
async def load_templates():
global LOADING_TEMPLATE, CHANNEL_TEMPLATE, SEARCH_TEMPLATE, INDEX_TEMPLATE, WATCH_WII_TEMPLATE
LOADING_TEMPLATE = await read_file(f"site_storage{FILE_SEPARATOR}loading_template.html")
CHANNEL_TEMPLATE = await read_file(f"site_storage{FILE_SEPARATOR}channel_template.html")
SEARCH_TEMPLATE = await read_file(f"site_storage{FILE_SEPARATOR}search_template.html")
INDEX_TEMPLATE = await read_file(f"site_storage{FILE_SEPARATOR}index_template.html")
WATCH_WII_TEMPLATE = await read_file(f"site_storage{FILE_SEPARATOR}watch_wii_template.html")
app.before_serving(load_templates)
os.makedirs(VIDEO_FOLDER, exist_ok=True) os.makedirs(VIDEO_FOLDER, exist_ok=True)
MAX_VIDEO_SIZE = 1 * 1024 * 1024 * 1024 MAX_VIDEO_SIZE = 1 * 1024 * 1024 * 1024
MAX_FOLDER_SIZE = 5 * 1024 * 1024 * 1024 MAX_FOLDER_SIZE = 5 * 1024 * 1024 * 1024
def get_folder_size(path): def get_folder_size(path):
total_size = 0 total_size = 0
for dirpath, dirnames, filenames in os.walk(path): for dirpath, dirnames, filenames in os.walk(path):
@ -73,35 +77,26 @@ def get_folder_size(path):
total_size += os.path.getsize(file_path) total_size += os.path.getsize(file_path)
return total_size return total_size
INDEX_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}index_template.html")
WATCH_WII_TEMPLATE = helper.read_file(f"site_storage{FILE_SEPARATOR}watch_wii_template.html")
@app.route("/thumbnail/<video_id>") @app.route("/thumbnail/<video_id>")
def get_thumbnail(video_id): async def get_thumbnail(video_id):
thumbnail_url = f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg" thumbnail_url = f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"
try: try:
async with aiohttp.ClientSession() as session:
response = requests.get(thumbnail_url, stream=True, timeout=1) async with session.get(thumbnail_url) as response:
if response.status_code == 200: if response.status == 200:
return await send_file(
return send_file( response.content,
response.raw,
mimetype=response.headers.get("Content-Type", "image/jpeg"), mimetype=response.headers.get("Content-Type", "image/jpeg"),
as_attachment=False, as_attachment=False,
) )
else: else:
return f"Failed to fetch thumbnail. Status: {response.status_code}", 500 return f"Failed to fetch thumbnail. Status: {response.status}", 500
except requests.exceptions.RequestException as e: except aiohttp.ClientError as e:
return f"Error fetching thumbnail: {str(e)}", 500 return f"Error fetching thumbnail: {str(e)}", 500
async def get_video_comments(video_id, max_results=20):
def get_video_comments(video_id, max_results=20): api_key = await helper.get_api_key()
api_key = helper.get_api_key()
params = { params = {
"part": "snippet", "part": "snippet",
@ -112,10 +107,10 @@ def get_video_comments(video_id, max_results=20):
} }
try: try:
response = requests.get("https://www.googleapis.com/youtube/v3/commentThreads", params=params, timeout=3) async with aiohttp.ClientSession() as session:
async with session.get("https://www.googleapis.com/youtube/v3/commentThreads", params=params, timeout=3) as response:
response.raise_for_status() response.raise_for_status()
data = await response.json()
data = response.json()
comments = [] comments = []
if "items" in data: if "items" in data:
@ -130,40 +125,40 @@ def get_video_comments(video_id, max_results=20):
return comments return comments
except requests.exceptions.RequestException as e: except (aiohttp.ClientError, asyncio.TimeoutError) as e:
print(f"Can't fetch Comments: {str(e)}") print(f"Can't fetch Comments: {str(e)}")
return [] return []
@app.route("/cookies.txt", methods=["GET"]) @app.route("/cookies.txt", methods=["GET"])
def cookies(): async def cookies():
return "403 Forbidden", 403 return "403 Forbidden", 403
@app.route("/token.txt", methods=["GET"]) @app.route("/token.txt", methods=["GET"])
def token(): async def token():
return "403 Forbidden", 403 return "403 Forbidden", 403
@app.route("/nohup.out", methods=["GET"]) @app.route("/nohup.out", methods=["GET"])
def nohup(): async def nohup():
return "403 Forbidden", 403 return "403 Forbidden", 403
@app.route("/", methods=["GET"]) @app.route("/", methods=["GET"])
def index(): async def index():
query = request.args.get("query") query = request.args.get("query")
results = None results = None
if query:
response = requests.get(f"https://invidious.materialio.us/api/v1/search?q={query}", timeout=3)
else:
response = requests.get("https://invidious.materialio.us/api/v1/trending", timeout=3)
try: try:
data = response.json() async with aiohttp.ClientSession() as session:
except ValueError: if query:
url = f"https://invidious.materialio.us/api/v1/search?q={query}"
else:
url = "https://invidious.materialio.us/api/v1/trending"
async with session.get(url, timeout=3) as response:
data = await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as e:
return "Can't parse Data. If this Issue persists, report it in the Discord Server.", 500 return "Can't parse Data. If this Issue persists, report it in the Discord Server.", 500
if response.status_code == 200 and isinstance(data, list): if response.status == 200 and isinstance(data, list):
if query: if query:
results = [] results = []
for entry in data: for entry in data:
@ -176,7 +171,7 @@ def index():
"thumbnail": f"/thumbnail/{entry['videoId']}", "thumbnail": f"/thumbnail/{entry['videoId']}",
"viewCount": entry.get("viewCountText", "Unknown"), "viewCount": entry.get("viewCountText", "Unknown"),
"published": entry.get("publishedText", "Unknown"), "published": entry.get("publishedText", "Unknown"),
"duration": helper.format_duration(entry.get("lengthSeconds", 0)) "duration": await helper.format_duration(entry.get("lengthSeconds", 0))
}) })
elif entry.get("type") == "channel": elif entry.get("type") == "channel":
results.append({ results.append({
@ -187,7 +182,7 @@ def index():
"subCount": entry.get("subCount", "Unknown"), "subCount": entry.get("subCount", "Unknown"),
"videoCount": entry.get("videoCount", "Unknown") "videoCount": entry.get("videoCount", "Unknown")
}) })
return render_template_string(SEARCH_TEMPLATE, results=results) return await render_template_string(SEARCH_TEMPLATE, results=results)
else: else:
results = [ results = [
{ {
@ -197,19 +192,17 @@ def index():
"thumbnail": f"/thumbnail/{entry['videoId']}", "thumbnail": f"/thumbnail/{entry['videoId']}",
"viewCount": entry.get("viewCountText", "Unknown"), "viewCount": entry.get("viewCountText", "Unknown"),
"published": entry.get("publishedText", "Unknown"), "published": entry.get("publishedText", "Unknown"),
"duration": helper.format_duration(entry.get("lengthSeconds", 0)) "duration": await helper.format_duration(entry.get("lengthSeconds", 0))
} }
for entry in data for entry in data
if entry.get("videoId") if entry.get("videoId")
] ]
return render_template_string(INDEX_TEMPLATE, results=results) return await render_template_string(INDEX_TEMPLATE, results=results)
else: else:
return "No Results or Error in the API.", 404 return "No Results or Error in the API.", 404
@app.route("/watch", methods=["GET"]) @app.route("/watch", methods=["GET"])
def watch(): async def watch():
video_id = request.args.get("video_id") video_id = request.args.get("video_id")
if not video_id: if not video_id:
return "Missing Video-ID.", 400 return "Missing Video-ID.", 400
@ -224,32 +217,31 @@ def watch():
is_wii = "wii" in user_agent and "wiiu" not in user_agent is_wii = "wii" in user_agent and "wiiu" not in user_agent
try: try:
# Metadaten des Videos abrufen async with aiohttp.ClientSession() as session:
response = requests.get(f"http://localhost:5000/video_metadata/{video_id}", timeout=20) async with session.get(f"http://localhost:5000/video_metadata/{video_id}", timeout=20) as response:
if response.status_code == 200: if response.status == 200:
metadata = response.json() metadata = await response.json()
else: else:
return f"Metadata API Error for Video-ID {video_id}.", 500 return f"Metadata API Error for Video-ID {video_id}.", 500
except requests.exceptions.RequestException as e: except (aiohttp.ClientError, asyncio.TimeoutError) as e:
return f"Can't connect to Metadata-API: {str(e)}", 500 return f"Can't connect to Metadata-API: {str(e)}", 500
# Kommentare des Videos abrufen
comments = [] comments = []
try: try:
comments = get_video_comments(video_id) comments = await get_video_comments(video_id)
except Exception as e: except Exception as e:
print(f"Video-Comments Error: {str(e)}") print(f"Video-Comments Error: {str(e)}")
comments = [] comments = []
# Kanal-Logo und Abonnentenanzahl über die SuperPlayCounts API abrufen
channel_logo_url = "" channel_logo_url = ""
subscriber_count = "Unbekannt" subscriber_count = "Unbekannt"
try: try:
channel_id = metadata['channelId'] channel_id = metadata['channelId']
api_url = f"https://api-superplaycounts.onrender.com/api/youtube-channel-counter/user/{channel_id}" api_url = f"https://api-superplaycounts.onrender.com/api/youtube-channel-counter/user/{channel_id}"
channel_response = requests.get(api_url, timeout=5) async with aiohttp.ClientSession() as session:
if channel_response.status_code == 200: async with session.get(api_url, timeout=5) as channel_response:
channel_data = channel_response.json() if channel_response.status == 200:
channel_data = await channel_response.json()
for stat in channel_data.get("statistics", []): for stat in channel_data.get("statistics", []):
for count in stat.get("counts", []): for count in stat.get("counts", []):
@ -268,7 +260,7 @@ def watch():
comment_count = len(comments) comment_count = len(comments)
if os.path.exists(video_mp4_path): if os.path.exists(video_mp4_path):
video_duration = helper.get_video_duration_from_file(video_flv_path) video_duration = await helper.get_video_duration_from_file(video_flv_path)
alert_script = "" alert_script = ""
if video_duration > 420: if video_duration > 420:
alert_script = """ alert_script = """
@ -278,7 +270,7 @@ def watch():
""" """
if is_wii and os.path.exists(video_flv_path): if is_wii and os.path.exists(video_flv_path):
return render_template_string(WATCH_WII_TEMPLATE + alert_script, return await render_template_string(WATCH_WII_TEMPLATE + alert_script,
title=metadata['title'], title=metadata['title'],
uploader=metadata['uploader'], uploader=metadata['uploader'],
channelId=metadata['channelId'], channelId=metadata['channelId'],
@ -294,7 +286,7 @@ def watch():
video_flv=f"/sigma/videos/{video_id}.flv", video_flv=f"/sigma/videos/{video_id}.flv",
alert_message="") alert_message="")
return render_template_string(WATCH_WII_TEMPLATE, return await render_template_string(WATCH_WII_TEMPLATE,
title=metadata['title'], title=metadata['title'],
uploader=metadata['uploader'], uploader=metadata['uploader'],
channelId=metadata['channelId'], channelId=metadata['channelId'],
@ -312,20 +304,15 @@ def watch():
if not os.path.exists(video_mp4_path): if not os.path.exists(video_mp4_path):
if video_status[video_id]["status"] == "processing": if video_status[video_id]["status"] == "processing":
threading.Thread(target=process_video, args=(video_id,)).start() asyncio.create_task(process_video(video_id))
return render_template_string(LOADING_TEMPLATE, video_id=video_id) return await render_template_string(LOADING_TEMPLATE, video_id=video_id)
async def process_video(video_id):
def process_video(video_id):
video_mp4_path = os.path.join(VIDEO_FOLDER, f"{video_id}.mp4") video_mp4_path = os.path.join(VIDEO_FOLDER, f"{video_id}.mp4")
video_flv_path = os.path.join(VIDEO_FOLDER, f"{video_id}.flv") video_flv_path = os.path.join(VIDEO_FOLDER, f"{video_id}.flv")
try: try:
video_status[video_id] = {"status": "downloading"} video_status[video_id] = {"status": "downloading"}
with tempfile.TemporaryDirectory() as temp_dir: with tempfile.TemporaryDirectory() as temp_dir:
temp_video_path = os.path.join(temp_dir, f"{video_id}.%(ext)s") temp_video_path = os.path.join(temp_dir, f"{video_id}.%(ext)s")
command = [ command = [
@ -390,15 +377,13 @@ def process_video(video_id):
except Exception as e: except Exception as e:
video_status[video_id] = {"status": "error", "message": str(e)} video_status[video_id] = {"status": "error", "message": str(e)}
@app.route("/status/<video_id>") @app.route("/status/<video_id>")
def check_status(video_id): async def check_status(video_id):
return jsonify(video_status.get(video_id, {"status": "pending"})) return jsonify(video_status.get(video_id, {"status": "pending"}))
@app.route("/video_metadata/<video_id>") @app.route("/video_metadata/<video_id>")
def video_metadata(video_id): async def video_metadata(video_id):
api_key = helper.get_api_key() api_key = await helper.get_api_key()
params = { params = {
"part": "snippet,statistics", "part": "snippet,statistics",
@ -407,10 +392,10 @@ def video_metadata(video_id):
} }
try: try:
response = requests.get(YOUTUBE_API_URL, params=params, timeout=1) async with aiohttp.ClientSession() as session:
async with session.get(YOUTUBE_API_URL, params=params, timeout=1) as response:
response.raise_for_status() response.raise_for_status()
data = await response.json()
data = response.json()
if "items" not in data or len(data["items"]) == 0: if "items" not in data or len(data["items"]) == 0:
return f"The Video with ID {video_id} was not found.", 404 return f"The Video with ID {video_id} was not found.", 404
@ -436,18 +421,17 @@ def video_metadata(video_id):
"publishedAt": published_at "publishedAt": published_at
} }
except requests.exceptions.RequestException as e: except (aiohttp.ClientError, asyncio.TimeoutError) as e:
return f"API Error: {str(e)}", 500 return f"API Error: {str(e)}", 500
@app.route("/<path:filename>") @app.route("/<path:filename>")
def serve_video(filename): async def serve_video(filename):
file_path = os.path.join(filename) file_path = os.path.join(filename)
if not os.path.exists(file_path): if not os.path.exists(file_path):
return "File not found.", 404 return "File not found.", 404
file_size = helper.get_file_size(file_path) file_size = await helper.get_file_size(file_path)
range_header = request.headers.get('Range', None) range_header = request.headers.get('Range', None)
if range_header: if range_header:
@ -459,7 +443,7 @@ def serve_video(filename):
if start_byte >= file_size or end_byte >= file_size: if start_byte >= file_size or end_byte >= file_size:
abort(416) abort(416)
data = helper.get_range(file_path, (start_byte, end_byte)) data = await helper.get_range(file_path, (start_byte, end_byte))
content_range = f"bytes {start_byte}-{end_byte}/{file_size}" content_range = f"bytes {start_byte}-{end_byte}/{file_size}"
response = Response( response = Response(
@ -467,18 +451,15 @@ def serve_video(filename):
status=206, status=206,
mimetype="video/mp4", mimetype="video/mp4",
content_type="video/mp4", content_type="video/mp4",
direct_passthrough=True
) )
response.headers["Content-Range"] = content_range response.headers["Content-Range"] = content_range
response.headers["Content-Length"] = str(len(data)) response.headers["Content-Length"] = str(len(data))
return response return response
return send_file(file_path) return await send_file(file_path)
@app.route('/channel', methods=['GET']) @app.route('/channel', methods=['GET'])
def channel_m(): async def channel_m():
channel_id = request.args.get('channel_id', None) channel_id = request.args.get('channel_id', None)
if not channel_id: if not channel_id:
@ -500,13 +481,14 @@ def channel_m():
channel_name = info.get('uploader', 'Unknown') channel_name = info.get('uploader', 'Unknown')
async with aiohttp.ClientSession() as session:
invidious_url = f"https://invidious.materialio.us/channel/{channel_id}" invidious_url = f"https://invidious.materialio.us/channel/{channel_id}"
response = requests.get(invidious_url, timeout=10) async with session.get(invidious_url, timeout=10) as response:
if response.status != 200:
if response.status_code != 200:
return "Failed to fetch channel page.", 500 return "Failed to fetch channel page.", 500
soup = BeautifulSoup(response.text, "html.parser") html = await response.text()
soup = BeautifulSoup(html, "html.parser")
profile_div = soup.find(class_="channel-profile") profile_div = soup.find(class_="channel-profile")
if profile_div: if profile_div:
@ -529,7 +511,7 @@ def channel_m():
for video in info['entries'] for video in info['entries']
] ]
return render_template_string( return await render_template_string(
CHANNEL_TEMPLATE, CHANNEL_TEMPLATE,
results=results, results=results,
channel_name=channel_name, channel_name=channel_name,
@ -539,7 +521,5 @@ def channel_m():
except Exception as e: except Exception as e:
return f"An error occurred: {str(e)}", 500 return f"An error occurred: {str(e)}", 500
if __name__ == "__main__": if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True, port=5000) app.run(host="0.0.0.0", port=5000)