[sohu] Fix info extractor and add tests
[youtube-dl] / youtube_dl / extractor / sohu.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import compat_str
8 from ..compat import compat_urllib_request
9
10
11 class SohuIE(InfoExtractor):
12     _VALID_URL = r'https?://(?P<mytv>my\.)?tv\.sohu\.com/.+?/(?(mytv)|n)(?P<id>\d+)\.shtml.*?'
13
14     _TESTS = [{
15         'note': 'This video is available only in Mainland China',
16         'url': 'http://tv.sohu.com/20130724/n382479172.shtml#super',
17         'md5': '29175c8cadd8b5cc4055001e85d6b372',
18         'info_dict': {
19             'id': '382479172',
20             'ext': 'mp4',
21             'title': 'MV:Far East Movement《The Illest》',
22         },
23         'params': {
24             'cn_verification_proxy': 'proxy.uku.im:8888'
25         }
26     }, {
27         'url': 'http://tv.sohu.com/20150305/n409385080.shtml',
28         'md5': '699060e75cf58858dd47fb9c03c42cfb',
29         'info_dict': {
30             'id': '409385080',
31             'ext': 'mp4',
32             'title': '《2015湖南卫视羊年元宵晚会》唐嫣《花好月圆》',
33         }
34     }, {
35         'url': 'http://my.tv.sohu.com/us/232799889/78693464.shtml',
36         'md5': '9bf34be48f2f4dadcb226c74127e203c',
37         'info_dict': {
38             'id': '78693464',
39             'ext': 'mp4',
40             'title': '【爱范品】第31期:MWC见不到的奇葩手机',
41         }
42     }]
43
44     def _real_extract(self, url):
45
46         def _fetch_data(vid_id, mytv=False):
47             if mytv:
48                 base_data_url = 'http://my.tv.sohu.com/play/videonew.do?vid='
49             else:
50                 base_data_url = 'http://hot.vrs.sohu.com/vrs_flash.action?vid='
51
52             req = compat_urllib_request.Request(base_data_url + vid_id)
53
54             cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
55             if cn_verification_proxy:
56                 req.add_header('Ytdl-request-proxy', cn_verification_proxy)
57
58             return self._download_json(req, video_id,
59                                        'Downloading JSON data for %s' % vid_id)
60
61         mobj = re.match(self._VALID_URL, url)
62         video_id = mobj.group('id')
63         mytv = mobj.group('mytv') is not None
64
65         webpage = self._download_webpage(url, video_id)
66         raw_title = self._html_search_regex(
67             r'(?s)<title>(.+?)</title>',
68             webpage, 'video title')
69         title = raw_title.partition('-')[0].strip()
70
71         vid = self._html_search_regex(
72             r'var vid ?= ?["\'](\d+)["\']',
73             webpage, 'video path')
74         vid_data = _fetch_data(vid, mytv)
75
76         formats_json = {}
77         for format_id in ('nor', 'high', 'super', 'ori', 'h2644k', 'h2654k'):
78             vid_id = vid_data['data'].get('%sVid' % format_id)
79             if not vid_id:
80                 continue
81             vid_id = compat_str(vid_id)
82             formats_json[format_id] = vid_data if vid == vid_id else _fetch_data(vid_id, mytv)
83
84         part_count = vid_data['data']['totalBlocks']
85
86         playlist = []
87         for i in range(part_count):
88             formats = []
89             for format_id, format_data in formats_json.items():
90                 allot = format_data['allot']
91                 prot = format_data['prot']
92
93                 data = format_data['data']
94                 clips_url = data['clipsURL']
95                 su = data['su']
96
97                 part_str = self._download_webpage(
98                     'http://%s/?prot=%s&file=%s&new=%s' %
99                     (allot, prot, clips_url[i], su[i]),
100                     video_id,
101                     'Downloading %s video URL part %d of %d'
102                     % (format_id, i + 1, part_count))
103
104                 part_info = part_str.split('|')
105
106                 # Sanitize URL to prevent download failure
107                 if part_info[0][-1] == '/' and su[i][0] == '/':
108                     su[i] = su[i][1:]
109
110                 video_url = '%s%s?key=%s' % (part_info[0], su[i], part_info[3])
111
112                 formats.append({
113                     'url': video_url,
114                     'format_id': format_id,
115                     'filesize': data['clipsBytes'][i],
116                     'width': data['width'],
117                     'height': data['height'],
118                     'fps': data['fps'],
119                 })
120             self._sort_formats(formats)
121
122             playlist.append({
123                 'id': '%s_part%d' % (video_id, i + 1),
124                 'title': title,
125                 'duration': vid_data['data']['clipsDuration'][i],
126                 'formats': formats,
127             })
128
129         if len(playlist) == 1:
130             info = playlist[0]
131             info['id'] = video_id
132         else:
133             info = {
134                 '_type': 'playlist',
135                 'entries': playlist,
136                 'id': video_id,
137             }
138
139         return info