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.

3358 lines
112 KiB

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