[sohu] Enhance error handling
[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 ..compat import (
8     compat_str,
9     compat_urllib_request
10 )
11 from ..utils import (
12     sanitize_url_path_consecutive_slashes,
13     ExtractorError,
14 )
15
16
17 class SohuIE(InfoExtractor):
18     _VALID_URL = r'https?://(?P<mytv>my\.)?tv\.sohu\.com/.+?/(?(mytv)|n)(?P<id>\d+)\.shtml.*?'
19
20     _TESTS = [{
21         'note': 'This video is available only in Mainland China',
22         'url': 'http://tv.sohu.com/20130724/n382479172.shtml#super',
23         'md5': '29175c8cadd8b5cc4055001e85d6b372',
24         'info_dict': {
25             'id': '382479172',
26             'ext': 'mp4',
27             'title': 'MV:Far East Movement《The Illest》',
28         },
29         'params': {
30             'cn_verification_proxy': 'proxy.uku.im:8888'
31         }
32     }, {
33         'url': 'http://tv.sohu.com/20150305/n409385080.shtml',
34         'md5': '699060e75cf58858dd47fb9c03c42cfb',
35         'info_dict': {
36             'id': '409385080',
37             'ext': 'mp4',
38             'title': '《2015湖南卫视羊年元宵晚会》唐嫣《花好月圆》',
39         }
40     }, {
41         'url': 'http://my.tv.sohu.com/us/232799889/78693464.shtml',
42         'md5': '9bf34be48f2f4dadcb226c74127e203c',
43         'info_dict': {
44             'id': '78693464',
45             'ext': 'mp4',
46             'title': '【爱范品】第31期:MWC见不到的奇葩手机',
47         }
48     }, {
49         'note': 'Multipart video',
50         'url': 'http://my.tv.sohu.com/pl/8384802/78910339.shtml',
51         'info_dict': {
52             'id': '78910339',
53             'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',
54         },
55         'playlist': [{
56             'md5': 'bdbfb8f39924725e6589c146bc1883ad',
57             'info_dict': {
58                 'id': '78910339_part1',
59                 'ext': 'mp4',
60                 'duration': 294,
61                 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',
62             }
63         }, {
64             'md5': '3e1f46aaeb95354fd10e7fca9fc1804e',
65             'info_dict': {
66                 'id': '78910339_part2',
67                 'ext': 'mp4',
68                 'duration': 300,
69                 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',
70             }
71         }, {
72             'md5': '8407e634175fdac706766481b9443450',
73             'info_dict': {
74                 'id': '78910339_part3',
75                 'ext': 'mp4',
76                 'duration': 150,
77                 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',
78             }
79         }]
80     }, {
81         'note': 'Video with title containing dash',
82         'url': 'http://my.tv.sohu.com/us/249884221/78932792.shtml',
83         'info_dict': {
84             'id': '78932792',
85             'ext': 'mp4',
86             'title': 'youtube-dl testing video',
87         },
88         'params': {
89             'skip_download': True
90         }
91     }]
92
93     def _real_extract(self, url):
94
95         def _fetch_data(vid_id, mytv=False):
96             if mytv:
97                 base_data_url = 'http://my.tv.sohu.com/play/videonew.do?vid='
98             else:
99                 base_data_url = 'http://hot.vrs.sohu.com/vrs_flash.action?vid='
100
101             req = compat_urllib_request.Request(base_data_url + vid_id)
102
103             cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
104             if cn_verification_proxy:
105                 req.add_header('Ytdl-request-proxy', cn_verification_proxy)
106
107             return self._download_json(
108                 req, video_id,
109                 'Downloading JSON data for %s' % vid_id)
110
111         mobj = re.match(self._VALID_URL, url)
112         video_id = mobj.group('id')
113         mytv = mobj.group('mytv') is not None
114
115         webpage = self._download_webpage(url, video_id)
116
117         title = re.sub(r' - 搜狐视频$', '', self._og_search_title(webpage))
118
119         vid = self._html_search_regex(
120             r'var vid ?= ?["\'](\d+)["\']',
121             webpage, 'video path')
122         vid_data = _fetch_data(vid, mytv)
123         if vid_data['play'] != 1:
124             if vid_data.get('status') == 12:
125                 raise ExtractorError(
126                     'Sohu said: There\'s something wrong in the video.',
127                     expected=True)
128             else:
129                 raise ExtractorError(
130                     'Sohu said: The video is only licensed to users in Mainland China.',
131                     expected=True)
132
133         formats_json = {}
134         for format_id in ('nor', 'high', 'super', 'ori', 'h2644k', 'h2654k'):
135             vid_id = vid_data['data'].get('%sVid' % format_id)
136             if not vid_id:
137                 continue
138             vid_id = compat_str(vid_id)
139             formats_json[format_id] = vid_data if vid == vid_id else _fetch_data(vid_id, mytv)
140
141         part_count = vid_data['data']['totalBlocks']
142
143         playlist = []
144         for i in range(part_count):
145             formats = []
146             for format_id, format_data in formats_json.items():
147                 allot = format_data['allot']
148                 prot = format_data['prot']
149
150                 data = format_data['data']
151                 clips_url = data['clipsURL']
152                 su = data['su']
153
154                 part_str = self._download_webpage(
155                     'http://%s/?prot=%s&file=%s&new=%s' %
156                     (allot, prot, clips_url[i], su[i]),
157                     video_id,
158                     'Downloading %s video URL part %d of %d'
159                     % (format_id, i + 1, part_count))
160
161                 part_info = part_str.split('|')
162
163                 video_url = sanitize_url_path_consecutive_slashes(
164                     '%s%s?key=%s' % (part_info[0], su[i], part_info[3]))
165
166                 formats.append({
167                     'url': video_url,
168                     'format_id': format_id,
169                     'filesize': data['clipsBytes'][i],
170                     'width': data['width'],
171                     'height': data['height'],
172                     'fps': data['fps'],
173                 })
174             self._sort_formats(formats)
175
176             playlist.append({
177                 'id': '%s_part%d' % (video_id, i + 1),
178                 'title': title,
179                 'duration': vid_data['data']['clipsDuration'][i],
180                 'formats': formats,
181             })
182
183         if len(playlist) == 1:
184             info = playlist[0]
185             info['id'] = video_id
186         else:
187             info = {
188                 '_type': 'multi_video',
189                 'entries': playlist,
190                 'id': video_id,
191                 'title': title,
192             }
193
194         return info