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.

4025 lines
160 KiB

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