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.

4151 lines
165 KiB

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