萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

解析優酷視頻真實下載地址的 PHP 實作原理與程式碼

優酷視頻採用加密演算法保護真實播放地址,需經過:請求播放清單 API → 解析 JSON → 解密 `streamfileids` → 組合最終 FLV/MP4 URL。本文還原解密邏輯並提供完整 PHP 實作,僅供技術研究與合法用途使用。

核心流程

  1. 從視頻頁面 URL 擷取 Video ID (如 `id_XMzkyODA2NTEy`)
  2. 請求 `https://v.youku.com/player/getPlayList/VideoIDS/{id}` 取得 JSON
  3. 解析 `seed`、`streamfileids` (加密 fileid)、`segs` (分段資訊含 `k` 值)
  4. 依優酷演算法解密 `fileid` (核心:`getMixString` 打亂字符表 + 索引還原)
  5. 組合最終下載 URL:`https://f.youku.com/player/getFlvPath/sid/{sid}_00/st/{type}/fileid/{fileid}?K={k}`

完整 PHP 實作

<?php
/**
 * 優酷視頻真實地址解析器
 * 僅供技術研究,請遵守相關法律法規與平台服務條款
 */
class YoukuVideoResolver {
    private $userAgent;

    public function __construct() {
        $this->userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0';
    }

    public function resolve(string $url): ?array {
        // 1. 擷取 Video ID
        if (!preg_match('#id_(.*?)\.html#', $url, $m)) return null;
        $videoId = $m[1];

        // 2. 取得播放清單 JSON
        $apiUrl = "https://v.youku.com/player/getPlayList/VideoIDS/{$videoId}";
        $json = $this->httpGet($apiUrl);
        if (!$json) return null;

        $data = json_decode($json, true);
        if (empty($data['data'][0])) return null;

        $videoData = $data['data'][0];
        $seed      = $videoData['seed'] ?? 0;
        $streamIds = $videoData['streamfileids'] ?? [];
        $segs      = $videoData['segs'] ?? [];

        $results = [];
        foreach ($streamIds as $type => $encryptedFileId) {
            if (!in_array($type, ['flv', 'mp4', 'hd2', 'hd3'], true)) continue;

            // 3. 解密 fileid
            $fileId = $this->decryptFileId($encryptedFileId, $seed);

            // 4. 取得分段金鑰 k (取第一段)
            $k = $segs[$type][0]['k'] ?? '';
            if (!$k) continue;

            // 5. 組合下載 URL
            $sid = $this->generateSid();
            $downloadUrl = "https://f.youku.com/player/getFlvPath/sid/{$sid}_00/st/{$type}/fileid/{$fileId}?K={$k}";

            $results[$type] = [
                'url'       => $downloadUrl,
                'file_id'   => $fileId,
                'container' => $type,
                'segments'  => $segs[$type] ?? [],
            ];
        }
        return $results ?: null;
    }

    /** 核心解密演算法:getMixString + 索引還原 */
    private function decryptFileId(string $encrypted, int $seed): string {
        $mixed = $this->getMixString($seed);
        $ids   = explode('*', $encrypted);
        array_pop($ids); // 最後一個空值
        $realId = '';
        foreach ($ids as $idx) {
            $realId .= $mixed[(int)$idx] ?? '';
        }
        return $realId;
    }

    /** 依 seed 產生打亂字符表 */
    private function getMixString(int $seed): string {
        $source = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/:._-1234567890';
        $mixed  = '';
        $len    = strlen($source);
        for ($i = 0; $i < $len; $i++) {
            $seed = ($seed * 211 + 30031) % 65536;
            $index = (int)($seed / 65536 * strlen($source));
            $c = $source[$index];
            $mixed .= $c;
            $source = str_replace($c, '', $source);
        }
        return $mixed;
    }

    private function generateSid(): string {
        return time() . mt_rand(10000, 99999) . '1000' . mt_rand(30, 80) . '00';
    }

    private function httpGet(string $url): ?string {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERAGENT      => $this->userAgent,
            CURLOPT_REFERER        => 'https://v.youku.com/',
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $resp = curl_exec($ch);
        curl_close($ch);
        return $resp ?: null;
    }
}

// 使用範例
$resolver = new YoukuVideoResolver();
$urls = $resolver->resolve('https://v.youku.com/v_show/id_XMzkyODA2NTEy.html');
if ($urls) {
    foreach ($urls as $type => $info) {
        echo "{$type}: {$info['url']}\n";
    }
} else {
    echo "解析失敗\n";
}

演算法核心解析:getMixString

此為線性同餘生成器 (LCG) 打亂字符表:

seed = (seed * 211 + 30031) % 65536
index = floor(seed / 65536 * len(source))
取 source[index] 加入 mixed,並從 source 移除該字符

此過程將固定字符集 `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/:._-1234567890` 依 seed 產生唯一排列,`streamfileids` 中的數字索引即對應此排列位置。

注意事項與法律聲明

  • 優酷演算法可能隨時更新,此實作基於歷史版本,不保證長期有效。
  • 繞過技術保護措施取得視頻下載地址,可能違反《著作權法》及平台服務條款。
  • 僅供安全研究、相容性測試、學術分析用途,請勿用於商業爬蟲、盜鏈、未授權分發。
  • 現代優酷多採用 DRM (Widevine/PlayReady) 加密,單純解析 URL 已無法播放受保護內容。

理解視頻平台的 URL 簽名與加密機制,有助於設計合法的影音整合方案 (如官方 API、嵌入播放器)。實際專案請優先使用平台提供的開放 API 或授權合作管道。

copyright © 萬盛學電腦網 all rights reserved