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.

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