You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

363 lines
13 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. from __future__ import unicode_literals
  2. import json
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_str,
  7. compat_urlparse
  8. )
  9. from ..utils import (
  10. extract_attributes,
  11. float_or_none,
  12. int_or_none,
  13. try_get,
  14. url_or_none,
  15. )
  16. class TEDIE(InfoExtractor):
  17. IE_NAME = 'ted'
  18. _VALID_URL = r'''(?x)
  19. (?P<proto>https?://)
  20. (?P<type>www|embed(?:-ssl)?)(?P<urlmain>\.ted\.com/
  21. (
  22. (?P<type_playlist>playlists(?:/(?P<playlist_id>\d+))?) # We have a playlist
  23. |
  24. ((?P<type_talk>talks)) # We have a simple talk
  25. |
  26. (?P<type_watch>watch)/[^/]+/[^/]+
  27. )
  28. (/lang/(.*?))? # The url may contain the language
  29. /(?P<name>[\w-]+) # Here goes the name and then ".html"
  30. .*)$
  31. '''
  32. _TESTS = [{
  33. 'url': 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html',
  34. 'md5': 'b0ce2b05ca215042124fbc9e3886493a',
  35. 'info_dict': {
  36. 'id': '102',
  37. 'ext': 'mp4',
  38. 'title': 'The illusion of consciousness',
  39. 'description': ('Philosopher Dan Dennett makes a compelling '
  40. 'argument that not only don\'t we understand our own '
  41. 'consciousness, but that half the time our brains are '
  42. 'actively fooling us.'),
  43. 'uploader': 'Dan Dennett',
  44. 'width': 853,
  45. 'duration': 1308,
  46. 'view_count': int,
  47. 'comment_count': int,
  48. 'tags': list,
  49. },
  50. 'params': {
  51. 'skip_download': True,
  52. },
  53. }, {
  54. # missing HTTP bitrates
  55. 'url': 'https://www.ted.com/talks/vishal_sikka_the_beauty_and_power_of_algorithms',
  56. 'info_dict': {
  57. 'id': '6069',
  58. 'ext': 'mp4',
  59. 'title': 'The beauty and power of algorithms',
  60. 'thumbnail': r're:^https?://.+\.jpg',
  61. 'description': 'md5:734e352710fb00d840ab87ae31aaf688',
  62. 'uploader': 'Vishal Sikka',
  63. },
  64. 'params': {
  65. 'skip_download': True,
  66. },
  67. }, {
  68. 'url': 'http://www.ted.com/talks/gabby_giffords_and_mark_kelly_be_passionate_be_courageous_be_your_best',
  69. 'md5': 'e6b9617c01a7970ceac8bb2c92c346c0',
  70. 'info_dict': {
  71. 'id': '1972',
  72. 'ext': 'mp4',
  73. 'title': 'Be passionate. Be courageous. Be your best.',
  74. 'uploader': 'Gabby Giffords and Mark Kelly',
  75. 'description': 'md5:5174aed4d0f16021b704120360f72b92',
  76. 'duration': 1128,
  77. },
  78. 'params': {
  79. 'skip_download': True,
  80. },
  81. }, {
  82. 'url': 'http://www.ted.com/playlists/who_are_the_hackers',
  83. 'info_dict': {
  84. 'id': '10',
  85. 'title': 'Who are the hackers?',
  86. 'description': 'md5:49a0dbe8fb76d81a0e64b4a80af7f15a'
  87. },
  88. 'playlist_mincount': 6,
  89. }, {
  90. # contains a youtube video
  91. 'url': 'https://www.ted.com/talks/douglas_adams_parrots_the_universe_and_everything',
  92. 'add_ie': ['Youtube'],
  93. 'info_dict': {
  94. 'id': '_ZG8HBuDjgc',
  95. 'ext': 'webm',
  96. 'title': 'Douglas Adams: Parrots the Universe and Everything',
  97. 'description': 'md5:01ad1e199c49ac640cb1196c0e9016af',
  98. 'uploader': 'University of California Television (UCTV)',
  99. 'uploader_id': 'UCtelevision',
  100. 'upload_date': '20080522',
  101. },
  102. 'params': {
  103. 'skip_download': True,
  104. },
  105. }, {
  106. # no nativeDownloads
  107. 'url': 'https://www.ted.com/talks/tom_thum_the_orchestra_in_my_mouth',
  108. 'info_dict': {
  109. 'id': '1792',
  110. 'ext': 'mp4',
  111. 'title': 'The orchestra in my mouth',
  112. 'description': 'md5:5d1d78650e2f8dfcbb8ebee2951ac29a',
  113. 'uploader': 'Tom Thum',
  114. 'view_count': int,
  115. 'comment_count': int,
  116. 'tags': list,
  117. },
  118. 'params': {
  119. 'skip_download': True,
  120. },
  121. }]
  122. _NATIVE_FORMATS = {
  123. 'low': {'width': 320, 'height': 180},
  124. 'medium': {'width': 512, 'height': 288},
  125. 'high': {'width': 854, 'height': 480},
  126. }
  127. def _extract_info(self, webpage):
  128. info_json = self._search_regex(
  129. r'(?s)q\(\s*"\w+.init"\s*,\s*({.+?})\)\s*</script>',
  130. webpage, 'info json')
  131. return json.loads(info_json)
  132. def _real_extract(self, url):
  133. m = re.match(self._VALID_URL, url, re.VERBOSE)
  134. if m.group('type').startswith('embed'):
  135. desktop_url = m.group('proto') + 'www' + m.group('urlmain')
  136. return self.url_result(desktop_url, 'TED')
  137. name = m.group('name')
  138. if m.group('type_talk'):
  139. return self._talk_info(url, name)
  140. elif m.group('type_watch'):
  141. return self._watch_info(url, name)
  142. else:
  143. return self._playlist_videos_info(url, name)
  144. def _playlist_videos_info(self, url, name):
  145. '''Returns the videos of the playlist'''
  146. webpage = self._download_webpage(url, name,
  147. 'Downloading playlist webpage')
  148. playlist_entries = []
  149. for entry in re.findall(r'(?s)<[^>]+data-ga-context=["\']playlist["\'][^>]*>', webpage):
  150. attrs = extract_attributes(entry)
  151. entry_url = compat_urlparse.urljoin(url, attrs['href'])
  152. playlist_entries.append(self.url_result(entry_url, self.ie_key()))
  153. final_url = self._og_search_url(webpage, fatal=False)
  154. playlist_id = (
  155. re.match(self._VALID_URL, final_url).group('playlist_id')
  156. if final_url else None)
  157. return self.playlist_result(
  158. playlist_entries, playlist_id=playlist_id,
  159. playlist_title=self._og_search_title(webpage, fatal=False),
  160. playlist_description=self._og_search_description(webpage))
  161. def _talk_info(self, url, video_name):
  162. webpage = self._download_webpage(url, video_name)
  163. info = self._extract_info(webpage)
  164. data = try_get(info, lambda x: x['__INITIAL_DATA__'], dict) or info
  165. talk_info = data['talks'][0]
  166. title = talk_info['title'].strip()
  167. downloads = talk_info.get('downloads') or {}
  168. native_downloads = downloads.get('nativeDownloads') or talk_info.get('nativeDownloads') or {}
  169. formats = [{
  170. 'url': format_url,
  171. 'format_id': format_id,
  172. } for (format_id, format_url) in native_downloads.items() if format_url is not None]
  173. subtitled_downloads = downloads.get('subtitledDownloads') or {}
  174. for lang, subtitled_download in subtitled_downloads.items():
  175. for q in self._NATIVE_FORMATS:
  176. q_url = subtitled_download.get(q)
  177. if not q_url:
  178. continue
  179. formats.append({
  180. 'url': q_url,
  181. 'format_id': '%s-%s' % (q, lang),
  182. 'language': lang,
  183. })
  184. if formats:
  185. for f in formats:
  186. finfo = self._NATIVE_FORMATS.get(f['format_id'].split('-')[0])
  187. if finfo:
  188. f.update(finfo)
  189. player_talk = talk_info['player_talks'][0]
  190. external = player_talk.get('external')
  191. if isinstance(external, dict):
  192. service = external.get('service')
  193. if isinstance(service, compat_str):
  194. ext_url = None
  195. if service.lower() == 'youtube':
  196. ext_url = external.get('code')
  197. return self.url_result(ext_url or external['uri'])
  198. resources_ = player_talk.get('resources') or talk_info.get('resources')
  199. http_url = None
  200. for format_id, resources in resources_.items():
  201. if format_id == 'hls':
  202. if not isinstance(resources, dict):
  203. continue
  204. stream_url = url_or_none(resources.get('stream'))
  205. if not stream_url:
  206. continue
  207. formats.extend(self._extract_m3u8_formats(
  208. stream_url, video_name, 'mp4', m3u8_id=format_id,
  209. fatal=False))
  210. else:
  211. if not isinstance(resources, list):
  212. continue
  213. if format_id == 'h264':
  214. for resource in resources:
  215. h264_url = resource.get('file')
  216. if not h264_url:
  217. continue
  218. bitrate = int_or_none(resource.get('bitrate'))
  219. formats.append({
  220. 'url': h264_url,
  221. 'format_id': '%s-%sk' % (format_id, bitrate),
  222. 'tbr': bitrate,
  223. })
  224. if re.search(r'\d+k', h264_url):
  225. http_url = h264_url
  226. elif format_id == 'rtmp':
  227. streamer = talk_info.get('streamer')
  228. if not streamer:
  229. continue
  230. for resource in resources:
  231. formats.append({
  232. 'format_id': '%s-%s' % (format_id, resource.get('name')),
  233. 'url': streamer,
  234. 'play_path': resource['file'],
  235. 'ext': 'flv',
  236. 'width': int_or_none(resource.get('width')),
  237. 'height': int_or_none(resource.get('height')),
  238. 'tbr': int_or_none(resource.get('bitrate')),
  239. })
  240. m3u8_formats = list(filter(
  241. lambda f: f.get('protocol') == 'm3u8' and f.get('vcodec') != 'none',
  242. formats))
  243. if http_url:
  244. for m3u8_format in m3u8_formats:
  245. bitrate = self._search_regex(r'(\d+k)', m3u8_format['url'], 'bitrate', default=None)
  246. if not bitrate:
  247. continue
  248. bitrate_url = re.sub(r'\d+k', bitrate, http_url)
  249. if not self._is_valid_url(
  250. bitrate_url, video_name, '%s bitrate' % bitrate):
  251. continue
  252. f = m3u8_format.copy()
  253. f.update({
  254. 'url': bitrate_url,
  255. 'format_id': m3u8_format['format_id'].replace('hls', 'http'),
  256. 'protocol': 'http',
  257. })
  258. if f.get('acodec') == 'none':
  259. del f['acodec']
  260. formats.append(f)
  261. audio_download = talk_info.get('audioDownload')
  262. if audio_download:
  263. formats.append({
  264. 'url': audio_download,
  265. 'format_id': 'audio',
  266. 'vcodec': 'none',
  267. })
  268. self._sort_formats(formats)
  269. video_id = compat_str(talk_info['id'])
  270. return {
  271. 'id': video_id,
  272. 'title': title,
  273. 'uploader': player_talk.get('speaker') or talk_info.get('speaker'),
  274. 'thumbnail': player_talk.get('thumb') or talk_info.get('thumb'),
  275. 'description': self._og_search_description(webpage),
  276. 'subtitles': self._get_subtitles(video_id, talk_info),
  277. 'formats': formats,
  278. 'duration': float_or_none(talk_info.get('duration')),
  279. 'view_count': int_or_none(data.get('viewed_count')),
  280. 'comment_count': int_or_none(
  281. try_get(data, lambda x: x['comments']['count'])),
  282. 'tags': try_get(talk_info, lambda x: x['tags'], list),
  283. }
  284. def _get_subtitles(self, video_id, talk_info):
  285. sub_lang_list = {}
  286. for language in try_get(
  287. talk_info,
  288. (lambda x: x['downloads']['languages'],
  289. lambda x: x['languages']), list):
  290. lang_code = language.get('languageCode') or language.get('ianaCode')
  291. if not lang_code:
  292. continue
  293. sub_lang_list[lang_code] = [
  294. {
  295. 'url': 'http://www.ted.com/talks/subtitles/id/%s/lang/%s/format/%s' % (video_id, lang_code, ext),
  296. 'ext': ext,
  297. }
  298. for ext in ['ted', 'srt']
  299. ]
  300. return sub_lang_list
  301. def _watch_info(self, url, name):
  302. webpage = self._download_webpage(url, name)
  303. config_json = self._html_search_regex(
  304. r'"pages\.jwplayer"\s*,\s*({.+?})\s*\)\s*</script>',
  305. webpage, 'config', default=None)
  306. if not config_json:
  307. embed_url = self._search_regex(
  308. r"<iframe[^>]+class='pages-video-embed__video__object'[^>]+src='([^']+)'", webpage, 'embed url')
  309. return self.url_result(self._proto_relative_url(embed_url))
  310. config = json.loads(config_json)['config']
  311. video_url = config['video']['url']
  312. thumbnail = config.get('image', {}).get('url')
  313. title = self._html_search_regex(
  314. r"(?s)<h1(?:\s+class='[^']+')?>(.+?)</h1>", webpage, 'title')
  315. description = self._html_search_regex(
  316. [
  317. r'(?s)<h4 class="[^"]+" id="h3--about-this-talk">.*?</h4>(.*?)</div>',
  318. r'(?s)<p><strong>About this talk:</strong>\s+(.*?)</p>',
  319. ],
  320. webpage, 'description', fatal=False)
  321. return {
  322. 'id': name,
  323. 'url': video_url,
  324. 'title': title,
  325. 'thumbnail': thumbnail,
  326. 'description': description,
  327. }