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.

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