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.

3357 lines
112 KiB

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