Spaces:
Build error
Build error
| from flask import Flask, jsonify, request, send_from_directory | |
| from flask_cors import CORS | |
| from utils import is_valid_url, bytes_to_human_readable, encode_episodeid | |
| import os | |
| import json | |
| from threading import Thread | |
| import urllib.parse | |
| from LoadBalancer import LoadBalancer | |
| import logging | |
| app = Flask(__name__) | |
| CORS(app) | |
| logging.basicConfig(level=logging.INFO) | |
| # Constants and Configuration | |
| CACHE_DIR = os.getenv("CACHE_DIR") | |
| INDEX_FILE = os.getenv("INDEX_FILE") | |
| TOKEN = os.getenv("TOKEN") | |
| REPO = os.getenv("REPO") | |
| load_balancer = LoadBalancer(cache_dir=CACHE_DIR, index_file=INDEX_FILE, token=TOKEN, repo=REPO) | |
| # Start polling in a separate thread | |
| polling_thread = Thread(target=load_balancer.start_polling) | |
| polling_thread.start() | |
| # API Endpoints | |
| def get_movie_api(title): | |
| """Endpoint to get the movie by title.""" | |
| if not title: | |
| return jsonify({"error": "Title parameter is required"}), 400 | |
| # Check if the film is already cached | |
| if title in load_balancer.FILM_STORE: | |
| url = load_balancer.FILM_STORE[title] | |
| return jsonify({"url":url}) | |
| movie_path = load_balancer.find_movie_path(title) | |
| if not movie_path: | |
| return jsonify({"error": "Movie not found"}), 404 | |
| # Start the download in a instance | |
| response = load_balancer.download_film_to_best_instance(title=title) | |
| if response: | |
| return jsonify(response) | |
| def get_tv_show_api(title, season, episode): | |
| """Endpoint to get the TV show by title, season, and episode.""" | |
| if not title or not season or not episode: | |
| return jsonify({"error": "Title, season, and episode parameters are required"}), 400 | |
| # Check if the episode is already cached | |
| if title in load_balancer.TV_STORE and season in load_balancer.TV_STORE[title]: | |
| for ep in load_balancer.TV_STORE[title][season]: | |
| if episode in ep: | |
| url = load_balancer.TV_STORE[title][season][ep] | |
| return jsonify({"url":url}) | |
| tv_path = load_balancer.find_tv_path(title) | |
| if not tv_path: | |
| return jsonify({"error": "TV show not found"}), 404 | |
| episode_path = None | |
| for directory in load_balancer.file_structure: | |
| if directory['type'] == 'directory' and directory['path'] == 'tv': | |
| for sub_directory in directory['contents']: | |
| if sub_directory['type'] == 'directory' and title.lower() in sub_directory['path'].lower(): | |
| for season_dir in sub_directory['contents']: | |
| if season_dir['type'] == 'directory' and season in season_dir['path']: | |
| for episode_file in season_dir['contents']: | |
| if episode_file['type'] == 'file' and episode in episode_file['path']: | |
| episode_path = episode_file['path'] | |
| break | |
| if not episode_path: | |
| return jsonify({"error": "Episode not found"}), 404 | |
| # Start the download in a instance | |
| response = load_balancer.download_episode_to_best_instance(title=title, season=season, episode=episode) | |
| if response: | |
| return jsonify(response) | |
| def get_film_id_by_title_api(title): | |
| """Endpoint to get the film ID by providing the movie title.""" | |
| if not title: | |
| return jsonify({"error": "Title parameter is required"}), 400 | |
| film_id = load_balancer.get_film_id(title) | |
| return jsonify({"film_id": film_id}) | |
| def get_episode_id_api(title,season,episode): | |
| """Endpoint to get the episode ID by providing the TV show title, season, and episode.""" | |
| if not title or not season or not episode: | |
| return jsonify({"error": "Title, season, and episode parameters are required"}), 400 | |
| episode_id = encode_episodeid(title,season,episode) | |
| return jsonify({"episode_id": episode_id}) | |
| def get_cache_size_api(): | |
| total_size = 0 | |
| for dirpath, dirnames, filenames in os.walk(CACHE_DIR): | |
| for f in filenames: | |
| fp = os.path.join(dirpath, f) | |
| total_size += os.path.getsize(fp) | |
| readable_size = bytes_to_human_readable(total_size) | |
| return jsonify({"cache_size": readable_size}) | |
| def clear_cache_api(): | |
| for dirpath, dirnames, filenames in os.walk(CACHE_DIR): | |
| for f in filenames: | |
| fp = os.path.join(dirpath, f) | |
| os.remove(fp) | |
| return jsonify({"status": "Cache cleared"}) | |
| def get_tv_store_api(): | |
| """Endpoint to get the TV store JSON.""" | |
| return jsonify(load_balancer.TV_STORE) | |
| def get_film_store_api(): | |
| """Endpoint to get the film store JSON.""" | |
| return jsonify(load_balancer.FILM_STORE) | |
| def get_film_metadata_api(title): | |
| """Endpoint to get the film metadata by title.""" | |
| if not title: | |
| return jsonify({'error': 'No title provided'}), 400 | |
| json_cache_path = os.path.join(CACHE_DIR, f"{urllib.parse.quote(title)}.json") | |
| if os.path.exists(json_cache_path): | |
| with open(json_cache_path, 'r') as f: | |
| data = json.load(f) | |
| return jsonify(data) | |
| return jsonify({'error': 'Metadata not found'}), 404 | |
| def get_tv_metadata_api(title): | |
| """Endpoint to get the TV show metadata by title.""" | |
| if not title: | |
| return jsonify({'error': 'No title provided'}), 400 | |
| json_cache_path = os.path.join(CACHE_DIR, f"{urllib.parse.quote(title)}.json") | |
| if os.path.exists(json_cache_path): | |
| with open(json_cache_path, 'r') as f: | |
| data = json.load(f) | |
| # Add the file structure to the metadata | |
| tv_structure_data = load_balancer.get_tv_structure(title) | |
| if tv_structure_data: | |
| data['file_structure'] = tv_structure_data | |
| return jsonify(data) | |
| return jsonify({'error': 'Metadata not found'}), 404 | |
| def get_all_films_api(): | |
| return load_balancer.get_all_films() | |
| def get_all_tvshows_api(): | |
| return load_balancer.get_all_tv_shows() | |
| def get_instances(): | |
| return load_balancer.instances | |
| def get_instances_health(): | |
| return load_balancer.instances_health | |
| ############################################################# | |
| # This API is only for instances | |
| def register_instance(): | |
| try: | |
| data = request.json | |
| if not data or "url" not in data: | |
| return jsonify({"error": "No URL provided"}), 400 | |
| url = data["url"] | |
| if not is_valid_url(url): | |
| return jsonify({"error": "Invalid URL"}), 400 | |
| # Register the instance | |
| load_balancer.register_instance(url) | |
| logging.info(f"Instance registered: {url}") | |
| return jsonify({"message": f"Instance {url} registered successfully"}), 200 | |
| except Exception as e: | |
| logging.error(f"Error registering instance: {e}") | |
| return jsonify({"error": "Failed to register instance"}), 500 | |
| ############################################################# | |
| # Routes | |
| def index(): | |
| return f"Load Balancer is Running {load_balancer.version}" | |
| # Main entry point | |
| if __name__ == "__main__": | |
| app.run(debug=True, host="0.0.0.0", port=7860) | |