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.

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