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.

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