技术 beesport 魔改

mybtjson · 2025年05月20日 · 21 次阅读

技术有限,大佬轻喷~!😀

谢安琪 SB 请继续,SB 一个,叫你全网出名 死骗子 技术没什么 骗人 骗 (忽悠) 得挺牛逼


import os
import hashlib
import time
import json
import requests
from flask import Flask, request, redirect, Response, stream_with_context

app = Flask(__name__)

# 自动创建缓存目录
def ensure_cache_dir_exists(cache_path):
    if not os.path.isdir(cache_path):
        os.makedirs(cache_path, mode=0o777, exist_ok=True)

# 定义缓存类
class Cache:
    def __init__(self, exp_time=3600, path="cache/"):
        self.cache_expire = exp_time
        self.cache_path = path
        ensure_cache_dir_exists(self.cache_path)  # 自动创建缓存目录

    def file_name(self, key):
        return os.path.join(self.cache_path, hashlib.md5(key.encode()).hexdigest())

    def remove(self, key):
        filename = self.file_name(key)
        if os.path.exists(filename):
            os.unlink(filename)

    def put(self, key, data):
        filename = self.file_name(key)
        try:
            with open(filename, 'w') as file:
                file.write(data)
            return True
        except:
            return False

    def get(self, key):
        filename = self.file_name(key)
        if not os.path.exists(filename) or not os.access(filename, os.R_OK):
            return False

        if time.time() < (os.path.getmtime(filename) + self.cache_expire):
            try:
                with open(filename, 'r') as file:
                    return file.read()
            except:
                return False
        else:
            os.unlink(filename)  # 超时后自动删除
            return False

# 添加代理路由
@app.route('/proxy')
def proxy():
    url = request.args.get('url')
    if not url:
        return "Missing URL parameter", 400

    # 添加必要的头信息,特别是Referer
    proxy_headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
        'Referer': 'https://p.m82xg4z0cdbz7.com/',
        'Origin': 'https://p.m82xg4z0cdbz7.com',
        'Accept': '*/*'
    }

    # 流式代理响应
    try:
        resp = requests.get(url, headers=proxy_headers, stream=True)
        resp.raise_for_status()

        # 获取原始内容类型
        content_type = resp.headers.get('Content-Type', 'application/octet-stream')

        # 如果是M3U8文件,修改其中的URL为我们的代理URL
        if 'application/vnd.apple.mpegurl' in content_type or url.endswith('.m3u8'):
            content = resp.text
            # 修改内部的TS文件URL,使其通过我们的代理
            lines = content.split('\n')
            for i in range(len(lines)):
                if not lines[i].startswith('#') and lines[i].strip():
                    # 如果是相对路径,构建完整URL
                    if not lines[i].startswith('http'):
                        base_url = url.rsplit('/', 1)[0]
                        full_url = f"{base_url}/{lines[i]}"
                    else:
                        full_url = lines[i]
                    lines[i] = f"/proxy?url={full_url}"
            content = '\n'.join(lines)

            return Response(content, content_type=content_type)

        # 返回流式响应
        return Response(
            stream_with_context(resp.iter_content(chunk_size=1024)),
            content_type=content_type,
            status=resp.status_code
        )

    except requests.exceptions.RequestException as e:
        return f"Error proxying request: {str(e)}", 500

@app.route('/')
def index():
    # 从 URL 查询参数中获取 `id`
    id_param = request.args.get('id')

    if not id_param:
        return "Error: Missing 'id' in input data", 400

    # 设定请求参数
    get_channel_api = 'https://beesport.net/authorize-channel'

    # 使用 JSON 来传递 id
    request_data = json.dumps({
        "channel": f"https://live_tv.starcdnup.com/{id_param}/index.m3u8"
    })

    # 初始化缓存
    cache = Cache(3600, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache/"))
    cache_key = hashlib.md5(id_param.encode()).hexdigest()

    # 尝试从缓存中获取结果
    cached_result = cache.get(cache_key)
    if cached_result:
        # 使用代理而不是直接重定向
        return redirect(f"/proxy?url={cached_result}")

    # 发送 POST 请求
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
        'Accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'no-cache',
        'origin': 'https://beesport.net',
        'referer': 'https://beesport.net/live-tv',
    }

    try:
        response = requests.post(get_channel_api, data=request_data, headers=headers, timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        return f"Error: External API request failed: {str(e)}", 500

    # 解析 JSON 响应
    try:
        response_json = response.json()
    except json.JSONDecodeError:
        return "Error: Invalid JSON response", 500

    if 'channels' in response_json and response_json['channels']:
        channel = response_json['channels'][0]  # 直接使用第一个通道
        cache.put(cache_key, channel)
        # 使用代理而不是直接重定向
        return redirect(f"/proxy?url={channel}")
    else:
        return "Error: No valid channels found in response", 404

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号