[TEDIE] Add support for embeded TED video URLs
[youtube-dl] / youtube_dl / extractor / ted.py
1 from __future__ import unicode_literals
2
3 import json
4 import re
5
6 from .subtitles import SubtitlesInfoExtractor
7
8 from ..utils import (
9     compat_str,
10 )
11
12
13 class TEDIE(SubtitlesInfoExtractor):
14     _VALID_URL = r'''(?x)http://(?P<type>www|embed)\.ted\.com/
15         (
16             (?P<type_playlist>playlists(?:/\d+)?) # We have a playlist
17             |
18             ((?P<type_talk>talks)) # We have a simple talk
19         )
20         (/lang/(.*?))? # The url may contain the language
21         /(?P<name>\w+) # Here goes the name and then ".html"
22         '''
23     _TEST = {
24         'url': 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html',
25         'md5': '4ea1dada91e4174b53dac2bb8ace429d',
26         'info_dict': {
27             'id': '102',
28             'ext': 'mp4',
29             'title': 'The illusion of consciousness',
30             'description': ('Philosopher Dan Dennett makes a compelling '
31                 'argument that not only don\'t we understand our own '
32                 'consciousness, but that half the time our brains are '
33                 'actively fooling us.'),
34             'uploader': 'Dan Dennett',
35         }
36     }
37
38     _FORMATS_PREFERENCE = {
39         'low': 1,
40         'medium': 2,
41         'high': 3,
42     }
43
44     def _extract_info(self, webpage):
45         info_json = self._search_regex(r'q\("\w+.init",({.+})\)</script>',
46             webpage, 'info json')
47         return json.loads(info_json)
48
49     def _real_extract(self, url):
50         m = re.match(self._VALID_URL, url, re.VERBOSE)
51         if m.group('type') == 'embed': # if the _VALID_URL is an embed 
52             desktop_url = re.sub("embed", "www", url) 
53             return self.url_result(desktop_url, 'TED') # pass the desktop version to the extractor
54         name = m.group('name')
55         if m.group('type_talk'):
56             return self._talk_info(url, name)
57         else:
58             return self._playlist_videos_info(url, name)
59
60     def _playlist_videos_info(self, url, name):
61         '''Returns the videos of the playlist'''
62
63         webpage = self._download_webpage(url, name,
64             'Downloading playlist webpage')
65         info = self._extract_info(webpage)
66         playlist_info = info['playlist']
67
68         playlist_entries = [
69             self.url_result(u'http://www.ted.com/talks/' + talk['slug'], self.ie_key())
70             for talk in info['talks']
71         ]
72         return self.playlist_result(
73             playlist_entries,
74             playlist_id=compat_str(playlist_info['id']),
75             playlist_title=playlist_info['title'])
76
77     def _talk_info(self, url, video_name):
78         webpage = self._download_webpage(url, video_name)
79         self.report_extraction(video_name)
80
81         talk_info = self._extract_info(webpage)['talks'][0]
82
83         formats = [{
84             'ext': 'mp4',
85             'url': format_url,
86             'format_id': format_id,
87             'format': format_id,
88             'preference': self._FORMATS_PREFERENCE.get(format_id, -1),
89         } for (format_id, format_url) in talk_info['nativeDownloads'].items()]
90         self._sort_formats(formats)
91
92         video_id = compat_str(talk_info['id'])
93         # subtitles
94         video_subtitles = self.extract_subtitles(video_id, talk_info)
95         if self._downloader.params.get('listsubtitles', False):
96             self._list_available_subtitles(video_id, talk_info)
97             return
98
99         thumbnail = talk_info['thumb']
100         if not thumbnail.startswith('http'):
101             thumbnail = 'http://' + thumbnail
102         return {
103             'id': video_id,
104             'title': talk_info['title'],
105             'uploader': talk_info['speaker'],
106             'thumbnail': thumbnail,
107             'description': self._og_search_description(webpage),
108             'subtitles': video_subtitles,
109             'formats': formats,
110         }
111
112     def _get_available_subtitles(self, video_id, talk_info):
113         languages = [lang['languageCode'] for lang in talk_info.get('languages', [])]
114         if languages:
115             sub_lang_list = {}
116             for l in languages:
117                 url = 'http://www.ted.com/talks/subtitles/id/%s/lang/%s/format/srt' % (video_id, l)
118                 sub_lang_list[l] = url
119             return sub_lang_list
120         else:
121             self._downloader.report_warning(u'video doesn\'t have subtitles')
122             return {}