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.

2945 lines
98 KiB

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