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.

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