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.

3695 lines
149 KiB

12 years ago
12 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import datetime
  5. import netrc
  6. import os
  7. import re
  8. import socket
  9. import time
  10. import email.utils
  11. import xml.etree.ElementTree
  12. import random
  13. import math
  14. from .utils import *
  15. class InfoExtractor(object):
  16. """Information Extractor class.
  17. Information extractors are the classes that, given a URL, extract
  18. information about the video (or videos) the URL refers to. This
  19. information includes the real video URL, the video title, author and
  20. others. The information is stored in a dictionary which is then
  21. passed to the FileDownloader. The FileDownloader processes this
  22. information possibly downloading the video to the file system, among
  23. other possible outcomes.
  24. The dictionaries must include the following fields:
  25. id: Video identifier.
  26. url: Final video URL.
  27. uploader: Full name of the video uploader, unescaped.
  28. upload_date: Video upload date (YYYYMMDD).
  29. title: Video title, unescaped.
  30. ext: Video filename extension.
  31. The following fields are optional:
  32. format: The video format, defaults to ext (used for --get-format)
  33. thumbnail: Full URL to a video thumbnail image.
  34. description: One-line video description.
  35. uploader_id: Nickname or id of the video uploader.
  36. player_url: SWF Player URL (used for rtmpdump).
  37. subtitles: The .srt file contents.
  38. urlhandle: [internal] The urlHandle to be used to download the file,
  39. like returned by urllib.request.urlopen
  40. The fields should all be Unicode strings.
  41. Subclasses of this one should re-define the _real_initialize() and
  42. _real_extract() methods and define a _VALID_URL regexp.
  43. Probably, they should also be added to the list of extractors.
  44. _real_extract() must return a *list* of information dictionaries as
  45. described above.
  46. Finally, the _WORKING attribute should be set to False for broken IEs
  47. in order to warn the users and skip the tests.
  48. """
  49. _ready = False
  50. _downloader = None
  51. _WORKING = True
  52. def __init__(self, downloader=None):
  53. """Constructor. Receives an optional downloader."""
  54. self._ready = False
  55. self.set_downloader(downloader)
  56. def suitable(self, url):
  57. """Receives a URL and returns True if suitable for this IE."""
  58. return re.match(self._VALID_URL, url) is not None
  59. def working(self):
  60. """Getter method for _WORKING."""
  61. return self._WORKING
  62. def initialize(self):
  63. """Initializes an instance (authentication, etc)."""
  64. if not self._ready:
  65. self._real_initialize()
  66. self._ready = True
  67. def extract(self, url):
  68. """Extracts URL information and returns it in list of dicts."""
  69. self.initialize()
  70. return self._real_extract(url)
  71. def set_downloader(self, downloader):
  72. """Sets the downloader for this IE."""
  73. self._downloader = downloader
  74. def _real_initialize(self):
  75. """Real initialization process. Redefine in subclasses."""
  76. pass
  77. def _real_extract(self, url):
  78. """Real extraction process. Redefine in subclasses."""
  79. pass
  80. class YoutubeIE(InfoExtractor):
  81. """Information extractor for youtube.com."""
  82. _VALID_URL = r"""^
  83. (
  84. (?:https?://)? # http(s):// (optional)
  85. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  86. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  87. (?:.*?\#/)? # handle anchor (#/) redirect urls
  88. (?!view_play_list|my_playlists|artist|playlist) # ignore playlist URLs
  89. (?: # the various things that can precede the ID:
  90. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  91. |(?: # or the v= param in all its forms
  92. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  93. (?:\?|\#!?) # the params delimiter ? or # or #!
  94. (?:.+&)? # any other preceding param (like /?s=tuff&v=xxxx)
  95. v=
  96. )
  97. )? # optional -> youtube.com/xxxx is OK
  98. )? # all until now is optional -> you can pass the naked ID
  99. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  100. (?(1).+)? # if we found the ID, everything can follow
  101. $"""
  102. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  103. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  104. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  105. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  106. _NETRC_MACHINE = 'youtube'
  107. # Listed in order of quality
  108. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  109. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  110. _video_extensions = {
  111. '13': '3gp',
  112. '17': 'mp4',
  113. '18': 'mp4',
  114. '22': 'mp4',
  115. '37': 'mp4',
  116. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  117. '43': 'webm',
  118. '44': 'webm',
  119. '45': 'webm',
  120. '46': 'webm',
  121. }
  122. _video_dimensions = {
  123. '5': '240x400',
  124. '6': '???',
  125. '13': '???',
  126. '17': '144x176',
  127. '18': '360x640',
  128. '22': '720x1280',
  129. '34': '360x640',
  130. '35': '480x854',
  131. '37': '1080x1920',
  132. '38': '3072x4096',
  133. '43': '360x640',
  134. '44': '480x854',
  135. '45': '720x1280',
  136. '46': '1080x1920',
  137. }
  138. IE_NAME = u'youtube'
  139. def suitable(self, url):
  140. """Receives a URL and returns True if suitable for this IE."""
  141. return re.match(self._VALID_URL, url, re.VERBOSE) is not None
  142. def report_lang(self):
  143. """Report attempt to set language."""
  144. self._downloader.to_screen(u'[youtube] Setting language')
  145. def report_login(self):
  146. """Report attempt to log in."""
  147. self._downloader.to_screen(u'[youtube] Logging in')
  148. def report_age_confirmation(self):
  149. """Report attempt to confirm age."""
  150. self._downloader.to_screen(u'[youtube] Confirming age')
  151. def report_video_webpage_download(self, video_id):
  152. """Report attempt to download video webpage."""
  153. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  154. def report_video_info_webpage_download(self, video_id):
  155. """Report attempt to download video info webpage."""
  156. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  157. def report_video_subtitles_download(self, video_id):
  158. """Report attempt to download video info webpage."""
  159. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles' % video_id)
  160. def report_information_extraction(self, video_id):
  161. """Report attempt to extract video information."""
  162. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  163. def report_unavailable_format(self, video_id, format):
  164. """Report extracted video URL."""
  165. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  166. def report_rtmp_download(self):
  167. """Indicate the download will use the RTMP protocol."""
  168. self._downloader.to_screen(u'[youtube] RTMP download detected')
  169. def _closed_captions_xml_to_srt(self, xml_string):
  170. srt = ''
  171. texts = re.findall(r'<text start="([\d\.]+)"( dur="([\d\.]+)")?>([^<]+)</text>', xml_string, re.MULTILINE)
  172. # TODO parse xml instead of regex
  173. for n, (start, dur_tag, dur, caption) in enumerate(texts):
  174. if not dur: dur = '4'
  175. start = float(start)
  176. end = start + float(dur)
  177. start = "%02i:%02i:%02i,%03i" %(start/(60*60), start/60%60, start%60, start%1*1000)
  178. end = "%02i:%02i:%02i,%03i" %(end/(60*60), end/60%60, end%60, end%1*1000)
  179. caption = unescapeHTML(caption)
  180. caption = unescapeHTML(caption) # double cycle, intentional
  181. srt += str(n+1) + '\n'
  182. srt += start + ' --> ' + end + '\n'
  183. srt += caption + '\n\n'
  184. return srt
  185. def _extract_subtitles(self, video_id):
  186. self.report_video_subtitles_download(video_id)
  187. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  188. try:
  189. srt_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  190. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  191. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  192. srt_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', srt_list)
  193. srt_lang_list = dict((l[1], l[0]) for l in srt_lang_list)
  194. if not srt_lang_list:
  195. return (u'WARNING: video has no closed captions', None)
  196. if self._downloader.params.get('subtitleslang', False):
  197. srt_lang = self._downloader.params.get('subtitleslang')
  198. elif 'en' in srt_lang_list:
  199. srt_lang = 'en'
  200. else:
  201. srt_lang = list(srt_lang_list.keys())[0]
  202. if not srt_lang in srt_lang_list:
  203. return (u'WARNING: no closed captions found in the specified language', None)
  204. request = compat_urllib_request.Request('http://www.youtube.com/api/timedtext?lang=%s&name=%s&v=%s' % (srt_lang, srt_lang_list[srt_lang], video_id))
  205. try:
  206. srt_xml = compat_urllib_request.urlopen(request).read().decode('utf-8')
  207. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  208. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  209. if not srt_xml:
  210. return (u'WARNING: unable to download video subtitles', None)
  211. return (None, self._closed_captions_xml_to_srt(srt_xml))
  212. def _print_formats(self, formats):
  213. print('Available formats:')
  214. for x in formats:
  215. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  216. def _real_initialize(self):
  217. if self._downloader is None:
  218. return
  219. username = None
  220. password = None
  221. downloader_params = self._downloader.params
  222. # Attempt to use provided username and password or .netrc data
  223. if downloader_params.get('username', None) is not None:
  224. username = downloader_params['username']
  225. password = downloader_params['password']
  226. elif downloader_params.get('usenetrc', False):
  227. try:
  228. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  229. if info is not None:
  230. username = info[0]
  231. password = info[2]
  232. else:
  233. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  234. except (IOError, netrc.NetrcParseError) as err:
  235. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  236. return
  237. # Set language
  238. request = compat_urllib_request.Request(self._LANG_URL)
  239. try:
  240. self.report_lang()
  241. compat_urllib_request.urlopen(request).read()
  242. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  243. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % compat_str(err))
  244. return
  245. # No authentication to be performed
  246. if username is None:
  247. return
  248. # Log in
  249. login_form = {
  250. 'current_form': 'loginForm',
  251. 'next': '/',
  252. 'action_login': 'Log In',
  253. 'username': username,
  254. 'password': password,
  255. }
  256. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  257. try:
  258. self.report_login()
  259. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  260. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  261. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  262. return
  263. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  264. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  265. return
  266. # Confirm age
  267. age_form = {
  268. 'next_url': '/',
  269. 'action_confirm': 'Confirm',
  270. }
  271. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  272. try:
  273. self.report_age_confirmation()
  274. age_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  275. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  276. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  277. return
  278. def _real_extract(self, url):
  279. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  280. mobj = re.search(self._NEXT_URL_RE, url)
  281. if mobj:
  282. url = 'http://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  283. # Extract video id from URL
  284. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  285. if mobj is None:
  286. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  287. return
  288. video_id = mobj.group(2)
  289. # Get video webpage
  290. self.report_video_webpage_download(video_id)
  291. request = compat_urllib_request.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id)
  292. try:
  293. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  294. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  295. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  296. return
  297. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  298. # Attempt to extract SWF player URL
  299. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  300. if mobj is not None:
  301. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  302. else:
  303. player_url = None
  304. # Get video info
  305. self.report_video_info_webpage_download(video_id)
  306. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  307. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  308. % (video_id, el_type))
  309. request = compat_urllib_request.Request(video_info_url)
  310. try:
  311. video_info_webpage_bytes = compat_urllib_request.urlopen(request).read()
  312. video_info_webpage = video_info_webpage_bytes.decode('utf-8', 'ignore')
  313. video_info = compat_parse_qs(video_info_webpage)
  314. if 'token' in video_info:
  315. break
  316. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  317. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  318. return
  319. if 'token' not in video_info:
  320. if 'reason' in video_info:
  321. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0])
  322. else:
  323. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  324. return
  325. # Check for "rental" videos
  326. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  327. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  328. return
  329. # Start extracting information
  330. self.report_information_extraction(video_id)
  331. # uploader
  332. if 'author' not in video_info:
  333. self._downloader.trouble(u'ERROR: unable to extract uploader name')
  334. return
  335. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  336. # uploader_id
  337. video_uploader_id = None
  338. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/user/([^"]+)">', video_webpage)
  339. if mobj is not None:
  340. video_uploader_id = mobj.group(1)
  341. else:
  342. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  343. # title
  344. if 'title' not in video_info:
  345. self._downloader.trouble(u'ERROR: unable to extract video title')
  346. return
  347. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  348. # thumbnail image
  349. if 'thumbnail_url' not in video_info:
  350. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  351. video_thumbnail = ''
  352. else: # don't panic if we can't find it
  353. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  354. # upload date
  355. upload_date = None
  356. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  357. if mobj is not None:
  358. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  359. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  360. for expression in format_expressions:
  361. try:
  362. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  363. except:
  364. pass
  365. # description
  366. video_description = get_element_by_id("eow-description", video_webpage)
  367. if video_description:
  368. video_description = clean_html(video_description)
  369. else:
  370. video_description = ''
  371. # closed captions
  372. video_subtitles = None
  373. if self._downloader.params.get('writesubtitles', False):
  374. (srt_error, video_subtitles) = self._extract_subtitles(video_id)
  375. if srt_error:
  376. self._downloader.trouble(srt_error)
  377. if 'length_seconds' not in video_info:
  378. self._downloader.trouble(u'WARNING: unable to extract video duration')
  379. video_duration = ''
  380. else:
  381. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  382. # token
  383. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  384. # Decide which formats to download
  385. req_format = self._downloader.params.get('format', None)
  386. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  387. self.report_rtmp_download()
  388. video_url_list = [(None, video_info['conn'][0])]
  389. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  390. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  391. url_data = [compat_parse_qs(uds) for uds in url_data_strs]
  392. url_data = [ud for ud in url_data if 'itag' in ud and 'url' in ud]
  393. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  394. format_limit = self._downloader.params.get('format_limit', None)
  395. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  396. if format_limit is not None and format_limit in available_formats:
  397. format_list = available_formats[available_formats.index(format_limit):]
  398. else:
  399. format_list = available_formats
  400. existing_formats = [x for x in format_list if x in url_map]
  401. if len(existing_formats) == 0:
  402. self._downloader.trouble(u'ERROR: no known formats available for video')
  403. return
  404. if self._downloader.params.get('listformats', None):
  405. self._print_formats(existing_formats)
  406. return
  407. if req_format is None or req_format == 'best':
  408. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  409. elif req_format == 'worst':
  410. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  411. elif req_format in ('-1', 'all'):
  412. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  413. else:
  414. # Specific formats. We pick the first in a slash-delimeted sequence.
  415. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  416. req_formats = req_format.split('/')
  417. video_url_list = None
  418. for rf in req_formats:
  419. if rf in url_map:
  420. video_url_list = [(rf, url_map[rf])]
  421. break
  422. if video_url_list is None:
  423. self._downloader.trouble(u'ERROR: requested format not available')
  424. return
  425. else:
  426. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  427. return
  428. results = []
  429. for format_param, video_real_url in video_url_list:
  430. # Extension
  431. video_extension = self._video_extensions.get(format_param, 'flv')
  432. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  433. self._video_dimensions.get(format_param, '???'))
  434. results.append({
  435. 'id': video_id,
  436. 'url': video_real_url,
  437. 'uploader': video_uploader,
  438. 'uploader_id': video_uploader_id,
  439. 'upload_date': upload_date,
  440. 'title': video_title,
  441. 'ext': video_extension,
  442. 'format': video_format,
  443. 'thumbnail': video_thumbnail,
  444. 'description': video_description,
  445. 'player_url': player_url,
  446. 'subtitles': video_subtitles,
  447. 'duration': video_duration
  448. })
  449. return results
  450. class MetacafeIE(InfoExtractor):
  451. """Information Extractor for metacafe.com."""
  452. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  453. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  454. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  455. IE_NAME = u'metacafe'
  456. def __init__(self, downloader=None):
  457. InfoExtractor.__init__(self, downloader)
  458. def report_disclaimer(self):
  459. """Report disclaimer retrieval."""
  460. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  461. def report_age_confirmation(self):
  462. """Report attempt to confirm age."""
  463. self._downloader.to_screen(u'[metacafe] Confirming age')
  464. def report_download_webpage(self, video_id):
  465. """Report webpage download."""
  466. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  467. def report_extraction(self, video_id):
  468. """Report information extraction."""
  469. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  470. def _real_initialize(self):
  471. # Retrieve disclaimer
  472. request = compat_urllib_request.Request(self._DISCLAIMER)
  473. try:
  474. self.report_disclaimer()
  475. disclaimer = compat_urllib_request.urlopen(request).read()
  476. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  477. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % compat_str(err))
  478. return
  479. # Confirm age
  480. disclaimer_form = {
  481. 'filters': '0',
  482. 'submit': "Continue - I'm over 18",
  483. }
  484. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  485. try:
  486. self.report_age_confirmation()
  487. disclaimer = compat_urllib_request.urlopen(request).read()
  488. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  489. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  490. return
  491. def _real_extract(self, url):
  492. # Extract id and simplified title from URL
  493. mobj = re.match(self._VALID_URL, url)
  494. if mobj is None:
  495. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  496. return
  497. video_id = mobj.group(1)
  498. # Check if video comes from YouTube
  499. mobj2 = re.match(r'^yt-(.*)$', video_id)
  500. if mobj2 is not None:
  501. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  502. return
  503. # Retrieve video webpage to extract further information
  504. request = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
  505. try:
  506. self.report_download_webpage(video_id)
  507. webpage = compat_urllib_request.urlopen(request).read()
  508. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  509. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  510. return
  511. # Extract URL, uploader and title from webpage
  512. self.report_extraction(video_id)
  513. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  514. if mobj is not None:
  515. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  516. video_extension = mediaURL[-3:]
  517. # Extract gdaKey if available
  518. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  519. if mobj is None:
  520. video_url = mediaURL
  521. else:
  522. gdaKey = mobj.group(1)
  523. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  524. else:
  525. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  526. if mobj is None:
  527. self._downloader.trouble(u'ERROR: unable to extract media URL')
  528. return
  529. vardict = compat_parse_qs(mobj.group(1))
  530. if 'mediaData' not in vardict:
  531. self._downloader.trouble(u'ERROR: unable to extract media URL')
  532. return
  533. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  534. if mobj is None:
  535. self._downloader.trouble(u'ERROR: unable to extract media URL')
  536. return
  537. mediaURL = mobj.group(1).replace('\\/', '/')
  538. video_extension = mediaURL[-3:]
  539. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  540. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  541. if mobj is None:
  542. self._downloader.trouble(u'ERROR: unable to extract title')
  543. return
  544. video_title = mobj.group(1).decode('utf-8')
  545. mobj = re.search(r'submitter=(.*?);', webpage)
  546. if mobj is None:
  547. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  548. return
  549. video_uploader = mobj.group(1)
  550. return [{
  551. 'id': video_id.decode('utf-8'),
  552. 'url': video_url.decode('utf-8'),
  553. 'uploader': video_uploader.decode('utf-8'),
  554. 'upload_date': None,
  555. 'title': video_title,
  556. 'ext': video_extension.decode('utf-8'),
  557. }]
  558. class DailymotionIE(InfoExtractor):
  559. """Information Extractor for Dailymotion"""
  560. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  561. IE_NAME = u'dailymotion'
  562. def __init__(self, downloader=None):
  563. InfoExtractor.__init__(self, downloader)
  564. def report_download_webpage(self, video_id):
  565. """Report webpage download."""
  566. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  567. def report_extraction(self, video_id):
  568. """Report information extraction."""
  569. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  570. def _real_extract(self, url):
  571. # Extract id and simplified title from URL
  572. mobj = re.match(self._VALID_URL, url)
  573. if mobj is None:
  574. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  575. return
  576. video_id = mobj.group(1).split('_')[0].split('?')[0]
  577. video_extension = 'mp4'
  578. # Retrieve video webpage to extract further information
  579. request = compat_urllib_request.Request(url)
  580. request.add_header('Cookie', 'family_filter=off')
  581. try:
  582. self.report_download_webpage(video_id)
  583. webpage_bytes = compat_urllib_request.urlopen(request).read()
  584. webpage = webpage_bytes.decode('utf-8')
  585. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  586. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  587. return
  588. # Extract URL, uploader and title from webpage
  589. self.report_extraction(video_id)
  590. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  591. if mobj is None:
  592. self._downloader.trouble(u'ERROR: unable to extract media URL')
  593. return
  594. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  595. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  596. if key in flashvars:
  597. max_quality = key
  598. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  599. break
  600. else:
  601. self._downloader.trouble(u'ERROR: unable to extract video URL')
  602. return
  603. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  604. if mobj is None:
  605. self._downloader.trouble(u'ERROR: unable to extract video URL')
  606. return
  607. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  608. # TODO: support choosing qualities
  609. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  610. if mobj is None:
  611. self._downloader.trouble(u'ERROR: unable to extract title')
  612. return
  613. video_title = unescapeHTML(mobj.group('title'))
  614. video_uploader = None
  615. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  616. if mobj is None:
  617. # lookin for official user
  618. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  619. if mobj_official is None:
  620. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  621. else:
  622. video_uploader = mobj_official.group(1)
  623. else:
  624. video_uploader = mobj.group(1)
  625. video_upload_date = None
  626. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  627. if mobj is not None:
  628. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  629. return [{
  630. 'id': video_id,
  631. 'url': video_url,
  632. 'uploader': video_uploader,
  633. 'upload_date': video_upload_date,
  634. 'title': video_title,
  635. 'ext': video_extension,
  636. }]
  637. class PhotobucketIE(InfoExtractor):
  638. """Information extractor for photobucket.com."""
  639. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  640. IE_NAME = u'photobucket'
  641. def __init__(self, downloader=None):
  642. InfoExtractor.__init__(self, downloader)
  643. def report_download_webpage(self, video_id):
  644. """Report webpage download."""
  645. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  646. def report_extraction(self, video_id):
  647. """Report information extraction."""
  648. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  649. def _real_extract(self, url):
  650. # Extract id from URL
  651. mobj = re.match(self._VALID_URL, url)
  652. if mobj is None:
  653. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  654. return
  655. video_id = mobj.group(1)
  656. video_extension = 'flv'
  657. # Retrieve video webpage to extract further information
  658. request = compat_urllib_request.Request(url)
  659. try:
  660. self.report_download_webpage(video_id)
  661. webpage = compat_urllib_request.urlopen(request).read()
  662. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  663. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  664. return
  665. # Extract URL, uploader, and title from webpage
  666. self.report_extraction(video_id)
  667. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  668. if mobj is None:
  669. self._downloader.trouble(u'ERROR: unable to extract media URL')
  670. return
  671. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  672. video_url = mediaURL
  673. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  674. if mobj is None:
  675. self._downloader.trouble(u'ERROR: unable to extract title')
  676. return
  677. video_title = mobj.group(1).decode('utf-8')
  678. video_uploader = mobj.group(2).decode('utf-8')
  679. return [{
  680. 'id': video_id.decode('utf-8'),
  681. 'url': video_url.decode('utf-8'),
  682. 'uploader': video_uploader,
  683. 'upload_date': None,
  684. 'title': video_title,
  685. 'ext': video_extension.decode('utf-8'),
  686. }]
  687. class YahooIE(InfoExtractor):
  688. """Information extractor for video.yahoo.com."""
  689. _WORKING = False
  690. # _VALID_URL matches all Yahoo! Video URLs
  691. # _VPAGE_URL matches only the extractable '/watch/' URLs
  692. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  693. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  694. IE_NAME = u'video.yahoo'
  695. def __init__(self, downloader=None):
  696. InfoExtractor.__init__(self, downloader)
  697. def report_download_webpage(self, video_id):
  698. """Report webpage download."""
  699. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  700. def report_extraction(self, video_id):
  701. """Report information extraction."""
  702. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  703. def _real_extract(self, url, new_video=True):
  704. # Extract ID from URL
  705. mobj = re.match(self._VALID_URL, url)
  706. if mobj is None:
  707. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  708. return
  709. video_id = mobj.group(2)
  710. video_extension = 'flv'
  711. # Rewrite valid but non-extractable URLs as
  712. # extractable English language /watch/ URLs
  713. if re.match(self._VPAGE_URL, url) is None:
  714. request = compat_urllib_request.Request(url)
  715. try:
  716. webpage = compat_urllib_request.urlopen(request).read()
  717. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  718. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  719. return
  720. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  721. if mobj is None:
  722. self._downloader.trouble(u'ERROR: Unable to extract id field')
  723. return
  724. yahoo_id = mobj.group(1)
  725. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  726. if mobj is None:
  727. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  728. return
  729. yahoo_vid = mobj.group(1)
  730. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  731. return self._real_extract(url, new_video=False)
  732. # Retrieve video webpage to extract further information
  733. request = compat_urllib_request.Request(url)
  734. try:
  735. self.report_download_webpage(video_id)
  736. webpage = compat_urllib_request.urlopen(request).read()
  737. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  738. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  739. return
  740. # Extract uploader and title from webpage
  741. self.report_extraction(video_id)
  742. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  743. if mobj is None:
  744. self._downloader.trouble(u'ERROR: unable to extract video title')
  745. return
  746. video_title = mobj.group(1).decode('utf-8')
  747. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  748. if mobj is None:
  749. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  750. return
  751. video_uploader = mobj.group(1).decode('utf-8')
  752. # Extract video thumbnail
  753. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  754. if mobj is None:
  755. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  756. return
  757. video_thumbnail = mobj.group(1).decode('utf-8')
  758. # Extract video description
  759. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  760. if mobj is None:
  761. self._downloader.trouble(u'ERROR: unable to extract video description')
  762. return
  763. video_description = mobj.group(1).decode('utf-8')
  764. if not video_description:
  765. video_description = 'No description available.'
  766. # Extract video height and width
  767. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  768. if mobj is None:
  769. self._downloader.trouble(u'ERROR: unable to extract video height')
  770. return
  771. yv_video_height = mobj.group(1)
  772. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  773. if mobj is None:
  774. self._downloader.trouble(u'ERROR: unable to extract video width')
  775. return
  776. yv_video_width = mobj.group(1)
  777. # Retrieve video playlist to extract media URL
  778. # I'm not completely sure what all these options are, but we
  779. # seem to need most of them, otherwise the server sends a 401.
  780. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  781. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  782. request = compat_urllib_request.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  783. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  784. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  785. try:
  786. self.report_download_webpage(video_id)
  787. webpage = compat_urllib_request.urlopen(request).read()
  788. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  789. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  790. return
  791. # Extract media URL from playlist XML
  792. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  793. if mobj is None:
  794. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  795. return
  796. video_url = compat_urllib_parse.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  797. video_url = unescapeHTML(video_url)
  798. return [{
  799. 'id': video_id.decode('utf-8'),
  800. 'url': video_url,
  801. 'uploader': video_uploader,
  802. 'upload_date': None,
  803. 'title': video_title,
  804. 'ext': video_extension.decode('utf-8'),
  805. 'thumbnail': video_thumbnail.decode('utf-8'),
  806. 'description': video_description,
  807. }]
  808. class VimeoIE(InfoExtractor):
  809. """Information extractor for vimeo.com."""
  810. # _VALID_URL matches Vimeo URLs
  811. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?:videos?/)?([0-9]+)'
  812. IE_NAME = u'vimeo'
  813. def __init__(self, downloader=None):
  814. InfoExtractor.__init__(self, downloader)
  815. def report_download_webpage(self, video_id):
  816. """Report webpage download."""
  817. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  818. def report_extraction(self, video_id):
  819. """Report information extraction."""
  820. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  821. def _real_extract(self, url, new_video=True):
  822. # Extract ID from URL
  823. mobj = re.match(self._VALID_URL, url)
  824. if mobj is None:
  825. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  826. return
  827. video_id = mobj.group(1)
  828. # Retrieve video webpage to extract further information
  829. request = compat_urllib_request.Request(url, None, std_headers)
  830. try:
  831. self.report_download_webpage(video_id)
  832. webpage_bytes = compat_urllib_request.urlopen(request).read()
  833. webpage = webpage_bytes.decode('utf-8')
  834. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  835. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  836. return
  837. # Now we begin extracting as much information as we can from what we
  838. # retrieved. First we extract the information common to all extractors,
  839. # and latter we extract those that are Vimeo specific.
  840. self.report_extraction(video_id)
  841. # Extract the config JSON
  842. try:
  843. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  844. config = json.loads(config)
  845. except:
  846. self._downloader.trouble(u'ERROR: unable to extract info section')
  847. return
  848. # Extract title
  849. video_title = config["video"]["title"]
  850. # Extract uploader and uploader_id
  851. video_uploader = config["video"]["owner"]["name"]
  852. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1]
  853. # Extract video thumbnail
  854. video_thumbnail = config["video"]["thumbnail"]
  855. # Extract video description
  856. video_description = get_element_by_attribute("itemprop", "description", webpage)
  857. if video_description: video_description = clean_html(video_description)
  858. else: video_description = ''
  859. # Extract upload date
  860. video_upload_date = None
  861. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  862. if mobj is not None:
  863. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  864. # Vimeo specific: extract request signature and timestamp
  865. sig = config['request']['signature']
  866. timestamp = config['request']['timestamp']
  867. # Vimeo specific: extract video codec and quality information
  868. # First consider quality, then codecs, then take everything
  869. # TODO bind to format param
  870. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  871. files = { 'hd': [], 'sd': [], 'other': []}
  872. for codec_name, codec_extension in codecs:
  873. if codec_name in config["video"]["files"]:
  874. if 'hd' in config["video"]["files"][codec_name]:
  875. files['hd'].append((codec_name, codec_extension, 'hd'))
  876. elif 'sd' in config["video"]["files"][codec_name]:
  877. files['sd'].append((codec_name, codec_extension, 'sd'))
  878. else:
  879. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  880. for quality in ('hd', 'sd', 'other'):
  881. if len(files[quality]) > 0:
  882. video_quality = files[quality][0][2]
  883. video_codec = files[quality][0][0]
  884. video_extension = files[quality][0][1]
  885. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  886. break
  887. else:
  888. self._downloader.trouble(u'ERROR: no known codec found')
  889. return
  890. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  891. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  892. return [{
  893. 'id': video_id,
  894. 'url': video_url,
  895. 'uploader': video_uploader,
  896. 'uploader_id': video_uploader_id,
  897. 'upload_date': video_upload_date,
  898. 'title': video_title,
  899. 'ext': video_extension,
  900. 'thumbnail': video_thumbnail,
  901. 'description': video_description,
  902. }]
  903. class ArteTvIE(InfoExtractor):
  904. """arte.tv information extractor."""
  905. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  906. _LIVE_URL = r'index-[0-9]+\.html$'
  907. IE_NAME = u'arte.tv'
  908. def __init__(self, downloader=None):
  909. InfoExtractor.__init__(self, downloader)
  910. def report_download_webpage(self, video_id):
  911. """Report webpage download."""
  912. self._downloader.to_screen(u'[arte.tv] %s: Downloading webpage' % video_id)
  913. def report_extraction(self, video_id):
  914. """Report information extraction."""
  915. self._downloader.to_screen(u'[arte.tv] %s: Extracting information' % video_id)
  916. def fetch_webpage(self, url):
  917. self._downloader.increment_downloads()
  918. request = compat_urllib_request.Request(url)
  919. try:
  920. self.report_download_webpage(url)
  921. webpage = compat_urllib_request.urlopen(request).read()
  922. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  923. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  924. return
  925. except ValueError as err:
  926. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  927. return
  928. return webpage
  929. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  930. page = self.fetch_webpage(url)
  931. mobj = re.search(regex, page, regexFlags)
  932. info = {}
  933. if mobj is None:
  934. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  935. return
  936. for (i, key, err) in matchTuples:
  937. if mobj.group(i) is None:
  938. self._downloader.trouble(err)
  939. return
  940. else:
  941. info[key] = mobj.group(i)
  942. return info
  943. def extractLiveStream(self, url):
  944. video_lang = url.split('/')[-4]
  945. info = self.grep_webpage(
  946. url,
  947. r'src="(.*?/videothek_js.*?\.js)',
  948. 0,
  949. [
  950. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  951. ]
  952. )
  953. http_host = url.split('/')[2]
  954. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  955. info = self.grep_webpage(
  956. next_url,
  957. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  958. '(http://.*?\.swf).*?' +
  959. '(rtmp://.*?)\'',
  960. re.DOTALL,
  961. [
  962. (1, 'path', u'ERROR: could not extract video path: %s' % url),
  963. (2, 'player', u'ERROR: could not extract video player: %s' % url),
  964. (3, 'url', u'ERROR: could not extract video url: %s' % url)
  965. ]
  966. )
  967. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  968. def extractPlus7Stream(self, url):
  969. video_lang = url.split('/')[-3]
  970. info = self.grep_webpage(
  971. url,
  972. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  973. 0,
  974. [
  975. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  976. ]
  977. )
  978. next_url = compat_urllib_parse.unquote(info.get('url'))
  979. info = self.grep_webpage(
  980. next_url,
  981. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  982. 0,
  983. [
  984. (1, 'url', u'ERROR: Could not find <video> tag: %s' % url)
  985. ]
  986. )
  987. next_url = compat_urllib_parse.unquote(info.get('url'))
  988. info = self.grep_webpage(
  989. next_url,
  990. r'<video id="(.*?)".*?>.*?' +
  991. '<name>(.*?)</name>.*?' +
  992. '<dateVideo>(.*?)</dateVideo>.*?' +
  993. '<url quality="hd">(.*?)</url>',
  994. re.DOTALL,
  995. [
  996. (1, 'id', u'ERROR: could not extract video id: %s' % url),
  997. (2, 'title', u'ERROR: could not extract video title: %s' % url),
  998. (3, 'date', u'ERROR: could not extract video date: %s' % url),
  999. (4, 'url', u'ERROR: could not extract video url: %s' % url)
  1000. ]
  1001. )
  1002. return {
  1003. 'id': info.get('id'),
  1004. 'url': compat_urllib_parse.unquote(info.get('url')),
  1005. 'uploader': u'arte.tv',
  1006. 'upload_date': info.get('date'),
  1007. 'title': info.get('title').decode('utf-8'),
  1008. 'ext': u'mp4',
  1009. 'format': u'NA',
  1010. 'player_url': None,
  1011. }
  1012. def _real_extract(self, url):
  1013. video_id = url.split('/')[-1]
  1014. self.report_extraction(video_id)
  1015. if re.search(self._LIVE_URL, video_id) is not None:
  1016. self.extractLiveStream(url)
  1017. return
  1018. else:
  1019. info = self.extractPlus7Stream(url)
  1020. return [info]
  1021. class GenericIE(InfoExtractor):
  1022. """Generic last-resort information extractor."""
  1023. _VALID_URL = r'.*'
  1024. IE_NAME = u'generic'
  1025. def __init__(self, downloader=None):
  1026. InfoExtractor.__init__(self, downloader)
  1027. def report_download_webpage(self, video_id):
  1028. """Report webpage download."""
  1029. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1030. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1031. def report_extraction(self, video_id):
  1032. """Report information extraction."""
  1033. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1034. def report_following_redirect(self, new_url):
  1035. """Report information extraction."""
  1036. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1037. def _test_redirect(self, url):
  1038. """Check if it is a redirect, like url shorteners, in case restart chain."""
  1039. class HeadRequest(compat_urllib_request.Request):
  1040. def get_method(self):
  1041. return "HEAD"
  1042. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1043. """
  1044. Subclass the HTTPRedirectHandler to make it use our
  1045. HeadRequest also on the redirected URL
  1046. """
  1047. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1048. if code in (301, 302, 303, 307):
  1049. newurl = newurl.replace(' ', '%20')
  1050. newheaders = dict((k,v) for k,v in req.headers.items()
  1051. if k.lower() not in ("content-length", "content-type"))
  1052. return HeadRequest(newurl,
  1053. headers=newheaders,
  1054. origin_req_host=req.get_origin_req_host(),
  1055. unverifiable=True)
  1056. else:
  1057. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1058. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1059. """
  1060. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1061. """
  1062. def http_error_405(self, req, fp, code, msg, headers):
  1063. fp.read()
  1064. fp.close()
  1065. newheaders = dict((k,v) for k,v in req.headers.items()
  1066. if k.lower() not in ("content-length", "content-type"))
  1067. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1068. headers=newheaders,
  1069. origin_req_host=req.get_origin_req_host(),
  1070. unverifiable=True))
  1071. # Build our opener
  1072. opener = compat_urllib_request.OpenerDirector()
  1073. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1074. HTTPMethodFallback, HEADRedirectHandler,
  1075. compat_urllib_error.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1076. opener.add_handler(handler())
  1077. response = opener.open(HeadRequest(url))
  1078. new_url = response.geturl()
  1079. if url == new_url:
  1080. return False
  1081. self.report_following_redirect(new_url)
  1082. self._downloader.download([new_url])
  1083. return True
  1084. def _real_extract(self, url):
  1085. if self._test_redirect(url): return
  1086. video_id = url.split('/')[-1]
  1087. request = compat_urllib_request.Request(url)
  1088. try:
  1089. self.report_download_webpage(video_id)
  1090. webpage = compat_urllib_request.urlopen(request).read()
  1091. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1092. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1093. return
  1094. except ValueError as err:
  1095. # since this is the last-resort InfoExtractor, if
  1096. # this error is thrown, it'll be thrown here
  1097. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1098. return
  1099. self.report_extraction(video_id)
  1100. # Start with something easy: JW Player in SWFObject
  1101. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1102. if mobj is None:
  1103. # Broaden the search a little bit
  1104. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1105. if mobj is None:
  1106. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1107. return
  1108. # It's possible that one of the regexes
  1109. # matched, but returned an empty group:
  1110. if mobj.group(1) is None:
  1111. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1112. return
  1113. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1114. video_id = os.path.basename(video_url)
  1115. # here's a fun little line of code for you:
  1116. video_extension = os.path.splitext(video_id)[1][1:]
  1117. video_id = os.path.splitext(video_id)[0]
  1118. # it's tempting to parse this further, but you would
  1119. # have to take into account all the variations like
  1120. # Video Title - Site Name
  1121. # Site Name | Video Title
  1122. # Video Title - Tagline | Site Name
  1123. # and so on and so forth; it's just not practical
  1124. mobj = re.search(r'<title>(.*)</title>', webpage)
  1125. if mobj is None:
  1126. self._downloader.trouble(u'ERROR: unable to extract title')
  1127. return
  1128. video_title = mobj.group(1)
  1129. # video uploader is domain name
  1130. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1131. if mobj is None:
  1132. self._downloader.trouble(u'ERROR: unable to extract title')
  1133. return
  1134. video_uploader = mobj.group(1)
  1135. return [{
  1136. 'id': video_id,
  1137. 'url': video_url,
  1138. 'uploader': video_uploader,
  1139. 'upload_date': None,
  1140. 'title': video_title,
  1141. 'ext': video_extension,
  1142. }]
  1143. class YoutubeSearchIE(InfoExtractor):
  1144. """Information Extractor for YouTube search queries."""
  1145. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1146. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1147. _max_youtube_results = 1000
  1148. IE_NAME = u'youtube:search'
  1149. def __init__(self, downloader=None):
  1150. InfoExtractor.__init__(self, downloader)
  1151. def report_download_page(self, query, pagenum):
  1152. """Report attempt to download search page with given number."""
  1153. query = query.decode(preferredencoding())
  1154. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1155. def _real_extract(self, query):
  1156. mobj = re.match(self._VALID_URL, query)
  1157. if mobj is None:
  1158. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1159. return
  1160. prefix, query = query.split(':')
  1161. prefix = prefix[8:]
  1162. query = query.encode('utf-8')
  1163. if prefix == '':
  1164. self._download_n_results(query, 1)
  1165. return
  1166. elif prefix == 'all':
  1167. self._download_n_results(query, self._max_youtube_results)
  1168. return
  1169. else:
  1170. try:
  1171. n = int(prefix)
  1172. if n <= 0:
  1173. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1174. return
  1175. elif n > self._max_youtube_results:
  1176. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1177. n = self._max_youtube_results
  1178. self._download_n_results(query, n)
  1179. return
  1180. except ValueError: # parsing prefix as integer fails
  1181. self._download_n_results(query, 1)
  1182. return
  1183. def _download_n_results(self, query, n):
  1184. """Downloads a specified number of results for a query"""
  1185. video_ids = []
  1186. pagenum = 0
  1187. limit = n
  1188. while (50 * pagenum) < limit:
  1189. self.report_download_page(query, pagenum+1)
  1190. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1191. request = compat_urllib_request.Request(result_url)
  1192. try:
  1193. data = compat_urllib_request.urlopen(request).read()
  1194. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1195. self._downloader.trouble(u'ERROR: unable to download API page: %s' % compat_str(err))
  1196. return
  1197. api_response = json.loads(data)['data']
  1198. new_ids = list(video['id'] for video in api_response['items'])
  1199. video_ids += new_ids
  1200. limit = min(n, api_response['totalItems'])
  1201. pagenum += 1
  1202. if len(video_ids) > n:
  1203. video_ids = video_ids[:n]
  1204. for id in video_ids:
  1205. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1206. return
  1207. class GoogleSearchIE(InfoExtractor):
  1208. """Information Extractor for Google Video search queries."""
  1209. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1210. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1211. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1212. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1213. _max_google_results = 1000
  1214. IE_NAME = u'video.google:search'
  1215. def __init__(self, downloader=None):
  1216. InfoExtractor.__init__(self, downloader)
  1217. def report_download_page(self, query, pagenum):
  1218. """Report attempt to download playlist page with given number."""
  1219. query = query.decode(preferredencoding())
  1220. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1221. def _real_extract(self, query):
  1222. mobj = re.match(self._VALID_URL, query)
  1223. if mobj is None:
  1224. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1225. return
  1226. prefix, query = query.split(':')
  1227. prefix = prefix[8:]
  1228. query = query.encode('utf-8')
  1229. if prefix == '':
  1230. self._download_n_results(query, 1)
  1231. return
  1232. elif prefix == 'all':
  1233. self._download_n_results(query, self._max_google_results)
  1234. return
  1235. else:
  1236. try:
  1237. n = int(prefix)
  1238. if n <= 0:
  1239. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1240. return
  1241. elif n > self._max_google_results:
  1242. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1243. n = self._max_google_results
  1244. self._download_n_results(query, n)
  1245. return
  1246. except ValueError: # parsing prefix as integer fails
  1247. self._download_n_results(query, 1)
  1248. return
  1249. def _download_n_results(self, query, n):
  1250. """Downloads a specified number of results for a query"""
  1251. video_ids = []
  1252. pagenum = 0
  1253. while True:
  1254. self.report_download_page(query, pagenum)
  1255. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1256. request = compat_urllib_request.Request(result_url)
  1257. try:
  1258. page = compat_urllib_request.urlopen(request).read()
  1259. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1260. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1261. return
  1262. # Extract video identifiers
  1263. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1264. video_id = mobj.group(1)
  1265. if video_id not in video_ids:
  1266. video_ids.append(video_id)
  1267. if len(video_ids) == n:
  1268. # Specified n videos reached
  1269. for id in video_ids:
  1270. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1271. return
  1272. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1273. for id in video_ids:
  1274. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1275. return
  1276. pagenum = pagenum + 1
  1277. class YahooSearchIE(InfoExtractor):
  1278. """Information Extractor for Yahoo! Video search queries."""
  1279. _WORKING = False
  1280. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1281. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1282. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1283. _MORE_PAGES_INDICATOR = r'\s*Next'
  1284. _max_yahoo_results = 1000
  1285. IE_NAME = u'video.yahoo:search'
  1286. def __init__(self, downloader=None):
  1287. InfoExtractor.__init__(self, downloader)
  1288. def report_download_page(self, query, pagenum):
  1289. """Report attempt to download playlist page with given number."""
  1290. query = query.decode(preferredencoding())
  1291. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1292. def _real_extract(self, query):
  1293. mobj = re.match(self._VALID_URL, query)
  1294. if mobj is None:
  1295. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1296. return
  1297. prefix, query = query.split(':')
  1298. prefix = prefix[8:]
  1299. query = query.encode('utf-8')
  1300. if prefix == '':
  1301. self._download_n_results(query, 1)
  1302. return
  1303. elif prefix == 'all':
  1304. self._download_n_results(query, self._max_yahoo_results)
  1305. return
  1306. else:
  1307. try:
  1308. n = int(prefix)
  1309. if n <= 0:
  1310. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1311. return
  1312. elif n > self._max_yahoo_results:
  1313. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1314. n = self._max_yahoo_results
  1315. self._download_n_results(query, n)
  1316. return
  1317. except ValueError: # parsing prefix as integer fails
  1318. self._download_n_results(query, 1)
  1319. return
  1320. def _download_n_results(self, query, n):
  1321. """Downloads a specified number of results for a query"""
  1322. video_ids = []
  1323. already_seen = set()
  1324. pagenum = 1
  1325. while True:
  1326. self.report_download_page(query, pagenum)
  1327. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1328. request = compat_urllib_request.Request(result_url)
  1329. try:
  1330. page = compat_urllib_request.urlopen(request).read()
  1331. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1332. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1333. return
  1334. # Extract video identifiers
  1335. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1336. video_id = mobj.group(1)
  1337. if video_id not in already_seen:
  1338. video_ids.append(video_id)
  1339. already_seen.add(video_id)
  1340. if len(video_ids) == n:
  1341. # Specified n videos reached
  1342. for id in video_ids:
  1343. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1344. return
  1345. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1346. for id in video_ids:
  1347. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1348. return
  1349. pagenum = pagenum + 1
  1350. class YoutubePlaylistIE(InfoExtractor):
  1351. """Information Extractor for YouTube playlists."""
  1352. _VALID_URL = r'(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:(?:course|view_play_list|my_playlists|artist|playlist)\?.*?(p|a|list)=|user/.*?/user/|p/|user/.*?#[pg]/c/)(?:PL|EC)?|PL|EC)([0-9A-Za-z-_]{10,})(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1353. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1354. _VIDEO_INDICATOR_TEMPLATE = r'/watch\?v=(.+?)&amp;([^&"]+&amp;)*list=.*?%s'
  1355. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1356. IE_NAME = u'youtube:playlist'
  1357. def __init__(self, downloader=None):
  1358. InfoExtractor.__init__(self, downloader)
  1359. def report_download_page(self, playlist_id, pagenum):
  1360. """Report attempt to download playlist page with given number."""
  1361. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1362. def _real_extract(self, url):
  1363. # Extract playlist id
  1364. mobj = re.match(self._VALID_URL, url)
  1365. if mobj is None:
  1366. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1367. return
  1368. # Single video case
  1369. if mobj.group(3) is not None:
  1370. self._downloader.download([mobj.group(3)])
  1371. return
  1372. # Download playlist pages
  1373. # prefix is 'p' as default for playlists but there are other types that need extra care
  1374. playlist_prefix = mobj.group(1)
  1375. if playlist_prefix == 'a':
  1376. playlist_access = 'artist'
  1377. else:
  1378. playlist_prefix = 'p'
  1379. playlist_access = 'view_play_list'
  1380. playlist_id = mobj.group(2)
  1381. video_ids = []
  1382. pagenum = 1
  1383. while True:
  1384. self.report_download_page(playlist_id, pagenum)
  1385. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  1386. request = compat_urllib_request.Request(url)
  1387. try:
  1388. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1389. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1390. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1391. return
  1392. # Extract video identifiers
  1393. ids_in_page = []
  1394. for mobj in re.finditer(self._VIDEO_INDICATOR_TEMPLATE % playlist_id, page):
  1395. if mobj.group(1) not in ids_in_page:
  1396. ids_in_page.append(mobj.group(1))
  1397. video_ids.extend(ids_in_page)
  1398. if self._MORE_PAGES_INDICATOR not in page:
  1399. break
  1400. pagenum = pagenum + 1
  1401. total = len(video_ids)
  1402. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1403. playlistend = self._downloader.params.get('playlistend', -1)
  1404. if playlistend == -1:
  1405. video_ids = video_ids[playliststart:]
  1406. else:
  1407. video_ids = video_ids[playliststart:playlistend]
  1408. if len(video_ids) == total:
  1409. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos' % (playlist_id, total))
  1410. else:
  1411. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos, downloading %i' % (playlist_id, total, len(video_ids)))
  1412. for id in video_ids:
  1413. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1414. return
  1415. class YoutubeChannelIE(InfoExtractor):
  1416. """Information Extractor for YouTube channels."""
  1417. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1418. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1419. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1420. IE_NAME = u'youtube:channel'
  1421. def report_download_page(self, channel_id, pagenum):
  1422. """Report attempt to download channel page with given number."""
  1423. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1424. def _real_extract(self, url):
  1425. # Extract channel id
  1426. mobj = re.match(self._VALID_URL, url)
  1427. if mobj is None:
  1428. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1429. return
  1430. # Download channel pages
  1431. channel_id = mobj.group(1)
  1432. video_ids = []
  1433. pagenum = 1
  1434. while True:
  1435. self.report_download_page(channel_id, pagenum)
  1436. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1437. request = compat_urllib_request.Request(url)
  1438. try:
  1439. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1440. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1441. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1442. return
  1443. # Extract video identifiers
  1444. ids_in_page = []
  1445. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1446. if mobj.group(1) not in ids_in_page:
  1447. ids_in_page.append(mobj.group(1))
  1448. video_ids.extend(ids_in_page)
  1449. if self._MORE_PAGES_INDICATOR not in page:
  1450. break
  1451. pagenum = pagenum + 1
  1452. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1453. for id in video_ids:
  1454. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1455. return
  1456. class YoutubeUserIE(InfoExtractor):
  1457. """Information Extractor for YouTube users."""
  1458. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1459. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1460. _GDATA_PAGE_SIZE = 50
  1461. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1462. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1463. IE_NAME = u'youtube:user'
  1464. def __init__(self, downloader=None):
  1465. InfoExtractor.__init__(self, downloader)
  1466. def report_download_page(self, username, start_index):
  1467. """Report attempt to download user page."""
  1468. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1469. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1470. def _real_extract(self, url):
  1471. # Extract username
  1472. mobj = re.match(self._VALID_URL, url)
  1473. if mobj is None:
  1474. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1475. return
  1476. username = mobj.group(1)
  1477. # Download video ids using YouTube Data API. Result size per
  1478. # query is limited (currently to 50 videos) so we need to query
  1479. # page by page until there are no video ids - it means we got
  1480. # all of them.
  1481. video_ids = []
  1482. pagenum = 0
  1483. while True:
  1484. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1485. self.report_download_page(username, start_index)
  1486. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1487. try:
  1488. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1489. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1490. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1491. return
  1492. # Extract video identifiers
  1493. ids_in_page = []
  1494. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1495. if mobj.group(1) not in ids_in_page:
  1496. ids_in_page.append(mobj.group(1))
  1497. video_ids.extend(ids_in_page)
  1498. # A little optimization - if current page is not
  1499. # "full", ie. does not contain PAGE_SIZE video ids then
  1500. # we can assume that this page is the last one - there
  1501. # are no more ids on further pages - no need to query
  1502. # again.
  1503. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1504. break
  1505. pagenum += 1
  1506. all_ids_count = len(video_ids)
  1507. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1508. playlistend = self._downloader.params.get('playlistend', -1)
  1509. if playlistend == -1:
  1510. video_ids = video_ids[playliststart:]
  1511. else:
  1512. video_ids = video_ids[playliststart:playlistend]
  1513. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1514. (username, all_ids_count, len(video_ids)))
  1515. for video_id in video_ids:
  1516. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1517. class BlipTVUserIE(InfoExtractor):
  1518. """Information Extractor for blip.tv users."""
  1519. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1520. _PAGE_SIZE = 12
  1521. IE_NAME = u'blip.tv:user'
  1522. def __init__(self, downloader=None):
  1523. InfoExtractor.__init__(self, downloader)
  1524. def report_download_page(self, username, pagenum):
  1525. """Report attempt to download user page."""
  1526. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1527. (self.IE_NAME, username, pagenum))
  1528. def _real_extract(self, url):
  1529. # Extract username
  1530. mobj = re.match(self._VALID_URL, url)
  1531. if mobj is None:
  1532. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1533. return
  1534. username = mobj.group(1)
  1535. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1536. request = compat_urllib_request.Request(url)
  1537. try:
  1538. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1539. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1540. page_base = page_base % mobj.group(1)
  1541. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1542. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1543. return
  1544. # Download video ids using BlipTV Ajax calls. Result size per
  1545. # query is limited (currently to 12 videos) so we need to query
  1546. # page by page until there are no video ids - it means we got
  1547. # all of them.
  1548. video_ids = []
  1549. pagenum = 1
  1550. while True:
  1551. self.report_download_page(username, pagenum)
  1552. request = compat_urllib_request.Request( page_base + "&page=" + str(pagenum) )
  1553. try:
  1554. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1555. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1556. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1557. return
  1558. # Extract video identifiers
  1559. ids_in_page = []
  1560. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1561. if mobj.group(1) not in ids_in_page:
  1562. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1563. video_ids.extend(ids_in_page)
  1564. # A little optimization - if current page is not
  1565. # "full", ie. does not contain PAGE_SIZE video ids then
  1566. # we can assume that this page is the last one - there
  1567. # are no more ids on further pages - no need to query
  1568. # again.
  1569. if len(ids_in_page) < self._PAGE_SIZE:
  1570. break
  1571. pagenum += 1
  1572. all_ids_count = len(video_ids)
  1573. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1574. playlistend = self._downloader.params.get('playlistend', -1)
  1575. if playlistend == -1:
  1576. video_ids = video_ids[playliststart:]
  1577. else:
  1578. video_ids = video_ids[playliststart:playlistend]
  1579. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1580. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1581. for video_id in video_ids:
  1582. self._downloader.download([u'http://blip.tv/'+video_id])
  1583. class DepositFilesIE(InfoExtractor):
  1584. """Information extractor for depositfiles.com"""
  1585. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1586. IE_NAME = u'DepositFiles'
  1587. def __init__(self, downloader=None):
  1588. InfoExtractor.__init__(self, downloader)
  1589. def report_download_webpage(self, file_id):
  1590. """Report webpage download."""
  1591. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1592. def report_extraction(self, file_id):
  1593. """Report information extraction."""
  1594. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1595. def _real_extract(self, url):
  1596. file_id = url.split('/')[-1]
  1597. # Rebuild url in english locale
  1598. url = 'http://depositfiles.com/en/files/' + file_id
  1599. # Retrieve file webpage with 'Free download' button pressed
  1600. free_download_indication = { 'gateway_result' : '1' }
  1601. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1602. try:
  1603. self.report_download_webpage(file_id)
  1604. webpage = compat_urllib_request.urlopen(request).read()
  1605. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1606. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % compat_str(err))
  1607. return
  1608. # Search for the real file URL
  1609. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1610. if (mobj is None) or (mobj.group(1) is None):
  1611. # Try to figure out reason of the error.
  1612. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1613. if (mobj is not None) and (mobj.group(1) is not None):
  1614. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1615. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1616. else:
  1617. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1618. return
  1619. file_url = mobj.group(1)
  1620. file_extension = os.path.splitext(file_url)[1][1:]
  1621. # Search for file title
  1622. mobj = re.search(r'<b title="(.*?)">', webpage)
  1623. if mobj is None:
  1624. self._downloader.trouble(u'ERROR: unable to extract title')
  1625. return
  1626. file_title = mobj.group(1).decode('utf-8')
  1627. return [{
  1628. 'id': file_id.decode('utf-8'),
  1629. 'url': file_url.decode('utf-8'),
  1630. 'uploader': None,
  1631. 'upload_date': None,
  1632. 'title': file_title,
  1633. 'ext': file_extension.decode('utf-8'),
  1634. }]
  1635. class FacebookIE(InfoExtractor):
  1636. """Information Extractor for Facebook"""
  1637. _WORKING = False
  1638. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1639. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1640. _NETRC_MACHINE = 'facebook'
  1641. _available_formats = ['video', 'highqual', 'lowqual']
  1642. _video_extensions = {
  1643. 'video': 'mp4',
  1644. 'highqual': 'mp4',
  1645. 'lowqual': 'mp4',
  1646. }
  1647. IE_NAME = u'facebook'
  1648. def __init__(self, downloader=None):
  1649. InfoExtractor.__init__(self, downloader)
  1650. def _reporter(self, message):
  1651. """Add header and report message."""
  1652. self._downloader.to_screen(u'[facebook] %s' % message)
  1653. def report_login(self):
  1654. """Report attempt to log in."""
  1655. self._reporter(u'Logging in')
  1656. def report_video_webpage_download(self, video_id):
  1657. """Report attempt to download video webpage."""
  1658. self._reporter(u'%s: Downloading video webpage' % video_id)
  1659. def report_information_extraction(self, video_id):
  1660. """Report attempt to extract video information."""
  1661. self._reporter(u'%s: Extracting video information' % video_id)
  1662. def _parse_page(self, video_webpage):
  1663. """Extract video information from page"""
  1664. # General data
  1665. data = {'title': r'\("video_title", "(.*?)"\)',
  1666. 'description': r'<div class="datawrap">(.*?)</div>',
  1667. 'owner': r'\("video_owner_name", "(.*?)"\)',
  1668. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  1669. }
  1670. video_info = {}
  1671. for piece in data.keys():
  1672. mobj = re.search(data[piece], video_webpage)
  1673. if mobj is not None:
  1674. video_info[piece] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1675. # Video urls
  1676. video_urls = {}
  1677. for fmt in self._available_formats:
  1678. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  1679. if mobj is not None:
  1680. # URL is in a Javascript segment inside an escaped Unicode format within
  1681. # the generally utf-8 page
  1682. video_urls[fmt] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1683. video_info['video_urls'] = video_urls
  1684. return video_info
  1685. def _real_initialize(self):
  1686. if self._downloader is None:
  1687. return
  1688. useremail = None
  1689. password = None
  1690. downloader_params = self._downloader.params
  1691. # Attempt to use provided username and password or .netrc data
  1692. if downloader_params.get('username', None) is not None:
  1693. useremail = downloader_params['username']
  1694. password = downloader_params['password']
  1695. elif downloader_params.get('usenetrc', False):
  1696. try:
  1697. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1698. if info is not None:
  1699. useremail = info[0]
  1700. password = info[2]
  1701. else:
  1702. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1703. except (IOError, netrc.NetrcParseError) as err:
  1704. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  1705. return
  1706. if useremail is None:
  1707. return
  1708. # Log in
  1709. login_form = {
  1710. 'email': useremail,
  1711. 'pass': password,
  1712. 'login': 'Log+In'
  1713. }
  1714. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1715. try:
  1716. self.report_login()
  1717. login_results = compat_urllib_request.urlopen(request).read()
  1718. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1719. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1720. return
  1721. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1722. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  1723. return
  1724. def _real_extract(self, url):
  1725. mobj = re.match(self._VALID_URL, url)
  1726. if mobj is None:
  1727. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1728. return
  1729. video_id = mobj.group('ID')
  1730. # Get video webpage
  1731. self.report_video_webpage_download(video_id)
  1732. request = compat_urllib_request.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  1733. try:
  1734. page = compat_urllib_request.urlopen(request)
  1735. video_webpage = page.read()
  1736. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1737. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  1738. return
  1739. # Start extracting information
  1740. self.report_information_extraction(video_id)
  1741. # Extract information
  1742. video_info = self._parse_page(video_webpage)
  1743. # uploader
  1744. if 'owner' not in video_info:
  1745. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1746. return
  1747. video_uploader = video_info['owner']
  1748. # title
  1749. if 'title' not in video_info:
  1750. self._downloader.trouble(u'ERROR: unable to extract video title')
  1751. return
  1752. video_title = video_info['title']
  1753. video_title = video_title.decode('utf-8')
  1754. # thumbnail image
  1755. if 'thumbnail' not in video_info:
  1756. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1757. video_thumbnail = ''
  1758. else:
  1759. video_thumbnail = video_info['thumbnail']
  1760. # upload date
  1761. upload_date = None
  1762. if 'upload_date' in video_info:
  1763. upload_time = video_info['upload_date']
  1764. timetuple = email.utils.parsedate_tz(upload_time)
  1765. if timetuple is not None:
  1766. try:
  1767. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  1768. except:
  1769. pass
  1770. # description
  1771. video_description = video_info.get('description', 'No description available.')
  1772. url_map = video_info['video_urls']
  1773. if len(list(url_map.keys())) > 0:
  1774. # Decide which formats to download
  1775. req_format = self._downloader.params.get('format', None)
  1776. format_limit = self._downloader.params.get('format_limit', None)
  1777. if format_limit is not None and format_limit in self._available_formats:
  1778. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1779. else:
  1780. format_list = self._available_formats
  1781. existing_formats = [x for x in format_list if x in url_map]
  1782. if len(existing_formats) == 0:
  1783. self._downloader.trouble(u'ERROR: no known formats available for video')
  1784. return
  1785. if req_format is None:
  1786. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1787. elif req_format == 'worst':
  1788. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1789. elif req_format == '-1':
  1790. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1791. else:
  1792. # Specific format
  1793. if req_format not in url_map:
  1794. self._downloader.trouble(u'ERROR: requested format not available')
  1795. return
  1796. video_url_list = [(req_format, url_map[req_format])] # Specific format
  1797. results = []
  1798. for format_param, video_real_url in video_url_list:
  1799. # Extension
  1800. video_extension = self._video_extensions.get(format_param, 'mp4')
  1801. results.append({
  1802. 'id': video_id.decode('utf-8'),
  1803. 'url': video_real_url.decode('utf-8'),
  1804. 'uploader': video_uploader.decode('utf-8'),
  1805. 'upload_date': upload_date,
  1806. 'title': video_title,
  1807. 'ext': video_extension.decode('utf-8'),
  1808. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1809. 'thumbnail': video_thumbnail.decode('utf-8'),
  1810. 'description': video_description.decode('utf-8'),
  1811. })
  1812. return results
  1813. class BlipTVIE(InfoExtractor):
  1814. """Information extractor for blip.tv"""
  1815. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1816. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1817. IE_NAME = u'blip.tv'
  1818. def report_extraction(self, file_id):
  1819. """Report information extraction."""
  1820. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1821. def report_direct_download(self, title):
  1822. """Report information extraction."""
  1823. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1824. def _real_extract(self, url):
  1825. mobj = re.match(self._VALID_URL, url)
  1826. if mobj is None:
  1827. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1828. return
  1829. if '?' in url:
  1830. cchar = '&'
  1831. else:
  1832. cchar = '?'
  1833. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1834. request = compat_urllib_request.Request(json_url)
  1835. self.report_extraction(mobj.group(1))
  1836. info = None
  1837. try:
  1838. urlh = compat_urllib_request.urlopen(request)
  1839. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1840. basename = url.split('/')[-1]
  1841. title,ext = os.path.splitext(basename)
  1842. title = title.decode('UTF-8')
  1843. ext = ext.replace('.', '')
  1844. self.report_direct_download(title)
  1845. info = {
  1846. 'id': title,
  1847. 'url': url,
  1848. 'uploader': None,
  1849. 'upload_date': None,
  1850. 'title': title,
  1851. 'ext': ext,
  1852. 'urlhandle': urlh
  1853. }
  1854. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1855. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1856. return
  1857. if info is None: # Regular URL
  1858. try:
  1859. json_code_bytes = urlh.read()
  1860. json_code = json_code_bytes.decode('utf-8')
  1861. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1862. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % compat_str(err))
  1863. return
  1864. try:
  1865. json_data = json.loads(json_code)
  1866. if 'Post' in json_data:
  1867. data = json_data['Post']
  1868. else:
  1869. data = json_data
  1870. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1871. video_url = data['media']['url']
  1872. umobj = re.match(self._URL_EXT, video_url)
  1873. if umobj is None:
  1874. raise ValueError('Can not determine filename extension')
  1875. ext = umobj.group(1)
  1876. info = {
  1877. 'id': data['item_id'],
  1878. 'url': video_url,
  1879. 'uploader': data['display_name'],
  1880. 'upload_date': upload_date,
  1881. 'title': data['title'],
  1882. 'ext': ext,
  1883. 'format': data['media']['mimeType'],
  1884. 'thumbnail': data['thumbnailUrl'],
  1885. 'description': data['description'],
  1886. 'player_url': data['embedUrl']
  1887. }
  1888. except (ValueError,KeyError) as err:
  1889. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1890. return
  1891. std_headers['User-Agent'] = 'iTunes/10.6.1'
  1892. return [info]
  1893. class MyVideoIE(InfoExtractor):
  1894. """Information Extractor for myvideo.de."""
  1895. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1896. IE_NAME = u'myvideo'
  1897. def __init__(self, downloader=None):
  1898. InfoExtractor.__init__(self, downloader)
  1899. def report_download_webpage(self, video_id):
  1900. """Report webpage download."""
  1901. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  1902. def report_extraction(self, video_id):
  1903. """Report information extraction."""
  1904. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1905. def _real_extract(self,url):
  1906. mobj = re.match(self._VALID_URL, url)
  1907. if mobj is None:
  1908. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1909. return
  1910. video_id = mobj.group(1)
  1911. # Get video webpage
  1912. request = compat_urllib_request.Request('http://www.myvideo.de/watch/%s' % video_id)
  1913. try:
  1914. self.report_download_webpage(video_id)
  1915. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1916. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1917. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1918. return
  1919. self.report_extraction(video_id)
  1920. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  1921. webpage)
  1922. if mobj is None:
  1923. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1924. return
  1925. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1926. mobj = re.search('<title>([^<]+)</title>', webpage)
  1927. if mobj is None:
  1928. self._downloader.trouble(u'ERROR: unable to extract title')
  1929. return
  1930. video_title = mobj.group(1)
  1931. return [{
  1932. 'id': video_id,
  1933. 'url': video_url,
  1934. 'uploader': None,
  1935. 'upload_date': None,
  1936. 'title': video_title,
  1937. 'ext': u'flv',
  1938. }]
  1939. class ComedyCentralIE(InfoExtractor):
  1940. """Information extractor for The Daily Show and Colbert Report """
  1941. # urls can be abbreviations like :thedailyshow or :colbert
  1942. # urls for episodes like:
  1943. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1944. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1945. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1946. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1947. |(https?://)?(www\.)?
  1948. (?P<showname>thedailyshow|colbertnation)\.com/
  1949. (full-episodes/(?P<episode>.*)|
  1950. (?P<clip>
  1951. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1952. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1953. $"""
  1954. IE_NAME = u'comedycentral'
  1955. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1956. _video_extensions = {
  1957. '3500': 'mp4',
  1958. '2200': 'mp4',
  1959. '1700': 'mp4',
  1960. '1200': 'mp4',
  1961. '750': 'mp4',
  1962. '400': 'mp4',
  1963. }
  1964. _video_dimensions = {
  1965. '3500': '1280x720',
  1966. '2200': '960x540',
  1967. '1700': '768x432',
  1968. '1200': '640x360',
  1969. '750': '512x288',
  1970. '400': '384x216',
  1971. }
  1972. def suitable(self, url):
  1973. """Receives a URL and returns True if suitable for this IE."""
  1974. return re.match(self._VALID_URL, url, re.VERBOSE) is not None
  1975. def report_extraction(self, episode_id):
  1976. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1977. def report_config_download(self, episode_id):
  1978. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  1979. def report_index_download(self, episode_id):
  1980. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  1981. def report_player_url(self, episode_id):
  1982. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  1983. def _print_formats(self, formats):
  1984. print('Available formats:')
  1985. for x in formats:
  1986. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  1987. def _real_extract(self, url):
  1988. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1989. if mobj is None:
  1990. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1991. return
  1992. if mobj.group('shortname'):
  1993. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1994. url = u'http://www.thedailyshow.com/full-episodes/'
  1995. else:
  1996. url = u'http://www.colbertnation.com/full-episodes/'
  1997. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1998. assert mobj is not None
  1999. if mobj.group('clip'):
  2000. if mobj.group('showname') == 'thedailyshow':
  2001. epTitle = mobj.group('tdstitle')
  2002. else:
  2003. epTitle = mobj.group('cntitle')
  2004. dlNewest = False
  2005. else:
  2006. dlNewest = not mobj.group('episode')
  2007. if dlNewest:
  2008. epTitle = mobj.group('showname')
  2009. else:
  2010. epTitle = mobj.group('episode')
  2011. req = compat_urllib_request.Request(url)
  2012. self.report_extraction(epTitle)
  2013. try:
  2014. htmlHandle = compat_urllib_request.urlopen(req)
  2015. html = htmlHandle.read()
  2016. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2017. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2018. return
  2019. if dlNewest:
  2020. url = htmlHandle.geturl()
  2021. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2022. if mobj is None:
  2023. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2024. return
  2025. if mobj.group('episode') == '':
  2026. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2027. return
  2028. epTitle = mobj.group('episode')
  2029. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', html)
  2030. if len(mMovieParams) == 0:
  2031. # The Colbert Report embeds the information in a without
  2032. # a URL prefix; so extract the alternate reference
  2033. # and then add the URL prefix manually.
  2034. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', html)
  2035. if len(altMovieParams) == 0:
  2036. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2037. return
  2038. else:
  2039. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2040. playerUrl_raw = mMovieParams[0][0]
  2041. self.report_player_url(epTitle)
  2042. try:
  2043. urlHandle = compat_urllib_request.urlopen(playerUrl_raw)
  2044. playerUrl = urlHandle.geturl()
  2045. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2046. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + compat_str(err))
  2047. return
  2048. uri = mMovieParams[0][1]
  2049. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2050. self.report_index_download(epTitle)
  2051. try:
  2052. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2053. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2054. self._downloader.trouble(u'ERROR: unable to download episode index: ' + compat_str(err))
  2055. return
  2056. results = []
  2057. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2058. itemEls = idoc.findall('.//item')
  2059. for itemEl in itemEls:
  2060. mediaId = itemEl.findall('./guid')[0].text
  2061. shortMediaId = mediaId.split(':')[-1]
  2062. showId = mediaId.split(':')[-2].replace('.com', '')
  2063. officialTitle = itemEl.findall('./title')[0].text
  2064. officialDate = itemEl.findall('./pubDate')[0].text
  2065. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2066. compat_urllib_parse.urlencode({'uri': mediaId}))
  2067. configReq = compat_urllib_request.Request(configUrl)
  2068. self.report_config_download(epTitle)
  2069. try:
  2070. configXml = compat_urllib_request.urlopen(configReq).read()
  2071. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2072. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2073. return
  2074. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2075. turls = []
  2076. for rendition in cdoc.findall('.//rendition'):
  2077. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2078. turls.append(finfo)
  2079. if len(turls) == 0:
  2080. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2081. continue
  2082. if self._downloader.params.get('listformats', None):
  2083. self._print_formats([i[0] for i in turls])
  2084. return
  2085. # For now, just pick the highest bitrate
  2086. format,video_url = turls[-1]
  2087. # Get the format arg from the arg stream
  2088. req_format = self._downloader.params.get('format', None)
  2089. # Select format if we can find one
  2090. for f,v in turls:
  2091. if f == req_format:
  2092. format, video_url = f, v
  2093. break
  2094. # Patch to download from alternative CDN, which does not
  2095. # break on current RTMPDump builds
  2096. broken_cdn = "rtmpe://viacomccstrmfs.fplive.net/viacomccstrm/gsp.comedystor/"
  2097. better_cdn = "rtmpe://cp10740.edgefcs.net/ondemand/mtvnorigin/gsp.comedystor/"
  2098. if video_url.startswith(broken_cdn):
  2099. video_url = video_url.replace(broken_cdn, better_cdn)
  2100. effTitle = showId + u'-' + epTitle
  2101. info = {
  2102. 'id': shortMediaId,
  2103. 'url': video_url,
  2104. 'uploader': showId,
  2105. 'upload_date': officialDate,
  2106. 'title': effTitle,
  2107. 'ext': 'mp4',
  2108. 'format': format,
  2109. 'thumbnail': None,
  2110. 'description': officialTitle,
  2111. 'player_url': None #playerUrl
  2112. }
  2113. results.append(info)
  2114. return results
  2115. class EscapistIE(InfoExtractor):
  2116. """Information extractor for The Escapist """
  2117. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2118. IE_NAME = u'escapist'
  2119. def report_extraction(self, showName):
  2120. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2121. def report_config_download(self, showName):
  2122. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2123. def _real_extract(self, url):
  2124. mobj = re.match(self._VALID_URL, url)
  2125. if mobj is None:
  2126. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2127. return
  2128. showName = mobj.group('showname')
  2129. videoId = mobj.group('episode')
  2130. self.report_extraction(showName)
  2131. try:
  2132. webPage = compat_urllib_request.urlopen(url)
  2133. webPageBytes = webPage.read()
  2134. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2135. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2136. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2137. self._downloader.trouble(u'ERROR: unable to download webpage: ' + compat_str(err))
  2138. return
  2139. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2140. description = unescapeHTML(descMatch.group(1))
  2141. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2142. imgUrl = unescapeHTML(imgMatch.group(1))
  2143. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2144. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2145. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2146. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2147. self.report_config_download(showName)
  2148. try:
  2149. configJSON = compat_urllib_request.urlopen(configUrl)
  2150. m = re.match(r'text/html; charset="?([^"]+)"?', configJSON.headers['Content-Type'])
  2151. configJSON = configJSON.read().decode(m.group(1) if m else 'utf-8')
  2152. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2153. self._downloader.trouble(u'ERROR: unable to download configuration: ' + compat_str(err))
  2154. return
  2155. # Technically, it's JavaScript, not JSON
  2156. configJSON = configJSON.replace("'", '"')
  2157. try:
  2158. config = json.loads(configJSON)
  2159. except (ValueError,) as err:
  2160. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + compat_str(err))
  2161. return
  2162. playlist = config['playlist']
  2163. videoUrl = playlist[1]['url']
  2164. info = {
  2165. 'id': videoId,
  2166. 'url': videoUrl,
  2167. 'uploader': showName,
  2168. 'upload_date': None,
  2169. 'title': showName,
  2170. 'ext': 'flv',
  2171. 'thumbnail': imgUrl,
  2172. 'description': description,
  2173. 'player_url': playerUrl,
  2174. }
  2175. return [info]
  2176. class CollegeHumorIE(InfoExtractor):
  2177. """Information extractor for collegehumor.com"""
  2178. _WORKING = False
  2179. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2180. IE_NAME = u'collegehumor'
  2181. def report_manifest(self, video_id):
  2182. """Report information extraction."""
  2183. self._downloader.to_screen(u'[%s] %s: Downloading XML manifest' % (self.IE_NAME, video_id))
  2184. def report_extraction(self, video_id):
  2185. """Report information extraction."""
  2186. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2187. def _real_extract(self, url):
  2188. mobj = re.match(self._VALID_URL, url)
  2189. if mobj is None:
  2190. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2191. return
  2192. video_id = mobj.group('videoid')
  2193. info = {
  2194. 'id': video_id,
  2195. 'uploader': None,
  2196. 'upload_date': None,
  2197. }
  2198. self.report_extraction(video_id)
  2199. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2200. try:
  2201. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2202. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2203. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2204. return
  2205. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2206. try:
  2207. videoNode = mdoc.findall('./video')[0]
  2208. info['description'] = videoNode.findall('./description')[0].text
  2209. info['title'] = videoNode.findall('./caption')[0].text
  2210. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2211. manifest_url = videoNode.findall('./file')[0].text
  2212. except IndexError:
  2213. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2214. return
  2215. manifest_url += '?hdcore=2.10.3'
  2216. self.report_manifest(video_id)
  2217. try:
  2218. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2219. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2220. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2221. return
  2222. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2223. try:
  2224. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2225. node_id = media_node.attrib['url']
  2226. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2227. except IndexError as err:
  2228. self._downloader.trouble(u'\nERROR: Invalid manifest file')
  2229. return
  2230. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2231. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2232. info['url'] = url
  2233. info['ext'] = 'f4f'
  2234. return [info]
  2235. class XVideosIE(InfoExtractor):
  2236. """Information extractor for xvideos.com"""
  2237. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2238. IE_NAME = u'xvideos'
  2239. def report_webpage(self, video_id):
  2240. """Report information extraction."""
  2241. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2242. def report_extraction(self, video_id):
  2243. """Report information extraction."""
  2244. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2245. def _real_extract(self, url):
  2246. mobj = re.match(self._VALID_URL, url)
  2247. if mobj is None:
  2248. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2249. return
  2250. video_id = mobj.group(1)
  2251. self.report_webpage(video_id)
  2252. request = compat_urllib_request.Request(r'http://www.xvideos.com/video' + video_id)
  2253. try:
  2254. webpage_bytes = compat_urllib_request.urlopen(request).read()
  2255. webpage = webpage_bytes.decode('utf-8', 'replace')
  2256. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2257. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2258. return
  2259. self.report_extraction(video_id)
  2260. # Extract video URL
  2261. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2262. if mobj is None:
  2263. self._downloader.trouble(u'ERROR: unable to extract video url')
  2264. return
  2265. video_url = compat_urllib_parse.unquote(mobj.group(1))
  2266. # Extract title
  2267. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2268. if mobj is None:
  2269. self._downloader.trouble(u'ERROR: unable to extract video title')
  2270. return
  2271. video_title = mobj.group(1)
  2272. # Extract video thumbnail
  2273. 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)
  2274. if mobj is None:
  2275. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2276. return
  2277. video_thumbnail = mobj.group(0)
  2278. info = {
  2279. 'id': video_id,
  2280. 'url': video_url,
  2281. 'uploader': None,
  2282. 'upload_date': None,
  2283. 'title': video_title,
  2284. 'ext': 'flv',
  2285. 'thumbnail': video_thumbnail,
  2286. 'description': None,
  2287. }
  2288. return [info]
  2289. class SoundcloudIE(InfoExtractor):
  2290. """Information extractor for soundcloud.com
  2291. To access the media, the uid of the song and a stream token
  2292. must be extracted from the page source and the script must make
  2293. a request to media.soundcloud.com/crossdomain.xml. Then
  2294. the media can be grabbed by requesting from an url composed
  2295. of the stream token and uid
  2296. """
  2297. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2298. IE_NAME = u'soundcloud'
  2299. def __init__(self, downloader=None):
  2300. InfoExtractor.__init__(self, downloader)
  2301. def report_resolve(self, video_id):
  2302. """Report information extraction."""
  2303. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2304. def report_extraction(self, video_id):
  2305. """Report information extraction."""
  2306. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2307. def _real_extract(self, url):
  2308. mobj = re.match(self._VALID_URL, url)
  2309. if mobj is None:
  2310. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2311. return
  2312. # extract uploader (which is in the url)
  2313. uploader = mobj.group(1)
  2314. # extract simple title (uploader + slug of song title)
  2315. slug_title = mobj.group(2)
  2316. simple_title = uploader + u'-' + slug_title
  2317. self.report_resolve('%s/%s' % (uploader, slug_title))
  2318. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  2319. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2320. request = compat_urllib_request.Request(resolv_url)
  2321. try:
  2322. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2323. info_json = info_json_bytes.decode('utf-8')
  2324. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2325. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2326. return
  2327. info = json.loads(info_json)
  2328. video_id = info['id']
  2329. self.report_extraction('%s/%s' % (uploader, slug_title))
  2330. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2331. request = compat_urllib_request.Request(streams_url)
  2332. try:
  2333. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2334. stream_json = stream_json_bytes.decode('utf-8')
  2335. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2336. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2337. return
  2338. streams = json.loads(stream_json)
  2339. mediaURL = streams['http_mp3_128_url']
  2340. return [{
  2341. 'id': info['id'],
  2342. 'url': mediaURL,
  2343. 'uploader': info['user']['username'],
  2344. 'upload_date': info['created_at'],
  2345. 'title': info['title'],
  2346. 'ext': u'mp3',
  2347. 'description': info['description'],
  2348. }]
  2349. class InfoQIE(InfoExtractor):
  2350. """Information extractor for infoq.com"""
  2351. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2352. IE_NAME = u'infoq'
  2353. def report_webpage(self, video_id):
  2354. """Report information extraction."""
  2355. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2356. def report_extraction(self, video_id):
  2357. """Report information extraction."""
  2358. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2359. def _real_extract(self, url):
  2360. mobj = re.match(self._VALID_URL, url)
  2361. if mobj is None:
  2362. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2363. return
  2364. self.report_webpage(url)
  2365. request = compat_urllib_request.Request(url)
  2366. try:
  2367. webpage = compat_urllib_request.urlopen(request).read()
  2368. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2369. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2370. return
  2371. self.report_extraction(url)
  2372. # Extract video URL
  2373. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2374. if mobj is None:
  2375. self._downloader.trouble(u'ERROR: unable to extract video url')
  2376. return
  2377. video_url = 'rtmpe://video.infoq.com/cfx/st/' + compat_urllib_parse.unquote(mobj.group(1).decode('base64'))
  2378. # Extract title
  2379. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2380. if mobj is None:
  2381. self._downloader.trouble(u'ERROR: unable to extract video title')
  2382. return
  2383. video_title = mobj.group(1).decode('utf-8')
  2384. # Extract description
  2385. video_description = u'No description available.'
  2386. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2387. if mobj is not None:
  2388. video_description = mobj.group(1).decode('utf-8')
  2389. video_filename = video_url.split('/')[-1]
  2390. video_id, extension = video_filename.split('.')
  2391. info = {
  2392. 'id': video_id,
  2393. 'url': video_url,
  2394. 'uploader': None,
  2395. 'upload_date': None,
  2396. 'title': video_title,
  2397. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2398. 'thumbnail': None,
  2399. 'description': video_description,
  2400. }
  2401. return [info]
  2402. class MixcloudIE(InfoExtractor):
  2403. """Information extractor for www.mixcloud.com"""
  2404. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2405. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2406. IE_NAME = u'mixcloud'
  2407. def __init__(self, downloader=None):
  2408. InfoExtractor.__init__(self, downloader)
  2409. def report_download_json(self, file_id):
  2410. """Report JSON download."""
  2411. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2412. def report_extraction(self, file_id):
  2413. """Report information extraction."""
  2414. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2415. def get_urls(self, jsonData, fmt, bitrate='best'):
  2416. """Get urls from 'audio_formats' section in json"""
  2417. file_url = None
  2418. try:
  2419. bitrate_list = jsonData[fmt]
  2420. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2421. bitrate = max(bitrate_list) # select highest
  2422. url_list = jsonData[fmt][bitrate]
  2423. except TypeError: # we have no bitrate info.
  2424. url_list = jsonData[fmt]
  2425. return url_list
  2426. def check_urls(self, url_list):
  2427. """Returns 1st active url from list"""
  2428. for url in url_list:
  2429. try:
  2430. compat_urllib_request.urlopen(url)
  2431. return url
  2432. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2433. url = None
  2434. return None
  2435. def _print_formats(self, formats):
  2436. print('Available formats:')
  2437. for fmt in formats.keys():
  2438. for b in formats[fmt]:
  2439. try:
  2440. ext = formats[fmt][b][0]
  2441. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2442. except TypeError: # we have no bitrate info
  2443. ext = formats[fmt][0]
  2444. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2445. break
  2446. def _real_extract(self, url):
  2447. mobj = re.match(self._VALID_URL, url)
  2448. if mobj is None:
  2449. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2450. return
  2451. # extract uploader & filename from url
  2452. uploader = mobj.group(1).decode('utf-8')
  2453. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2454. # construct API request
  2455. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2456. # retrieve .json file with links to files
  2457. request = compat_urllib_request.Request(file_url)
  2458. try:
  2459. self.report_download_json(file_url)
  2460. jsonData = compat_urllib_request.urlopen(request).read()
  2461. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2462. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % compat_str(err))
  2463. return
  2464. # parse JSON
  2465. json_data = json.loads(jsonData)
  2466. player_url = json_data['player_swf_url']
  2467. formats = dict(json_data['audio_formats'])
  2468. req_format = self._downloader.params.get('format', None)
  2469. bitrate = None
  2470. if self._downloader.params.get('listformats', None):
  2471. self._print_formats(formats)
  2472. return
  2473. if req_format is None or req_format == 'best':
  2474. for format_param in formats.keys():
  2475. url_list = self.get_urls(formats, format_param)
  2476. # check urls
  2477. file_url = self.check_urls(url_list)
  2478. if file_url is not None:
  2479. break # got it!
  2480. else:
  2481. if req_format not in list(formats.keys()):
  2482. self._downloader.trouble(u'ERROR: format is not available')
  2483. return
  2484. url_list = self.get_urls(formats, req_format)
  2485. file_url = self.check_urls(url_list)
  2486. format_param = req_format
  2487. return [{
  2488. 'id': file_id.decode('utf-8'),
  2489. 'url': file_url.decode('utf-8'),
  2490. 'uploader': uploader.decode('utf-8'),
  2491. 'upload_date': None,
  2492. 'title': json_data['name'],
  2493. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2494. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2495. 'thumbnail': json_data['thumbnail_url'],
  2496. 'description': json_data['description'],
  2497. 'player_url': player_url.decode('utf-8'),
  2498. }]
  2499. class StanfordOpenClassroomIE(InfoExtractor):
  2500. """Information extractor for Stanford's Open ClassRoom"""
  2501. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2502. IE_NAME = u'stanfordoc'
  2503. def report_download_webpage(self, objid):
  2504. """Report information extraction."""
  2505. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2506. def report_extraction(self, video_id):
  2507. """Report information extraction."""
  2508. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2509. def _real_extract(self, url):
  2510. mobj = re.match(self._VALID_URL, url)
  2511. if mobj is None:
  2512. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2513. return
  2514. if mobj.group('course') and mobj.group('video'): # A specific video
  2515. course = mobj.group('course')
  2516. video = mobj.group('video')
  2517. info = {
  2518. 'id': course + '_' + video,
  2519. 'uploader': None,
  2520. 'upload_date': None,
  2521. }
  2522. self.report_extraction(info['id'])
  2523. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2524. xmlUrl = baseUrl + video + '.xml'
  2525. try:
  2526. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2527. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2528. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2529. return
  2530. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2531. try:
  2532. info['title'] = mdoc.findall('./title')[0].text
  2533. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2534. except IndexError:
  2535. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2536. return
  2537. info['ext'] = info['url'].rpartition('.')[2]
  2538. return [info]
  2539. elif mobj.group('course'): # A course page
  2540. course = mobj.group('course')
  2541. info = {
  2542. 'id': course,
  2543. 'type': 'playlist',
  2544. 'uploader': None,
  2545. 'upload_date': None,
  2546. }
  2547. self.report_download_webpage(info['id'])
  2548. try:
  2549. coursepage = compat_urllib_request.urlopen(url).read()
  2550. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2551. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2552. return
  2553. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2554. if m:
  2555. info['title'] = unescapeHTML(m.group(1))
  2556. else:
  2557. info['title'] = info['id']
  2558. m = re.search('<description>([^<]+)</description>', coursepage)
  2559. if m:
  2560. info['description'] = unescapeHTML(m.group(1))
  2561. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2562. info['list'] = [
  2563. {
  2564. 'type': 'reference',
  2565. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2566. }
  2567. for vpage in links]
  2568. results = []
  2569. for entry in info['list']:
  2570. assert entry['type'] == 'reference'
  2571. results += self.extract(entry['url'])
  2572. return results
  2573. else: # Root page
  2574. info = {
  2575. 'id': 'Stanford OpenClassroom',
  2576. 'type': 'playlist',
  2577. 'uploader': None,
  2578. 'upload_date': None,
  2579. }
  2580. self.report_download_webpage(info['id'])
  2581. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2582. try:
  2583. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2584. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2585. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2586. return
  2587. info['title'] = info['id']
  2588. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2589. info['list'] = [
  2590. {
  2591. 'type': 'reference',
  2592. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2593. }
  2594. for cpage in links]
  2595. results = []
  2596. for entry in info['list']:
  2597. assert entry['type'] == 'reference'
  2598. results += self.extract(entry['url'])
  2599. return results
  2600. class MTVIE(InfoExtractor):
  2601. """Information extractor for MTV.com"""
  2602. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2603. IE_NAME = u'mtv'
  2604. def report_webpage(self, video_id):
  2605. """Report information extraction."""
  2606. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2607. def report_extraction(self, video_id):
  2608. """Report information extraction."""
  2609. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2610. def _real_extract(self, url):
  2611. mobj = re.match(self._VALID_URL, url)
  2612. if mobj is None:
  2613. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2614. return
  2615. if not mobj.group('proto'):
  2616. url = 'http://' + url
  2617. video_id = mobj.group('videoid')
  2618. self.report_webpage(video_id)
  2619. request = compat_urllib_request.Request(url)
  2620. try:
  2621. webpage = compat_urllib_request.urlopen(request).read()
  2622. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2623. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2624. return
  2625. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2626. if mobj is None:
  2627. self._downloader.trouble(u'ERROR: unable to extract song name')
  2628. return
  2629. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2630. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2631. if mobj is None:
  2632. self._downloader.trouble(u'ERROR: unable to extract performer')
  2633. return
  2634. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2635. video_title = performer + ' - ' + song_name
  2636. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2637. if mobj is None:
  2638. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2639. return
  2640. mtvn_uri = mobj.group(1)
  2641. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2642. if mobj is None:
  2643. self._downloader.trouble(u'ERROR: unable to extract content id')
  2644. return
  2645. content_id = mobj.group(1)
  2646. 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
  2647. self.report_extraction(video_id)
  2648. request = compat_urllib_request.Request(videogen_url)
  2649. try:
  2650. metadataXml = compat_urllib_request.urlopen(request).read()
  2651. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2652. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % compat_str(err))
  2653. return
  2654. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2655. renditions = mdoc.findall('.//rendition')
  2656. # For now, always pick the highest quality.
  2657. rendition = renditions[-1]
  2658. try:
  2659. _,_,ext = rendition.attrib['type'].partition('/')
  2660. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2661. video_url = rendition.find('./src').text
  2662. except KeyError:
  2663. self._downloader.trouble('Invalid rendition field.')
  2664. return
  2665. info = {
  2666. 'id': video_id,
  2667. 'url': video_url,
  2668. 'uploader': performer,
  2669. 'upload_date': None,
  2670. 'title': video_title,
  2671. 'ext': ext,
  2672. 'format': format,
  2673. }
  2674. return [info]
  2675. class YoukuIE(InfoExtractor):
  2676. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2677. IE_NAME = u'Youku'
  2678. def __init__(self, downloader=None):
  2679. InfoExtractor.__init__(self, downloader)
  2680. def report_download_webpage(self, file_id):
  2681. """Report webpage download."""
  2682. self._downloader.to_screen(u'[Youku] %s: Downloading webpage' % file_id)
  2683. def report_extraction(self, file_id):
  2684. """Report information extraction."""
  2685. self._downloader.to_screen(u'[Youku] %s: Extracting information' % file_id)
  2686. def _gen_sid(self):
  2687. nowTime = int(time.time() * 1000)
  2688. random1 = random.randint(1000,1998)
  2689. random2 = random.randint(1000,9999)
  2690. return "%d%d%d" %(nowTime,random1,random2)
  2691. def _get_file_ID_mix_string(self, seed):
  2692. mixed = []
  2693. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2694. seed = float(seed)
  2695. for i in range(len(source)):
  2696. seed = (seed * 211 + 30031 ) % 65536
  2697. index = math.floor(seed / 65536 * len(source) )
  2698. mixed.append(source[int(index)])
  2699. source.remove(source[int(index)])
  2700. #return ''.join(mixed)
  2701. return mixed
  2702. def _get_file_id(self, fileId, seed):
  2703. mixed = self._get_file_ID_mix_string(seed)
  2704. ids = fileId.split('*')
  2705. realId = []
  2706. for ch in ids:
  2707. if ch:
  2708. realId.append(mixed[int(ch)])
  2709. return ''.join(realId)
  2710. def _real_extract(self, url):
  2711. mobj = re.match(self._VALID_URL, url)
  2712. if mobj is None:
  2713. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2714. return
  2715. video_id = mobj.group('ID')
  2716. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2717. request = compat_urllib_request.Request(info_url, None, std_headers)
  2718. try:
  2719. self.report_download_webpage(video_id)
  2720. jsondata = compat_urllib_request.urlopen(request).read()
  2721. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2722. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2723. return
  2724. self.report_extraction(video_id)
  2725. try:
  2726. jsonstr = jsondata.decode('utf-8')
  2727. config = json.loads(jsonstr)
  2728. video_title = config['data'][0]['title']
  2729. seed = config['data'][0]['seed']
  2730. format = self._downloader.params.get('format', None)
  2731. supported_format = list(config['data'][0]['streamfileids'].keys())
  2732. if format is None or format == 'best':
  2733. if 'hd2' in supported_format:
  2734. format = 'hd2'
  2735. else:
  2736. format = 'flv'
  2737. ext = u'flv'
  2738. elif format == 'worst':
  2739. format = 'mp4'
  2740. ext = u'mp4'
  2741. else:
  2742. format = 'flv'
  2743. ext = u'flv'
  2744. fileid = config['data'][0]['streamfileids'][format]
  2745. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2746. except (UnicodeDecodeError, ValueError, KeyError):
  2747. self._downloader.trouble(u'ERROR: unable to extract info section')
  2748. return
  2749. files_info=[]
  2750. sid = self._gen_sid()
  2751. fileid = self._get_file_id(fileid, seed)
  2752. #column 8,9 of fileid represent the segment number
  2753. #fileid[7:9] should be changed
  2754. for index, key in enumerate(keys):
  2755. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2756. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2757. info = {
  2758. 'id': '%s_part%02d' % (video_id, index),
  2759. 'url': download_url,
  2760. 'uploader': None,
  2761. 'upload_date': None,
  2762. 'title': video_title,
  2763. 'ext': ext,
  2764. }
  2765. files_info.append(info)
  2766. return files_info
  2767. class XNXXIE(InfoExtractor):
  2768. """Information extractor for xnxx.com"""
  2769. _VALID_URL = r'^http://video\.xnxx\.com/video([0-9]+)/(.*)'
  2770. IE_NAME = u'xnxx'
  2771. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2772. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2773. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2774. def report_webpage(self, video_id):
  2775. """Report information extraction"""
  2776. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2777. def report_extraction(self, video_id):
  2778. """Report information extraction"""
  2779. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2780. def _real_extract(self, url):
  2781. mobj = re.match(self._VALID_URL, url)
  2782. if mobj is None:
  2783. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2784. return
  2785. video_id = mobj.group(1)
  2786. self.report_webpage(video_id)
  2787. # Get webpage content
  2788. try:
  2789. webpage_bytes = compat_urllib_request.urlopen(url).read()
  2790. webpage = webpage_bytes.decode('utf-8')
  2791. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2792. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2793. return
  2794. result = re.search(self.VIDEO_URL_RE, webpage)
  2795. if result is None:
  2796. self._downloader.trouble(u'ERROR: unable to extract video url')
  2797. return
  2798. video_url = compat_urllib_parse.unquote(result.group(1))
  2799. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2800. if result is None:
  2801. self._downloader.trouble(u'ERROR: unable to extract video title')
  2802. return
  2803. video_title = result.group(1)
  2804. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2805. if result is None:
  2806. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2807. return
  2808. video_thumbnail = result.group(1)
  2809. return [{
  2810. 'id': video_id,
  2811. 'url': video_url,
  2812. 'uploader': None,
  2813. 'upload_date': None,
  2814. 'title': video_title,
  2815. 'ext': 'flv',
  2816. 'thumbnail': video_thumbnail,
  2817. 'description': None,
  2818. }]
  2819. class GooglePlusIE(InfoExtractor):
  2820. """Information extractor for plus.google.com."""
  2821. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2822. IE_NAME = u'plus.google'
  2823. def __init__(self, downloader=None):
  2824. InfoExtractor.__init__(self, downloader)
  2825. def report_extract_entry(self, url):
  2826. """Report downloading extry"""
  2827. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url)
  2828. def report_date(self, upload_date):
  2829. """Report downloading extry"""
  2830. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2831. def report_uploader(self, uploader):
  2832. """Report downloading extry"""
  2833. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader)
  2834. def report_title(self, video_title):
  2835. """Report downloading extry"""
  2836. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title)
  2837. def report_extract_vid_page(self, video_page):
  2838. """Report information extraction."""
  2839. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page)
  2840. def _real_extract(self, url):
  2841. # Extract id from URL
  2842. mobj = re.match(self._VALID_URL, url)
  2843. if mobj is None:
  2844. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  2845. return
  2846. post_url = mobj.group(0)
  2847. video_id = mobj.group(1)
  2848. video_extension = 'flv'
  2849. # Step 1, Retrieve post webpage to extract further information
  2850. self.report_extract_entry(post_url)
  2851. request = compat_urllib_request.Request(post_url)
  2852. try:
  2853. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2854. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2855. self._downloader.trouble(u'ERROR: Unable to retrieve entry webpage: %s' % compat_str(err))
  2856. return
  2857. # Extract update date
  2858. upload_date = None
  2859. pattern = 'title="Timestamp">(.*?)</a>'
  2860. mobj = re.search(pattern, webpage)
  2861. if mobj:
  2862. upload_date = mobj.group(1)
  2863. # Convert timestring to a format suitable for filename
  2864. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2865. upload_date = upload_date.strftime('%Y%m%d')
  2866. self.report_date(upload_date)
  2867. # Extract uploader
  2868. uploader = None
  2869. pattern = r'rel\="author".*?>(.*?)</a>'
  2870. mobj = re.search(pattern, webpage)
  2871. if mobj:
  2872. uploader = mobj.group(1)
  2873. self.report_uploader(uploader)
  2874. # Extract title
  2875. # Get the first line for title
  2876. video_title = u'NA'
  2877. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2878. mobj = re.search(pattern, webpage)
  2879. if mobj:
  2880. video_title = mobj.group(1)
  2881. self.report_title(video_title)
  2882. # Step 2, Stimulate clicking the image box to launch video
  2883. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2884. mobj = re.search(pattern, webpage)
  2885. if mobj is None:
  2886. self._downloader.trouble(u'ERROR: unable to extract video page URL')
  2887. video_page = mobj.group(1)
  2888. request = compat_urllib_request.Request(video_page)
  2889. try:
  2890. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2891. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2892. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2893. return
  2894. self.report_extract_vid_page(video_page)
  2895. # Extract video links on video page
  2896. """Extract video links of all sizes"""
  2897. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2898. mobj = re.findall(pattern, webpage)
  2899. if len(mobj) == 0:
  2900. self._downloader.trouble(u'ERROR: unable to extract video links')
  2901. # Sort in resolution
  2902. links = sorted(mobj)
  2903. # Choose the lowest of the sort, i.e. highest resolution
  2904. video_url = links[-1]
  2905. # Only get the url. The resolution part in the tuple has no use anymore
  2906. video_url = video_url[-1]
  2907. # Treat escaped \u0026 style hex
  2908. try:
  2909. video_url = video_url.decode("unicode_escape")
  2910. except AttributeError: # Python 3
  2911. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2912. return [{
  2913. 'id': video_id,
  2914. 'url': video_url,
  2915. 'uploader': uploader,
  2916. 'upload_date': upload_date,
  2917. 'title': video_title,
  2918. 'ext': video_extension,
  2919. }]
  2920. class NBAIE(InfoExtractor):
  2921. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*)(\?.*)?$'
  2922. IE_NAME = u'nba'
  2923. def report_extraction(self, video_id):
  2924. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2925. def _real_extract(self, url):
  2926. mobj = re.match(self._VALID_URL, url)
  2927. if mobj is None:
  2928. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2929. return
  2930. video_id = mobj.group(1)
  2931. if video_id.endswith('/index.html'):
  2932. video_id = video_id[:-len('/index.html')]
  2933. self.report_extraction(video_id)
  2934. try:
  2935. urlh = compat_urllib_request.urlopen(url)
  2936. webpage_bytes = urlh.read()
  2937. webpage = webpage_bytes.decode('utf-8', 'ignore')
  2938. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2939. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2940. return
  2941. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2942. def _findProp(rexp, default=None):
  2943. m = re.search(rexp, webpage)
  2944. if m:
  2945. return unescapeHTML(m.group(1))
  2946. else:
  2947. return default
  2948. shortened_video_id = video_id.rpartition('/')[2]
  2949. title = _findProp(r'<meta property="og:title" content="(.*?)"', shortened_video_id).replace('NBA.com: ', '')
  2950. info = {
  2951. 'id': shortened_video_id,
  2952. 'url': video_url,
  2953. 'ext': 'mp4',
  2954. 'title': title,
  2955. 'uploader_date': _findProp(r'<b>Date:</b> (.*?)</div>'),
  2956. 'description': _findProp(r'<div class="description">(.*?)</h1>'),
  2957. }
  2958. return [info]
  2959. class JustinTVIE(InfoExtractor):
  2960. """Information extractor for justin.tv and twitch.tv"""
  2961. # TODO: One broadcast may be split into multiple videos. The key
  2962. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2963. # starts at 1 and increases. Can we treat all parts as one video?
  2964. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2965. ([^/]+)(?:/b/([^/]+))?/?(?:\#.*)?$"""
  2966. _JUSTIN_PAGE_LIMIT = 100
  2967. IE_NAME = u'justin.tv'
  2968. def report_extraction(self, file_id):
  2969. """Report information extraction."""
  2970. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2971. def report_download_page(self, channel, offset):
  2972. """Report attempt to download a single page of videos."""
  2973. self._downloader.to_screen(u'[%s] %s: Downloading video information from %d to %d' %
  2974. (self.IE_NAME, channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  2975. # Return count of items, list of *valid* items
  2976. def _parse_page(self, url):
  2977. try:
  2978. urlh = compat_urllib_request.urlopen(url)
  2979. webpage_bytes = urlh.read()
  2980. webpage = webpage_bytes.decode('utf-8', 'ignore')
  2981. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2982. self._downloader.trouble(u'ERROR: unable to download video info JSON: %s' % compat_str(err))
  2983. return
  2984. response = json.loads(webpage)
  2985. info = []
  2986. for clip in response:
  2987. video_url = clip['video_file_url']
  2988. if video_url:
  2989. video_extension = os.path.splitext(video_url)[1][1:]
  2990. video_date = re.sub('-', '', clip['created_on'][:10])
  2991. info.append({
  2992. 'id': clip['id'],
  2993. 'url': video_url,
  2994. 'title': clip['title'],
  2995. 'uploader': clip.get('user_id', clip.get('channel_id')),
  2996. 'upload_date': video_date,
  2997. 'ext': video_extension,
  2998. })
  2999. return (len(response), info)
  3000. def _real_extract(self, url):
  3001. mobj = re.match(self._VALID_URL, url)
  3002. if mobj is None:
  3003. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3004. return
  3005. api = 'http://api.justin.tv'
  3006. video_id = mobj.group(mobj.lastindex)
  3007. paged = False
  3008. if mobj.lastindex == 1:
  3009. paged = True
  3010. api += '/channel/archives/%s.json'
  3011. else:
  3012. api += '/clip/show/%s.json'
  3013. api = api % (video_id,)
  3014. self.report_extraction(video_id)
  3015. info = []
  3016. offset = 0
  3017. limit = self._JUSTIN_PAGE_LIMIT
  3018. while True:
  3019. if paged:
  3020. self.report_download_page(video_id, offset)
  3021. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  3022. page_count, page_info = self._parse_page(page_url)
  3023. info.extend(page_info)
  3024. if not paged or page_count != limit:
  3025. break
  3026. offset += limit
  3027. return info
  3028. class FunnyOrDieIE(InfoExtractor):
  3029. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  3030. IE_NAME = u'FunnyOrDie'
  3031. def report_extraction(self, video_id):
  3032. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3033. def _real_extract(self, url):
  3034. mobj = re.match(self._VALID_URL, url)
  3035. if mobj is None:
  3036. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3037. return
  3038. video_id = mobj.group('id')
  3039. self.report_extraction(video_id)
  3040. try:
  3041. urlh = compat_urllib_request.urlopen(url)
  3042. webpage_bytes = urlh.read()
  3043. webpage = webpage_bytes.decode('utf-8', 'ignore')
  3044. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  3045. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  3046. return
  3047. m = re.search(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"', webpage, re.DOTALL)
  3048. if not m:
  3049. self._downloader.trouble(u'ERROR: unable to find video information')
  3050. video_url = unescapeHTML(m.group('url'))
  3051. print(video_url)
  3052. m = re.search(r"class='player_page_h1'>\s+<a.*?>(?P<title>.*?)</a>", webpage)
  3053. if not m:
  3054. self._downloader.trouble(u'Cannot find video title')
  3055. title = unescapeHTML(m.group('title'))
  3056. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3057. if m:
  3058. desc = unescapeHTML(m.group('desc'))
  3059. else:
  3060. desc = None
  3061. info = {
  3062. 'id': video_id,
  3063. 'url': video_url,
  3064. 'ext': 'mp4',
  3065. 'title': title,
  3066. 'description': desc,
  3067. }
  3068. return [info]