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.

4424 lines
174 KiB

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