Merge remote-tracking branch 'rzhxeo/crunchyroll'
[youtube-dl] / youtube_dl / extractor / sina.py
1 # coding: utf-8
2
3 import re
4
5 from .common import InfoExtractor
6 from ..utils import (
7     compat_urllib_request,
8     compat_urllib_parse,
9 )
10
11
12 class SinaIE(InfoExtractor):
13     _VALID_URL = r'''https?://(.*?\.)?video\.sina\.com\.cn/
14                         (
15                             (.+?/(((?P<pseudo_id>\d+).html)|(.*?(\#|(vid=))(?P<id>\d+?)($|&))))
16                             |
17                             # This is used by external sites like Weibo
18                             (api/sinawebApi/outplay.php/(?P<token>.+?)\.swf)
19                         )
20                   '''
21
22     _TEST = {
23         u'url': u'http://video.sina.com.cn/news/vlist/zt/chczlj2013/?opsubject_id=top12#110028898',
24         u'file': u'110028898.flv',
25         u'md5': u'd65dd22ddcf44e38ce2bf58a10c3e71f',
26         u'info_dict': {
27             u'title': u'《中国新闻》 朝鲜要求巴拿马立即释放被扣船员',
28         }
29     }
30
31     @classmethod
32     def suitable(cls, url):
33         return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
34
35     def _extract_video(self, video_id):
36         data = compat_urllib_parse.urlencode({'vid': video_id})
37         url_doc = self._download_xml('http://v.iask.com/v_play.php?%s' % data,
38             video_id, u'Downloading video url')
39         image_page = self._download_webpage(
40             'http://interface.video.sina.com.cn/interface/common/getVideoImage.php?%s' % data,
41             video_id, u'Downloading thumbnail info')
42
43         return {'id': video_id,
44                 'url': url_doc.find('./durl/url').text,
45                 'ext': 'flv',
46                 'title': url_doc.find('./vname').text,
47                 'thumbnail': image_page.split('=')[1],
48                 }
49
50     def _real_extract(self, url):
51         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
52         video_id = mobj.group('id')
53         if mobj.group('token') is not None:
54             # The video id is in the redirected url
55             self.to_screen(u'Getting video id')
56             request = compat_urllib_request.Request(url)
57             request.get_method = lambda: 'HEAD'
58             (_, urlh) = self._download_webpage_handle(request, 'NA', False)
59             return self._real_extract(urlh.geturl())
60         elif video_id is None:
61             pseudo_id = mobj.group('pseudo_id')
62             webpage = self._download_webpage(url, pseudo_id)
63             video_id = self._search_regex(r'vid:\'(\d+?)\'', webpage, u'video id')
64
65         return self._extract_video(video_id)