<?php namespace Api\Video\Remote;
use Dever;
class Douyin extends Base
{
    # 参考 https://github.com/NearHuiwen/TiktokDouyinCrawler
    protected $type = 'douyin';
    private $host = 'www.douyin.com';
    private $msToken = '';
    private $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
    private $odin_tt = '324fb4ea4a89c0c05827e18a1ed9cf9bf8a17f7705fcc793fec935b637867e2a5a9b8168c885554d029919117a18ba69';
    private $webid = '7246605341814654516';
    private $ttwid = '1%7C7ZLJzwjjEw7NLeADTpVd-3eId-ZEIg0jpCEzTV9p_2A%7C1677681848%7C4ff4f97328ddc18b6d46c259bc26a05d2e654b50e3f21b27b8f9e9e8f9fcec82';
    private $bd_ticket_guard_client_data = 'eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWNsaWVudC1jc3IiOiItLS0tLUJFR0lOIENFUlRJRklDQVRFIFJFUVVFU1QtLS0tLVxyXG5NSUlCRFRDQnRRSUJBREFuTVFzd0NRWURWUVFHRXdKRFRqRVlNQllHQTFVRUF3d1BZbVJmZEdsamEyVjBYMmQxXHJcbllYSmtNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVKUDZzbjNLRlFBNUROSEcyK2F4bXAwNG5cclxud1hBSTZDU1IyZW1sVUE5QTZ4aGQzbVlPUlI4NVRLZ2tXd1FJSmp3Nyszdnc0Z2NNRG5iOTRoS3MvSjFJc3FBc1xyXG5NQ29HQ1NxR1NJYjNEUUVKRGpFZE1Cc3dHUVlEVlIwUkJCSXdFSUlPZDNkM0xtUnZkWGxwYmk1amIyMHdDZ1lJXHJcbktvWkl6ajBFQXdJRFJ3QXdSQUlnVmJkWTI0c0RYS0c0S2h3WlBmOHpxVDRBU0ROamNUb2FFRi9MQnd2QS8xSUNcclxuSURiVmZCUk1PQVB5cWJkcytld1QwSDZqdDg1czZZTVNVZEo5Z2dmOWlmeTBcclxuLS0tLS1FTkQgQ0VSVElGSUNBVEUgUkVRVUVTVC0tLS0tXHJcbiJ9';

