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.

3636 lines
147 KiB

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