[tudou] Improve error handling (closes #8988)
[youtube-dl] / youtube_dl / extractor / tudou.py
1 # coding: utf-8
2
3 from __future__ import unicode_literals
4
5 from .common import InfoExtractor
6 from ..compat import compat_str
7 from ..utils import (
8     ExtractorError,
9     int_or_none,
10     InAdvancePagedList,
11     float_or_none,
12     unescapeHTML,
13 )
14
15
16 class TudouIE(InfoExtractor):
17     IE_NAME = 'tudou'
18     _VALID_URL = r'https?://(?:www\.)?tudou\.com/(?:(?:programs|wlplay)/view|(?:listplay|albumplay)/[\w-]{11})/(?P<id>[\w-]{11})'
19     _TESTS = [{
20         'url': 'http://www.tudou.com/listplay/zzdE77v6Mmo/2xN2duXMxmw.html',
21         'md5': '140a49ed444bd22f93330985d8475fcb',
22         'info_dict': {
23             'id': '159448201',
24             'ext': 'f4v',
25             'title': '卡马乔国足开大脚长传冲吊集锦',
26             'thumbnail': 're:^https?://.*\.jpg$',
27             'timestamp': 1372113489000,
28             'description': '卡马乔卡家军,开大脚先进战术不完全集锦!',
29             'duration': 289.04,
30             'view_count': int,
31             'filesize': int,
32         }
33     }, {
34         'url': 'http://www.tudou.com/programs/view/ajX3gyhL0pc/',
35         'info_dict': {
36             'id': '117049447',
37             'ext': 'f4v',
38             'title': 'La Sylphide-Bolshoi-Ekaterina Krysanova & Vyacheslav Lopatin 2012',
39             'thumbnail': 're:^https?://.*\.jpg$',
40             'timestamp': 1349207518000,
41             'description': 'md5:294612423894260f2dcd5c6c04fe248b',
42             'duration': 5478.33,
43             'view_count': int,
44             'filesize': int,
45         }
46     }]
47
48     _PLAYER_URL = 'http://js.tudouui.com/bin/lingtong/PortalPlayer_177.swf'
49
50     # Translated from tudou/tools/TVCHelper.as in PortalPlayer_193.swf
51     # 0001, 0002 and 4001 are not included as they indicate temporary issues
52     TVC_ERRORS = {
53         '0003': 'The video is deleted or does not exist',
54         '1001': 'This video is unavailable due to licensing issues',
55         '1002': 'This video is unavailable as it\'s under review',
56         '1003': 'This video is unavailable as it\'s under review',
57         '3001': 'Password required',
58         '5001': 'This video is available in Mainland China only due to licensing issues',
59         '7001': 'This video is unavailable',
60         '8001': 'This video is unavailable due to licensing issues',
61     }
62
63     def _url_for_id(self, video_id, quality=None):
64         info_url = 'http://v2.tudou.com/f?id=' + compat_str(video_id)
65         if quality:
66             info_url += '&hd' + quality
67         xml_data = self._download_xml(info_url, video_id, 'Opening the info XML page')
68         final_url = xml_data.text
69         return final_url
70
71     def _real_extract(self, url):
72         video_id = self._match_id(url)
73         item_data = self._download_json(
74             'http://www.tudou.com/tvp/getItemInfo.action?ic=%s' % video_id, video_id)
75
76         youku_vcode = item_data.get('vcode')
77         if youku_vcode:
78             return self.url_result('youku:' + youku_vcode, ie='Youku')
79
80         if not item_data.get('itemSegs'):
81             tvc_code = item_data.get('tvcCode')
82             if tvc_code:
83                 err_msg = self.TVC_ERRORS.get(tvc_code)
84                 if err_msg:
85                     raise ExtractorError('Tudou said: %s' % err_msg, expected=True)
86                 raise ExtractorError('Unexpected error %s returned from Tudou' % tvc_code)
87             raise ExtractorError('Unxpected error returned from Tudou')
88
89         title = unescapeHTML(item_data['kw'])
90         description = item_data.get('desc')
91         thumbnail_url = item_data.get('pic')
92         view_count = int_or_none(item_data.get('playTimes'))
93         timestamp = int_or_none(item_data.get('pt'))
94
95         segments = self._parse_json(item_data['itemSegs'], video_id)
96         # It looks like the keys are the arguments that have to be passed as
97         # the hd field in the request url, we pick the higher
98         # Also, filter non-number qualities (see issue #3643).
99         quality = sorted(filter(lambda k: k.isdigit(), segments.keys()),
100                          key=lambda k: int(k))[-1]
101         parts = segments[quality]
102         len_parts = len(parts)
103         if len_parts > 1:
104             self.to_screen('%s: found %s parts' % (video_id, len_parts))
105
106         def part_func(partnum):
107             part = parts[partnum]
108             part_id = part['k']
109             final_url = self._url_for_id(part_id, quality)
110             ext = (final_url.split('?')[0]).split('.')[-1]
111             return [{
112                 'id': '%s' % part_id,
113                 'url': final_url,
114                 'ext': ext,
115                 'title': title,
116                 'thumbnail': thumbnail_url,
117                 'description': description,
118                 'view_count': view_count,
119                 'timestamp': timestamp,
120                 'duration': float_or_none(part.get('seconds'), 1000),
121                 'filesize': int_or_none(part.get('size')),
122                 'http_headers': {
123                     'Referer': self._PLAYER_URL,
124                 },
125             }]
126
127         entries = InAdvancePagedList(part_func, len_parts, 1)
128
129         return {
130             '_type': 'multi_video',
131             'entries': entries,
132             'id': video_id,
133             'title': title,
134         }
135
136
137 class TudouPlaylistIE(InfoExtractor):
138     IE_NAME = 'tudou:playlist'
139     _VALID_URL = r'https?://(?:www\.)?tudou\.com/listplay/(?P<id>[\w-]{11})\.html'
140     _TESTS = [{
141         'url': 'http://www.tudou.com/listplay/zzdE77v6Mmo.html',
142         'info_dict': {
143             'id': 'zzdE77v6Mmo',
144         },
145         'playlist_mincount': 209,
146     }]
147
148     def _real_extract(self, url):
149         playlist_id = self._match_id(url)
150         playlist_data = self._download_json(
151             'http://www.tudou.com/tvp/plist.action?lcode=%s' % playlist_id, playlist_id)
152         entries = [self.url_result(
153             'http://www.tudou.com/programs/view/%s' % item['icode'],
154             'Tudou', item['icode'],
155             item['kw']) for item in playlist_data['items']]
156         return self.playlist_result(entries, playlist_id)
157
158
159 class TudouAlbumIE(InfoExtractor):
160     IE_NAME = 'tudou:album'
161     _VALID_URL = r'https?://(?:www\.)?tudou\.com/album(?:cover|play)/(?P<id>[\w-]{11})'
162     _TESTS = [{
163         'url': 'http://www.tudou.com/albumplay/v5qckFJvNJg.html',
164         'info_dict': {
165             'id': 'v5qckFJvNJg',
166         },
167         'playlist_mincount': 45,
168     }]
169
170     def _real_extract(self, url):
171         album_id = self._match_id(url)
172         album_data = self._download_json(
173             'http://www.tudou.com/tvp/alist.action?acode=%s' % album_id, album_id)
174         entries = [self.url_result(
175             'http://www.tudou.com/programs/view/%s' % item['icode'],
176             'Tudou', item['icode'],
177             item['kw']) for item in album_data['items']]
178         return self.playlist_result(entries, album_id)