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.

3577 lines
144 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. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  907. try:
  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-_]+)(?:/.*?/([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 = r'yt-uix-pager-next'
  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()
  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 re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1460. break
  1461. pagenum = pagenum + 1
  1462. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1463. playlistend = self._downloader.params.get('playlistend', -1)
  1464. if playlistend == -1:
  1465. video_ids = video_ids[playliststart:]
  1466. else:
  1467. video_ids = video_ids[playliststart:playlistend]
  1468. for id in video_ids:
  1469. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1470. return
  1471. class YoutubeChannelIE(InfoExtractor):
  1472. """Information Extractor for YouTube channels."""
  1473. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1474. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1475. _MORE_PAGES_INDICATOR = r'yt-uix-button-content">Next' # TODO
  1476. IE_NAME = u'youtube:channel'
  1477. def report_download_page(self, channel_id, pagenum):
  1478. """Report attempt to download channel page with given number."""
  1479. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1480. def _real_extract(self, url):
  1481. # Extract channel id
  1482. mobj = re.match(self._VALID_URL, url)
  1483. if mobj is None:
  1484. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1485. return
  1486. # Download channel pages
  1487. channel_id = mobj.group(1)
  1488. video_ids = []
  1489. pagenum = 1
  1490. while True:
  1491. self.report_download_page(channel_id, pagenum)
  1492. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1493. request = compat_urllib_request.Request(url)
  1494. try:
  1495. page = compat_urllib_request.urlopen(request).read()
  1496. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1497. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1498. return
  1499. # Extract video identifiers
  1500. ids_in_page = []
  1501. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1502. if mobj.group(1) not in ids_in_page:
  1503. ids_in_page.append(mobj.group(1))
  1504. video_ids.extend(ids_in_page)
  1505. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1506. break
  1507. pagenum = pagenum + 1
  1508. for id in video_ids:
  1509. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1510. return
  1511. class YoutubeUserIE(InfoExtractor):
  1512. """Information Extractor for YouTube users."""
  1513. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1514. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1515. _GDATA_PAGE_SIZE = 50
  1516. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1517. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1518. IE_NAME = u'youtube:user'
  1519. def __init__(self, downloader=None):
  1520. InfoExtractor.__init__(self, downloader)
  1521. def report_download_page(self, username, start_index):
  1522. """Report attempt to download user page."""
  1523. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1524. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1525. def _real_extract(self, url):
  1526. # Extract username
  1527. mobj = re.match(self._VALID_URL, url)
  1528. if mobj is None:
  1529. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1530. return
  1531. username = mobj.group(1)
  1532. # Download video ids using YouTube Data API. Result size per
  1533. # query is limited (currently to 50 videos) so we need to query
  1534. # page by page until there are no video ids - it means we got
  1535. # all of them.
  1536. video_ids = []
  1537. pagenum = 0
  1538. while True:
  1539. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1540. self.report_download_page(username, start_index)
  1541. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1542. try:
  1543. page = compat_urllib_request.urlopen(request).read()
  1544. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1545. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1546. return
  1547. # Extract video identifiers
  1548. ids_in_page = []
  1549. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1550. if mobj.group(1) not in ids_in_page:
  1551. ids_in_page.append(mobj.group(1))
  1552. video_ids.extend(ids_in_page)
  1553. # A little optimization - if current page is not
  1554. # "full", ie. does not contain PAGE_SIZE video ids then
  1555. # we can assume that this page is the last one - there
  1556. # are no more ids on further pages - no need to query
  1557. # again.
  1558. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1559. break
  1560. pagenum += 1
  1561. all_ids_count = len(video_ids)
  1562. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1563. playlistend = self._downloader.params.get('playlistend', -1)
  1564. if playlistend == -1:
  1565. video_ids = video_ids[playliststart:]
  1566. else:
  1567. video_ids = video_ids[playliststart:playlistend]
  1568. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1569. (username, all_ids_count, len(video_ids)))
  1570. for video_id in video_ids:
  1571. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1572. class BlipTVUserIE(InfoExtractor):
  1573. """Information Extractor for blip.tv users."""
  1574. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1575. _PAGE_SIZE = 12
  1576. IE_NAME = u'blip.tv:user'
  1577. def __init__(self, downloader=None):
  1578. InfoExtractor.__init__(self, downloader)
  1579. def report_download_page(self, username, pagenum):
  1580. """Report attempt to download user page."""
  1581. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1582. (self.IE_NAME, username, pagenum))
  1583. def _real_extract(self, url):
  1584. # Extract username
  1585. mobj = re.match(self._VALID_URL, url)
  1586. if mobj is None:
  1587. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1588. return
  1589. username = mobj.group(1)
  1590. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1591. request = compat_urllib_request.Request(url)
  1592. try:
  1593. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1594. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1595. page_base = page_base % mobj.group(1)
  1596. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1597. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1598. return
  1599. # Download video ids using BlipTV Ajax calls. Result size per
  1600. # query is limited (currently to 12 videos) so we need to query
  1601. # page by page until there are no video ids - it means we got
  1602. # all of them.
  1603. video_ids = []
  1604. pagenum = 1
  1605. while True:
  1606. self.report_download_page(username, pagenum)
  1607. request = compat_urllib_request.Request( page_base + "&page=" + str(pagenum) )
  1608. try:
  1609. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1610. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1611. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1612. return
  1613. # Extract video identifiers
  1614. ids_in_page = []
  1615. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1616. if mobj.group(1) not in ids_in_page:
  1617. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1618. video_ids.extend(ids_in_page)
  1619. # A little optimization - if current page is not
  1620. # "full", ie. does not contain PAGE_SIZE video ids then
  1621. # we can assume that this page is the last one - there
  1622. # are no more ids on further pages - no need to query
  1623. # again.
  1624. if len(ids_in_page) < self._PAGE_SIZE:
  1625. break
  1626. pagenum += 1
  1627. all_ids_count = len(video_ids)
  1628. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1629. playlistend = self._downloader.params.get('playlistend', -1)
  1630. if playlistend == -1:
  1631. video_ids = video_ids[playliststart:]
  1632. else:
  1633. video_ids = video_ids[playliststart:playlistend]
  1634. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1635. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1636. for video_id in video_ids:
  1637. self._downloader.download([u'http://blip.tv/'+video_id])
  1638. class DepositFilesIE(InfoExtractor):
  1639. """Information extractor for depositfiles.com"""
  1640. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1641. IE_NAME = u'DepositFiles'
  1642. def __init__(self, downloader=None):
  1643. InfoExtractor.__init__(self, downloader)
  1644. def report_download_webpage(self, file_id):
  1645. """Report webpage download."""
  1646. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1647. def report_extraction(self, file_id):
  1648. """Report information extraction."""
  1649. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1650. def _real_extract(self, url):
  1651. file_id = url.split('/')[-1]
  1652. # Rebuild url in english locale
  1653. url = 'http://depositfiles.com/en/files/' + file_id
  1654. # Retrieve file webpage with 'Free download' button pressed
  1655. free_download_indication = { 'gateway_result' : '1' }
  1656. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1657. try:
  1658. self.report_download_webpage(file_id)
  1659. webpage = compat_urllib_request.urlopen(request).read()
  1660. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1661. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % compat_str(err))
  1662. return
  1663. # Search for the real file URL
  1664. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1665. if (mobj is None) or (mobj.group(1) is None):
  1666. # Try to figure out reason of the error.
  1667. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1668. if (mobj is not None) and (mobj.group(1) is not None):
  1669. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1670. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1671. else:
  1672. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1673. return
  1674. file_url = mobj.group(1)
  1675. file_extension = os.path.splitext(file_url)[1][1:]
  1676. # Search for file title
  1677. mobj = re.search(r'<b title="(.*?)">', webpage)
  1678. if mobj is None:
  1679. self._downloader.trouble(u'ERROR: unable to extract title')
  1680. return
  1681. file_title = mobj.group(1).decode('utf-8')
  1682. return [{
  1683. 'id': file_id.decode('utf-8'),
  1684. 'url': file_url.decode('utf-8'),
  1685. 'uploader': None,
  1686. 'upload_date': None,
  1687. 'title': file_title,
  1688. 'ext': file_extension.decode('utf-8'),
  1689. }]
  1690. class FacebookIE(InfoExtractor):
  1691. """Information Extractor for Facebook"""
  1692. _WORKING = False
  1693. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1694. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1695. _NETRC_MACHINE = 'facebook'
  1696. _available_formats = ['video', 'highqual', 'lowqual']
  1697. _video_extensions = {
  1698. 'video': 'mp4',
  1699. 'highqual': 'mp4',
  1700. 'lowqual': 'mp4',
  1701. }
  1702. IE_NAME = u'facebook'
  1703. def __init__(self, downloader=None):
  1704. InfoExtractor.__init__(self, downloader)
  1705. def _reporter(self, message):
  1706. """Add header and report message."""
  1707. self._downloader.to_screen(u'[facebook] %s' % message)
  1708. def report_login(self):
  1709. """Report attempt to log in."""
  1710. self._reporter(u'Logging in')
  1711. def report_video_webpage_download(self, video_id):
  1712. """Report attempt to download video webpage."""
  1713. self._reporter(u'%s: Downloading video webpage' % video_id)
  1714. def report_information_extraction(self, video_id):
  1715. """Report attempt to extract video information."""
  1716. self._reporter(u'%s: Extracting video information' % video_id)
  1717. def _parse_page(self, video_webpage):
  1718. """Extract video information from page"""
  1719. # General data
  1720. data = {'title': r'\("video_title", "(.*?)"\)',
  1721. 'description': r'<div class="datawrap">(.*?)</div>',
  1722. 'owner': r'\("video_owner_name", "(.*?)"\)',
  1723. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  1724. }
  1725. video_info = {}
  1726. for piece in data.keys():
  1727. mobj = re.search(data[piece], video_webpage)
  1728. if mobj is not None:
  1729. video_info[piece] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1730. # Video urls
  1731. video_urls = {}
  1732. for fmt in self._available_formats:
  1733. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  1734. if mobj is not None:
  1735. # URL is in a Javascript segment inside an escaped Unicode format within
  1736. # the generally utf-8 page
  1737. video_urls[fmt] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1738. video_info['video_urls'] = video_urls
  1739. return video_info
  1740. def _real_initialize(self):
  1741. if self._downloader is None:
  1742. return
  1743. useremail = None
  1744. password = None
  1745. downloader_params = self._downloader.params
  1746. # Attempt to use provided username and password or .netrc data
  1747. if downloader_params.get('username', None) is not None:
  1748. useremail = downloader_params['username']
  1749. password = downloader_params['password']
  1750. elif downloader_params.get('usenetrc', False):
  1751. try:
  1752. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1753. if info is not None:
  1754. useremail = info[0]
  1755. password = info[2]
  1756. else:
  1757. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1758. except (IOError, netrc.NetrcParseError) as err:
  1759. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  1760. return
  1761. if useremail is None:
  1762. return
  1763. # Log in
  1764. login_form = {
  1765. 'email': useremail,
  1766. 'pass': password,
  1767. 'login': 'Log+In'
  1768. }
  1769. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1770. try:
  1771. self.report_login()
  1772. login_results = compat_urllib_request.urlopen(request).read()
  1773. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1774. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1775. return
  1776. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1777. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  1778. return
  1779. def _real_extract(self, url):
  1780. mobj = re.match(self._VALID_URL, url)
  1781. if mobj is None:
  1782. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1783. return
  1784. video_id = mobj.group('ID')
  1785. # Get video webpage
  1786. self.report_video_webpage_download(video_id)
  1787. request = compat_urllib_request.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  1788. try:
  1789. page = compat_urllib_request.urlopen(request)
  1790. video_webpage = page.read()
  1791. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1792. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  1793. return
  1794. # Start extracting information
  1795. self.report_information_extraction(video_id)
  1796. # Extract information
  1797. video_info = self._parse_page(video_webpage)
  1798. # uploader
  1799. if 'owner' not in video_info:
  1800. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1801. return
  1802. video_uploader = video_info['owner']
  1803. # title
  1804. if 'title' not in video_info:
  1805. self._downloader.trouble(u'ERROR: unable to extract video title')
  1806. return
  1807. video_title = video_info['title']
  1808. video_title = video_title.decode('utf-8')
  1809. # thumbnail image
  1810. if 'thumbnail' not in video_info:
  1811. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1812. video_thumbnail = ''
  1813. else:
  1814. video_thumbnail = video_info['thumbnail']
  1815. # upload date
  1816. upload_date = None
  1817. if 'upload_date' in video_info:
  1818. upload_time = video_info['upload_date']
  1819. timetuple = email.utils.parsedate_tz(upload_time)
  1820. if timetuple is not None:
  1821. try:
  1822. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  1823. except:
  1824. pass
  1825. # description
  1826. video_description = video_info.get('description', 'No description available.')
  1827. url_map = video_info['video_urls']
  1828. if len(url_map.keys()) > 0:
  1829. # Decide which formats to download
  1830. req_format = self._downloader.params.get('format', None)
  1831. format_limit = self._downloader.params.get('format_limit', None)
  1832. if format_limit is not None and format_limit in self._available_formats:
  1833. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1834. else:
  1835. format_list = self._available_formats
  1836. existing_formats = [x for x in format_list if x in url_map]
  1837. if len(existing_formats) == 0:
  1838. self._downloader.trouble(u'ERROR: no known formats available for video')
  1839. return
  1840. if req_format is None:
  1841. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1842. elif req_format == 'worst':
  1843. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1844. elif req_format == '-1':
  1845. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1846. else:
  1847. # Specific format
  1848. if req_format not in url_map:
  1849. self._downloader.trouble(u'ERROR: requested format not available')
  1850. return
  1851. video_url_list = [(req_format, url_map[req_format])] # Specific format
  1852. results = []
  1853. for format_param, video_real_url in video_url_list:
  1854. # Extension
  1855. video_extension = self._video_extensions.get(format_param, 'mp4')
  1856. results.append({
  1857. 'id': video_id.decode('utf-8'),
  1858. 'url': video_real_url.decode('utf-8'),
  1859. 'uploader': video_uploader.decode('utf-8'),
  1860. 'upload_date': upload_date,
  1861. 'title': video_title,
  1862. 'ext': video_extension.decode('utf-8'),
  1863. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1864. 'thumbnail': video_thumbnail.decode('utf-8'),
  1865. 'description': video_description.decode('utf-8'),
  1866. })
  1867. return results
  1868. class BlipTVIE(InfoExtractor):
  1869. """Information extractor for blip.tv"""
  1870. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1871. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1872. IE_NAME = u'blip.tv'
  1873. def report_extraction(self, file_id):
  1874. """Report information extraction."""
  1875. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1876. def report_direct_download(self, title):
  1877. """Report information extraction."""
  1878. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1879. def _real_extract(self, url):
  1880. mobj = re.match(self._VALID_URL, url)
  1881. if mobj is None:
  1882. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1883. return
  1884. if '?' in url:
  1885. cchar = '&'
  1886. else:
  1887. cchar = '?'
  1888. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1889. request = compat_urllib_request.Request(json_url.encode('utf-8'))
  1890. self.report_extraction(mobj.group(1))
  1891. info = None
  1892. try:
  1893. urlh = compat_urllib_request.urlopen(request)
  1894. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1895. basename = url.split('/')[-1]
  1896. title,ext = os.path.splitext(basename)
  1897. title = title.decode('UTF-8')
  1898. ext = ext.replace('.', '')
  1899. self.report_direct_download(title)
  1900. info = {
  1901. 'id': title,
  1902. 'url': url,
  1903. 'uploader': None,
  1904. 'upload_date': None,
  1905. 'title': title,
  1906. 'ext': ext,
  1907. 'urlhandle': urlh
  1908. }
  1909. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1910. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1911. return
  1912. if info is None: # Regular URL
  1913. try:
  1914. json_code = urlh.read()
  1915. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1916. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % compat_str(err))
  1917. return
  1918. try:
  1919. json_data = json.loads(json_code)
  1920. if 'Post' in json_data:
  1921. data = json_data['Post']
  1922. else:
  1923. data = json_data
  1924. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1925. video_url = data['media']['url']
  1926. umobj = re.match(self._URL_EXT, video_url)
  1927. if umobj is None:
  1928. raise ValueError('Can not determine filename extension')
  1929. ext = umobj.group(1)
  1930. info = {
  1931. 'id': data['item_id'],
  1932. 'url': video_url,
  1933. 'uploader': data['display_name'],
  1934. 'upload_date': upload_date,
  1935. 'title': data['title'],
  1936. 'ext': ext,
  1937. 'format': data['media']['mimeType'],
  1938. 'thumbnail': data['thumbnailUrl'],
  1939. 'description': data['description'],
  1940. 'player_url': data['embedUrl']
  1941. }
  1942. except (ValueError,KeyError) as err:
  1943. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1944. return
  1945. std_headers['User-Agent'] = 'iTunes/10.6.1'
  1946. return [info]
  1947. class MyVideoIE(InfoExtractor):
  1948. """Information Extractor for myvideo.de."""
  1949. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1950. IE_NAME = u'myvideo'
  1951. def __init__(self, downloader=None):
  1952. InfoExtractor.__init__(self, downloader)
  1953. def report_download_webpage(self, video_id):
  1954. """Report webpage download."""
  1955. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  1956. def report_extraction(self, video_id):
  1957. """Report information extraction."""
  1958. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1959. def _real_extract(self,url):
  1960. mobj = re.match(self._VALID_URL, url)
  1961. if mobj is None:
  1962. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1963. return
  1964. video_id = mobj.group(1)
  1965. # Get video webpage
  1966. request = compat_urllib_request.Request('http://www.myvideo.de/watch/%s' % video_id)
  1967. try:
  1968. self.report_download_webpage(video_id)
  1969. webpage = compat_urllib_request.urlopen(request).read()
  1970. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1971. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1972. return
  1973. self.report_extraction(video_id)
  1974. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  1975. webpage)
  1976. if mobj is None:
  1977. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1978. return
  1979. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1980. mobj = re.search('<title>([^<]+)</title>', webpage)
  1981. if mobj is None:
  1982. self._downloader.trouble(u'ERROR: unable to extract title')
  1983. return
  1984. video_title = mobj.group(1)
  1985. return [{
  1986. 'id': video_id,
  1987. 'url': video_url,
  1988. 'uploader': None,
  1989. 'upload_date': None,
  1990. 'title': video_title,
  1991. 'ext': u'flv',
  1992. }]
  1993. class ComedyCentralIE(InfoExtractor):
  1994. """Information extractor for The Daily Show and Colbert Report """
  1995. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  1996. IE_NAME = u'comedycentral'
  1997. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1998. _video_extensions = {
  1999. '3500': 'mp4',
  2000. '2200': 'mp4',
  2001. '1700': 'mp4',
  2002. '1200': 'mp4',
  2003. '750': 'mp4',
  2004. '400': 'mp4',
  2005. }
  2006. _video_dimensions = {
  2007. '3500': '1280x720',
  2008. '2200': '960x540',
  2009. '1700': '768x432',
  2010. '1200': '640x360',
  2011. '750': '512x288',
  2012. '400': '384x216',
  2013. }
  2014. def report_extraction(self, episode_id):
  2015. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  2016. def report_config_download(self, episode_id):
  2017. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  2018. def report_index_download(self, episode_id):
  2019. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  2020. def report_player_url(self, episode_id):
  2021. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  2022. def _print_formats(self, formats):
  2023. print('Available formats:')
  2024. for x in formats:
  2025. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  2026. def _real_extract(self, url):
  2027. mobj = re.match(self._VALID_URL, url)
  2028. if mobj is None:
  2029. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2030. return
  2031. if mobj.group('shortname'):
  2032. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  2033. url = u'http://www.thedailyshow.com/full-episodes/'
  2034. else:
  2035. url = u'http://www.colbertnation.com/full-episodes/'
  2036. mobj = re.match(self._VALID_URL, url)
  2037. assert mobj is not None
  2038. dlNewest = not mobj.group('episode')
  2039. if dlNewest:
  2040. epTitle = mobj.group('showname')
  2041. else:
  2042. epTitle = mobj.group('episode')
  2043. req = compat_urllib_request.Request(url)
  2044. self.report_extraction(epTitle)
  2045. try:
  2046. htmlHandle = compat_urllib_request.urlopen(req)
  2047. html = htmlHandle.read()
  2048. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2049. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2050. return
  2051. if dlNewest:
  2052. url = htmlHandle.geturl()
  2053. mobj = re.match(self._VALID_URL, url)
  2054. if mobj is None:
  2055. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2056. return
  2057. if mobj.group('episode') == '':
  2058. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2059. return
  2060. epTitle = mobj.group('episode')
  2061. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"', html)
  2062. if len(mMovieParams) == 0:
  2063. # The Colbert Report embeds the information in a without
  2064. # a URL prefix; so extract the alternate reference
  2065. # and then add the URL prefix manually.
  2066. altMovieParams = re.findall('data-mgid="([^"]*episode.*?:.*?)"', html)
  2067. if len(altMovieParams) == 0:
  2068. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2069. return
  2070. else:
  2071. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2072. playerUrl_raw = mMovieParams[0][0]
  2073. self.report_player_url(epTitle)
  2074. try:
  2075. urlHandle = compat_urllib_request.urlopen(playerUrl_raw)
  2076. playerUrl = urlHandle.geturl()
  2077. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2078. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + compat_str(err))
  2079. return
  2080. uri = mMovieParams[0][1]
  2081. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2082. self.report_index_download(epTitle)
  2083. try:
  2084. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2085. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2086. self._downloader.trouble(u'ERROR: unable to download episode index: ' + compat_str(err))
  2087. return
  2088. results = []
  2089. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2090. itemEls = idoc.findall('.//item')
  2091. for itemEl in itemEls:
  2092. mediaId = itemEl.findall('./guid')[0].text
  2093. shortMediaId = mediaId.split(':')[-1]
  2094. showId = mediaId.split(':')[-2].replace('.com', '')
  2095. officialTitle = itemEl.findall('./title')[0].text
  2096. officialDate = itemEl.findall('./pubDate')[0].text
  2097. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2098. compat_urllib_parse.urlencode({'uri': mediaId}))
  2099. configReq = compat_urllib_request.Request(configUrl)
  2100. self.report_config_download(epTitle)
  2101. try:
  2102. configXml = compat_urllib_request.urlopen(configReq).read()
  2103. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2104. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2105. return
  2106. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2107. turls = []
  2108. for rendition in cdoc.findall('.//rendition'):
  2109. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2110. turls.append(finfo)
  2111. if len(turls) == 0:
  2112. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2113. continue
  2114. if self._downloader.params.get('listformats', None):
  2115. self._print_formats([i[0] for i in turls])
  2116. return
  2117. # For now, just pick the highest bitrate
  2118. format,video_url = turls[-1]
  2119. # Get the format arg from the arg stream
  2120. req_format = self._downloader.params.get('format', None)
  2121. # Select format if we can find one
  2122. for f,v in turls:
  2123. if f == req_format:
  2124. format, video_url = f, v
  2125. break
  2126. # Patch to download from alternative CDN, which does not
  2127. # break on current RTMPDump builds
  2128. broken_cdn = "rtmpe://viacomccstrmfs.fplive.net/viacomccstrm/gsp.comedystor/"
  2129. better_cdn = "rtmpe://cp10740.edgefcs.net/ondemand/mtvnorigin/gsp.comedystor/"
  2130. if video_url.startswith(broken_cdn):
  2131. video_url = video_url.replace(broken_cdn, better_cdn)
  2132. effTitle = showId + u'-' + epTitle
  2133. info = {
  2134. 'id': shortMediaId,
  2135. 'url': video_url,
  2136. 'uploader': showId,
  2137. 'upload_date': officialDate,
  2138. 'title': effTitle,
  2139. 'ext': 'mp4',
  2140. 'format': format,
  2141. 'thumbnail': None,
  2142. 'description': officialTitle,
  2143. 'player_url': None #playerUrl
  2144. }
  2145. results.append(info)
  2146. return results
  2147. class EscapistIE(InfoExtractor):
  2148. """Information extractor for The Escapist """
  2149. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2150. IE_NAME = u'escapist'
  2151. def report_extraction(self, showName):
  2152. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2153. def report_config_download(self, showName):
  2154. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2155. def _real_extract(self, url):
  2156. mobj = re.match(self._VALID_URL, url)
  2157. if mobj is None:
  2158. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2159. return
  2160. showName = mobj.group('showname')
  2161. videoId = mobj.group('episode')
  2162. self.report_extraction(showName)
  2163. try:
  2164. webPage = compat_urllib_request.urlopen(url)
  2165. webPageBytes = webPage.read()
  2166. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2167. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2168. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2169. self._downloader.trouble(u'ERROR: unable to download webpage: ' + compat_str(err))
  2170. return
  2171. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2172. description = unescapeHTML(descMatch.group(1))
  2173. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2174. imgUrl = unescapeHTML(imgMatch.group(1))
  2175. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2176. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2177. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2178. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2179. self.report_config_download(showName)
  2180. try:
  2181. configJSON = compat_urllib_request.urlopen(configUrl).read()
  2182. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2183. self._downloader.trouble(u'ERROR: unable to download configuration: ' + compat_str(err))
  2184. return
  2185. # Technically, it's JavaScript, not JSON
  2186. configJSON = configJSON.replace("'", '"')
  2187. try:
  2188. config = json.loads(configJSON)
  2189. except (ValueError,) as err:
  2190. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + compat_str(err))
  2191. return
  2192. playlist = config['playlist']
  2193. videoUrl = playlist[1]['url']
  2194. info = {
  2195. 'id': videoId,
  2196. 'url': videoUrl,
  2197. 'uploader': showName,
  2198. 'upload_date': None,
  2199. 'title': showName,
  2200. 'ext': 'flv',
  2201. 'thumbnail': imgUrl,
  2202. 'description': description,
  2203. 'player_url': playerUrl,
  2204. }
  2205. return [info]
  2206. class CollegeHumorIE(InfoExtractor):
  2207. """Information extractor for collegehumor.com"""
  2208. _WORKING = False
  2209. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2210. IE_NAME = u'collegehumor'
  2211. def report_manifest(self, video_id):
  2212. """Report information extraction."""
  2213. self._downloader.to_screen(u'[%s] %s: Downloading XML manifest' % (self.IE_NAME, video_id))
  2214. def report_extraction(self, video_id):
  2215. """Report information extraction."""
  2216. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2217. def _real_extract(self, url):
  2218. mobj = re.match(self._VALID_URL, url)
  2219. if mobj is None:
  2220. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2221. return
  2222. video_id = mobj.group('videoid')
  2223. info = {
  2224. 'id': video_id,
  2225. 'uploader': None,
  2226. 'upload_date': None,
  2227. }
  2228. self.report_extraction(video_id)
  2229. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2230. try:
  2231. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2232. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2233. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2234. return
  2235. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2236. try:
  2237. videoNode = mdoc.findall('./video')[0]
  2238. info['description'] = videoNode.findall('./description')[0].text
  2239. info['title'] = videoNode.findall('./caption')[0].text
  2240. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2241. manifest_url = videoNode.findall('./file')[0].text
  2242. except IndexError:
  2243. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2244. return
  2245. manifest_url += '?hdcore=2.10.3'
  2246. self.report_manifest(video_id)
  2247. try:
  2248. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2249. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2250. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2251. return
  2252. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2253. try:
  2254. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2255. node_id = media_node.attrib['url']
  2256. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2257. except IndexError as err:
  2258. self._downloader.trouble(u'\nERROR: Invalid manifest file')
  2259. return
  2260. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2261. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2262. info['url'] = url
  2263. info['ext'] = 'f4f'
  2264. return [info]
  2265. class XVideosIE(InfoExtractor):
  2266. """Information extractor for xvideos.com"""
  2267. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2268. IE_NAME = u'xvideos'
  2269. def report_webpage(self, video_id):
  2270. """Report information extraction."""
  2271. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2272. def report_extraction(self, video_id):
  2273. """Report information extraction."""
  2274. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2275. def _real_extract(self, url):
  2276. mobj = re.match(self._VALID_URL, url)
  2277. if mobj is None:
  2278. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2279. return
  2280. video_id = mobj.group(1).decode('utf-8')
  2281. self.report_webpage(video_id)
  2282. request = compat_urllib_request.Request(r'http://www.xvideos.com/video' + video_id)
  2283. try:
  2284. webpage = compat_urllib_request.urlopen(request).read()
  2285. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2286. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2287. return
  2288. self.report_extraction(video_id)
  2289. # Extract video URL
  2290. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2291. if mobj is None:
  2292. self._downloader.trouble(u'ERROR: unable to extract video url')
  2293. return
  2294. video_url = compat_urllib_parse.unquote(mobj.group(1).decode('utf-8'))
  2295. # Extract title
  2296. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2297. if mobj is None:
  2298. self._downloader.trouble(u'ERROR: unable to extract video title')
  2299. return
  2300. video_title = mobj.group(1).decode('utf-8')
  2301. # Extract video thumbnail
  2302. 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)
  2303. if mobj is None:
  2304. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2305. return
  2306. video_thumbnail = mobj.group(0).decode('utf-8')
  2307. info = {
  2308. 'id': video_id,
  2309. 'url': video_url,
  2310. 'uploader': None,
  2311. 'upload_date': None,
  2312. 'title': video_title,
  2313. 'ext': 'flv',
  2314. 'thumbnail': video_thumbnail,
  2315. 'description': None,
  2316. }
  2317. return [info]
  2318. class SoundcloudIE(InfoExtractor):
  2319. """Information extractor for soundcloud.com
  2320. To access the media, the uid of the song and a stream token
  2321. must be extracted from the page source and the script must make
  2322. a request to media.soundcloud.com/crossdomain.xml. Then
  2323. the media can be grabbed by requesting from an url composed
  2324. of the stream token and uid
  2325. """
  2326. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2327. IE_NAME = u'soundcloud'
  2328. def __init__(self, downloader=None):
  2329. InfoExtractor.__init__(self, downloader)
  2330. def report_webpage(self, video_id):
  2331. """Report information extraction."""
  2332. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2333. def report_extraction(self, video_id):
  2334. """Report information extraction."""
  2335. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2336. def _real_extract(self, url):
  2337. mobj = re.match(self._VALID_URL, url)
  2338. if mobj is None:
  2339. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2340. return
  2341. # extract uploader (which is in the url)
  2342. uploader = mobj.group(1).decode('utf-8')
  2343. # extract simple title (uploader + slug of song title)
  2344. slug_title = mobj.group(2).decode('utf-8')
  2345. simple_title = uploader + u'-' + slug_title
  2346. self.report_webpage('%s/%s' % (uploader, slug_title))
  2347. request = compat_urllib_request.Request('http://soundcloud.com/%s/%s' % (uploader, slug_title))
  2348. try:
  2349. webpage = compat_urllib_request.urlopen(request).read()
  2350. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2351. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2352. return
  2353. self.report_extraction('%s/%s' % (uploader, slug_title))
  2354. # extract uid and stream token that soundcloud hands out for access
  2355. mobj = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', webpage)
  2356. if mobj:
  2357. video_id = mobj.group(1)
  2358. stream_token = mobj.group(2)
  2359. # extract unsimplified title
  2360. mobj = re.search('"title":"(.*?)",', webpage)
  2361. if mobj:
  2362. title = mobj.group(1).decode('utf-8')
  2363. else:
  2364. title = simple_title
  2365. # construct media url (with uid/token)
  2366. mediaURL = "http://media.soundcloud.com/stream/%s?stream_token=%s"
  2367. mediaURL = mediaURL % (video_id, stream_token)
  2368. # description
  2369. description = u'No description available'
  2370. mobj = re.search('track-description-value"><p>(.*?)</p>', webpage)
  2371. if mobj:
  2372. description = mobj.group(1)
  2373. # upload date
  2374. upload_date = None
  2375. mobj = re.search("pretty-date'>on ([\w]+ [\d]+, [\d]+ \d+:\d+)</abbr></h2>", webpage)
  2376. if mobj:
  2377. try:
  2378. upload_date = datetime.datetime.strptime(mobj.group(1), '%B %d, %Y %H:%M').strftime('%Y%m%d')
  2379. except Exception as err:
  2380. self._downloader.to_stderr(compat_str(err))
  2381. # for soundcloud, a request to a cross domain is required for cookies
  2382. request = compat_urllib_request.Request('http://media.soundcloud.com/crossdomain.xml', std_headers)
  2383. return [{
  2384. 'id': video_id.decode('utf-8'),
  2385. 'url': mediaURL,
  2386. 'uploader': uploader.decode('utf-8'),
  2387. 'upload_date': upload_date,
  2388. 'title': title,
  2389. 'ext': u'mp3',
  2390. 'description': description.decode('utf-8')
  2391. }]
  2392. class InfoQIE(InfoExtractor):
  2393. """Information extractor for infoq.com"""
  2394. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2395. IE_NAME = u'infoq'
  2396. def report_webpage(self, video_id):
  2397. """Report information extraction."""
  2398. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2399. def report_extraction(self, video_id):
  2400. """Report information extraction."""
  2401. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2402. def _real_extract(self, url):
  2403. mobj = re.match(self._VALID_URL, url)
  2404. if mobj is None:
  2405. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2406. return
  2407. self.report_webpage(url)
  2408. request = compat_urllib_request.Request(url)
  2409. try:
  2410. webpage = compat_urllib_request.urlopen(request).read()
  2411. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2412. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2413. return
  2414. self.report_extraction(url)
  2415. # Extract video URL
  2416. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2417. if mobj is None:
  2418. self._downloader.trouble(u'ERROR: unable to extract video url')
  2419. return
  2420. video_url = 'rtmpe://video.infoq.com/cfx/st/' + compat_urllib_parse.unquote(mobj.group(1).decode('base64'))
  2421. # Extract title
  2422. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2423. if mobj is None:
  2424. self._downloader.trouble(u'ERROR: unable to extract video title')
  2425. return
  2426. video_title = mobj.group(1).decode('utf-8')
  2427. # Extract description
  2428. video_description = u'No description available.'
  2429. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2430. if mobj is not None:
  2431. video_description = mobj.group(1).decode('utf-8')
  2432. video_filename = video_url.split('/')[-1]
  2433. video_id, extension = video_filename.split('.')
  2434. info = {
  2435. 'id': video_id,
  2436. 'url': video_url,
  2437. 'uploader': None,
  2438. 'upload_date': None,
  2439. 'title': video_title,
  2440. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2441. 'thumbnail': None,
  2442. 'description': video_description,
  2443. }
  2444. return [info]
  2445. class MixcloudIE(InfoExtractor):
  2446. """Information extractor for www.mixcloud.com"""
  2447. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2448. IE_NAME = u'mixcloud'
  2449. def __init__(self, downloader=None):
  2450. InfoExtractor.__init__(self, downloader)
  2451. def report_download_json(self, file_id):
  2452. """Report JSON download."""
  2453. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2454. def report_extraction(self, file_id):
  2455. """Report information extraction."""
  2456. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2457. def get_urls(self, jsonData, fmt, bitrate='best'):
  2458. """Get urls from 'audio_formats' section in json"""
  2459. file_url = None
  2460. try:
  2461. bitrate_list = jsonData[fmt]
  2462. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2463. bitrate = max(bitrate_list) # select highest
  2464. url_list = jsonData[fmt][bitrate]
  2465. except TypeError: # we have no bitrate info.
  2466. url_list = jsonData[fmt]
  2467. return url_list
  2468. def check_urls(self, url_list):
  2469. """Returns 1st active url from list"""
  2470. for url in url_list:
  2471. try:
  2472. compat_urllib_request.urlopen(url)
  2473. return url
  2474. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2475. url = None
  2476. return None
  2477. def _print_formats(self, formats):
  2478. print('Available formats:')
  2479. for fmt in formats.keys():
  2480. for b in formats[fmt]:
  2481. try:
  2482. ext = formats[fmt][b][0]
  2483. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2484. except TypeError: # we have no bitrate info
  2485. ext = formats[fmt][0]
  2486. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2487. break
  2488. def _real_extract(self, url):
  2489. mobj = re.match(self._VALID_URL, url)
  2490. if mobj is None:
  2491. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2492. return
  2493. # extract uploader & filename from url
  2494. uploader = mobj.group(1).decode('utf-8')
  2495. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2496. # construct API request
  2497. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2498. # retrieve .json file with links to files
  2499. request = compat_urllib_request.Request(file_url)
  2500. try:
  2501. self.report_download_json(file_url)
  2502. jsonData = compat_urllib_request.urlopen(request).read()
  2503. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2504. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % compat_str(err))
  2505. return
  2506. # parse JSON
  2507. json_data = json.loads(jsonData)
  2508. player_url = json_data['player_swf_url']
  2509. formats = dict(json_data['audio_formats'])
  2510. req_format = self._downloader.params.get('format', None)
  2511. bitrate = None
  2512. if self._downloader.params.get('listformats', None):
  2513. self._print_formats(formats)
  2514. return
  2515. if req_format is None or req_format == 'best':
  2516. for format_param in formats.keys():
  2517. url_list = self.get_urls(formats, format_param)
  2518. # check urls
  2519. file_url = self.check_urls(url_list)
  2520. if file_url is not None:
  2521. break # got it!
  2522. else:
  2523. if req_format not in formats.keys():
  2524. self._downloader.trouble(u'ERROR: format is not available')
  2525. return
  2526. url_list = self.get_urls(formats, req_format)
  2527. file_url = self.check_urls(url_list)
  2528. format_param = req_format
  2529. return [{
  2530. 'id': file_id.decode('utf-8'),
  2531. 'url': file_url.decode('utf-8'),
  2532. 'uploader': uploader.decode('utf-8'),
  2533. 'upload_date': None,
  2534. 'title': json_data['name'],
  2535. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2536. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2537. 'thumbnail': json_data['thumbnail_url'],
  2538. 'description': json_data['description'],
  2539. 'player_url': player_url.decode('utf-8'),
  2540. }]
  2541. class StanfordOpenClassroomIE(InfoExtractor):
  2542. """Information extractor for Stanford's Open ClassRoom"""
  2543. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2544. IE_NAME = u'stanfordoc'
  2545. def report_download_webpage(self, objid):
  2546. """Report information extraction."""
  2547. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2548. def report_extraction(self, video_id):
  2549. """Report information extraction."""
  2550. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2551. def _real_extract(self, url):
  2552. mobj = re.match(self._VALID_URL, url)
  2553. if mobj is None:
  2554. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2555. return
  2556. if mobj.group('course') and mobj.group('video'): # A specific video
  2557. course = mobj.group('course')
  2558. video = mobj.group('video')
  2559. info = {
  2560. 'id': course + '_' + video,
  2561. 'uploader': None,
  2562. 'upload_date': None,
  2563. }
  2564. self.report_extraction(info['id'])
  2565. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2566. xmlUrl = baseUrl + video + '.xml'
  2567. try:
  2568. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2569. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2570. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2571. return
  2572. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2573. try:
  2574. info['title'] = mdoc.findall('./title')[0].text
  2575. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2576. except IndexError:
  2577. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2578. return
  2579. info['ext'] = info['url'].rpartition('.')[2]
  2580. return [info]
  2581. elif mobj.group('course'): # A course page
  2582. course = mobj.group('course')
  2583. info = {
  2584. 'id': course,
  2585. 'type': 'playlist',
  2586. 'uploader': None,
  2587. 'upload_date': None,
  2588. }
  2589. self.report_download_webpage(info['id'])
  2590. try:
  2591. coursepage = compat_urllib_request.urlopen(url).read()
  2592. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2593. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2594. return
  2595. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2596. if m:
  2597. info['title'] = unescapeHTML(m.group(1))
  2598. else:
  2599. info['title'] = info['id']
  2600. m = re.search('<description>([^<]+)</description>', coursepage)
  2601. if m:
  2602. info['description'] = unescapeHTML(m.group(1))
  2603. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2604. info['list'] = [
  2605. {
  2606. 'type': 'reference',
  2607. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2608. }
  2609. for vpage in links]
  2610. results = []
  2611. for entry in info['list']:
  2612. assert entry['type'] == 'reference'
  2613. results += self.extract(entry['url'])
  2614. return results
  2615. else: # Root page
  2616. info = {
  2617. 'id': 'Stanford OpenClassroom',
  2618. 'type': 'playlist',
  2619. 'uploader': None,
  2620. 'upload_date': None,
  2621. }
  2622. self.report_download_webpage(info['id'])
  2623. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2624. try:
  2625. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2626. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2627. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2628. return
  2629. info['title'] = info['id']
  2630. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2631. info['list'] = [
  2632. {
  2633. 'type': 'reference',
  2634. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2635. }
  2636. for cpage in links]
  2637. results = []
  2638. for entry in info['list']:
  2639. assert entry['type'] == 'reference'
  2640. results += self.extract(entry['url'])
  2641. return results
  2642. class MTVIE(InfoExtractor):
  2643. """Information extractor for MTV.com"""
  2644. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2645. IE_NAME = u'mtv'
  2646. def report_webpage(self, video_id):
  2647. """Report information extraction."""
  2648. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2649. def report_extraction(self, video_id):
  2650. """Report information extraction."""
  2651. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2652. def _real_extract(self, url):
  2653. mobj = re.match(self._VALID_URL, url)
  2654. if mobj is None:
  2655. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2656. return
  2657. if not mobj.group('proto'):
  2658. url = 'http://' + url
  2659. video_id = mobj.group('videoid')
  2660. self.report_webpage(video_id)
  2661. request = compat_urllib_request.Request(url)
  2662. try:
  2663. webpage = compat_urllib_request.urlopen(request).read()
  2664. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2665. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2666. return
  2667. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2668. if mobj is None:
  2669. self._downloader.trouble(u'ERROR: unable to extract song name')
  2670. return
  2671. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2672. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2673. if mobj is None:
  2674. self._downloader.trouble(u'ERROR: unable to extract performer')
  2675. return
  2676. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2677. video_title = performer + ' - ' + song_name
  2678. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2679. if mobj is None:
  2680. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2681. return
  2682. mtvn_uri = mobj.group(1)
  2683. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2684. if mobj is None:
  2685. self._downloader.trouble(u'ERROR: unable to extract content id')
  2686. return
  2687. content_id = mobj.group(1)
  2688. 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
  2689. self.report_extraction(video_id)
  2690. request = compat_urllib_request.Request(videogen_url)
  2691. try:
  2692. metadataXml = compat_urllib_request.urlopen(request).read()
  2693. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2694. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % compat_str(err))
  2695. return
  2696. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2697. renditions = mdoc.findall('.//rendition')
  2698. # For now, always pick the highest quality.
  2699. rendition = renditions[-1]
  2700. try:
  2701. _,_,ext = rendition.attrib['type'].partition('/')
  2702. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2703. video_url = rendition.find('./src').text
  2704. except KeyError:
  2705. self._downloader.trouble('Invalid rendition field.')
  2706. return
  2707. info = {
  2708. 'id': video_id,
  2709. 'url': video_url,
  2710. 'uploader': performer,
  2711. 'upload_date': None,
  2712. 'title': video_title,
  2713. 'ext': ext,
  2714. 'format': format,
  2715. }
  2716. return [info]
  2717. class YoukuIE(InfoExtractor):
  2718. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2719. IE_NAME = u'Youku'
  2720. def __init__(self, downloader=None):
  2721. InfoExtractor.__init__(self, downloader)
  2722. def report_download_webpage(self, file_id):
  2723. """Report webpage download."""
  2724. self._downloader.to_screen(u'[Youku] %s: Downloading webpage' % file_id)
  2725. def report_extraction(self, file_id):
  2726. """Report information extraction."""
  2727. self._downloader.to_screen(u'[Youku] %s: Extracting information' % file_id)
  2728. def _gen_sid(self):
  2729. nowTime = int(time.time() * 1000)
  2730. random1 = random.randint(1000,1998)
  2731. random2 = random.randint(1000,9999)
  2732. return "%d%d%d" %(nowTime,random1,random2)
  2733. def _get_file_ID_mix_string(self, seed):
  2734. mixed = []
  2735. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2736. seed = float(seed)
  2737. for i in range(len(source)):
  2738. seed = (seed * 211 + 30031 ) % 65536
  2739. index = math.floor(seed / 65536 * len(source) )
  2740. mixed.append(source[int(index)])
  2741. source.remove(source[int(index)])
  2742. #return ''.join(mixed)
  2743. return mixed
  2744. def _get_file_id(self, fileId, seed):
  2745. mixed = self._get_file_ID_mix_string(seed)
  2746. ids = fileId.split('*')
  2747. realId = []
  2748. for ch in ids:
  2749. if ch:
  2750. realId.append(mixed[int(ch)])
  2751. return ''.join(realId)
  2752. def _real_extract(self, url):
  2753. mobj = re.match(self._VALID_URL, url)
  2754. if mobj is None:
  2755. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2756. return
  2757. video_id = mobj.group('ID')
  2758. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2759. request = compat_urllib_request.Request(info_url, None, std_headers)
  2760. try:
  2761. self.report_download_webpage(video_id)
  2762. jsondata = compat_urllib_request.urlopen(request).read()
  2763. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2764. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2765. return
  2766. self.report_extraction(video_id)
  2767. try:
  2768. config = json.loads(jsondata)
  2769. video_title = config['data'][0]['title']
  2770. seed = config['data'][0]['seed']
  2771. format = self._downloader.params.get('format', None)
  2772. supported_format = config['data'][0]['streamfileids'].keys()
  2773. if format is None or format == 'best':
  2774. if 'hd2' in supported_format:
  2775. format = 'hd2'
  2776. else:
  2777. format = 'flv'
  2778. ext = u'flv'
  2779. elif format == 'worst':
  2780. format = 'mp4'
  2781. ext = u'mp4'
  2782. else:
  2783. format = 'flv'
  2784. ext = u'flv'
  2785. fileid = config['data'][0]['streamfileids'][format]
  2786. seg_number = len(config['data'][0]['segs'][format])
  2787. keys=[]
  2788. for i in xrange(seg_number):
  2789. keys.append(config['data'][0]['segs'][format][i]['k'])
  2790. #TODO check error
  2791. #youku only could be viewed from mainland china
  2792. except:
  2793. self._downloader.trouble(u'ERROR: unable to extract info section')
  2794. return
  2795. files_info=[]
  2796. sid = self._gen_sid()
  2797. fileid = self._get_file_id(fileid, seed)
  2798. #column 8,9 of fileid represent the segment number
  2799. #fileid[7:9] should be changed
  2800. for index, key in enumerate(keys):
  2801. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2802. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2803. info = {
  2804. 'id': '%s_part%02d' % (video_id, index),
  2805. 'url': download_url,
  2806. 'uploader': None,
  2807. 'upload_date': None,
  2808. 'title': video_title,
  2809. 'ext': ext,
  2810. }
  2811. files_info.append(info)
  2812. return files_info
  2813. class XNXXIE(InfoExtractor):
  2814. """Information extractor for xnxx.com"""
  2815. _VALID_URL = r'^http://video\.xnxx\.com/video([0-9]+)/(.*)'
  2816. IE_NAME = u'xnxx'
  2817. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2818. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2819. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2820. def report_webpage(self, video_id):
  2821. """Report information extraction"""
  2822. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2823. def report_extraction(self, video_id):
  2824. """Report information extraction"""
  2825. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2826. def _real_extract(self, url):
  2827. mobj = re.match(self._VALID_URL, url)
  2828. if mobj is None:
  2829. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2830. return
  2831. video_id = mobj.group(1).decode('utf-8')
  2832. self.report_webpage(video_id)
  2833. # Get webpage content
  2834. try:
  2835. webpage = compat_urllib_request.urlopen(url).read()
  2836. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2837. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2838. return
  2839. result = re.search(self.VIDEO_URL_RE, webpage)
  2840. if result is None:
  2841. self._downloader.trouble(u'ERROR: unable to extract video url')
  2842. return
  2843. video_url = compat_urllib_parse.unquote(result.group(1).decode('utf-8'))
  2844. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2845. if result is None:
  2846. self._downloader.trouble(u'ERROR: unable to extract video title')
  2847. return
  2848. video_title = result.group(1).decode('utf-8')
  2849. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2850. if result is None:
  2851. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2852. return
  2853. video_thumbnail = result.group(1).decode('utf-8')
  2854. return [{
  2855. 'id': video_id,
  2856. 'url': video_url,
  2857. 'uploader': None,
  2858. 'upload_date': None,
  2859. 'title': video_title,
  2860. 'ext': 'flv',
  2861. 'thumbnail': video_thumbnail,
  2862. 'description': None,
  2863. }]
  2864. class GooglePlusIE(InfoExtractor):
  2865. """Information extractor for plus.google.com."""
  2866. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:\w+/)*?(\d+)/posts/(\w+)'
  2867. IE_NAME = u'plus.google'
  2868. def __init__(self, downloader=None):
  2869. InfoExtractor.__init__(self, downloader)
  2870. def report_extract_entry(self, url):
  2871. """Report downloading extry"""
  2872. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url.decode('utf-8'))
  2873. def report_date(self, upload_date):
  2874. """Report downloading extry"""
  2875. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2876. def report_uploader(self, uploader):
  2877. """Report downloading extry"""
  2878. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader.decode('utf-8'))
  2879. def report_title(self, video_title):
  2880. """Report downloading extry"""
  2881. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title.decode('utf-8'))
  2882. def report_extract_vid_page(self, video_page):
  2883. """Report information extraction."""
  2884. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page.decode('utf-8'))
  2885. def _real_extract(self, url):
  2886. # Extract id from URL
  2887. mobj = re.match(self._VALID_URL, url)
  2888. if mobj is None:
  2889. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  2890. return
  2891. post_url = mobj.group(0)
  2892. video_id = mobj.group(2)
  2893. video_extension = 'flv'
  2894. # Step 1, Retrieve post webpage to extract further information
  2895. self.report_extract_entry(post_url)
  2896. request = compat_urllib_request.Request(post_url)
  2897. try:
  2898. webpage = compat_urllib_request.urlopen(request).read()
  2899. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2900. self._downloader.trouble(u'ERROR: Unable to retrieve entry webpage: %s' % compat_str(err))
  2901. return
  2902. # Extract update date
  2903. upload_date = None
  2904. pattern = 'title="Timestamp">(.*?)</a>'
  2905. mobj = re.search(pattern, webpage)
  2906. if mobj:
  2907. upload_date = mobj.group(1)
  2908. # Convert timestring to a format suitable for filename
  2909. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2910. upload_date = upload_date.strftime('%Y%m%d')
  2911. self.report_date(upload_date)
  2912. # Extract uploader
  2913. uploader = None
  2914. pattern = r'rel\="author".*?>(.*?)</a>'
  2915. mobj = re.search(pattern, webpage)
  2916. if mobj:
  2917. uploader = mobj.group(1)
  2918. self.report_uploader(uploader)
  2919. # Extract title
  2920. # Get the first line for title
  2921. video_title = u'NA'
  2922. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2923. mobj = re.search(pattern, webpage)
  2924. if mobj:
  2925. video_title = mobj.group(1)
  2926. self.report_title(video_title)
  2927. # Step 2, Stimulate clicking the image box to launch video
  2928. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2929. mobj = re.search(pattern, webpage)
  2930. if mobj is None:
  2931. self._downloader.trouble(u'ERROR: unable to extract video page URL')
  2932. video_page = mobj.group(1)
  2933. request = compat_urllib_request.Request(video_page)
  2934. try:
  2935. webpage = compat_urllib_request.urlopen(request).read()
  2936. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2937. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2938. return
  2939. self.report_extract_vid_page(video_page)
  2940. # Extract video links on video page
  2941. """Extract video links of all sizes"""
  2942. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2943. mobj = re.findall(pattern, webpage)
  2944. if len(mobj) == 0:
  2945. self._downloader.trouble(u'ERROR: unable to extract video links')
  2946. # Sort in resolution
  2947. links = sorted(mobj)
  2948. # Choose the lowest of the sort, i.e. highest resolution
  2949. video_url = links[-1]
  2950. # Only get the url. The resolution part in the tuple has no use anymore
  2951. video_url = video_url[-1]
  2952. # Treat escaped \u0026 style hex
  2953. video_url = unicode(video_url, "unicode_escape")
  2954. return [{
  2955. 'id': video_id.decode('utf-8'),
  2956. 'url': video_url,
  2957. 'uploader': uploader.decode('utf-8'),
  2958. 'upload_date': upload_date.decode('utf-8'),
  2959. 'title': video_title.decode('utf-8'),
  2960. 'ext': video_extension.decode('utf-8'),
  2961. }]