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.

2947 lines
98 KiB

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