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.

3392 lines
114 KiB

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