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.

3792 lines
152 KiB

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