File size: 3,907 Bytes
71f9056
 
 
 
21678bc
71f9056
 
 
 
 
 
 
 
 
 
 
 
21678bc
 
 
 
71f9056
 
 
 
 
 
 
21678bc
71f9056
 
 
 
 
 
 
 
21678bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71f9056
21678bc
 
 
 
71f9056
21678bc
 
71f9056
21678bc
 
 
 
 
 
71f9056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)