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.

3770 lines
151 KiB

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