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.

3112 lines
104 KiB

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