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.

4216 lines
168 KiB

13 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
13 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import base64
  5. import datetime
  6. import itertools
  7. import netrc
  8. import os
  9. import re
  10. import socket
  11. import time
  12. import email.utils
  13. import xml.etree.ElementTree
  14. import random
  15. import math
  16. import operator
  17. from .utils import *
  18. class InfoExtractor(object):
  19. """Information Extractor class.
  20. Information extractors are the classes that, given a URL, extract
  21. information about the video (or videos) the URL refers to. This
  22. information includes the real video URL, the video title, author and
  23. others. The information is stored in a dictionary which is then
  24. passed to the FileDownloader. The FileDownloader processes this
  25. information possibly downloading the video to the file system, among
  26. other possible outcomes.
  27. The dictionaries must include the following fields:
  28. id: Video identifier.
  29. url: Final video URL.
  30. title: Video title, unescaped.
  31. ext: Video filename extension.
  32. The following fields are optional:
  33. format: The video format, defaults to ext (used for --get-format)
  34. thumbnail: Full URL to a video thumbnail image.
  35. description: One-line video description.
  36. uploader: Full name of the video uploader.
  37. upload_date: Video upload date (YYYYMMDD).
  38. uploader_id: Nickname or id of the video uploader.
  39. location: Physical location of the video.
  40. player_url: SWF Player URL (used for rtmpdump).
  41. subtitles: The subtitle file contents.
  42. urlhandle: [internal] The urlHandle to be used to download the file,
  43. like returned by urllib.request.urlopen
  44. The fields should all be Unicode strings.
  45. Subclasses of this one should re-define the _real_initialize() and
  46. _real_extract() methods and define a _VALID_URL regexp.
  47. Probably, they should also be added to the list of extractors.
  48. _real_extract() must return a *list* of information dictionaries as
  49. described above.
  50. Finally, the _WORKING attribute should be set to False for broken IEs
  51. in order to warn the users and skip the tests.
  52. """
  53. _ready = False
  54. _downloader = None
  55. _WORKING = True
  56. def __init__(self, downloader=None):
  57. """Constructor. Receives an optional downloader."""
  58. self._ready = False
  59. self.set_downloader(downloader)
  60. @classmethod
  61. def suitable(cls, url):
  62. """Receives a URL and returns True if suitable for this IE."""
  63. return re.match(cls._VALID_URL, url) is not None
  64. @classmethod
  65. def working(cls):
  66. """Getter method for _WORKING."""
  67. return cls._WORKING
  68. def initialize(self):
  69. """Initializes an instance (authentication, etc)."""
  70. if not self._ready:
  71. self._real_initialize()
  72. self._ready = True
  73. def extract(self, url):
  74. """Extracts URL information and returns it in list of dicts."""
  75. self.initialize()
  76. return self._real_extract(url)
  77. def set_downloader(self, downloader):
  78. """Sets the downloader for this IE."""
  79. self._downloader = downloader
  80. def _real_initialize(self):
  81. """Real initialization process. Redefine in subclasses."""
  82. pass
  83. def _real_extract(self, url):
  84. """Real extraction process. Redefine in subclasses."""
  85. pass
  86. @property
  87. def IE_NAME(self):
  88. return type(self).__name__[:-2]
  89. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None):
  90. """ Returns the response handle """
  91. if note is None:
  92. note = u'Downloading video webpage'
  93. self._downloader.to_screen(u'[%s] %s: %s' % (self.IE_NAME, video_id, note))
  94. try:
  95. return compat_urllib_request.urlopen(url_or_request)
  96. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  97. if errnote is None:
  98. errnote = u'Unable to download webpage'
  99. raise ExtractorError(u'%s: %s' % (errnote, compat_str(err)), sys.exc_info()[2])
  100. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None):
  101. """ Returns the data of the page as a string """
  102. urlh = self._request_webpage(url_or_request, video_id, note, errnote)
  103. content_type = urlh.headers.get('Content-Type', '')
  104. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  105. if m:
  106. encoding = m.group(1)
  107. else:
  108. encoding = 'utf-8'
  109. webpage_bytes = urlh.read()
  110. return webpage_bytes.decode(encoding, 'replace')
  111. class YoutubeIE(InfoExtractor):
  112. """Information extractor for youtube.com."""
  113. _VALID_URL = r"""^
  114. (
  115. (?:https?://)? # http(s):// (optional)
  116. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  117. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  118. (?:.*?\#/)? # handle anchor (#/) redirect urls
  119. (?: # the various things that can precede the ID:
  120. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  121. |(?: # or the v= param in all its forms
  122. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  123. (?:\?|\#!?) # the params delimiter ? or # or #!
  124. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  125. v=
  126. )
  127. )? # optional -> youtube.com/xxxx is OK
  128. )? # all until now is optional -> you can pass the naked ID
  129. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  130. (?(1).+)? # if we found the ID, everything can follow
  131. $"""
  132. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  133. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  134. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  135. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  136. _NETRC_MACHINE = 'youtube'
  137. # Listed in order of quality
  138. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  139. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  140. _video_extensions = {
  141. '13': '3gp',
  142. '17': 'mp4',
  143. '18': 'mp4',
  144. '22': 'mp4',
  145. '37': 'mp4',
  146. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  147. '43': 'webm',
  148. '44': 'webm',
  149. '45': 'webm',
  150. '46': 'webm',
  151. }
  152. _video_dimensions = {
  153. '5': '240x400',
  154. '6': '???',
  155. '13': '???',
  156. '17': '144x176',
  157. '18': '360x640',
  158. '22': '720x1280',
  159. '34': '360x640',
  160. '35': '480x854',
  161. '37': '1080x1920',
  162. '38': '3072x4096',
  163. '43': '360x640',
  164. '44': '480x854',
  165. '45': '720x1280',
  166. '46': '1080x1920',
  167. }
  168. IE_NAME = u'youtube'
  169. @classmethod
  170. def suitable(cls, url):
  171. """Receives a URL and returns True if suitable for this IE."""
  172. if YoutubePlaylistIE.suitable(url): return False
  173. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  174. def report_lang(self):
  175. """Report attempt to set language."""
  176. self._downloader.to_screen(u'[youtube] Setting language')
  177. def report_login(self):
  178. """Report attempt to log in."""
  179. self._downloader.to_screen(u'[youtube] Logging in')
  180. def report_age_confirmation(self):
  181. """Report attempt to confirm age."""
  182. self._downloader.to_screen(u'[youtube] Confirming age')
  183. def report_video_webpage_download(self, video_id):
  184. """Report attempt to download video webpage."""
  185. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  186. def report_video_info_webpage_download(self, video_id):
  187. """Report attempt to download video info webpage."""
  188. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  189. def report_video_subtitles_download(self, video_id):
  190. """Report attempt to download video info webpage."""
  191. self._downloader.to_screen(u'[youtube] %s: Checking available subtitles' % video_id)
  192. def report_video_subtitles_request(self, video_id, sub_lang, format):
  193. """Report attempt to download video info webpage."""
  194. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
  195. def report_video_subtitles_available(self, video_id, sub_lang_list):
  196. """Report available subtitles."""
  197. sub_lang = ",".join(list(sub_lang_list.keys()))
  198. self._downloader.to_screen(u'[youtube] %s: Available subtitles for video: %s' % (video_id, sub_lang))
  199. def report_information_extraction(self, video_id):
  200. """Report attempt to extract video information."""
  201. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  202. def report_unavailable_format(self, video_id, format):
  203. """Report extracted video URL."""
  204. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  205. def report_rtmp_download(self):
  206. """Indicate the download will use the RTMP protocol."""
  207. self._downloader.to_screen(u'[youtube] RTMP download detected')
  208. def _get_available_subtitles(self, video_id):
  209. self.report_video_subtitles_download(video_id)
  210. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  211. try:
  212. sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  213. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  214. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  215. sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  216. sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
  217. if not sub_lang_list:
  218. return (u'WARNING: video doesn\'t have subtitles', None)
  219. return sub_lang_list
  220. def _list_available_subtitles(self, video_id):
  221. sub_lang_list = self._get_available_subtitles(video_id)
  222. self.report_video_subtitles_available(video_id, sub_lang_list)
  223. def _request_subtitle(self, sub_lang, sub_name, video_id, format):
  224. self.report_video_subtitles_request(video_id, sub_lang, format)
  225. params = compat_urllib_parse.urlencode({
  226. 'lang': sub_lang,
  227. 'name': sub_name,
  228. 'v': video_id,
  229. 'fmt': format,
  230. })
  231. url = 'http://www.youtube.com/api/timedtext?' + params
  232. try:
  233. sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
  234. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  235. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  236. if not sub:
  237. return (u'WARNING: Did not fetch video subtitles', None)
  238. return (None, sub_lang, sub)
  239. def _extract_subtitle(self, video_id):
  240. sub_lang_list = self._get_available_subtitles(video_id)
  241. sub_format = self._downloader.params.get('subtitlesformat')
  242. if self._downloader.params.get('subtitleslang', False):
  243. sub_lang = self._downloader.params.get('subtitleslang')
  244. elif 'en' in sub_lang_list:
  245. sub_lang = 'en'
  246. else:
  247. sub_lang = list(sub_lang_list.keys())[0]
  248. if not sub_lang in sub_lang_list:
  249. return (u'WARNING: no closed captions found in the specified language "%s"' % sub_lang, None)
  250. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  251. return [subtitle]
  252. def _extract_all_subtitles(self, video_id):
  253. sub_lang_list = self._get_available_subtitles(video_id)
  254. sub_format = self._downloader.params.get('subtitlesformat')
  255. subtitles = []
  256. for sub_lang in sub_lang_list:
  257. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  258. subtitles.append(subtitle)
  259. return subtitles
  260. def _print_formats(self, formats):
  261. print('Available formats:')
  262. for x in formats:
  263. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  264. def _real_initialize(self):
  265. if self._downloader is None:
  266. return
  267. username = None
  268. password = None
  269. downloader_params = self._downloader.params
  270. # Attempt to use provided username and password or .netrc data
  271. if downloader_params.get('username', None) is not None:
  272. username = downloader_params['username']
  273. password = downloader_params['password']
  274. elif downloader_params.get('usenetrc', False):
  275. try:
  276. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  277. if info is not None:
  278. username = info[0]
  279. password = info[2]
  280. else:
  281. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  282. except (IOError, netrc.NetrcParseError) as err:
  283. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  284. return
  285. # Set language
  286. request = compat_urllib_request.Request(self._LANG_URL)
  287. try:
  288. self.report_lang()
  289. compat_urllib_request.urlopen(request).read()
  290. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  291. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  292. return
  293. # No authentication to be performed
  294. if username is None:
  295. return
  296. request = compat_urllib_request.Request(self._LOGIN_URL)
  297. try:
  298. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  299. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  300. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  301. return
  302. galx = None
  303. dsh = None
  304. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  305. if match:
  306. galx = match.group(1)
  307. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  308. if match:
  309. dsh = match.group(1)
  310. # Log in
  311. login_form_strs = {
  312. u'continue': u'http://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  313. u'Email': username,
  314. u'GALX': galx,
  315. u'Passwd': password,
  316. u'PersistentCookie': u'yes',
  317. u'_utf8': u'',
  318. u'bgresponse': u'js_disabled',
  319. u'checkConnection': u'',
  320. u'checkedDomains': u'youtube',
  321. u'dnConn': u'',
  322. u'dsh': dsh,
  323. u'pstMsg': u'0',
  324. u'rmShown': u'1',
  325. u'secTok': u'',
  326. u'signIn': u'Sign in',
  327. u'timeStmp': u'',
  328. u'service': u'youtube',
  329. u'uilel': u'3',
  330. u'hl': u'en_US',
  331. }
  332. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  333. # chokes on unicode
  334. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  335. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  336. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  337. try:
  338. self.report_login()
  339. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  340. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  341. self._downloader.report_warning(u'unable to log in: bad username or password')
  342. return
  343. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  344. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  345. return
  346. # Confirm age
  347. age_form = {
  348. 'next_url': '/',
  349. 'action_confirm': 'Confirm',
  350. }
  351. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  352. try:
  353. self.report_age_confirmation()
  354. age_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  355. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  356. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  357. return
  358. def _extract_id(self, url):
  359. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  360. if mobj is None:
  361. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  362. return
  363. video_id = mobj.group(2)
  364. return video_id
  365. def _real_extract(self, url):
  366. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  367. mobj = re.search(self._NEXT_URL_RE, url)
  368. if mobj:
  369. url = 'http://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  370. video_id = self._extract_id(url)
  371. # Get video webpage
  372. self.report_video_webpage_download(video_id)
  373. url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  374. request = compat_urllib_request.Request(url)
  375. try:
  376. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  377. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  378. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  379. return
  380. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  381. # Attempt to extract SWF player URL
  382. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  383. if mobj is not None:
  384. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  385. else:
  386. player_url = None
  387. # Get video info
  388. self.report_video_info_webpage_download(video_id)
  389. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  390. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  391. % (video_id, el_type))
  392. request = compat_urllib_request.Request(video_info_url)
  393. try:
  394. video_info_webpage_bytes = compat_urllib_request.urlopen(request).read()
  395. video_info_webpage = video_info_webpage_bytes.decode('utf-8', 'ignore')
  396. video_info = compat_parse_qs(video_info_webpage)
  397. if 'token' in video_info:
  398. break
  399. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  400. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  401. return
  402. if 'token' not in video_info:
  403. if 'reason' in video_info:
  404. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0])
  405. else:
  406. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  407. return
  408. # Check for "rental" videos
  409. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  410. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  411. return
  412. # Start extracting information
  413. self.report_information_extraction(video_id)
  414. # uploader
  415. if 'author' not in video_info:
  416. self._downloader.trouble(u'ERROR: unable to extract uploader name')
  417. return
  418. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  419. # uploader_id
  420. video_uploader_id = None
  421. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  422. if mobj is not None:
  423. video_uploader_id = mobj.group(1)
  424. else:
  425. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  426. # title
  427. if 'title' not in video_info:
  428. self._downloader.trouble(u'ERROR: unable to extract video title')
  429. return
  430. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  431. # thumbnail image
  432. if 'thumbnail_url' not in video_info:
  433. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  434. video_thumbnail = ''
  435. else: # don't panic if we can't find it
  436. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  437. # upload date
  438. upload_date = None
  439. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  440. if mobj is not None:
  441. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  442. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  443. for expression in format_expressions:
  444. try:
  445. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  446. except:
  447. pass
  448. # description
  449. video_description = get_element_by_id("eow-description", video_webpage)
  450. if video_description:
  451. video_description = clean_html(video_description)
  452. else:
  453. video_description = ''
  454. # subtitles
  455. video_subtitles = None
  456. if self._downloader.params.get('writesubtitles', False):
  457. video_subtitles = self._extract_subtitle(video_id)
  458. if video_subtitles:
  459. (sub_error, sub_lang, sub) = video_subtitles[0]
  460. if sub_error:
  461. self._downloader.trouble(sub_error)
  462. if self._downloader.params.get('allsubtitles', False):
  463. video_subtitles = self._extract_all_subtitles(video_id)
  464. for video_subtitle in video_subtitles:
  465. (sub_error, sub_lang, sub) = video_subtitle
  466. if sub_error:
  467. self._downloader.trouble(sub_error)
  468. if self._downloader.params.get('listsubtitles', False):
  469. sub_lang_list = self._list_available_subtitles(video_id)
  470. return
  471. if 'length_seconds' not in video_info:
  472. self._downloader.trouble(u'WARNING: unable to extract video duration')
  473. video_duration = ''
  474. else:
  475. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  476. # token
  477. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  478. # Decide which formats to download
  479. req_format = self._downloader.params.get('format', None)
  480. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  481. self.report_rtmp_download()
  482. video_url_list = [(None, video_info['conn'][0])]
  483. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  484. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  485. url_data = [compat_parse_qs(uds) for uds in url_data_strs]
  486. url_data = [ud for ud in url_data if 'itag' in ud and 'url' in ud]
  487. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  488. format_limit = self._downloader.params.get('format_limit', None)
  489. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  490. if format_limit is not None and format_limit in available_formats:
  491. format_list = available_formats[available_formats.index(format_limit):]
  492. else:
  493. format_list = available_formats
  494. existing_formats = [x for x in format_list if x in url_map]
  495. if len(existing_formats) == 0:
  496. self._downloader.trouble(u'ERROR: no known formats available for video')
  497. return
  498. if self._downloader.params.get('listformats', None):
  499. self._print_formats(existing_formats)
  500. return
  501. if req_format is None or req_format == 'best':
  502. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  503. elif req_format == 'worst':
  504. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  505. elif req_format in ('-1', 'all'):
  506. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  507. else:
  508. # Specific formats. We pick the first in a slash-delimeted sequence.
  509. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  510. req_formats = req_format.split('/')
  511. video_url_list = None
  512. for rf in req_formats:
  513. if rf in url_map:
  514. video_url_list = [(rf, url_map[rf])]
  515. break
  516. if video_url_list is None:
  517. self._downloader.trouble(u'ERROR: requested format not available')
  518. return
  519. else:
  520. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  521. return
  522. results = []
  523. for format_param, video_real_url in video_url_list:
  524. # Extension
  525. video_extension = self._video_extensions.get(format_param, 'flv')
  526. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  527. self._video_dimensions.get(format_param, '???'))
  528. results.append({
  529. 'id': video_id,
  530. 'url': video_real_url,
  531. 'uploader': video_uploader,
  532. 'uploader_id': video_uploader_id,
  533. 'upload_date': upload_date,
  534. 'title': video_title,
  535. 'ext': video_extension,
  536. 'format': video_format,
  537. 'thumbnail': video_thumbnail,
  538. 'description': video_description,
  539. 'player_url': player_url,
  540. 'subtitles': video_subtitles,
  541. 'duration': video_duration
  542. })
  543. return results
  544. class MetacafeIE(InfoExtractor):
  545. """Information Extractor for metacafe.com."""
  546. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  547. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  548. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  549. IE_NAME = u'metacafe'
  550. def __init__(self, downloader=None):
  551. InfoExtractor.__init__(self, downloader)
  552. def report_disclaimer(self):
  553. """Report disclaimer retrieval."""
  554. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  555. def report_age_confirmation(self):
  556. """Report attempt to confirm age."""
  557. self._downloader.to_screen(u'[metacafe] Confirming age')
  558. def report_download_webpage(self, video_id):
  559. """Report webpage download."""
  560. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  561. def report_extraction(self, video_id):
  562. """Report information extraction."""
  563. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  564. def _real_initialize(self):
  565. # Retrieve disclaimer
  566. request = compat_urllib_request.Request(self._DISCLAIMER)
  567. try:
  568. self.report_disclaimer()
  569. disclaimer = compat_urllib_request.urlopen(request).read()
  570. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  571. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % compat_str(err))
  572. return
  573. # Confirm age
  574. disclaimer_form = {
  575. 'filters': '0',
  576. 'submit': "Continue - I'm over 18",
  577. }
  578. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  579. try:
  580. self.report_age_confirmation()
  581. disclaimer = compat_urllib_request.urlopen(request).read()
  582. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  583. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  584. return
  585. def _real_extract(self, url):
  586. # Extract id and simplified title from URL
  587. mobj = re.match(self._VALID_URL, url)
  588. if mobj is None:
  589. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  590. return
  591. video_id = mobj.group(1)
  592. # Check if video comes from YouTube
  593. mobj2 = re.match(r'^yt-(.*)$', video_id)
  594. if mobj2 is not None:
  595. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  596. return
  597. # Retrieve video webpage to extract further information
  598. request = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
  599. try:
  600. self.report_download_webpage(video_id)
  601. webpage = compat_urllib_request.urlopen(request).read()
  602. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  603. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  604. return
  605. # Extract URL, uploader and title from webpage
  606. self.report_extraction(video_id)
  607. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  608. if mobj is not None:
  609. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  610. video_extension = mediaURL[-3:]
  611. # Extract gdaKey if available
  612. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  613. if mobj is None:
  614. video_url = mediaURL
  615. else:
  616. gdaKey = mobj.group(1)
  617. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  618. else:
  619. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  620. if mobj is None:
  621. self._downloader.trouble(u'ERROR: unable to extract media URL')
  622. return
  623. vardict = compat_parse_qs(mobj.group(1))
  624. if 'mediaData' not in vardict:
  625. self._downloader.trouble(u'ERROR: unable to extract media URL')
  626. return
  627. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  628. if mobj is None:
  629. self._downloader.trouble(u'ERROR: unable to extract media URL')
  630. return
  631. mediaURL = mobj.group(1).replace('\\/', '/')
  632. video_extension = mediaURL[-3:]
  633. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  634. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  635. if mobj is None:
  636. self._downloader.trouble(u'ERROR: unable to extract title')
  637. return
  638. video_title = mobj.group(1).decode('utf-8')
  639. mobj = re.search(r'submitter=(.*?);', webpage)
  640. if mobj is None:
  641. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  642. return
  643. video_uploader = mobj.group(1)
  644. return [{
  645. 'id': video_id.decode('utf-8'),
  646. 'url': video_url.decode('utf-8'),
  647. 'uploader': video_uploader.decode('utf-8'),
  648. 'upload_date': None,
  649. 'title': video_title,
  650. 'ext': video_extension.decode('utf-8'),
  651. }]
  652. class DailymotionIE(InfoExtractor):
  653. """Information Extractor for Dailymotion"""
  654. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  655. IE_NAME = u'dailymotion'
  656. _WORKING = False
  657. def __init__(self, downloader=None):
  658. InfoExtractor.__init__(self, downloader)
  659. def report_extraction(self, video_id):
  660. """Report information extraction."""
  661. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  662. def _real_extract(self, url):
  663. # Extract id and simplified title from URL
  664. mobj = re.match(self._VALID_URL, url)
  665. if mobj is None:
  666. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  667. return
  668. video_id = mobj.group(1).split('_')[0].split('?')[0]
  669. video_extension = 'mp4'
  670. # Retrieve video webpage to extract further information
  671. request = compat_urllib_request.Request(url)
  672. request.add_header('Cookie', 'family_filter=off')
  673. webpage = self._download_webpage(request, video_id)
  674. # Extract URL, uploader and title from webpage
  675. self.report_extraction(video_id)
  676. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  677. if mobj is None:
  678. self._downloader.trouble(u'ERROR: unable to extract media URL')
  679. return
  680. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  681. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  682. if key in flashvars:
  683. max_quality = key
  684. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  685. break
  686. else:
  687. self._downloader.trouble(u'ERROR: unable to extract video URL')
  688. return
  689. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  690. if mobj is None:
  691. self._downloader.trouble(u'ERROR: unable to extract video URL')
  692. return
  693. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  694. # TODO: support choosing qualities
  695. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  696. if mobj is None:
  697. self._downloader.trouble(u'ERROR: unable to extract title')
  698. return
  699. video_title = unescapeHTML(mobj.group('title'))
  700. video_uploader = None
  701. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  702. if mobj is None:
  703. # lookin for official user
  704. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  705. if mobj_official is None:
  706. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  707. else:
  708. video_uploader = mobj_official.group(1)
  709. else:
  710. video_uploader = mobj.group(1)
  711. video_upload_date = None
  712. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  713. if mobj is not None:
  714. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  715. return [{
  716. 'id': video_id,
  717. 'url': video_url,
  718. 'uploader': video_uploader,
  719. 'upload_date': video_upload_date,
  720. 'title': video_title,
  721. 'ext': video_extension,
  722. }]
  723. class PhotobucketIE(InfoExtractor):
  724. """Information extractor for photobucket.com."""
  725. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  726. IE_NAME = u'photobucket'
  727. def __init__(self, downloader=None):
  728. InfoExtractor.__init__(self, downloader)
  729. def report_download_webpage(self, video_id):
  730. """Report webpage download."""
  731. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  732. def report_extraction(self, video_id):
  733. """Report information extraction."""
  734. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  735. def _real_extract(self, url):
  736. # Extract id from URL
  737. mobj = re.match(self._VALID_URL, url)
  738. if mobj is None:
  739. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  740. return
  741. video_id = mobj.group(1)
  742. video_extension = 'flv'
  743. # Retrieve video webpage to extract further information
  744. request = compat_urllib_request.Request(url)
  745. try:
  746. self.report_download_webpage(video_id)
  747. webpage = compat_urllib_request.urlopen(request).read()
  748. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  749. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  750. return
  751. # Extract URL, uploader, and title from webpage
  752. self.report_extraction(video_id)
  753. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  754. if mobj is None:
  755. self._downloader.trouble(u'ERROR: unable to extract media URL')
  756. return
  757. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  758. video_url = mediaURL
  759. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  760. if mobj is None:
  761. self._downloader.trouble(u'ERROR: unable to extract title')
  762. return
  763. video_title = mobj.group(1).decode('utf-8')
  764. video_uploader = mobj.group(2).decode('utf-8')
  765. return [{
  766. 'id': video_id.decode('utf-8'),
  767. 'url': video_url.decode('utf-8'),
  768. 'uploader': video_uploader,
  769. 'upload_date': None,
  770. 'title': video_title,
  771. 'ext': video_extension.decode('utf-8'),
  772. }]
  773. class YahooIE(InfoExtractor):
  774. """Information extractor for video.yahoo.com."""
  775. _WORKING = False
  776. # _VALID_URL matches all Yahoo! Video URLs
  777. # _VPAGE_URL matches only the extractable '/watch/' URLs
  778. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  779. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  780. IE_NAME = u'video.yahoo'
  781. def __init__(self, downloader=None):
  782. InfoExtractor.__init__(self, downloader)
  783. def report_download_webpage(self, video_id):
  784. """Report webpage download."""
  785. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  786. def report_extraction(self, video_id):
  787. """Report information extraction."""
  788. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  789. def _real_extract(self, url, new_video=True):
  790. # Extract ID from URL
  791. mobj = re.match(self._VALID_URL, url)
  792. if mobj is None:
  793. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  794. return
  795. video_id = mobj.group(2)
  796. video_extension = 'flv'
  797. # Rewrite valid but non-extractable URLs as
  798. # extractable English language /watch/ URLs
  799. if re.match(self._VPAGE_URL, url) is None:
  800. request = compat_urllib_request.Request(url)
  801. try:
  802. webpage = compat_urllib_request.urlopen(request).read()
  803. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  804. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  805. return
  806. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  807. if mobj is None:
  808. self._downloader.trouble(u'ERROR: Unable to extract id field')
  809. return
  810. yahoo_id = mobj.group(1)
  811. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  812. if mobj is None:
  813. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  814. return
  815. yahoo_vid = mobj.group(1)
  816. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  817. return self._real_extract(url, new_video=False)
  818. # Retrieve video webpage to extract further information
  819. request = compat_urllib_request.Request(url)
  820. try:
  821. self.report_download_webpage(video_id)
  822. webpage = compat_urllib_request.urlopen(request).read()
  823. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  824. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  825. return
  826. # Extract uploader and title from webpage
  827. self.report_extraction(video_id)
  828. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  829. if mobj is None:
  830. self._downloader.trouble(u'ERROR: unable to extract video title')
  831. return
  832. video_title = mobj.group(1).decode('utf-8')
  833. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  834. if mobj is None:
  835. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  836. return
  837. video_uploader = mobj.group(1).decode('utf-8')
  838. # Extract video thumbnail
  839. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  840. if mobj is None:
  841. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  842. return
  843. video_thumbnail = mobj.group(1).decode('utf-8')
  844. # Extract video description
  845. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  846. if mobj is None:
  847. self._downloader.trouble(u'ERROR: unable to extract video description')
  848. return
  849. video_description = mobj.group(1).decode('utf-8')
  850. if not video_description:
  851. video_description = 'No description available.'
  852. # Extract video height and width
  853. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  854. if mobj is None:
  855. self._downloader.trouble(u'ERROR: unable to extract video height')
  856. return
  857. yv_video_height = mobj.group(1)
  858. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  859. if mobj is None:
  860. self._downloader.trouble(u'ERROR: unable to extract video width')
  861. return
  862. yv_video_width = mobj.group(1)
  863. # Retrieve video playlist to extract media URL
  864. # I'm not completely sure what all these options are, but we
  865. # seem to need most of them, otherwise the server sends a 401.
  866. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  867. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  868. request = compat_urllib_request.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  869. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  870. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  871. try:
  872. self.report_download_webpage(video_id)
  873. webpage = compat_urllib_request.urlopen(request).read()
  874. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  875. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  876. return
  877. # Extract media URL from playlist XML
  878. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  879. if mobj is None:
  880. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  881. return
  882. video_url = compat_urllib_parse.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  883. video_url = unescapeHTML(video_url)
  884. return [{
  885. 'id': video_id.decode('utf-8'),
  886. 'url': video_url,
  887. 'uploader': video_uploader,
  888. 'upload_date': None,
  889. 'title': video_title,
  890. 'ext': video_extension.decode('utf-8'),
  891. 'thumbnail': video_thumbnail.decode('utf-8'),
  892. 'description': video_description,
  893. }]
  894. class VimeoIE(InfoExtractor):
  895. """Information extractor for vimeo.com."""
  896. # _VALID_URL matches Vimeo URLs
  897. _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)'
  898. IE_NAME = u'vimeo'
  899. def __init__(self, downloader=None):
  900. InfoExtractor.__init__(self, downloader)
  901. def report_download_webpage(self, video_id):
  902. """Report webpage download."""
  903. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  904. def report_extraction(self, video_id):
  905. """Report information extraction."""
  906. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  907. def _real_extract(self, url, new_video=True):
  908. # Extract ID from URL
  909. mobj = re.match(self._VALID_URL, url)
  910. if mobj is None:
  911. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  912. return
  913. video_id = mobj.group('id')
  914. if not mobj.group('proto'):
  915. url = 'https://' + url
  916. if mobj.group('direct_link'):
  917. url = 'https://vimeo.com/' + video_id
  918. # Retrieve video webpage to extract further information
  919. request = compat_urllib_request.Request(url, None, std_headers)
  920. try:
  921. self.report_download_webpage(video_id)
  922. webpage_bytes = compat_urllib_request.urlopen(request).read()
  923. webpage = webpage_bytes.decode('utf-8')
  924. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  925. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  926. return
  927. # Now we begin extracting as much information as we can from what we
  928. # retrieved. First we extract the information common to all extractors,
  929. # and latter we extract those that are Vimeo specific.
  930. self.report_extraction(video_id)
  931. # Extract the config JSON
  932. try:
  933. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  934. config = json.loads(config)
  935. except:
  936. self._downloader.trouble(u'ERROR: unable to extract info section')
  937. return
  938. # Extract title
  939. video_title = config["video"]["title"]
  940. # Extract uploader and uploader_id
  941. video_uploader = config["video"]["owner"]["name"]
  942. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1]
  943. # Extract video thumbnail
  944. video_thumbnail = config["video"]["thumbnail"]
  945. # Extract video description
  946. video_description = get_element_by_attribute("itemprop", "description", webpage)
  947. if video_description: video_description = clean_html(video_description)
  948. else: video_description = ''
  949. # Extract upload date
  950. video_upload_date = None
  951. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  952. if mobj is not None:
  953. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  954. # Vimeo specific: extract request signature and timestamp
  955. sig = config['request']['signature']
  956. timestamp = config['request']['timestamp']
  957. # Vimeo specific: extract video codec and quality information
  958. # First consider quality, then codecs, then take everything
  959. # TODO bind to format param
  960. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  961. files = { 'hd': [], 'sd': [], 'other': []}
  962. for codec_name, codec_extension in codecs:
  963. if codec_name in config["video"]["files"]:
  964. if 'hd' in config["video"]["files"][codec_name]:
  965. files['hd'].append((codec_name, codec_extension, 'hd'))
  966. elif 'sd' in config["video"]["files"][codec_name]:
  967. files['sd'].append((codec_name, codec_extension, 'sd'))
  968. else:
  969. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  970. for quality in ('hd', 'sd', 'other'):
  971. if len(files[quality]) > 0:
  972. video_quality = files[quality][0][2]
  973. video_codec = files[quality][0][0]
  974. video_extension = files[quality][0][1]
  975. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  976. break
  977. else:
  978. self._downloader.trouble(u'ERROR: no known codec found')
  979. return
  980. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  981. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  982. return [{
  983. 'id': video_id,
  984. 'url': video_url,
  985. 'uploader': video_uploader,
  986. 'uploader_id': video_uploader_id,
  987. 'upload_date': video_upload_date,
  988. 'title': video_title,
  989. 'ext': video_extension,
  990. 'thumbnail': video_thumbnail,
  991. 'description': video_description,
  992. }]
  993. class ArteTvIE(InfoExtractor):
  994. """arte.tv information extractor."""
  995. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  996. _LIVE_URL = r'index-[0-9]+\.html$'
  997. IE_NAME = u'arte.tv'
  998. def __init__(self, downloader=None):
  999. InfoExtractor.__init__(self, downloader)
  1000. def report_download_webpage(self, video_id):
  1001. """Report webpage download."""
  1002. self._downloader.to_screen(u'[arte.tv] %s: Downloading webpage' % video_id)
  1003. def report_extraction(self, video_id):
  1004. """Report information extraction."""
  1005. self._downloader.to_screen(u'[arte.tv] %s: Extracting information' % video_id)
  1006. def fetch_webpage(self, url):
  1007. request = compat_urllib_request.Request(url)
  1008. try:
  1009. self.report_download_webpage(url)
  1010. webpage = compat_urllib_request.urlopen(request).read()
  1011. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1012. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1013. return
  1014. except ValueError as err:
  1015. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1016. return
  1017. return webpage
  1018. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  1019. page = self.fetch_webpage(url)
  1020. mobj = re.search(regex, page, regexFlags)
  1021. info = {}
  1022. if mobj is None:
  1023. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1024. return
  1025. for (i, key, err) in matchTuples:
  1026. if mobj.group(i) is None:
  1027. self._downloader.trouble(err)
  1028. return
  1029. else:
  1030. info[key] = mobj.group(i)
  1031. return info
  1032. def extractLiveStream(self, url):
  1033. video_lang = url.split('/')[-4]
  1034. info = self.grep_webpage(
  1035. url,
  1036. r'src="(.*?/videothek_js.*?\.js)',
  1037. 0,
  1038. [
  1039. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1040. ]
  1041. )
  1042. http_host = url.split('/')[2]
  1043. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  1044. info = self.grep_webpage(
  1045. next_url,
  1046. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  1047. '(http://.*?\.swf).*?' +
  1048. '(rtmp://.*?)\'',
  1049. re.DOTALL,
  1050. [
  1051. (1, 'path', u'ERROR: could not extract video path: %s' % url),
  1052. (2, 'player', u'ERROR: could not extract video player: %s' % url),
  1053. (3, 'url', u'ERROR: could not extract video url: %s' % url)
  1054. ]
  1055. )
  1056. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  1057. def extractPlus7Stream(self, url):
  1058. video_lang = url.split('/')[-3]
  1059. info = self.grep_webpage(
  1060. url,
  1061. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  1062. 0,
  1063. [
  1064. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1065. ]
  1066. )
  1067. next_url = compat_urllib_parse.unquote(info.get('url'))
  1068. info = self.grep_webpage(
  1069. next_url,
  1070. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  1071. 0,
  1072. [
  1073. (1, 'url', u'ERROR: Could not find <video> tag: %s' % url)
  1074. ]
  1075. )
  1076. next_url = compat_urllib_parse.unquote(info.get('url'))
  1077. info = self.grep_webpage(
  1078. next_url,
  1079. r'<video id="(.*?)".*?>.*?' +
  1080. '<name>(.*?)</name>.*?' +
  1081. '<dateVideo>(.*?)</dateVideo>.*?' +
  1082. '<url quality="hd">(.*?)</url>',
  1083. re.DOTALL,
  1084. [
  1085. (1, 'id', u'ERROR: could not extract video id: %s' % url),
  1086. (2, 'title', u'ERROR: could not extract video title: %s' % url),
  1087. (3, 'date', u'ERROR: could not extract video date: %s' % url),
  1088. (4, 'url', u'ERROR: could not extract video url: %s' % url)
  1089. ]
  1090. )
  1091. return {
  1092. 'id': info.get('id'),
  1093. 'url': compat_urllib_parse.unquote(info.get('url')),
  1094. 'uploader': u'arte.tv',
  1095. 'upload_date': info.get('date'),
  1096. 'title': info.get('title').decode('utf-8'),
  1097. 'ext': u'mp4',
  1098. 'format': u'NA',
  1099. 'player_url': None,
  1100. }
  1101. def _real_extract(self, url):
  1102. video_id = url.split('/')[-1]
  1103. self.report_extraction(video_id)
  1104. if re.search(self._LIVE_URL, video_id) is not None:
  1105. self.extractLiveStream(url)
  1106. return
  1107. else:
  1108. info = self.extractPlus7Stream(url)
  1109. return [info]
  1110. class GenericIE(InfoExtractor):
  1111. """Generic last-resort information extractor."""
  1112. _VALID_URL = r'.*'
  1113. IE_NAME = u'generic'
  1114. def __init__(self, downloader=None):
  1115. InfoExtractor.__init__(self, downloader)
  1116. def report_download_webpage(self, video_id):
  1117. """Report webpage download."""
  1118. if not self._downloader.params.get('test', False):
  1119. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1120. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1121. def report_extraction(self, video_id):
  1122. """Report information extraction."""
  1123. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1124. def report_following_redirect(self, new_url):
  1125. """Report information extraction."""
  1126. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1127. def _test_redirect(self, url):
  1128. """Check if it is a redirect, like url shorteners, in case restart chain."""
  1129. class HeadRequest(compat_urllib_request.Request):
  1130. def get_method(self):
  1131. return "HEAD"
  1132. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1133. """
  1134. Subclass the HTTPRedirectHandler to make it use our
  1135. HeadRequest also on the redirected URL
  1136. """
  1137. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1138. if code in (301, 302, 303, 307):
  1139. newurl = newurl.replace(' ', '%20')
  1140. newheaders = dict((k,v) for k,v in req.headers.items()
  1141. if k.lower() not in ("content-length", "content-type"))
  1142. return HeadRequest(newurl,
  1143. headers=newheaders,
  1144. origin_req_host=req.get_origin_req_host(),
  1145. unverifiable=True)
  1146. else:
  1147. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1148. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1149. """
  1150. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1151. """
  1152. def http_error_405(self, req, fp, code, msg, headers):
  1153. fp.read()
  1154. fp.close()
  1155. newheaders = dict((k,v) for k,v in req.headers.items()
  1156. if k.lower() not in ("content-length", "content-type"))
  1157. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1158. headers=newheaders,
  1159. origin_req_host=req.get_origin_req_host(),
  1160. unverifiable=True))
  1161. # Build our opener
  1162. opener = compat_urllib_request.OpenerDirector()
  1163. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1164. HTTPMethodFallback, HEADRedirectHandler,
  1165. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1166. opener.add_handler(handler())
  1167. response = opener.open(HeadRequest(url))
  1168. new_url = response.geturl()
  1169. if url == new_url:
  1170. return False
  1171. self.report_following_redirect(new_url)
  1172. self._downloader.download([new_url])
  1173. return True
  1174. def _real_extract(self, url):
  1175. if self._test_redirect(url): return
  1176. video_id = url.split('/')[-1]
  1177. try:
  1178. webpage = self._download_webpage(url, video_id)
  1179. except ValueError as err:
  1180. # since this is the last-resort InfoExtractor, if
  1181. # this error is thrown, it'll be thrown here
  1182. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1183. return
  1184. self.report_extraction(video_id)
  1185. # Start with something easy: JW Player in SWFObject
  1186. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1187. if mobj is None:
  1188. # Broaden the search a little bit
  1189. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1190. if mobj is None:
  1191. # Broaden the search a little bit: JWPlayer JS loader
  1192. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  1193. if mobj is None:
  1194. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1195. return
  1196. # It's possible that one of the regexes
  1197. # matched, but returned an empty group:
  1198. if mobj.group(1) is None:
  1199. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1200. return
  1201. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1202. video_id = os.path.basename(video_url)
  1203. # here's a fun little line of code for you:
  1204. video_extension = os.path.splitext(video_id)[1][1:]
  1205. video_id = os.path.splitext(video_id)[0]
  1206. # it's tempting to parse this further, but you would
  1207. # have to take into account all the variations like
  1208. # Video Title - Site Name
  1209. # Site Name | Video Title
  1210. # Video Title - Tagline | Site Name
  1211. # and so on and so forth; it's just not practical
  1212. mobj = re.search(r'<title>(.*)</title>', webpage)
  1213. if mobj is None:
  1214. self._downloader.trouble(u'ERROR: unable to extract title')
  1215. return
  1216. video_title = mobj.group(1)
  1217. # video uploader is domain name
  1218. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1219. if mobj is None:
  1220. self._downloader.trouble(u'ERROR: unable to extract title')
  1221. return
  1222. video_uploader = mobj.group(1)
  1223. return [{
  1224. 'id': video_id,
  1225. 'url': video_url,
  1226. 'uploader': video_uploader,
  1227. 'upload_date': None,
  1228. 'title': video_title,
  1229. 'ext': video_extension,
  1230. }]
  1231. class YoutubeSearchIE(InfoExtractor):
  1232. """Information Extractor for YouTube search queries."""
  1233. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1234. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1235. _max_youtube_results = 1000
  1236. IE_NAME = u'youtube:search'
  1237. def __init__(self, downloader=None):
  1238. InfoExtractor.__init__(self, downloader)
  1239. def report_download_page(self, query, pagenum):
  1240. """Report attempt to download search page with given number."""
  1241. query = query.decode(preferredencoding())
  1242. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1243. def _real_extract(self, query):
  1244. mobj = re.match(self._VALID_URL, query)
  1245. if mobj is None:
  1246. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1247. return
  1248. prefix, query = query.split(':')
  1249. prefix = prefix[8:]
  1250. query = query.encode('utf-8')
  1251. if prefix == '':
  1252. self._download_n_results(query, 1)
  1253. return
  1254. elif prefix == 'all':
  1255. self._download_n_results(query, self._max_youtube_results)
  1256. return
  1257. else:
  1258. try:
  1259. n = int(prefix)
  1260. if n <= 0:
  1261. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1262. return
  1263. elif n > self._max_youtube_results:
  1264. self._downloader.report_warning(u'ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1265. n = self._max_youtube_results
  1266. self._download_n_results(query, n)
  1267. return
  1268. except ValueError: # parsing prefix as integer fails
  1269. self._download_n_results(query, 1)
  1270. return
  1271. def _download_n_results(self, query, n):
  1272. """Downloads a specified number of results for a query"""
  1273. video_ids = []
  1274. pagenum = 0
  1275. limit = n
  1276. while (50 * pagenum) < limit:
  1277. self.report_download_page(query, pagenum+1)
  1278. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1279. request = compat_urllib_request.Request(result_url)
  1280. try:
  1281. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1282. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1283. self._downloader.trouble(u'ERROR: unable to download API page: %s' % compat_str(err))
  1284. return
  1285. api_response = json.loads(data)['data']
  1286. if not 'items' in api_response:
  1287. self._downloader.trouble(u'[youtube] No video results')
  1288. return
  1289. new_ids = list(video['id'] for video in api_response['items'])
  1290. video_ids += new_ids
  1291. limit = min(n, api_response['totalItems'])
  1292. pagenum += 1
  1293. if len(video_ids) > n:
  1294. video_ids = video_ids[:n]
  1295. for id in video_ids:
  1296. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1297. return
  1298. class GoogleSearchIE(InfoExtractor):
  1299. """Information Extractor for Google Video search queries."""
  1300. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1301. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1302. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1303. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1304. _max_google_results = 1000
  1305. IE_NAME = u'video.google:search'
  1306. def __init__(self, downloader=None):
  1307. InfoExtractor.__init__(self, downloader)
  1308. def report_download_page(self, query, pagenum):
  1309. """Report attempt to download playlist page with given number."""
  1310. query = query.decode(preferredencoding())
  1311. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1312. def _real_extract(self, query):
  1313. mobj = re.match(self._VALID_URL, query)
  1314. if mobj is None:
  1315. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1316. return
  1317. prefix, query = query.split(':')
  1318. prefix = prefix[8:]
  1319. query = query.encode('utf-8')
  1320. if prefix == '':
  1321. self._download_n_results(query, 1)
  1322. return
  1323. elif prefix == 'all':
  1324. self._download_n_results(query, self._max_google_results)
  1325. return
  1326. else:
  1327. try:
  1328. n = int(prefix)
  1329. if n <= 0:
  1330. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1331. return
  1332. elif n > self._max_google_results:
  1333. self._downloader.report_warning(u'gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1334. n = self._max_google_results
  1335. self._download_n_results(query, n)
  1336. return
  1337. except ValueError: # parsing prefix as integer fails
  1338. self._download_n_results(query, 1)
  1339. return
  1340. def _download_n_results(self, query, n):
  1341. """Downloads a specified number of results for a query"""
  1342. video_ids = []
  1343. pagenum = 0
  1344. while True:
  1345. self.report_download_page(query, pagenum)
  1346. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1347. request = compat_urllib_request.Request(result_url)
  1348. try:
  1349. page = compat_urllib_request.urlopen(request).read()
  1350. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1351. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1352. return
  1353. # Extract video identifiers
  1354. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1355. video_id = mobj.group(1)
  1356. if video_id not in video_ids:
  1357. video_ids.append(video_id)
  1358. if len(video_ids) == n:
  1359. # Specified n videos reached
  1360. for id in video_ids:
  1361. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1362. return
  1363. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1364. for id in video_ids:
  1365. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1366. return
  1367. pagenum = pagenum + 1
  1368. class YahooSearchIE(InfoExtractor):
  1369. """Information Extractor for Yahoo! Video search queries."""
  1370. _WORKING = False
  1371. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1372. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1373. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1374. _MORE_PAGES_INDICATOR = r'\s*Next'
  1375. _max_yahoo_results = 1000
  1376. IE_NAME = u'video.yahoo:search'
  1377. def __init__(self, downloader=None):
  1378. InfoExtractor.__init__(self, downloader)
  1379. def report_download_page(self, query, pagenum):
  1380. """Report attempt to download playlist page with given number."""
  1381. query = query.decode(preferredencoding())
  1382. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1383. def _real_extract(self, query):
  1384. mobj = re.match(self._VALID_URL, query)
  1385. if mobj is None:
  1386. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1387. return
  1388. prefix, query = query.split(':')
  1389. prefix = prefix[8:]
  1390. query = query.encode('utf-8')
  1391. if prefix == '':
  1392. self._download_n_results(query, 1)
  1393. return
  1394. elif prefix == 'all':
  1395. self._download_n_results(query, self._max_yahoo_results)
  1396. return
  1397. else:
  1398. try:
  1399. n = int(prefix)
  1400. if n <= 0:
  1401. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1402. return
  1403. elif n > self._max_yahoo_results:
  1404. self._downloader.report_warning(u'yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1405. n = self._max_yahoo_results
  1406. self._download_n_results(query, n)
  1407. return
  1408. except ValueError: # parsing prefix as integer fails
  1409. self._download_n_results(query, 1)
  1410. return
  1411. def _download_n_results(self, query, n):
  1412. """Downloads a specified number of results for a query"""
  1413. video_ids = []
  1414. already_seen = set()
  1415. pagenum = 1
  1416. while True:
  1417. self.report_download_page(query, pagenum)
  1418. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1419. request = compat_urllib_request.Request(result_url)
  1420. try:
  1421. page = compat_urllib_request.urlopen(request).read()
  1422. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1423. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1424. return
  1425. # Extract video identifiers
  1426. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1427. video_id = mobj.group(1)
  1428. if video_id not in already_seen:
  1429. video_ids.append(video_id)
  1430. already_seen.add(video_id)
  1431. if len(video_ids) == n:
  1432. # Specified n videos reached
  1433. for id in video_ids:
  1434. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1435. return
  1436. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1437. for id in video_ids:
  1438. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1439. return
  1440. pagenum = pagenum + 1
  1441. class YoutubePlaylistIE(InfoExtractor):
  1442. """Information Extractor for YouTube playlists."""
  1443. _VALID_URL = r"""(?:
  1444. (?:https?://)?
  1445. (?:\w+\.)?
  1446. youtube\.com/
  1447. (?:
  1448. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1449. \? (?:.*?&)*? (?:p|a|list)=
  1450. | user/.*?/user/
  1451. | p/
  1452. | user/.*?#[pg]/c/
  1453. )
  1454. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  1455. .*
  1456. |
  1457. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  1458. )"""
  1459. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json'
  1460. _MAX_RESULTS = 50
  1461. IE_NAME = u'youtube:playlist'
  1462. def __init__(self, downloader=None):
  1463. InfoExtractor.__init__(self, downloader)
  1464. @classmethod
  1465. def suitable(cls, url):
  1466. """Receives a URL and returns True if suitable for this IE."""
  1467. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1468. def report_download_page(self, playlist_id, pagenum):
  1469. """Report attempt to download playlist page with given number."""
  1470. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1471. def _real_extract(self, url):
  1472. # Extract playlist id
  1473. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1474. if mobj is None:
  1475. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1476. return
  1477. # Download playlist videos from API
  1478. playlist_id = mobj.group(1) or mobj.group(2)
  1479. page_num = 1
  1480. videos = []
  1481. while True:
  1482. self.report_download_page(playlist_id, page_num)
  1483. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  1484. try:
  1485. page = compat_urllib_request.urlopen(url).read().decode('utf8')
  1486. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1487. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1488. return
  1489. try:
  1490. response = json.loads(page)
  1491. except ValueError as err:
  1492. self._downloader.trouble(u'ERROR: Invalid JSON in API response: ' + compat_str(err))
  1493. return
  1494. if not 'feed' in response or not 'entry' in response['feed']:
  1495. self._downloader.trouble(u'ERROR: Got a malformed response from YouTube API')
  1496. return
  1497. videos += [ (entry['yt$position']['$t'], entry['content']['src'])
  1498. for entry in response['feed']['entry']
  1499. if 'content' in entry ]
  1500. if len(response['feed']['entry']) < self._MAX_RESULTS:
  1501. break
  1502. page_num += 1
  1503. videos = [v[1] for v in sorted(videos)]
  1504. total = len(videos)
  1505. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1506. playlistend = self._downloader.params.get('playlistend', -1)
  1507. if playlistend == -1:
  1508. videos = videos[playliststart:]
  1509. else:
  1510. videos = videos[playliststart:playlistend]
  1511. if len(videos) == total:
  1512. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos' % (playlist_id, total))
  1513. else:
  1514. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos, downloading %i' % (playlist_id, total, len(videos)))
  1515. for video in videos:
  1516. self._downloader.download([video])
  1517. return
  1518. class YoutubeChannelIE(InfoExtractor):
  1519. """Information Extractor for YouTube channels."""
  1520. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1521. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1522. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1523. IE_NAME = u'youtube:channel'
  1524. def report_download_page(self, channel_id, pagenum):
  1525. """Report attempt to download channel page with given number."""
  1526. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1527. def _real_extract(self, url):
  1528. # Extract channel id
  1529. mobj = re.match(self._VALID_URL, url)
  1530. if mobj is None:
  1531. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1532. return
  1533. # Download channel pages
  1534. channel_id = mobj.group(1)
  1535. video_ids = []
  1536. pagenum = 1
  1537. while True:
  1538. self.report_download_page(channel_id, pagenum)
  1539. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1540. request = compat_urllib_request.Request(url)
  1541. try:
  1542. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1543. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1544. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1545. return
  1546. # Extract video identifiers
  1547. ids_in_page = []
  1548. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1549. if mobj.group(1) not in ids_in_page:
  1550. ids_in_page.append(mobj.group(1))
  1551. video_ids.extend(ids_in_page)
  1552. if self._MORE_PAGES_INDICATOR not in page:
  1553. break
  1554. pagenum = pagenum + 1
  1555. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1556. for id in video_ids:
  1557. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1558. return
  1559. class YoutubeUserIE(InfoExtractor):
  1560. """Information Extractor for YouTube users."""
  1561. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1562. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1563. _GDATA_PAGE_SIZE = 50
  1564. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1565. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1566. IE_NAME = u'youtube:user'
  1567. def __init__(self, downloader=None):
  1568. InfoExtractor.__init__(self, downloader)
  1569. def report_download_page(self, username, start_index):
  1570. """Report attempt to download user page."""
  1571. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1572. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1573. def _real_extract(self, url):
  1574. # Extract username
  1575. mobj = re.match(self._VALID_URL, url)
  1576. if mobj is None:
  1577. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1578. return
  1579. username = mobj.group(1)
  1580. # Download video ids using YouTube Data API. Result size per
  1581. # query is limited (currently to 50 videos) so we need to query
  1582. # page by page until there are no video ids - it means we got
  1583. # all of them.
  1584. video_ids = []
  1585. pagenum = 0
  1586. while True:
  1587. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1588. self.report_download_page(username, start_index)
  1589. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1590. try:
  1591. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1592. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1593. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1594. return
  1595. # Extract video identifiers
  1596. ids_in_page = []
  1597. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1598. if mobj.group(1) not in ids_in_page:
  1599. ids_in_page.append(mobj.group(1))
  1600. video_ids.extend(ids_in_page)
  1601. # A little optimization - if current page is not
  1602. # "full", ie. does not contain PAGE_SIZE video ids then
  1603. # we can assume that this page is the last one - there
  1604. # are no more ids on further pages - no need to query
  1605. # again.
  1606. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1607. break
  1608. pagenum += 1
  1609. all_ids_count = len(video_ids)
  1610. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1611. playlistend = self._downloader.params.get('playlistend', -1)
  1612. if playlistend == -1:
  1613. video_ids = video_ids[playliststart:]
  1614. else:
  1615. video_ids = video_ids[playliststart:playlistend]
  1616. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1617. (username, all_ids_count, len(video_ids)))
  1618. for video_id in video_ids:
  1619. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1620. class BlipTVUserIE(InfoExtractor):
  1621. """Information Extractor for blip.tv users."""
  1622. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1623. _PAGE_SIZE = 12
  1624. IE_NAME = u'blip.tv:user'
  1625. def __init__(self, downloader=None):
  1626. InfoExtractor.__init__(self, downloader)
  1627. def report_download_page(self, username, pagenum):
  1628. """Report attempt to download user page."""
  1629. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1630. (self.IE_NAME, username, pagenum))
  1631. def _real_extract(self, url):
  1632. # Extract username
  1633. mobj = re.match(self._VALID_URL, url)
  1634. if mobj is None:
  1635. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1636. return
  1637. username = mobj.group(1)
  1638. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1639. request = compat_urllib_request.Request(url)
  1640. try:
  1641. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1642. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1643. page_base = page_base % mobj.group(1)
  1644. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1645. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1646. return
  1647. # Download video ids using BlipTV Ajax calls. Result size per
  1648. # query is limited (currently to 12 videos) so we need to query
  1649. # page by page until there are no video ids - it means we got
  1650. # all of them.
  1651. video_ids = []
  1652. pagenum = 1
  1653. while True:
  1654. self.report_download_page(username, pagenum)
  1655. url = page_base + "&page=" + str(pagenum)
  1656. request = compat_urllib_request.Request( url )
  1657. try:
  1658. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1659. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1660. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1661. return
  1662. # Extract video identifiers
  1663. ids_in_page = []
  1664. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1665. if mobj.group(1) not in ids_in_page:
  1666. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1667. video_ids.extend(ids_in_page)
  1668. # A little optimization - if current page is not
  1669. # "full", ie. does not contain PAGE_SIZE video ids then
  1670. # we can assume that this page is the last one - there
  1671. # are no more ids on further pages - no need to query
  1672. # again.
  1673. if len(ids_in_page) < self._PAGE_SIZE:
  1674. break
  1675. pagenum += 1
  1676. all_ids_count = len(video_ids)
  1677. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1678. playlistend = self._downloader.params.get('playlistend', -1)
  1679. if playlistend == -1:
  1680. video_ids = video_ids[playliststart:]
  1681. else:
  1682. video_ids = video_ids[playliststart:playlistend]
  1683. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1684. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1685. for video_id in video_ids:
  1686. self._downloader.download([u'http://blip.tv/'+video_id])
  1687. class DepositFilesIE(InfoExtractor):
  1688. """Information extractor for depositfiles.com"""
  1689. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1690. def report_download_webpage(self, file_id):
  1691. """Report webpage download."""
  1692. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1693. def report_extraction(self, file_id):
  1694. """Report information extraction."""
  1695. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1696. def _real_extract(self, url):
  1697. file_id = url.split('/')[-1]
  1698. # Rebuild url in english locale
  1699. url = 'http://depositfiles.com/en/files/' + file_id
  1700. # Retrieve file webpage with 'Free download' button pressed
  1701. free_download_indication = { 'gateway_result' : '1' }
  1702. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1703. try:
  1704. self.report_download_webpage(file_id)
  1705. webpage = compat_urllib_request.urlopen(request).read()
  1706. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1707. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % compat_str(err))
  1708. return
  1709. # Search for the real file URL
  1710. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1711. if (mobj is None) or (mobj.group(1) is None):
  1712. # Try to figure out reason of the error.
  1713. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1714. if (mobj is not None) and (mobj.group(1) is not None):
  1715. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1716. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1717. else:
  1718. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1719. return
  1720. file_url = mobj.group(1)
  1721. file_extension = os.path.splitext(file_url)[1][1:]
  1722. # Search for file title
  1723. mobj = re.search(r'<b title="(.*?)">', webpage)
  1724. if mobj is None:
  1725. self._downloader.trouble(u'ERROR: unable to extract title')
  1726. return
  1727. file_title = mobj.group(1).decode('utf-8')
  1728. return [{
  1729. 'id': file_id.decode('utf-8'),
  1730. 'url': file_url.decode('utf-8'),
  1731. 'uploader': None,
  1732. 'upload_date': None,
  1733. 'title': file_title,
  1734. 'ext': file_extension.decode('utf-8'),
  1735. }]
  1736. class FacebookIE(InfoExtractor):
  1737. """Information Extractor for Facebook"""
  1738. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1739. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1740. _NETRC_MACHINE = 'facebook'
  1741. IE_NAME = u'facebook'
  1742. def report_login(self):
  1743. """Report attempt to log in."""
  1744. self._downloader.to_screen(u'[%s] Logging in' % self.IE_NAME)
  1745. def _real_initialize(self):
  1746. if self._downloader is None:
  1747. return
  1748. useremail = None
  1749. password = None
  1750. downloader_params = self._downloader.params
  1751. # Attempt to use provided username and password or .netrc data
  1752. if downloader_params.get('username', None) is not None:
  1753. useremail = downloader_params['username']
  1754. password = downloader_params['password']
  1755. elif downloader_params.get('usenetrc', False):
  1756. try:
  1757. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1758. if info is not None:
  1759. useremail = info[0]
  1760. password = info[2]
  1761. else:
  1762. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1763. except (IOError, netrc.NetrcParseError) as err:
  1764. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  1765. return
  1766. if useremail is None:
  1767. return
  1768. # Log in
  1769. login_form = {
  1770. 'email': useremail,
  1771. 'pass': password,
  1772. 'login': 'Log+In'
  1773. }
  1774. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1775. try:
  1776. self.report_login()
  1777. login_results = compat_urllib_request.urlopen(request).read()
  1778. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1779. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1780. return
  1781. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1782. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  1783. return
  1784. def _real_extract(self, url):
  1785. mobj = re.match(self._VALID_URL, url)
  1786. if mobj is None:
  1787. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1788. return
  1789. video_id = mobj.group('ID')
  1790. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  1791. webpage = self._download_webpage(url, video_id)
  1792. BEFORE = '[["allowFullScreen","true"],["allowScriptAccess","always"],["salign","tl"],["scale","noscale"],["wmode","opaque"]].forEach(function(param) {swf.addParam(param[0], param[1]);});\n'
  1793. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  1794. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  1795. if not m:
  1796. raise ExtractorError(u'Cannot parse data')
  1797. data = dict(json.loads(m.group(1)))
  1798. params_raw = compat_urllib_parse.unquote(data['params'])
  1799. params = json.loads(params_raw)
  1800. video_url = params['hd_src']
  1801. if not video_url:
  1802. video_url = params['sd_src']
  1803. if not video_url:
  1804. raise ExtractorError(u'Cannot find video URL')
  1805. video_duration = int(params['video_duration'])
  1806. m = re.search('<h2 class="uiHeaderTitle">([^<]+)</h2>', webpage)
  1807. if not m:
  1808. raise ExtractorError(u'Cannot find title in webpage')
  1809. video_title = unescapeHTML(m.group(1))
  1810. info = {
  1811. 'id': video_id,
  1812. 'title': video_title,
  1813. 'url': video_url,
  1814. 'ext': 'mp4',
  1815. 'duration': video_duration,
  1816. 'thumbnail': params['thumbnail_src'],
  1817. }
  1818. return [info]
  1819. class BlipTVIE(InfoExtractor):
  1820. """Information extractor for blip.tv"""
  1821. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1822. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1823. IE_NAME = u'blip.tv'
  1824. def report_extraction(self, file_id):
  1825. """Report information extraction."""
  1826. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1827. def report_direct_download(self, title):
  1828. """Report information extraction."""
  1829. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1830. def _real_extract(self, url):
  1831. mobj = re.match(self._VALID_URL, url)
  1832. if mobj is None:
  1833. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1834. return
  1835. urlp = compat_urllib_parse_urlparse(url)
  1836. if urlp.path.startswith('/play/'):
  1837. request = compat_urllib_request.Request(url)
  1838. response = compat_urllib_request.urlopen(request)
  1839. redirecturl = response.geturl()
  1840. rurlp = compat_urllib_parse_urlparse(redirecturl)
  1841. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  1842. url = 'http://blip.tv/a/a-' + file_id
  1843. return self._real_extract(url)
  1844. if '?' in url:
  1845. cchar = '&'
  1846. else:
  1847. cchar = '?'
  1848. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1849. request = compat_urllib_request.Request(json_url)
  1850. request.add_header('User-Agent', 'iTunes/10.6.1')
  1851. self.report_extraction(mobj.group(1))
  1852. info = None
  1853. try:
  1854. urlh = compat_urllib_request.urlopen(request)
  1855. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1856. basename = url.split('/')[-1]
  1857. title,ext = os.path.splitext(basename)
  1858. title = title.decode('UTF-8')
  1859. ext = ext.replace('.', '')
  1860. self.report_direct_download(title)
  1861. info = {
  1862. 'id': title,
  1863. 'url': url,
  1864. 'uploader': None,
  1865. 'upload_date': None,
  1866. 'title': title,
  1867. 'ext': ext,
  1868. 'urlhandle': urlh
  1869. }
  1870. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1871. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1872. if info is None: # Regular URL
  1873. try:
  1874. json_code_bytes = urlh.read()
  1875. json_code = json_code_bytes.decode('utf-8')
  1876. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1877. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % compat_str(err))
  1878. return
  1879. try:
  1880. json_data = json.loads(json_code)
  1881. if 'Post' in json_data:
  1882. data = json_data['Post']
  1883. else:
  1884. data = json_data
  1885. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1886. video_url = data['media']['url']
  1887. umobj = re.match(self._URL_EXT, video_url)
  1888. if umobj is None:
  1889. raise ValueError('Can not determine filename extension')
  1890. ext = umobj.group(1)
  1891. info = {
  1892. 'id': data['item_id'],
  1893. 'url': video_url,
  1894. 'uploader': data['display_name'],
  1895. 'upload_date': upload_date,
  1896. 'title': data['title'],
  1897. 'ext': ext,
  1898. 'format': data['media']['mimeType'],
  1899. 'thumbnail': data['thumbnailUrl'],
  1900. 'description': data['description'],
  1901. 'player_url': data['embedUrl'],
  1902. 'user_agent': 'iTunes/10.6.1',
  1903. }
  1904. except (ValueError,KeyError) as err:
  1905. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1906. return
  1907. return [info]
  1908. class MyVideoIE(InfoExtractor):
  1909. """Information Extractor for myvideo.de."""
  1910. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1911. IE_NAME = u'myvideo'
  1912. def __init__(self, downloader=None):
  1913. InfoExtractor.__init__(self, downloader)
  1914. def report_extraction(self, video_id):
  1915. """Report information extraction."""
  1916. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1917. def _real_extract(self,url):
  1918. mobj = re.match(self._VALID_URL, url)
  1919. if mobj is None:
  1920. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1921. return
  1922. video_id = mobj.group(1)
  1923. # Get video webpage
  1924. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  1925. webpage = self._download_webpage(webpage_url, video_id)
  1926. self.report_extraction(video_id)
  1927. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/.*?\.jpg\' />',
  1928. webpage)
  1929. if mobj is None:
  1930. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1931. return
  1932. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1933. mobj = re.search('<title>([^<]+)</title>', webpage)
  1934. if mobj is None:
  1935. self._downloader.trouble(u'ERROR: unable to extract title')
  1936. return
  1937. video_title = mobj.group(1)
  1938. return [{
  1939. 'id': video_id,
  1940. 'url': video_url,
  1941. 'uploader': None,
  1942. 'upload_date': None,
  1943. 'title': video_title,
  1944. 'ext': u'flv',
  1945. }]
  1946. class ComedyCentralIE(InfoExtractor):
  1947. """Information extractor for The Daily Show and Colbert Report """
  1948. # urls can be abbreviations like :thedailyshow or :colbert
  1949. # urls for episodes like:
  1950. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1951. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1952. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1953. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1954. |(https?://)?(www\.)?
  1955. (?P<showname>thedailyshow|colbertnation)\.com/
  1956. (full-episodes/(?P<episode>.*)|
  1957. (?P<clip>
  1958. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1959. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1960. $"""
  1961. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1962. _video_extensions = {
  1963. '3500': 'mp4',
  1964. '2200': 'mp4',
  1965. '1700': 'mp4',
  1966. '1200': 'mp4',
  1967. '750': 'mp4',
  1968. '400': 'mp4',
  1969. }
  1970. _video_dimensions = {
  1971. '3500': '1280x720',
  1972. '2200': '960x540',
  1973. '1700': '768x432',
  1974. '1200': '640x360',
  1975. '750': '512x288',
  1976. '400': '384x216',
  1977. }
  1978. @classmethod
  1979. def suitable(cls, url):
  1980. """Receives a URL and returns True if suitable for this IE."""
  1981. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1982. def report_extraction(self, episode_id):
  1983. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1984. def report_config_download(self, episode_id, media_id):
  1985. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration for %s' % (episode_id, media_id))
  1986. def report_index_download(self, episode_id):
  1987. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  1988. def _print_formats(self, formats):
  1989. print('Available formats:')
  1990. for x in formats:
  1991. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  1992. def _real_extract(self, url):
  1993. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1994. if mobj is None:
  1995. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1996. return
  1997. if mobj.group('shortname'):
  1998. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1999. url = u'http://www.thedailyshow.com/full-episodes/'
  2000. else:
  2001. url = u'http://www.colbertnation.com/full-episodes/'
  2002. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2003. assert mobj is not None
  2004. if mobj.group('clip'):
  2005. if mobj.group('showname') == 'thedailyshow':
  2006. epTitle = mobj.group('tdstitle')
  2007. else:
  2008. epTitle = mobj.group('cntitle')
  2009. dlNewest = False
  2010. else:
  2011. dlNewest = not mobj.group('episode')
  2012. if dlNewest:
  2013. epTitle = mobj.group('showname')
  2014. else:
  2015. epTitle = mobj.group('episode')
  2016. req = compat_urllib_request.Request(url)
  2017. self.report_extraction(epTitle)
  2018. try:
  2019. htmlHandle = compat_urllib_request.urlopen(req)
  2020. html = htmlHandle.read()
  2021. webpage = html.decode('utf-8')
  2022. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2023. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2024. return
  2025. if dlNewest:
  2026. url = htmlHandle.geturl()
  2027. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2028. if mobj is None:
  2029. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2030. return
  2031. if mobj.group('episode') == '':
  2032. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2033. return
  2034. epTitle = mobj.group('episode')
  2035. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  2036. if len(mMovieParams) == 0:
  2037. # The Colbert Report embeds the information in a without
  2038. # a URL prefix; so extract the alternate reference
  2039. # and then add the URL prefix manually.
  2040. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  2041. if len(altMovieParams) == 0:
  2042. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2043. return
  2044. else:
  2045. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2046. uri = mMovieParams[0][1]
  2047. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2048. self.report_index_download(epTitle)
  2049. try:
  2050. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2051. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2052. self._downloader.trouble(u'ERROR: unable to download episode index: ' + compat_str(err))
  2053. return
  2054. results = []
  2055. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2056. itemEls = idoc.findall('.//item')
  2057. for partNum,itemEl in enumerate(itemEls):
  2058. mediaId = itemEl.findall('./guid')[0].text
  2059. shortMediaId = mediaId.split(':')[-1]
  2060. showId = mediaId.split(':')[-2].replace('.com', '')
  2061. officialTitle = itemEl.findall('./title')[0].text
  2062. officialDate = itemEl.findall('./pubDate')[0].text
  2063. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2064. compat_urllib_parse.urlencode({'uri': mediaId}))
  2065. configReq = compat_urllib_request.Request(configUrl)
  2066. self.report_config_download(epTitle, shortMediaId)
  2067. try:
  2068. configXml = compat_urllib_request.urlopen(configReq).read()
  2069. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2070. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2071. return
  2072. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2073. turls = []
  2074. for rendition in cdoc.findall('.//rendition'):
  2075. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2076. turls.append(finfo)
  2077. if len(turls) == 0:
  2078. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2079. continue
  2080. if self._downloader.params.get('listformats', None):
  2081. self._print_formats([i[0] for i in turls])
  2082. return
  2083. # For now, just pick the highest bitrate
  2084. format,rtmp_video_url = turls[-1]
  2085. # Get the format arg from the arg stream
  2086. req_format = self._downloader.params.get('format', None)
  2087. # Select format if we can find one
  2088. for f,v in turls:
  2089. if f == req_format:
  2090. format, rtmp_video_url = f, v
  2091. break
  2092. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  2093. if not m:
  2094. raise ExtractorError(u'Cannot transform RTMP url')
  2095. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  2096. video_url = base + m.group('finalid')
  2097. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  2098. info = {
  2099. 'id': shortMediaId,
  2100. 'url': video_url,
  2101. 'uploader': showId,
  2102. 'upload_date': officialDate,
  2103. 'title': effTitle,
  2104. 'ext': 'mp4',
  2105. 'format': format,
  2106. 'thumbnail': None,
  2107. 'description': officialTitle,
  2108. }
  2109. results.append(info)
  2110. return results
  2111. class EscapistIE(InfoExtractor):
  2112. """Information extractor for The Escapist """
  2113. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2114. IE_NAME = u'escapist'
  2115. def report_extraction(self, showName):
  2116. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2117. def report_config_download(self, showName):
  2118. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2119. def _real_extract(self, url):
  2120. mobj = re.match(self._VALID_URL, url)
  2121. if mobj is None:
  2122. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2123. return
  2124. showName = mobj.group('showname')
  2125. videoId = mobj.group('episode')
  2126. self.report_extraction(showName)
  2127. try:
  2128. webPage = compat_urllib_request.urlopen(url)
  2129. webPageBytes = webPage.read()
  2130. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2131. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2132. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2133. self._downloader.trouble(u'ERROR: unable to download webpage: ' + compat_str(err))
  2134. return
  2135. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2136. description = unescapeHTML(descMatch.group(1))
  2137. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2138. imgUrl = unescapeHTML(imgMatch.group(1))
  2139. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2140. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2141. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2142. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2143. self.report_config_download(showName)
  2144. try:
  2145. configJSON = compat_urllib_request.urlopen(configUrl)
  2146. m = re.match(r'text/html; charset="?([^"]+)"?', configJSON.headers['Content-Type'])
  2147. configJSON = configJSON.read().decode(m.group(1) if m else 'utf-8')
  2148. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2149. self._downloader.trouble(u'ERROR: unable to download configuration: ' + compat_str(err))
  2150. return
  2151. # Technically, it's JavaScript, not JSON
  2152. configJSON = configJSON.replace("'", '"')
  2153. try:
  2154. config = json.loads(configJSON)
  2155. except (ValueError,) as err:
  2156. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + compat_str(err))
  2157. return
  2158. playlist = config['playlist']
  2159. videoUrl = playlist[1]['url']
  2160. info = {
  2161. 'id': videoId,
  2162. 'url': videoUrl,
  2163. 'uploader': showName,
  2164. 'upload_date': None,
  2165. 'title': showName,
  2166. 'ext': 'mp4',
  2167. 'thumbnail': imgUrl,
  2168. 'description': description,
  2169. 'player_url': playerUrl,
  2170. }
  2171. return [info]
  2172. class CollegeHumorIE(InfoExtractor):
  2173. """Information extractor for collegehumor.com"""
  2174. _WORKING = False
  2175. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2176. IE_NAME = u'collegehumor'
  2177. def report_manifest(self, video_id):
  2178. """Report information extraction."""
  2179. self._downloader.to_screen(u'[%s] %s: Downloading XML manifest' % (self.IE_NAME, video_id))
  2180. def report_extraction(self, video_id):
  2181. """Report information extraction."""
  2182. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2183. def _real_extract(self, url):
  2184. mobj = re.match(self._VALID_URL, url)
  2185. if mobj is None:
  2186. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2187. return
  2188. video_id = mobj.group('videoid')
  2189. info = {
  2190. 'id': video_id,
  2191. 'uploader': None,
  2192. 'upload_date': None,
  2193. }
  2194. self.report_extraction(video_id)
  2195. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2196. try:
  2197. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2198. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2199. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2200. return
  2201. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2202. try:
  2203. videoNode = mdoc.findall('./video')[0]
  2204. info['description'] = videoNode.findall('./description')[0].text
  2205. info['title'] = videoNode.findall('./caption')[0].text
  2206. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2207. manifest_url = videoNode.findall('./file')[0].text
  2208. except IndexError:
  2209. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2210. return
  2211. manifest_url += '?hdcore=2.10.3'
  2212. self.report_manifest(video_id)
  2213. try:
  2214. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2215. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2216. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2217. return
  2218. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2219. try:
  2220. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2221. node_id = media_node.attrib['url']
  2222. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2223. except IndexError as err:
  2224. self._downloader.trouble(u'\nERROR: Invalid manifest file')
  2225. return
  2226. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2227. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2228. info['url'] = url
  2229. info['ext'] = 'f4f'
  2230. return [info]
  2231. class XVideosIE(InfoExtractor):
  2232. """Information extractor for xvideos.com"""
  2233. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2234. IE_NAME = u'xvideos'
  2235. def report_extraction(self, video_id):
  2236. """Report information extraction."""
  2237. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2238. def _real_extract(self, url):
  2239. mobj = re.match(self._VALID_URL, url)
  2240. if mobj is None:
  2241. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2242. return
  2243. video_id = mobj.group(1)
  2244. webpage = self._download_webpage(url, video_id)
  2245. self.report_extraction(video_id)
  2246. # Extract video URL
  2247. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2248. if mobj is None:
  2249. self._downloader.trouble(u'ERROR: unable to extract video url')
  2250. return
  2251. video_url = compat_urllib_parse.unquote(mobj.group(1))
  2252. # Extract title
  2253. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2254. if mobj is None:
  2255. self._downloader.trouble(u'ERROR: unable to extract video title')
  2256. return
  2257. video_title = mobj.group(1)
  2258. # Extract video thumbnail
  2259. mobj = re.search(r'http://(?:img.*?\.)xvideos.com/videos/thumbs/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/[a-fA-F0-9]+/([a-fA-F0-9.]+jpg)', webpage)
  2260. if mobj is None:
  2261. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2262. return
  2263. video_thumbnail = mobj.group(0)
  2264. info = {
  2265. 'id': video_id,
  2266. 'url': video_url,
  2267. 'uploader': None,
  2268. 'upload_date': None,
  2269. 'title': video_title,
  2270. 'ext': 'flv',
  2271. 'thumbnail': video_thumbnail,
  2272. 'description': None,
  2273. }
  2274. return [info]
  2275. class SoundcloudIE(InfoExtractor):
  2276. """Information extractor for soundcloud.com
  2277. To access the media, the uid of the song and a stream token
  2278. must be extracted from the page source and the script must make
  2279. a request to media.soundcloud.com/crossdomain.xml. Then
  2280. the media can be grabbed by requesting from an url composed
  2281. of the stream token and uid
  2282. """
  2283. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2284. IE_NAME = u'soundcloud'
  2285. def __init__(self, downloader=None):
  2286. InfoExtractor.__init__(self, downloader)
  2287. def report_resolve(self, video_id):
  2288. """Report information extraction."""
  2289. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2290. def report_extraction(self, video_id):
  2291. """Report information extraction."""
  2292. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2293. def _real_extract(self, url):
  2294. mobj = re.match(self._VALID_URL, url)
  2295. if mobj is None:
  2296. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2297. return
  2298. # extract uploader (which is in the url)
  2299. uploader = mobj.group(1)
  2300. # extract simple title (uploader + slug of song title)
  2301. slug_title = mobj.group(2)
  2302. simple_title = uploader + u'-' + slug_title
  2303. self.report_resolve('%s/%s' % (uploader, slug_title))
  2304. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  2305. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2306. request = compat_urllib_request.Request(resolv_url)
  2307. try:
  2308. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2309. info_json = info_json_bytes.decode('utf-8')
  2310. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2311. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2312. return
  2313. info = json.loads(info_json)
  2314. video_id = info['id']
  2315. self.report_extraction('%s/%s' % (uploader, slug_title))
  2316. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2317. request = compat_urllib_request.Request(streams_url)
  2318. try:
  2319. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2320. stream_json = stream_json_bytes.decode('utf-8')
  2321. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2322. self._downloader.trouble(u'ERROR: unable to download stream definitions: %s' % compat_str(err))
  2323. return
  2324. streams = json.loads(stream_json)
  2325. mediaURL = streams['http_mp3_128_url']
  2326. return [{
  2327. 'id': info['id'],
  2328. 'url': mediaURL,
  2329. 'uploader': info['user']['username'],
  2330. 'upload_date': info['created_at'],
  2331. 'title': info['title'],
  2332. 'ext': u'mp3',
  2333. 'description': info['description'],
  2334. }]
  2335. class InfoQIE(InfoExtractor):
  2336. """Information extractor for infoq.com"""
  2337. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2338. def report_extraction(self, video_id):
  2339. """Report information extraction."""
  2340. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2341. def _real_extract(self, url):
  2342. mobj = re.match(self._VALID_URL, url)
  2343. if mobj is None:
  2344. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2345. return
  2346. webpage = self._download_webpage(url, video_id=url)
  2347. self.report_extraction(url)
  2348. # Extract video URL
  2349. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2350. if mobj is None:
  2351. self._downloader.trouble(u'ERROR: unable to extract video url')
  2352. return
  2353. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  2354. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  2355. # Extract title
  2356. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2357. if mobj is None:
  2358. self._downloader.trouble(u'ERROR: unable to extract video title')
  2359. return
  2360. video_title = mobj.group(1)
  2361. # Extract description
  2362. video_description = u'No description available.'
  2363. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2364. if mobj is not None:
  2365. video_description = mobj.group(1)
  2366. video_filename = video_url.split('/')[-1]
  2367. video_id, extension = video_filename.split('.')
  2368. info = {
  2369. 'id': video_id,
  2370. 'url': video_url,
  2371. 'uploader': None,
  2372. 'upload_date': None,
  2373. 'title': video_title,
  2374. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2375. 'thumbnail': None,
  2376. 'description': video_description,
  2377. }
  2378. return [info]
  2379. class MixcloudIE(InfoExtractor):
  2380. """Information extractor for www.mixcloud.com"""
  2381. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2382. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2383. IE_NAME = u'mixcloud'
  2384. def __init__(self, downloader=None):
  2385. InfoExtractor.__init__(self, downloader)
  2386. def report_download_json(self, file_id):
  2387. """Report JSON download."""
  2388. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2389. def report_extraction(self, file_id):
  2390. """Report information extraction."""
  2391. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2392. def get_urls(self, jsonData, fmt, bitrate='best'):
  2393. """Get urls from 'audio_formats' section in json"""
  2394. file_url = None
  2395. try:
  2396. bitrate_list = jsonData[fmt]
  2397. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2398. bitrate = max(bitrate_list) # select highest
  2399. url_list = jsonData[fmt][bitrate]
  2400. except TypeError: # we have no bitrate info.
  2401. url_list = jsonData[fmt]
  2402. return url_list
  2403. def check_urls(self, url_list):
  2404. """Returns 1st active url from list"""
  2405. for url in url_list:
  2406. try:
  2407. compat_urllib_request.urlopen(url)
  2408. return url
  2409. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2410. url = None
  2411. return None
  2412. def _print_formats(self, formats):
  2413. print('Available formats:')
  2414. for fmt in formats.keys():
  2415. for b in formats[fmt]:
  2416. try:
  2417. ext = formats[fmt][b][0]
  2418. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2419. except TypeError: # we have no bitrate info
  2420. ext = formats[fmt][0]
  2421. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2422. break
  2423. def _real_extract(self, url):
  2424. mobj = re.match(self._VALID_URL, url)
  2425. if mobj is None:
  2426. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2427. return
  2428. # extract uploader & filename from url
  2429. uploader = mobj.group(1).decode('utf-8')
  2430. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2431. # construct API request
  2432. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2433. # retrieve .json file with links to files
  2434. request = compat_urllib_request.Request(file_url)
  2435. try:
  2436. self.report_download_json(file_url)
  2437. jsonData = compat_urllib_request.urlopen(request).read()
  2438. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2439. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % compat_str(err))
  2440. return
  2441. # parse JSON
  2442. json_data = json.loads(jsonData)
  2443. player_url = json_data['player_swf_url']
  2444. formats = dict(json_data['audio_formats'])
  2445. req_format = self._downloader.params.get('format', None)
  2446. bitrate = None
  2447. if self._downloader.params.get('listformats', None):
  2448. self._print_formats(formats)
  2449. return
  2450. if req_format is None or req_format == 'best':
  2451. for format_param in formats.keys():
  2452. url_list = self.get_urls(formats, format_param)
  2453. # check urls
  2454. file_url = self.check_urls(url_list)
  2455. if file_url is not None:
  2456. break # got it!
  2457. else:
  2458. if req_format not in formats:
  2459. self._downloader.trouble(u'ERROR: format is not available')
  2460. return
  2461. url_list = self.get_urls(formats, req_format)
  2462. file_url = self.check_urls(url_list)
  2463. format_param = req_format
  2464. return [{
  2465. 'id': file_id.decode('utf-8'),
  2466. 'url': file_url.decode('utf-8'),
  2467. 'uploader': uploader.decode('utf-8'),
  2468. 'upload_date': None,
  2469. 'title': json_data['name'],
  2470. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2471. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2472. 'thumbnail': json_data['thumbnail_url'],
  2473. 'description': json_data['description'],
  2474. 'player_url': player_url.decode('utf-8'),
  2475. }]
  2476. class StanfordOpenClassroomIE(InfoExtractor):
  2477. """Information extractor for Stanford's Open ClassRoom"""
  2478. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2479. IE_NAME = u'stanfordoc'
  2480. def report_download_webpage(self, objid):
  2481. """Report information extraction."""
  2482. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2483. def report_extraction(self, video_id):
  2484. """Report information extraction."""
  2485. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2486. def _real_extract(self, url):
  2487. mobj = re.match(self._VALID_URL, url)
  2488. if mobj is None:
  2489. raise ExtractorError(u'Invalid URL: %s' % url)
  2490. if mobj.group('course') and mobj.group('video'): # A specific video
  2491. course = mobj.group('course')
  2492. video = mobj.group('video')
  2493. info = {
  2494. 'id': course + '_' + video,
  2495. 'uploader': None,
  2496. 'upload_date': None,
  2497. }
  2498. self.report_extraction(info['id'])
  2499. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2500. xmlUrl = baseUrl + video + '.xml'
  2501. try:
  2502. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2503. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2504. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2505. return
  2506. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2507. try:
  2508. info['title'] = mdoc.findall('./title')[0].text
  2509. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2510. except IndexError:
  2511. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2512. return
  2513. info['ext'] = info['url'].rpartition('.')[2]
  2514. return [info]
  2515. elif mobj.group('course'): # A course page
  2516. course = mobj.group('course')
  2517. info = {
  2518. 'id': course,
  2519. 'type': 'playlist',
  2520. 'uploader': None,
  2521. 'upload_date': None,
  2522. }
  2523. coursepage = self._download_webpage(url, info['id'],
  2524. note='Downloading course info page',
  2525. errnote='Unable to download course info page')
  2526. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2527. if m:
  2528. info['title'] = unescapeHTML(m.group(1))
  2529. else:
  2530. info['title'] = info['id']
  2531. m = re.search('<description>([^<]+)</description>', coursepage)
  2532. if m:
  2533. info['description'] = unescapeHTML(m.group(1))
  2534. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2535. info['list'] = [
  2536. {
  2537. 'type': 'reference',
  2538. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2539. }
  2540. for vpage in links]
  2541. results = []
  2542. for entry in info['list']:
  2543. assert entry['type'] == 'reference'
  2544. results += self.extract(entry['url'])
  2545. return results
  2546. else: # Root page
  2547. info = {
  2548. 'id': 'Stanford OpenClassroom',
  2549. 'type': 'playlist',
  2550. 'uploader': None,
  2551. 'upload_date': None,
  2552. }
  2553. self.report_download_webpage(info['id'])
  2554. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2555. try:
  2556. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2557. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2558. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2559. return
  2560. info['title'] = info['id']
  2561. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2562. info['list'] = [
  2563. {
  2564. 'type': 'reference',
  2565. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2566. }
  2567. for cpage in links]
  2568. results = []
  2569. for entry in info['list']:
  2570. assert entry['type'] == 'reference'
  2571. results += self.extract(entry['url'])
  2572. return results
  2573. class MTVIE(InfoExtractor):
  2574. """Information extractor for MTV.com"""
  2575. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2576. IE_NAME = u'mtv'
  2577. def report_extraction(self, video_id):
  2578. """Report information extraction."""
  2579. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2580. def _real_extract(self, url):
  2581. mobj = re.match(self._VALID_URL, url)
  2582. if mobj is None:
  2583. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2584. return
  2585. if not mobj.group('proto'):
  2586. url = 'http://' + url
  2587. video_id = mobj.group('videoid')
  2588. webpage = self._download_webpage(url, video_id)
  2589. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2590. if mobj is None:
  2591. self._downloader.trouble(u'ERROR: unable to extract song name')
  2592. return
  2593. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2594. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2595. if mobj is None:
  2596. self._downloader.trouble(u'ERROR: unable to extract performer')
  2597. return
  2598. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2599. video_title = performer + ' - ' + song_name
  2600. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2601. if mobj is None:
  2602. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2603. return
  2604. mtvn_uri = mobj.group(1)
  2605. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2606. if mobj is None:
  2607. self._downloader.trouble(u'ERROR: unable to extract content id')
  2608. return
  2609. content_id = mobj.group(1)
  2610. videogen_url = 'http://www.mtv.com/player/includes/mediaGen.jhtml?uri=' + mtvn_uri + '&id=' + content_id + '&vid=' + video_id + '&ref=www.mtvn.com&viewUri=' + mtvn_uri
  2611. self.report_extraction(video_id)
  2612. request = compat_urllib_request.Request(videogen_url)
  2613. try:
  2614. metadataXml = compat_urllib_request.urlopen(request).read()
  2615. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2616. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % compat_str(err))
  2617. return
  2618. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2619. renditions = mdoc.findall('.//rendition')
  2620. # For now, always pick the highest quality.
  2621. rendition = renditions[-1]
  2622. try:
  2623. _,_,ext = rendition.attrib['type'].partition('/')
  2624. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2625. video_url = rendition.find('./src').text
  2626. except KeyError:
  2627. self._downloader.trouble('Invalid rendition field.')
  2628. return
  2629. info = {
  2630. 'id': video_id,
  2631. 'url': video_url,
  2632. 'uploader': performer,
  2633. 'upload_date': None,
  2634. 'title': video_title,
  2635. 'ext': ext,
  2636. 'format': format,
  2637. }
  2638. return [info]
  2639. class YoukuIE(InfoExtractor):
  2640. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2641. def report_download_webpage(self, file_id):
  2642. """Report webpage download."""
  2643. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, file_id))
  2644. def report_extraction(self, file_id):
  2645. """Report information extraction."""
  2646. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2647. def _gen_sid(self):
  2648. nowTime = int(time.time() * 1000)
  2649. random1 = random.randint(1000,1998)
  2650. random2 = random.randint(1000,9999)
  2651. return "%d%d%d" %(nowTime,random1,random2)
  2652. def _get_file_ID_mix_string(self, seed):
  2653. mixed = []
  2654. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2655. seed = float(seed)
  2656. for i in range(len(source)):
  2657. seed = (seed * 211 + 30031 ) % 65536
  2658. index = math.floor(seed / 65536 * len(source) )
  2659. mixed.append(source[int(index)])
  2660. source.remove(source[int(index)])
  2661. #return ''.join(mixed)
  2662. return mixed
  2663. def _get_file_id(self, fileId, seed):
  2664. mixed = self._get_file_ID_mix_string(seed)
  2665. ids = fileId.split('*')
  2666. realId = []
  2667. for ch in ids:
  2668. if ch:
  2669. realId.append(mixed[int(ch)])
  2670. return ''.join(realId)
  2671. def _real_extract(self, url):
  2672. mobj = re.match(self._VALID_URL, url)
  2673. if mobj is None:
  2674. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2675. return
  2676. video_id = mobj.group('ID')
  2677. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2678. request = compat_urllib_request.Request(info_url, None, std_headers)
  2679. try:
  2680. self.report_download_webpage(video_id)
  2681. jsondata = compat_urllib_request.urlopen(request).read()
  2682. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2683. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2684. return
  2685. self.report_extraction(video_id)
  2686. try:
  2687. jsonstr = jsondata.decode('utf-8')
  2688. config = json.loads(jsonstr)
  2689. video_title = config['data'][0]['title']
  2690. seed = config['data'][0]['seed']
  2691. format = self._downloader.params.get('format', None)
  2692. supported_format = list(config['data'][0]['streamfileids'].keys())
  2693. if format is None or format == 'best':
  2694. if 'hd2' in supported_format:
  2695. format = 'hd2'
  2696. else:
  2697. format = 'flv'
  2698. ext = u'flv'
  2699. elif format == 'worst':
  2700. format = 'mp4'
  2701. ext = u'mp4'
  2702. else:
  2703. format = 'flv'
  2704. ext = u'flv'
  2705. fileid = config['data'][0]['streamfileids'][format]
  2706. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2707. except (UnicodeDecodeError, ValueError, KeyError):
  2708. self._downloader.trouble(u'ERROR: unable to extract info section')
  2709. return
  2710. files_info=[]
  2711. sid = self._gen_sid()
  2712. fileid = self._get_file_id(fileid, seed)
  2713. #column 8,9 of fileid represent the segment number
  2714. #fileid[7:9] should be changed
  2715. for index, key in enumerate(keys):
  2716. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2717. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2718. info = {
  2719. 'id': '%s_part%02d' % (video_id, index),
  2720. 'url': download_url,
  2721. 'uploader': None,
  2722. 'upload_date': None,
  2723. 'title': video_title,
  2724. 'ext': ext,
  2725. }
  2726. files_info.append(info)
  2727. return files_info
  2728. class XNXXIE(InfoExtractor):
  2729. """Information extractor for xnxx.com"""
  2730. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  2731. IE_NAME = u'xnxx'
  2732. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2733. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2734. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2735. def report_webpage(self, video_id):
  2736. """Report information extraction"""
  2737. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2738. def report_extraction(self, video_id):
  2739. """Report information extraction"""
  2740. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2741. def _real_extract(self, url):
  2742. mobj = re.match(self._VALID_URL, url)
  2743. if mobj is None:
  2744. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2745. return
  2746. video_id = mobj.group(1)
  2747. self.report_webpage(video_id)
  2748. # Get webpage content
  2749. try:
  2750. webpage_bytes = compat_urllib_request.urlopen(url).read()
  2751. webpage = webpage_bytes.decode('utf-8')
  2752. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2753. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2754. return
  2755. result = re.search(self.VIDEO_URL_RE, webpage)
  2756. if result is None:
  2757. self._downloader.trouble(u'ERROR: unable to extract video url')
  2758. return
  2759. video_url = compat_urllib_parse.unquote(result.group(1))
  2760. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2761. if result is None:
  2762. self._downloader.trouble(u'ERROR: unable to extract video title')
  2763. return
  2764. video_title = result.group(1)
  2765. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2766. if result is None:
  2767. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2768. return
  2769. video_thumbnail = result.group(1)
  2770. return [{
  2771. 'id': video_id,
  2772. 'url': video_url,
  2773. 'uploader': None,
  2774. 'upload_date': None,
  2775. 'title': video_title,
  2776. 'ext': 'flv',
  2777. 'thumbnail': video_thumbnail,
  2778. 'description': None,
  2779. }]
  2780. class GooglePlusIE(InfoExtractor):
  2781. """Information extractor for plus.google.com."""
  2782. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2783. IE_NAME = u'plus.google'
  2784. def __init__(self, downloader=None):
  2785. InfoExtractor.__init__(self, downloader)
  2786. def report_extract_entry(self, url):
  2787. """Report downloading extry"""
  2788. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url)
  2789. def report_date(self, upload_date):
  2790. """Report downloading extry"""
  2791. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2792. def report_uploader(self, uploader):
  2793. """Report downloading extry"""
  2794. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader)
  2795. def report_title(self, video_title):
  2796. """Report downloading extry"""
  2797. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title)
  2798. def report_extract_vid_page(self, video_page):
  2799. """Report information extraction."""
  2800. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page)
  2801. def _real_extract(self, url):
  2802. # Extract id from URL
  2803. mobj = re.match(self._VALID_URL, url)
  2804. if mobj is None:
  2805. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  2806. return
  2807. post_url = mobj.group(0)
  2808. video_id = mobj.group(1)
  2809. video_extension = 'flv'
  2810. # Step 1, Retrieve post webpage to extract further information
  2811. self.report_extract_entry(post_url)
  2812. request = compat_urllib_request.Request(post_url)
  2813. try:
  2814. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2815. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2816. self._downloader.trouble(u'ERROR: Unable to retrieve entry webpage: %s' % compat_str(err))
  2817. return
  2818. # Extract update date
  2819. upload_date = None
  2820. pattern = 'title="Timestamp">(.*?)</a>'
  2821. mobj = re.search(pattern, webpage)
  2822. if mobj:
  2823. upload_date = mobj.group(1)
  2824. # Convert timestring to a format suitable for filename
  2825. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2826. upload_date = upload_date.strftime('%Y%m%d')
  2827. self.report_date(upload_date)
  2828. # Extract uploader
  2829. uploader = None
  2830. pattern = r'rel\="author".*?>(.*?)</a>'
  2831. mobj = re.search(pattern, webpage)
  2832. if mobj:
  2833. uploader = mobj.group(1)
  2834. self.report_uploader(uploader)
  2835. # Extract title
  2836. # Get the first line for title
  2837. video_title = u'NA'
  2838. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2839. mobj = re.search(pattern, webpage)
  2840. if mobj:
  2841. video_title = mobj.group(1)
  2842. self.report_title(video_title)
  2843. # Step 2, Stimulate clicking the image box to launch video
  2844. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2845. mobj = re.search(pattern, webpage)
  2846. if mobj is None:
  2847. self._downloader.trouble(u'ERROR: unable to extract video page URL')
  2848. video_page = mobj.group(1)
  2849. request = compat_urllib_request.Request(video_page)
  2850. try:
  2851. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2852. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2853. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2854. return
  2855. self.report_extract_vid_page(video_page)
  2856. # Extract video links on video page
  2857. """Extract video links of all sizes"""
  2858. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2859. mobj = re.findall(pattern, webpage)
  2860. if len(mobj) == 0:
  2861. self._downloader.trouble(u'ERROR: unable to extract video links')
  2862. # Sort in resolution
  2863. links = sorted(mobj)
  2864. # Choose the lowest of the sort, i.e. highest resolution
  2865. video_url = links[-1]
  2866. # Only get the url. The resolution part in the tuple has no use anymore
  2867. video_url = video_url[-1]
  2868. # Treat escaped \u0026 style hex
  2869. try:
  2870. video_url = video_url.decode("unicode_escape")
  2871. except AttributeError: # Python 3
  2872. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2873. return [{
  2874. 'id': video_id,
  2875. 'url': video_url,
  2876. 'uploader': uploader,
  2877. 'upload_date': upload_date,
  2878. 'title': video_title,
  2879. 'ext': video_extension,
  2880. }]
  2881. class NBAIE(InfoExtractor):
  2882. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*)(\?.*)?$'
  2883. IE_NAME = u'nba'
  2884. def _real_extract(self, url):
  2885. mobj = re.match(self._VALID_URL, url)
  2886. if mobj is None:
  2887. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2888. return
  2889. video_id = mobj.group(1)
  2890. if video_id.endswith('/index.html'):
  2891. video_id = video_id[:-len('/index.html')]
  2892. webpage = self._download_webpage(url, video_id)
  2893. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2894. def _findProp(rexp, default=None):
  2895. m = re.search(rexp, webpage)
  2896. if m:
  2897. return unescapeHTML(m.group(1))
  2898. else:
  2899. return default
  2900. shortened_video_id = video_id.rpartition('/')[2]
  2901. title = _findProp(r'<meta property="og:title" content="(.*?)"', shortened_video_id).replace('NBA.com: ', '')
  2902. info = {
  2903. 'id': shortened_video_id,
  2904. 'url': video_url,
  2905. 'ext': 'mp4',
  2906. 'title': title,
  2907. 'uploader_date': _findProp(r'<b>Date:</b> (.*?)</div>'),
  2908. 'description': _findProp(r'<div class="description">(.*?)</h1>'),
  2909. }
  2910. return [info]
  2911. class JustinTVIE(InfoExtractor):
  2912. """Information extractor for justin.tv and twitch.tv"""
  2913. # TODO: One broadcast may be split into multiple videos. The key
  2914. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2915. # starts at 1 and increases. Can we treat all parts as one video?
  2916. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2917. ([^/]+)(?:/b/([^/]+))?/?(?:\#.*)?$"""
  2918. _JUSTIN_PAGE_LIMIT = 100
  2919. IE_NAME = u'justin.tv'
  2920. def report_extraction(self, file_id):
  2921. """Report information extraction."""
  2922. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2923. def report_download_page(self, channel, offset):
  2924. """Report attempt to download a single page of videos."""
  2925. self._downloader.to_screen(u'[%s] %s: Downloading video information from %d to %d' %
  2926. (self.IE_NAME, channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  2927. # Return count of items, list of *valid* items
  2928. def _parse_page(self, url):
  2929. try:
  2930. urlh = compat_urllib_request.urlopen(url)
  2931. webpage_bytes = urlh.read()
  2932. webpage = webpage_bytes.decode('utf-8', 'ignore')
  2933. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2934. self._downloader.trouble(u'ERROR: unable to download video info JSON: %s' % compat_str(err))
  2935. return
  2936. response = json.loads(webpage)
  2937. if type(response) != list:
  2938. error_text = response.get('error', 'unknown error')
  2939. self._downloader.trouble(u'ERROR: Justin.tv API: %s' % error_text)
  2940. return
  2941. info = []
  2942. for clip in response:
  2943. video_url = clip['video_file_url']
  2944. if video_url:
  2945. video_extension = os.path.splitext(video_url)[1][1:]
  2946. video_date = re.sub('-', '', clip['start_time'][:10])
  2947. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  2948. video_id = clip['id']
  2949. video_title = clip.get('title', video_id)
  2950. info.append({
  2951. 'id': video_id,
  2952. 'url': video_url,
  2953. 'title': video_title,
  2954. 'uploader': clip.get('channel_name', video_uploader_id),
  2955. 'uploader_id': video_uploader_id,
  2956. 'upload_date': video_date,
  2957. 'ext': video_extension,
  2958. })
  2959. return (len(response), info)
  2960. def _real_extract(self, url):
  2961. mobj = re.match(self._VALID_URL, url)
  2962. if mobj is None:
  2963. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2964. return
  2965. api = 'http://api.justin.tv'
  2966. video_id = mobj.group(mobj.lastindex)
  2967. paged = False
  2968. if mobj.lastindex == 1:
  2969. paged = True
  2970. api += '/channel/archives/%s.json'
  2971. else:
  2972. api += '/broadcast/by_archive/%s.json'
  2973. api = api % (video_id,)
  2974. self.report_extraction(video_id)
  2975. info = []
  2976. offset = 0
  2977. limit = self._JUSTIN_PAGE_LIMIT
  2978. while True:
  2979. if paged:
  2980. self.report_download_page(video_id, offset)
  2981. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  2982. page_count, page_info = self._parse_page(page_url)
  2983. info.extend(page_info)
  2984. if not paged or page_count != limit:
  2985. break
  2986. offset += limit
  2987. return info
  2988. class FunnyOrDieIE(InfoExtractor):
  2989. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  2990. def _real_extract(self, url):
  2991. mobj = re.match(self._VALID_URL, url)
  2992. if mobj is None:
  2993. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2994. return
  2995. video_id = mobj.group('id')
  2996. webpage = self._download_webpage(url, video_id)
  2997. m = re.search(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"', webpage, re.DOTALL)
  2998. if not m:
  2999. self._downloader.trouble(u'ERROR: unable to find video information')
  3000. video_url = unescapeHTML(m.group('url'))
  3001. m = re.search(r"class='player_page_h1'>\s+<a.*?>(?P<title>.*?)</a>", webpage)
  3002. if not m:
  3003. self._downloader.trouble(u'Cannot find video title')
  3004. title = unescapeHTML(m.group('title'))
  3005. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3006. if m:
  3007. desc = unescapeHTML(m.group('desc'))
  3008. else:
  3009. desc = None
  3010. info = {
  3011. 'id': video_id,
  3012. 'url': video_url,
  3013. 'ext': 'mp4',
  3014. 'title': title,
  3015. 'description': desc,
  3016. }
  3017. return [info]
  3018. class SteamIE(InfoExtractor):
  3019. _VALID_URL = r"""http://store.steampowered.com/
  3020. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  3021. (?P<gameID>\d+)/?
  3022. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  3023. """
  3024. @classmethod
  3025. def suitable(cls, url):
  3026. """Receives a URL and returns True if suitable for this IE."""
  3027. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3028. def _real_extract(self, url):
  3029. m = re.match(self._VALID_URL, url, re.VERBOSE)
  3030. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  3031. gameID = m.group('gameID')
  3032. videourl = 'http://store.steampowered.com/video/%s/' % gameID
  3033. webpage = self._download_webpage(videourl, gameID)
  3034. mweb = re.finditer(urlRE, webpage)
  3035. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  3036. titles = re.finditer(namesRE, webpage)
  3037. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  3038. thumbs = re.finditer(thumbsRE, webpage)
  3039. videos = []
  3040. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  3041. video_id = vid.group('videoID')
  3042. title = vtitle.group('videoName')
  3043. video_url = vid.group('videoURL')
  3044. video_thumb = thumb.group('thumbnail')
  3045. if not video_url:
  3046. self._downloader.trouble(u'ERROR: Cannot find video url for %s' % video_id)
  3047. info = {
  3048. 'id':video_id,
  3049. 'url':video_url,
  3050. 'ext': 'flv',
  3051. 'title': unescapeHTML(title),
  3052. 'thumbnail': video_thumb
  3053. }
  3054. videos.append(info)
  3055. return videos
  3056. class UstreamIE(InfoExtractor):
  3057. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  3058. IE_NAME = u'ustream'
  3059. def _real_extract(self, url):
  3060. m = re.match(self._VALID_URL, url)
  3061. video_id = m.group('videoID')
  3062. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  3063. webpage = self._download_webpage(url, video_id)
  3064. m = re.search(r'data-title="(?P<title>.+)"',webpage)
  3065. title = m.group('title')
  3066. m = re.search(r'<a class="state" data-content-type="channel" data-content-id="(?P<uploader>\d+)"',webpage)
  3067. uploader = m.group('uploader')
  3068. info = {
  3069. 'id':video_id,
  3070. 'url':video_url,
  3071. 'ext': 'flv',
  3072. 'title': title,
  3073. 'uploader': uploader
  3074. }
  3075. return [info]
  3076. class RBMARadioIE(InfoExtractor):
  3077. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  3078. def _real_extract(self, url):
  3079. m = re.match(self._VALID_URL, url)
  3080. video_id = m.group('videoID')
  3081. webpage = self._download_webpage(url, video_id)
  3082. m = re.search(r'<script>window.gon = {.*?};gon\.show=(.+?);</script>', webpage)
  3083. if not m:
  3084. raise ExtractorError(u'Cannot find metadata')
  3085. json_data = m.group(1)
  3086. try:
  3087. data = json.loads(json_data)
  3088. except ValueError as e:
  3089. raise ExtractorError(u'Invalid JSON: ' + str(e))
  3090. video_url = data['akamai_url'] + '&cbr=256'
  3091. url_parts = compat_urllib_parse_urlparse(video_url)
  3092. video_ext = url_parts.path.rpartition('.')[2]
  3093. info = {
  3094. 'id': video_id,
  3095. 'url': video_url,
  3096. 'ext': video_ext,
  3097. 'title': data['title'],
  3098. 'description': data.get('teaser_text'),
  3099. 'location': data.get('country_of_origin'),
  3100. 'uploader': data.get('host', {}).get('name'),
  3101. 'uploader_id': data.get('host', {}).get('slug'),
  3102. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  3103. 'duration': data.get('duration'),
  3104. }
  3105. return [info]
  3106. class YouPornIE(InfoExtractor):
  3107. """Information extractor for youporn.com."""
  3108. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  3109. def _print_formats(self, formats):
  3110. """Print all available formats"""
  3111. print(u'Available formats:')
  3112. print(u'ext\t\tformat')
  3113. print(u'---------------------------------')
  3114. for format in formats:
  3115. print(u'%s\t\t%s' % (format['ext'], format['format']))
  3116. def _specific(self, req_format, formats):
  3117. for x in formats:
  3118. if(x["format"]==req_format):
  3119. return x
  3120. return None
  3121. def _real_extract(self, url):
  3122. mobj = re.match(self._VALID_URL, url)
  3123. if mobj is None:
  3124. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3125. return
  3126. video_id = mobj.group('videoid')
  3127. req = compat_urllib_request.Request(url)
  3128. req.add_header('Cookie', 'age_verified=1')
  3129. webpage = self._download_webpage(req, video_id)
  3130. # Get the video title
  3131. result = re.search(r'<h1.*?>(?P<title>.*)</h1>', webpage)
  3132. if result is None:
  3133. raise ExtractorError(u'Unable to extract video title')
  3134. video_title = result.group('title').strip()
  3135. # Get the video date
  3136. result = re.search(r'Date:</label>(?P<date>.*) </li>', webpage)
  3137. if result is None:
  3138. self._downloader.report_warning(u'unable to extract video date')
  3139. upload_date = None
  3140. else:
  3141. upload_date = result.group('date').strip()
  3142. # Get the video uploader
  3143. result = re.search(r'Submitted:</label>(?P<uploader>.*)</li>', webpage)
  3144. if result is None:
  3145. self._downloader.report_warning(u'unable to extract uploader')
  3146. video_uploader = None
  3147. else:
  3148. video_uploader = result.group('uploader').strip()
  3149. video_uploader = clean_html( video_uploader )
  3150. # Get all of the formats available
  3151. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  3152. result = re.search(DOWNLOAD_LIST_RE, webpage)
  3153. if result is None:
  3154. raise ExtractorError(u'Unable to extract download list')
  3155. download_list_html = result.group('download_list').strip()
  3156. # Get all of the links from the page
  3157. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  3158. links = re.findall(LINK_RE, download_list_html)
  3159. if(len(links) == 0):
  3160. raise ExtractorError(u'ERROR: no known formats available for video')
  3161. self._downloader.to_screen(u'[youporn] Links found: %d' % len(links))
  3162. formats = []
  3163. for link in links:
  3164. # A link looks like this:
  3165. # http://cdn1.download.youporn.phncdn.com/201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4?nvb=20121113051249&nva=20121114051249&ir=1200&sr=1200&hash=014b882080310e95fb6a0
  3166. # A path looks like this:
  3167. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  3168. video_url = unescapeHTML( link )
  3169. path = compat_urllib_parse_urlparse( video_url ).path
  3170. extension = os.path.splitext( path )[1][1:]
  3171. format = path.split('/')[4].split('_')[:2]
  3172. size = format[0]
  3173. bitrate = format[1]
  3174. format = "-".join( format )
  3175. title = u'%s-%s-%s' % (video_title, size, bitrate)
  3176. formats.append({
  3177. 'id': video_id,
  3178. 'url': video_url,
  3179. 'uploader': video_uploader,
  3180. 'upload_date': upload_date,
  3181. 'title': title,
  3182. 'ext': extension,
  3183. 'format': format,
  3184. 'thumbnail': None,
  3185. 'description': None,
  3186. 'player_url': None
  3187. })
  3188. if self._downloader.params.get('listformats', None):
  3189. self._print_formats(formats)
  3190. return
  3191. req_format = self._downloader.params.get('format', None)
  3192. self._downloader.to_screen(u'[youporn] Format: %s' % req_format)
  3193. if req_format is None or req_format == 'best':
  3194. return [formats[0]]
  3195. elif req_format == 'worst':
  3196. return [formats[-1]]
  3197. elif req_format in ('-1', 'all'):
  3198. return formats
  3199. else:
  3200. format = self._specific( req_format, formats )
  3201. if result is None:
  3202. self._downloader.trouble(u'ERROR: requested format not available')
  3203. return
  3204. return [format]
  3205. class PornotubeIE(InfoExtractor):
  3206. """Information extractor for pornotube.com."""
  3207. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  3208. def _real_extract(self, url):
  3209. mobj = re.match(self._VALID_URL, url)
  3210. if mobj is None:
  3211. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3212. return
  3213. video_id = mobj.group('videoid')
  3214. video_title = mobj.group('title')
  3215. # Get webpage content
  3216. webpage = self._download_webpage(url, video_id)
  3217. # Get the video URL
  3218. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  3219. result = re.search(VIDEO_URL_RE, webpage)
  3220. if result is None:
  3221. self._downloader.trouble(u'ERROR: unable to extract video url')
  3222. return
  3223. video_url = compat_urllib_parse.unquote(result.group('url'))
  3224. #Get the uploaded date
  3225. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  3226. result = re.search(VIDEO_UPLOADED_RE, webpage)
  3227. if result is None:
  3228. self._downloader.trouble(u'ERROR: unable to extract video title')
  3229. return
  3230. upload_date = result.group('date')
  3231. info = {'id': video_id,
  3232. 'url': video_url,
  3233. 'uploader': None,
  3234. 'upload_date': upload_date,
  3235. 'title': video_title,
  3236. 'ext': 'flv',
  3237. 'format': 'flv'}
  3238. return [info]
  3239. class YouJizzIE(InfoExtractor):
  3240. """Information extractor for youjizz.com."""
  3241. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  3242. def _real_extract(self, url):
  3243. mobj = re.match(self._VALID_URL, url)
  3244. if mobj is None:
  3245. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3246. return
  3247. video_id = mobj.group('videoid')
  3248. # Get webpage content
  3249. webpage = self._download_webpage(url, video_id)
  3250. # Get the video title
  3251. result = re.search(r'<title>(?P<title>.*)</title>', webpage)
  3252. if result is None:
  3253. raise ExtractorError(u'ERROR: unable to extract video title')
  3254. video_title = result.group('title').strip()
  3255. # Get the embed page
  3256. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  3257. if result is None:
  3258. raise ExtractorError(u'ERROR: unable to extract embed page')
  3259. embed_page_url = result.group(0).strip()
  3260. video_id = result.group('videoid')
  3261. webpage = self._download_webpage(embed_page_url, video_id)
  3262. # Get the video URL
  3263. result = re.search(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);', webpage)
  3264. if result is None:
  3265. raise ExtractorError(u'ERROR: unable to extract video url')
  3266. video_url = result.group('source')
  3267. info = {'id': video_id,
  3268. 'url': video_url,
  3269. 'title': video_title,
  3270. 'ext': 'flv',
  3271. 'format': 'flv',
  3272. 'player_url': embed_page_url}
  3273. return [info]
  3274. class EightTracksIE(InfoExtractor):
  3275. IE_NAME = '8tracks'
  3276. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  3277. def _real_extract(self, url):
  3278. mobj = re.match(self._VALID_URL, url)
  3279. if mobj is None:
  3280. raise ExtractorError(u'Invalid URL: %s' % url)
  3281. playlist_id = mobj.group('id')
  3282. webpage = self._download_webpage(url, playlist_id)
  3283. m = re.search(r"PAGE.mix = (.*?);\n", webpage, flags=re.DOTALL)
  3284. if not m:
  3285. raise ExtractorError(u'Cannot find trax information')
  3286. json_like = m.group(1)
  3287. data = json.loads(json_like)
  3288. session = str(random.randint(0, 1000000000))
  3289. mix_id = data['id']
  3290. track_count = data['tracks_count']
  3291. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  3292. next_url = first_url
  3293. res = []
  3294. for i in itertools.count():
  3295. api_json = self._download_webpage(next_url, playlist_id,
  3296. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  3297. errnote=u'Failed to download song information')
  3298. api_data = json.loads(api_json)
  3299. track_data = api_data[u'set']['track']
  3300. info = {
  3301. 'id': track_data['id'],
  3302. 'url': track_data['track_file_stream_url'],
  3303. 'title': track_data['performer'] + u' - ' + track_data['name'],
  3304. 'raw_title': track_data['name'],
  3305. 'uploader_id': data['user']['login'],
  3306. 'ext': 'm4a',
  3307. }
  3308. res.append(info)
  3309. if api_data['set']['at_last_track']:
  3310. break
  3311. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  3312. return res
  3313. class KeekIE(InfoExtractor):
  3314. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  3315. IE_NAME = u'keek'
  3316. def _real_extract(self, url):
  3317. m = re.match(self._VALID_URL, url)
  3318. video_id = m.group('videoID')
  3319. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  3320. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  3321. webpage = self._download_webpage(url, video_id)
  3322. m = re.search(r'<meta property="og:title" content="(?P<title>.+)"', webpage)
  3323. title = unescapeHTML(m.group('title'))
  3324. m = re.search(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>', webpage)
  3325. uploader = clean_html(m.group('uploader'))
  3326. info = {
  3327. 'id': video_id,
  3328. 'url': video_url,
  3329. 'ext': 'mp4',
  3330. 'title': title,
  3331. 'thumbnail': thumbnail,
  3332. 'uploader': uploader
  3333. }
  3334. return [info]
  3335. class TEDIE(InfoExtractor):
  3336. _VALID_URL=r'''http://www.ted.com/
  3337. (
  3338. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  3339. |
  3340. ((?P<type_talk>talks)) # We have a simple talk
  3341. )
  3342. /(?P<name>\w+) # Here goes the name and then ".html"
  3343. '''
  3344. @classmethod
  3345. def suitable(cls, url):
  3346. """Receives a URL and returns True if suitable for this IE."""
  3347. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3348. def _real_extract(self, url):
  3349. m=re.match(self._VALID_URL, url, re.VERBOSE)
  3350. if m.group('type_talk'):
  3351. return [self._talk_info(url)]
  3352. else :
  3353. playlist_id=m.group('playlist_id')
  3354. name=m.group('name')
  3355. self._downloader.to_screen(u'[%s] Getting info of playlist %s: "%s"' % (self.IE_NAME,playlist_id,name))
  3356. return self._playlist_videos_info(url,name,playlist_id)
  3357. def _talk_video_link(self,mediaSlug):
  3358. '''Returns the video link for that mediaSlug'''
  3359. return 'http://download.ted.com/talks/%s.mp4' % mediaSlug
  3360. def _playlist_videos_info(self,url,name,playlist_id=0):
  3361. '''Returns the videos of the playlist'''
  3362. video_RE=r'''
  3363. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  3364. ([.\s]*?)data-playlist_item_id="(\d+)"
  3365. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  3366. '''
  3367. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  3368. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  3369. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  3370. m_names=re.finditer(video_name_RE,webpage)
  3371. info=[]
  3372. for m_video, m_name in zip(m_videos,m_names):
  3373. video_id=m_video.group('video_id')
  3374. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  3375. info.append(self._talk_info(talk_url,video_id))
  3376. return info
  3377. def _talk_info(self, url, video_id=0):
  3378. """Return the video for the talk in the url"""
  3379. m=re.match(self._VALID_URL, url,re.VERBOSE)
  3380. videoName=m.group('name')
  3381. webpage=self._download_webpage(url, video_id, 'Downloading \"%s\" page' % videoName)
  3382. # If the url includes the language we get the title translated
  3383. title_RE=r'<h1><span id="altHeadline" >(?P<title>.*)</span></h1>'
  3384. title=re.search(title_RE, webpage).group('title')
  3385. info_RE=r'''<script\ type="text/javascript">var\ talkDetails\ =(.*?)
  3386. "id":(?P<videoID>[\d]+).*?
  3387. "mediaSlug":"(?P<mediaSlug>[\w\d]+?)"'''
  3388. thumb_RE=r'</span>[\s.]*</div>[\s.]*<img src="(?P<thumbnail>.*?)"'
  3389. thumb_match=re.search(thumb_RE,webpage)
  3390. info_match=re.search(info_RE,webpage,re.VERBOSE)
  3391. video_id=info_match.group('videoID')
  3392. mediaSlug=info_match.group('mediaSlug')
  3393. video_url=self._talk_video_link(mediaSlug)
  3394. info = {
  3395. 'id': video_id,
  3396. 'url': video_url,
  3397. 'ext': 'mp4',
  3398. 'title': title,
  3399. 'thumbnail': thumb_match.group('thumbnail')
  3400. }
  3401. return info
  3402. class MySpassIE(InfoExtractor):
  3403. _VALID_URL = r'http://www.myspass.de/.*'
  3404. def _real_extract(self, url):
  3405. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  3406. # video id is the last path element of the URL
  3407. # usually there is a trailing slash, so also try the second but last
  3408. url_path = compat_urllib_parse_urlparse(url).path
  3409. url_parent_path, video_id = os.path.split(url_path)
  3410. if not video_id:
  3411. _, video_id = os.path.split(url_parent_path)
  3412. # get metadata
  3413. metadata_url = META_DATA_URL_TEMPLATE % video_id
  3414. metadata_text = self._download_webpage(metadata_url, video_id)
  3415. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  3416. # extract values from metadata
  3417. url_flv_el = metadata.find('url_flv')
  3418. if url_flv_el is None:
  3419. self._downloader.trouble(u'ERROR: unable to extract download url')
  3420. return
  3421. video_url = url_flv_el.text
  3422. extension = os.path.splitext(video_url)[1][1:]
  3423. title_el = metadata.find('title')
  3424. if title_el is None:
  3425. self._downloader.trouble(u'ERROR: unable to extract title')
  3426. return
  3427. title = title_el.text
  3428. format_id_el = metadata.find('format_id')
  3429. if format_id_el is None:
  3430. format = ext
  3431. else:
  3432. format = format_id_el.text
  3433. description_el = metadata.find('description')
  3434. if description_el is not None:
  3435. description = description_el.text
  3436. else:
  3437. description = None
  3438. imagePreview_el = metadata.find('imagePreview')
  3439. if imagePreview_el is not None:
  3440. thumbnail = imagePreview_el.text
  3441. else:
  3442. thumbnail = None
  3443. info = {
  3444. 'id': video_id,
  3445. 'url': video_url,
  3446. 'title': title,
  3447. 'ext': extension,
  3448. 'format': format,
  3449. 'thumbnail': thumbnail,
  3450. 'description': description
  3451. }
  3452. return [info]
  3453. class SpiegelIE(InfoExtractor):
  3454. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?$'
  3455. def _real_extract(self, url):
  3456. m = re.match(self._VALID_URL, url)
  3457. video_id = m.group('videoID')
  3458. webpage = self._download_webpage(url, video_id)
  3459. m = re.search(r'<div class="spVideoTitle">(.*?)</div>', webpage)
  3460. if not m:
  3461. raise ExtractorError(u'Cannot find title')
  3462. video_title = unescapeHTML(m.group(1))
  3463. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  3464. xml_code = self._download_webpage(xml_url, video_id,
  3465. note=u'Downloading XML', errnote=u'Failed to download XML')
  3466. idoc = xml.etree.ElementTree.fromstring(xml_code)
  3467. last_type = idoc[-1]
  3468. filename = last_type.findall('./filename')[0].text
  3469. duration = float(last_type.findall('./duration')[0].text)
  3470. video_url = 'http://video2.spiegel.de/flash/' + filename
  3471. video_ext = filename.rpartition('.')[2]
  3472. info = {
  3473. 'id': video_id,
  3474. 'url': video_url,
  3475. 'ext': video_ext,
  3476. 'title': video_title,
  3477. 'duration': duration,
  3478. }
  3479. return [info]
  3480. def gen_extractors():
  3481. """ Return a list of an instance of every supported extractor.
  3482. The order does matter; the first extractor matched is the one handling the URL.
  3483. """
  3484. return [
  3485. YoutubePlaylistIE(),
  3486. YoutubeChannelIE(),
  3487. YoutubeUserIE(),
  3488. YoutubeSearchIE(),
  3489. YoutubeIE(),
  3490. MetacafeIE(),
  3491. DailymotionIE(),
  3492. GoogleSearchIE(),
  3493. PhotobucketIE(),
  3494. YahooIE(),
  3495. YahooSearchIE(),
  3496. DepositFilesIE(),
  3497. FacebookIE(),
  3498. BlipTVUserIE(),
  3499. BlipTVIE(),
  3500. VimeoIE(),
  3501. MyVideoIE(),
  3502. ComedyCentralIE(),
  3503. EscapistIE(),
  3504. CollegeHumorIE(),
  3505. XVideosIE(),
  3506. SoundcloudIE(),
  3507. InfoQIE(),
  3508. MixcloudIE(),
  3509. StanfordOpenClassroomIE(),
  3510. MTVIE(),
  3511. YoukuIE(),
  3512. XNXXIE(),
  3513. YouJizzIE(),
  3514. PornotubeIE(),
  3515. YouPornIE(),
  3516. GooglePlusIE(),
  3517. ArteTvIE(),
  3518. NBAIE(),
  3519. JustinTVIE(),
  3520. FunnyOrDieIE(),
  3521. SteamIE(),
  3522. UstreamIE(),
  3523. RBMARadioIE(),
  3524. EightTracksIE(),
  3525. KeekIE(),
  3526. TEDIE(),
  3527. MySpassIE(),
  3528. SpiegelIE(),
  3529. GenericIE()
  3530. ]