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.

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