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.

2859 lines
95 KiB

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