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.

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