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.

4328 lines
170 KiB

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