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.

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