    # 获取视频信息
    public function info($txt, $local = false)
    {
        //$txt = '3.00 复制打开抖音，看看【电视剧《庆余年》的作品】# 范思辙郭保坤南庆卧龙凤雏 两个显眼包的相遇：相... https://v.douyin.com/i2Tq9R93/ fBT:/ T@l.PX 05/05';
        //$url = 'https://ansnid.com/douyin/api/?text=https://www.douyin.com/share/video/' . $ids;
        //https://www.douyin.com/video/7367585269219986723
        $id = $this->getVideo($txt, $local);
        if (is_array($id)) {
            return $id;
        }

        $url = 'https://www.douyin.com/aweme/v1/web/aweme/detail/?device_platform=webapp&aid=6383&channel=channel_pc_web&aweme_id='.$id.'&update_version_code=170400&pc_client_type=1&version_code=190500&version_name=19.5.0&cookie_enabled=true&screen_width=1536&screen_height=864&browser_language=zh-CN&browser_platform=Win32&browser_name=Chrome&browser_version=124.0.0.0&browser_online=true&engine_name=Blink&engine_version=124.0.0.0&os_name=Windows&os_version=10&cpu_core_num=16&device_memory=8&platform=PC';

        $refer = $this->getRefererUrl($id);
        $result = $this->get($url, $refer);

        if ($result['status_code'] == 0) {
            // 重新组装需要的视频参数
            $tags = array();
            foreach ($result['aweme_detail']['video_tag'] as $v) {
                $tags[] = $v['tag_name'];
            }
            $data = array
            (
                'type' => $this->type,
                'id' => $result['aweme_detail']['aweme_id'],
                'cdate' => $result['aweme_detail']['create_time'],
                'title' => $result['aweme_detail']['item_title'],
                'desc' => $result['aweme_detail']['desc'],
                'tags' => $tags,
                'media_type' => $result['aweme_detail']['media_type'],

                'images' => $result['aweme_detail']['images'] ?? array(),

                'video' => array
                (
                    'cover' => $result['aweme_detail']['video']['origin_cover']['url_list'][0],
                    'format' => $result['aweme_detail']['video']['format'],
                    'url' => $result['aweme_detail']['video']['play_addr']['url_list'][0],
                    'ratio' => $result['aweme_detail']['video']['ratio'],
                    'height' => $result['aweme_detail']['video']['height'],
                    'width' => $result['aweme_detail']['video']['width'],
                    'duration' => $result['aweme_detail']['video']['duration'],
                    'cdn_url_expired' => $result['aweme_detail']['video']['cdn_url_expired'],
                ),

                'music'    => array
                (
                    'id' => $result['aweme_detail']['music']['id'],
                    'author' => $result['aweme_detail']['music']['author'],
                    'avatar' => $result['aweme_detail']['music']['cover_large']['url_list'][0],
                    'owner_nickname' => $result['aweme_detail']['music']['owner_nickname'],
                    'title' => $result['aweme_detail']['music']['title'],
                    'url' => $result['aweme_detail']['music']['play_url']['url_list'][0],
                ),

                'author'    => array
                (
                    'uid' => $result['aweme_detail']['author_user_id'],
                    'avatar' => $result['aweme_detail']['author']['avatar_thumb']['url_list'][0],
                    'follower_count'    => $result['aweme_detail']['author']['follower_count'],
                    'nickname'    => $result['aweme_detail']['author']['nickname'],
                    'sec_uid'    => $result['aweme_detail']['author']['sec_uid'],
                    'short_id'    => $result['aweme_detail']['author']['short_id'],
                    'signature'    => $result['aweme_detail']['author']['signature'],
                    'total_favorited'    => $result['aweme_detail']['author']['total_favorited'],
                    'unique_id'    => $result['aweme_detail']['author']['unique_id'],
                    'user_agent'    => $result['aweme_detail']['author']['user_agent'] ?? null,
                    'verification_type'    => $result['aweme_detail']['author']['verification_type'],
                    'status'    => $result['aweme_detail']['author']['status'],
                    'favoriting_count'    => $result['aweme_detail']['author']['favoriting_count'],
                    'contacts_status'    => $result['aweme_detail']['author']['contacts_status'],
                    'enterprise_verify_reason'    => $result['aweme_detail']['author']['enterprise_verify_reason'],
                ),
            );
            return $this->saveVideo($data);
        }
        Dever::error('请求错误');
    }

    private function get($url, $refer = '')
    {
        $this->msToken = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 107);
        $header['User-Agent'] = $this->agent;
        $header['Referer'] = 'https://'.$this->host.'/';
        if ($refer) {
            $header['Referer'] = $refer;
            $url .= '&webid=' . $this->webid;
        }
        $header['Cookie'] = 'msToken=' . $this->msToken . ';odin_tt=' . $this->odin_tt . ';ttwid=' . $this->ttwid . ';bd_ticket_guard_client_data=' . $this->bd_ticket_guard_client_data;
        $header['Accept'] = '*/*';
        $header['Host'] = $this->host;
        $header['Connection'] = 'keep-alive';
        
        $result = Dever::curl($this->url($url), array(), 'get', false, $header)->result();
        if (!$result) {
            Dever::error('请求错误');
        }
        return Dever::json_decode($result);
    }

    private function url($url)
    {
        $params = array
        (
            'type' => 'bogus',
            'url' => $url,
            'user_agent' => $this->agent,
        );
        $client = Dever::data() . 'douyin/client.py';
        $params = Dever::json_encode($params);
        putenv('PATH=/usr/local/bin:/usr/bin:/bin');
        $cmd = "python3 {$client} " . escapeshellarg($params);
        exec($cmd, $out, $state);
        if ($state != 0) {
            Dever::error('解析错误');
        }
        return $out[0];
    }

    private function getRefererUrl($id)
    {
        return false;
        $refer = 'https://www.douyin.com/discover?modal_id=' . $id;
        $params = array
        (
            'type' => 'webid',
            'url' => $refer,
            'user_agent' => $this->agent,
        );
        $client = Dever::data() . 'douyin/client.py';
        $params = Dever::json_encode($params);
        putenv('PATH=/usr/local/bin:/usr/bin:/bin');
        $cmd = "python3 {$client} " . escapeshellarg($params);
        exec($cmd, $out, $state);
        if ($state != 0) {
            Dever::error('解析错误');
        }
        $temp = str_replace(array("('", "')", "'"), '', $out[0]);
        $temp = explode(', ', $temp);
        $this->ttwid = $temp[0];
        $this->webid = $temp[1];
        return $refer;
    }
}