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.

3759 lines
151 KiB

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