from flask import Flask, render_template, jsonify, request import requests import logging import os import random app = Flask(__name__) # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) API_URL = "https://v2.xxapi.cn/api/meinv" HEADERS = { 'User-Agent': 'xiaoxiaoapi/1.0.0 (https://xxapi.cn)' } # Video URL cache video_url_cache = [] CACHE_SIZE = 20 @app.route('/') def index(): """Render the main application page""" return render_template('index.html') @app.route('/api/videos', methods=['GET']) def get_videos(): """Fetch videos from the external API with caching""" try: # Get count parameter (default to 1) count = int(request.args.get('count', 1)) # Limit count to reasonable number to prevent abuse count = min(count, 5) videos = [] # If cache has enough videos, return from cache if len(video_url_cache) >= count: # Randomly select videos instead of sequential order selected_videos = random.sample(video_url_cache, count) for video_url in selected_videos: videos.append({ 'url': video_url, 'timestamp': None }) # Remove used videos from cache to avoid repetition if video_url in video_url_cache: video_url_cache.remove(video_url) # If we need more videos (either for response or to refill cache) fetch_count = max(count - len(videos), CACHE_SIZE - len(video_url_cache)) if fetch_count > 0: new_urls = [] for _ in range(fetch_count): try: response = requests.get(API_URL, headers=HEADERS, timeout=3) if response.status_code == 200: data = response.json() if data.get('code') == 200 and data.get('data'): video_url = data.get('data') new_urls.append(video_url) else: logger.warning(f"API returned status code: {response.status_code}") except Exception as e: logger.error(f"Error in API request: {str(e)}") # Add to response if needed needed_for_response = count - len(videos) if needed_for_response > 0 and new_urls: for i in range(min(needed_for_response, len(new_urls))): videos.append({ 'url': new_urls[i], 'timestamp': None }) # Don't add these to cache since we're using them now new_urls[i] = None # Add remaining new URLs to cache video_url_cache.extend([url for url in new_urls if url is not None]) return jsonify({ 'success': True, 'videos': videos }) except Exception as e: logger.error(f"Error fetching videos: {str(e)}") return jsonify({ 'success': False, 'error': 'Failed to fetch videos', 'message': str(e) }), 500 @app.errorhandler(404) def page_not_found(e): """Handle 404 errors""" return render_template('error.html', error='Page not found'), 404 @app.errorhandler(500) def server_error(e): """Handle 500 errors""" return render_template('error.html', error='Server error'), 500 if __name__ == '__main__': # Get port from environment variable or default to 7860 port = int(os.environ.get('PORT', 7860)) app.run(host='0.0.0.0', port=port, debug=False)