import http.cookiejar import json from flask import Flask, Response import requests from bs4 import BeautifulSoup app = Flask(__name__) cookie_jar = http.cookiejar.MozillaCookieJar('cookies.txt') try: cookie_jar.load(ignore_discard=True, ignore_expires=True) except FileNotFoundError: print("cookies.txt not found, starting with empty cookie jar") s = requests.Session() s.headers.update({ "User-Agent": "Twitterbot/1.0" }) s.cookies = cookie_jar # type: ignore @app.route("/watch/") def proxy(video_id): real_url = f"https://www.nicovideo.jp/watch/{video_id}" try: r = s.get(real_url, timeout=10) except requests.RequestException as e: return Response(f"Error fetching the page: {e}", status=500) soup = BeautifulSoup(r.text, "html.parser") thumbnail_url = None if soup.find("meta", {"name": "server-response"}): params = json.loads(soup.find("meta", {"name": "server-response"})["content"])["data"]["response"] # type: ignore thumbnail_url = ( # Use highest quality thumbnail available params["video"]["thumbnail"]["ogp"] or params["video"]["thumbnail"]["player"] or params["video"]["thumbnail"]["largeUrl"] or params["video"]["thumbnail"]["middleUrl"] or params["video"]["thumbnail"]["url"] ) og_tags = soup.find_all("meta", property=lambda x: x) # type: ignore for tag in og_tags: if tag.get("property") == "og:image": tag["content"] = thumbnail_url og_tags_str = "\n".join(str(tag) for tag in og_tags) html_response = f""" {og_tags_str} """ return Response(html_response, mimetype="text/html") if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, debug=False)