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.

4456 lines
176 KiB

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