[udn] Add new extractor
[youtube-dl] / youtube_dl / extractor / udn.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 from .common import InfoExtractor
6 from ..utils import (
7     url_infer_protocol,
8     js_to_json
9 )
10
11
12 class UDNEmbedIE(InfoExtractor):
13     _VALID_URL = r'(?:https?:)?//video\.udn\.com/embed/news/(?P<id>\d+)'
14     _TESTS = [{
15         'url': 'http://video.udn.com/embed/news/300040',
16         'md5': 'de06b4c90b042c128395a88f0384817e',
17         'info_dict': {
18             'id': '300040',
19             'ext': 'mp4',
20             'title': '生物老師男變女 全校挺"做自己"',
21             'thumbnail': 're:^https?://.*\.jpg$',
22         }
23     }, {
24         'url': '//video.udn.com/embed/news/300040',
25         'only_matching': True,
26     }]
27
28     def _real_extract(self, url):
29         video_id = self._match_id(url)
30
31         page = self._download_webpage(url, video_id)
32
33         options = json.loads(js_to_json(self._html_search_regex(
34             r'var options\s*=\s*([^;]+);', page, 'video urls dictionary')))
35
36         video_urls = options['video']
37
38         if video_urls.get('youtube'):
39             return self.url_result(video_urls.get('youtube'), 'Youtube')
40
41         try:
42             del video_urls['youtube']
43         except KeyError:
44             pass
45
46         formats = [{
47             'url': self._download_webpage(
48                 url_infer_protocol(url, api_url), video_id,
49                 'retrieve url for %s video' % video_type),
50             'format_id': video_type,
51             'preference': 0 if video_type == 'mp4' else -1,
52         } for video_type, api_url in video_urls.items()]
53
54         self._sort_formats(formats)
55
56         thumbnail = None
57
58         if options.get('gallery') and len(options['gallery']):
59             thumbnail = options['gallery'][0].get('original')
60
61         return {
62             'id': video_id,
63             'formats': formats,
64             'title': options['title'],
65             'thumbnail': thumbnail
66         }