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.

2854 lines
95 KiB

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