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.

4185 lines
166 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
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. from __future__ import absolute_import
  4. import base64
  5. import datetime
  6. import itertools
  7. import netrc
  8. import os
  9. import re
  10. import socket
  11. import time
  12. import email.utils
  13. import xml.etree.ElementTree
  14. import random
  15. import math
  16. import operator
  17. from .utils import *
  18. class InfoExtractor(object):
  19. """Information Extractor class.
  20. Information extractors are the classes that, given a URL, extract
  21. information about the video (or videos) the URL refers to. This
  22. information includes the real video URL, the video title, author and
  23. others. The information is stored in a dictionary which is then
  24. passed to the FileDownloader. The FileDownloader processes this
  25. information possibly downloading the video to the file system, among
  26. other possible outcomes.
  27. The dictionaries must include the following fields:
  28. id: Video identifier.
  29. url: Final video URL.
  30. title: Video title, unescaped.
  31. ext: Video filename extension.
  32. The following fields are optional:
  33. format: The video format, defaults to ext (used for --get-format)
  34. thumbnail: Full URL to a video thumbnail image.
  35. description: One-line video description.
  36. uploader: Full name of the video uploader.
  37. upload_date: Video upload date (YYYYMMDD).
  38. uploader_id: Nickname or id of the video uploader.
  39. location: Physical location of the video.
  40. player_url: SWF Player URL (used for rtmpdump).
  41. subtitles: The .srt file contents.
  42. urlhandle: [internal] The urlHandle to be used to download the file,
  43. like returned by urllib.request.urlopen
  44. The fields should all be Unicode strings.
  45. Subclasses of this one should re-define the _real_initialize() and
  46. _real_extract() methods and define a _VALID_URL regexp.
  47. Probably, they should also be added to the list of extractors.
  48. _real_extract() must return a *list* of information dictionaries as
  49. described above.
  50. Finally, the _WORKING attribute should be set to False for broken IEs
  51. in order to warn the users and skip the tests.
  52. """
  53. _ready = False
  54. _downloader = None
  55. _WORKING = True
  56. def __init__(self, downloader=None):
  57. """Constructor. Receives an optional downloader."""
  58. self._ready = False
  59. self.set_downloader(downloader)
  60. @classmethod
  61. def suitable(cls, url):
  62. """Receives a URL and returns True if suitable for this IE."""
  63. return re.match(cls._VALID_URL, url) is not None
  64. @classmethod
  65. def working(cls):
  66. """Getter method for _WORKING."""
  67. return cls._WORKING
  68. def initialize(self):
  69. """Initializes an instance (authentication, etc)."""
  70. if not self._ready:
  71. self._real_initialize()
  72. self._ready = True
  73. def extract(self, url):
  74. """Extracts URL information and returns it in list of dicts."""
  75. self.initialize()
  76. return self._real_extract(url)
  77. def set_downloader(self, downloader):
  78. """Sets the downloader for this IE."""
  79. self._downloader = downloader
  80. def _real_initialize(self):
  81. """Real initialization process. Redefine in subclasses."""
  82. pass
  83. def _real_extract(self, url):
  84. """Real extraction process. Redefine in subclasses."""
  85. pass
  86. @property
  87. def IE_NAME(self):
  88. return type(self).__name__[:-2]
  89. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None):
  90. """ Returns the response handle """
  91. if note is None:
  92. note = u'Downloading video webpage'
  93. self._downloader.to_screen(u'[%s] %s: %s' % (self.IE_NAME, video_id, note))
  94. try:
  95. return compat_urllib_request.urlopen(url_or_request)
  96. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  97. if errnote is None:
  98. errnote = u'Unable to download webpage'
  99. raise ExtractorError(u'%s: %s' % (errnote, compat_str(err)), sys.exc_info()[2])
  100. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None):
  101. """ Returns the data of the page as a string """
  102. urlh = self._request_webpage(url_or_request, video_id, note, errnote)
  103. content_type = urlh.headers.get('Content-Type', '')
  104. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  105. if m:
  106. encoding = m.group(1)
  107. else:
  108. encoding = 'utf-8'
  109. webpage_bytes = urlh.read()
  110. return webpage_bytes.decode(encoding, 'replace')
  111. class YoutubeIE(InfoExtractor):
  112. """Information extractor for youtube.com."""
  113. _VALID_URL = r"""^
  114. (
  115. (?:https?://)? # http(s):// (optional)
  116. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  117. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  118. (?:.*?\#/)? # handle anchor (#/) redirect urls
  119. (?: # the various things that can precede the ID:
  120. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  121. |(?: # or the v= param in all its forms
  122. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  123. (?:\?|\#!?) # the params delimiter ? or # or #!
  124. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  125. v=
  126. )
  127. )? # optional -> youtube.com/xxxx is OK
  128. )? # all until now is optional -> you can pass the naked ID
  129. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  130. (?(1).+)? # if we found the ID, everything can follow
  131. $"""
  132. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  133. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  134. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  135. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  136. _NETRC_MACHINE = 'youtube'
  137. # Listed in order of quality
  138. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  139. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  140. _video_extensions = {
  141. '13': '3gp',
  142. '17': 'mp4',
  143. '18': 'mp4',
  144. '22': 'mp4',
  145. '37': 'mp4',
  146. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  147. '43': 'webm',
  148. '44': 'webm',
  149. '45': 'webm',
  150. '46': 'webm',
  151. }
  152. _video_dimensions = {
  153. '5': '240x400',
  154. '6': '???',
  155. '13': '???',
  156. '17': '144x176',
  157. '18': '360x640',
  158. '22': '720x1280',
  159. '34': '360x640',
  160. '35': '480x854',
  161. '37': '1080x1920',
  162. '38': '3072x4096',
  163. '43': '360x640',
  164. '44': '480x854',
  165. '45': '720x1280',
  166. '46': '1080x1920',
  167. }
  168. IE_NAME = u'youtube'
  169. @classmethod
  170. def suitable(cls, url):
  171. """Receives a URL and returns True if suitable for this IE."""
  172. if YoutubePlaylistIE.suitable(url): return False
  173. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  174. def report_lang(self):
  175. """Report attempt to set language."""
  176. self._downloader.to_screen(u'[youtube] Setting language')
  177. def report_login(self):
  178. """Report attempt to log in."""
  179. self._downloader.to_screen(u'[youtube] Logging in')
  180. def report_age_confirmation(self):
  181. """Report attempt to confirm age."""
  182. self._downloader.to_screen(u'[youtube] Confirming age')
  183. def report_video_webpage_download(self, video_id):
  184. """Report attempt to download video webpage."""
  185. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  186. def report_video_info_webpage_download(self, video_id):
  187. """Report attempt to download video info webpage."""
  188. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  189. def report_video_subtitles_download(self, video_id):
  190. """Report attempt to download video info webpage."""
  191. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles' % video_id)
  192. def report_information_extraction(self, video_id):
  193. """Report attempt to extract video information."""
  194. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  195. def report_unavailable_format(self, video_id, format):
  196. """Report extracted video URL."""
  197. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  198. def report_rtmp_download(self):
  199. """Indicate the download will use the RTMP protocol."""
  200. self._downloader.to_screen(u'[youtube] RTMP download detected')
  201. def _closed_captions_xml_to_srt(self, xml_string):
  202. srt = ''
  203. texts = re.findall(r'<text start="([\d\.]+)"( dur="([\d\.]+)")?>([^<]+)</text>', xml_string, re.MULTILINE)
  204. # TODO parse xml instead of regex
  205. for n, (start, dur_tag, dur, caption) in enumerate(texts):
  206. if not dur: dur = '4'
  207. start = float(start)
  208. end = start + float(dur)
  209. start = "%02i:%02i:%02i,%03i" %(start/(60*60), start/60%60, start%60, start%1*1000)
  210. end = "%02i:%02i:%02i,%03i" %(end/(60*60), end/60%60, end%60, end%1*1000)
  211. caption = unescapeHTML(caption)
  212. caption = unescapeHTML(caption) # double cycle, intentional
  213. srt += str(n+1) + '\n'
  214. srt += start + ' --> ' + end + '\n'
  215. srt += caption + '\n\n'
  216. return srt
  217. def _extract_subtitles(self, video_id):
  218. self.report_video_subtitles_download(video_id)
  219. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  220. try:
  221. srt_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  222. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  223. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  224. srt_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', srt_list)
  225. srt_lang_list = dict((l[1], l[0]) for l in srt_lang_list)
  226. if not srt_lang_list:
  227. return (u'WARNING: video has no closed captions', None)
  228. if self._downloader.params.get('subtitleslang', False):
  229. srt_lang = self._downloader.params.get('subtitleslang')
  230. elif 'en' in srt_lang_list:
  231. srt_lang = 'en'
  232. else:
  233. srt_lang = list(srt_lang_list.keys())[0]
  234. if not srt_lang in srt_lang_list:
  235. return (u'WARNING: no closed captions found in the specified language', None)
  236. params = compat_urllib_parse.urlencode({
  237. 'lang': srt_lang,
  238. 'name': srt_lang_list[srt_lang].encode('utf-8'),
  239. 'v': video_id,
  240. })
  241. url = 'http://www.youtube.com/api/timedtext?' + params
  242. try:
  243. srt_xml = compat_urllib_request.urlopen(url).read().decode('utf-8')
  244. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  245. return (u'WARNING: unable to download video subtitles: %s' % compat_str(err), None)
  246. if not srt_xml:
  247. return (u'WARNING: Did not fetch video subtitles', None)
  248. return (None, self._closed_captions_xml_to_srt(srt_xml))
  249. def _print_formats(self, formats):
  250. print('Available formats:')
  251. for x in formats:
  252. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  253. def _real_initialize(self):
  254. if self._downloader is None:
  255. return
  256. username = None
  257. password = None
  258. downloader_params = self._downloader.params
  259. # Attempt to use provided username and password or .netrc data
  260. if downloader_params.get('username', None) is not None:
  261. username = downloader_params['username']
  262. password = downloader_params['password']
  263. elif downloader_params.get('usenetrc', False):
  264. try:
  265. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  266. if info is not None:
  267. username = info[0]
  268. password = info[2]
  269. else:
  270. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  271. except (IOError, netrc.NetrcParseError) as err:
  272. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  273. return
  274. # Set language
  275. request = compat_urllib_request.Request(self._LANG_URL)
  276. try:
  277. self.report_lang()
  278. compat_urllib_request.urlopen(request).read()
  279. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  280. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  281. return
  282. # No authentication to be performed
  283. if username is None:
  284. return
  285. request = compat_urllib_request.Request(self._LOGIN_URL)
  286. try:
  287. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  288. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  289. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  290. return
  291. galx = None
  292. dsh = None
  293. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  294. if match:
  295. galx = match.group(1)
  296. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  297. if match:
  298. dsh = match.group(1)
  299. # Log in
  300. login_form_strs = {
  301. u'continue': u'http://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  302. u'Email': username,
  303. u'GALX': galx,
  304. u'Passwd': password,
  305. u'PersistentCookie': u'yes',
  306. u'_utf8': u'',
  307. u'bgresponse': u'js_disabled',
  308. u'checkConnection': u'',
  309. u'checkedDomains': u'youtube',
  310. u'dnConn': u'',
  311. u'dsh': dsh,
  312. u'pstMsg': u'0',
  313. u'rmShown': u'1',
  314. u'secTok': u'',
  315. u'signIn': u'Sign in',
  316. u'timeStmp': u'',
  317. u'service': u'youtube',
  318. u'uilel': u'3',
  319. u'hl': u'en_US',
  320. }
  321. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  322. # chokes on unicode
  323. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  324. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  325. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  326. try:
  327. self.report_login()
  328. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  329. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  330. self._downloader.report_warning(u'unable to log in: bad username or password')
  331. return
  332. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  333. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  334. return
  335. # Confirm age
  336. age_form = {
  337. 'next_url': '/',
  338. 'action_confirm': 'Confirm',
  339. }
  340. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  341. try:
  342. self.report_age_confirmation()
  343. age_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  344. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  345. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  346. return
  347. def _extract_id(self, url):
  348. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  349. if mobj is None:
  350. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  351. return
  352. video_id = mobj.group(2)
  353. return video_id
  354. def _real_extract(self, url):
  355. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  356. mobj = re.search(self._NEXT_URL_RE, url)
  357. if mobj:
  358. url = 'http://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  359. video_id = self._extract_id(url)
  360. # Get video webpage
  361. self.report_video_webpage_download(video_id)
  362. url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  363. request = compat_urllib_request.Request(url)
  364. try:
  365. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  366. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  367. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  368. return
  369. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  370. # Attempt to extract SWF player URL
  371. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  372. if mobj is not None:
  373. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  374. else:
  375. player_url = None
  376. # Get video info
  377. self.report_video_info_webpage_download(video_id)
  378. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  379. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  380. % (video_id, el_type))
  381. request = compat_urllib_request.Request(video_info_url)
  382. try:
  383. video_info_webpage_bytes = compat_urllib_request.urlopen(request).read()
  384. video_info_webpage = video_info_webpage_bytes.decode('utf-8', 'ignore')
  385. video_info = compat_parse_qs(video_info_webpage)
  386. if 'token' in video_info:
  387. break
  388. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  389. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  390. return
  391. if 'token' not in video_info:
  392. if 'reason' in video_info:
  393. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0])
  394. else:
  395. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  396. return
  397. # Check for "rental" videos
  398. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  399. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  400. return
  401. # Start extracting information
  402. self.report_information_extraction(video_id)
  403. # uploader
  404. if 'author' not in video_info:
  405. self._downloader.trouble(u'ERROR: unable to extract uploader name')
  406. return
  407. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  408. # uploader_id
  409. video_uploader_id = None
  410. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  411. if mobj is not None:
  412. video_uploader_id = mobj.group(1)
  413. else:
  414. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  415. # title
  416. if 'title' not in video_info:
  417. self._downloader.trouble(u'ERROR: unable to extract video title')
  418. return
  419. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  420. # thumbnail image
  421. if 'thumbnail_url' not in video_info:
  422. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  423. video_thumbnail = ''
  424. else: # don't panic if we can't find it
  425. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  426. # upload date
  427. upload_date = None
  428. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  429. if mobj is not None:
  430. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  431. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  432. for expression in format_expressions:
  433. try:
  434. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  435. except:
  436. pass
  437. # description
  438. video_description = get_element_by_id("eow-description", video_webpage)
  439. if video_description:
  440. video_description = clean_html(video_description)
  441. else:
  442. video_description = ''
  443. # closed captions
  444. video_subtitles = None
  445. if self._downloader.params.get('writesubtitles', False):
  446. (srt_error, video_subtitles) = self._extract_subtitles(video_id)
  447. if srt_error:
  448. self._downloader.trouble(srt_error)
  449. if 'length_seconds' not in video_info:
  450. self._downloader.trouble(u'WARNING: unable to extract video duration')
  451. video_duration = ''
  452. else:
  453. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  454. # token
  455. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  456. # Decide which formats to download
  457. req_format = self._downloader.params.get('format', None)
  458. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  459. self.report_rtmp_download()
  460. video_url_list = [(None, video_info['conn'][0])]
  461. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  462. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  463. url_data = [compat_parse_qs(uds) for uds in url_data_strs]
  464. url_data = [ud for ud in url_data if 'itag' in ud and 'url' in ud]
  465. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  466. format_limit = self._downloader.params.get('format_limit', None)
  467. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  468. if format_limit is not None and format_limit in available_formats:
  469. format_list = available_formats[available_formats.index(format_limit):]
  470. else:
  471. format_list = available_formats
  472. existing_formats = [x for x in format_list if x in url_map]
  473. if len(existing_formats) == 0:
  474. self._downloader.trouble(u'ERROR: no known formats available for video')
  475. return
  476. if self._downloader.params.get('listformats', None):
  477. self._print_formats(existing_formats)
  478. return
  479. if req_format is None or req_format == 'best':
  480. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  481. elif req_format == 'worst':
  482. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  483. elif req_format in ('-1', 'all'):
  484. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  485. else:
  486. # Specific formats. We pick the first in a slash-delimeted sequence.
  487. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  488. req_formats = req_format.split('/')
  489. video_url_list = None
  490. for rf in req_formats:
  491. if rf in url_map:
  492. video_url_list = [(rf, url_map[rf])]
  493. break
  494. if video_url_list is None:
  495. self._downloader.trouble(u'ERROR: requested format not available')
  496. return
  497. else:
  498. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  499. return
  500. results = []
  501. for format_param, video_real_url in video_url_list:
  502. # Extension
  503. video_extension = self._video_extensions.get(format_param, 'flv')
  504. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  505. self._video_dimensions.get(format_param, '???'))
  506. results.append({
  507. 'id': video_id,
  508. 'url': video_real_url,
  509. 'uploader': video_uploader,
  510. 'uploader_id': video_uploader_id,
  511. 'upload_date': upload_date,
  512. 'title': video_title,
  513. 'ext': video_extension,
  514. 'format': video_format,
  515. 'thumbnail': video_thumbnail,
  516. 'description': video_description,
  517. 'player_url': player_url,
  518. 'subtitles': video_subtitles,
  519. 'duration': video_duration
  520. })
  521. return results
  522. class MetacafeIE(InfoExtractor):
  523. """Information Extractor for metacafe.com."""
  524. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  525. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  526. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  527. IE_NAME = u'metacafe'
  528. def __init__(self, downloader=None):
  529. InfoExtractor.__init__(self, downloader)
  530. def report_disclaimer(self):
  531. """Report disclaimer retrieval."""
  532. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  533. def report_age_confirmation(self):
  534. """Report attempt to confirm age."""
  535. self._downloader.to_screen(u'[metacafe] Confirming age')
  536. def report_download_webpage(self, video_id):
  537. """Report webpage download."""
  538. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  539. def report_extraction(self, video_id):
  540. """Report information extraction."""
  541. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  542. def _real_initialize(self):
  543. # Retrieve disclaimer
  544. request = compat_urllib_request.Request(self._DISCLAIMER)
  545. try:
  546. self.report_disclaimer()
  547. disclaimer = compat_urllib_request.urlopen(request).read()
  548. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  549. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % compat_str(err))
  550. return
  551. # Confirm age
  552. disclaimer_form = {
  553. 'filters': '0',
  554. 'submit': "Continue - I'm over 18",
  555. }
  556. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  557. try:
  558. self.report_age_confirmation()
  559. disclaimer = compat_urllib_request.urlopen(request).read()
  560. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  561. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  562. return
  563. def _real_extract(self, url):
  564. # Extract id and simplified title from URL
  565. mobj = re.match(self._VALID_URL, url)
  566. if mobj is None:
  567. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  568. return
  569. video_id = mobj.group(1)
  570. # Check if video comes from YouTube
  571. mobj2 = re.match(r'^yt-(.*)$', video_id)
  572. if mobj2 is not None:
  573. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  574. return
  575. # Retrieve video webpage to extract further information
  576. request = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
  577. try:
  578. self.report_download_webpage(video_id)
  579. webpage = compat_urllib_request.urlopen(request).read()
  580. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  581. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  582. return
  583. # Extract URL, uploader and title from webpage
  584. self.report_extraction(video_id)
  585. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  586. if mobj is not None:
  587. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  588. video_extension = mediaURL[-3:]
  589. # Extract gdaKey if available
  590. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  591. if mobj is None:
  592. video_url = mediaURL
  593. else:
  594. gdaKey = mobj.group(1)
  595. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  596. else:
  597. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  598. if mobj is None:
  599. self._downloader.trouble(u'ERROR: unable to extract media URL')
  600. return
  601. vardict = compat_parse_qs(mobj.group(1))
  602. if 'mediaData' not in vardict:
  603. self._downloader.trouble(u'ERROR: unable to extract media URL')
  604. return
  605. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  606. if mobj is None:
  607. self._downloader.trouble(u'ERROR: unable to extract media URL')
  608. return
  609. mediaURL = mobj.group(1).replace('\\/', '/')
  610. video_extension = mediaURL[-3:]
  611. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  612. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  613. if mobj is None:
  614. self._downloader.trouble(u'ERROR: unable to extract title')
  615. return
  616. video_title = mobj.group(1).decode('utf-8')
  617. mobj = re.search(r'submitter=(.*?);', webpage)
  618. if mobj is None:
  619. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  620. return
  621. video_uploader = mobj.group(1)
  622. return [{
  623. 'id': video_id.decode('utf-8'),
  624. 'url': video_url.decode('utf-8'),
  625. 'uploader': video_uploader.decode('utf-8'),
  626. 'upload_date': None,
  627. 'title': video_title,
  628. 'ext': video_extension.decode('utf-8'),
  629. }]
  630. class DailymotionIE(InfoExtractor):
  631. """Information Extractor for Dailymotion"""
  632. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  633. IE_NAME = u'dailymotion'
  634. _WORKING = False
  635. def __init__(self, downloader=None):
  636. InfoExtractor.__init__(self, downloader)
  637. def report_extraction(self, video_id):
  638. """Report information extraction."""
  639. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  640. def _real_extract(self, url):
  641. # Extract id and simplified title from URL
  642. mobj = re.match(self._VALID_URL, url)
  643. if mobj is None:
  644. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  645. return
  646. video_id = mobj.group(1).split('_')[0].split('?')[0]
  647. video_extension = 'mp4'
  648. # Retrieve video webpage to extract further information
  649. request = compat_urllib_request.Request(url)
  650. request.add_header('Cookie', 'family_filter=off')
  651. webpage = self._download_webpage(request, video_id)
  652. # Extract URL, uploader and title from webpage
  653. self.report_extraction(video_id)
  654. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  655. if mobj is None:
  656. self._downloader.trouble(u'ERROR: unable to extract media URL')
  657. return
  658. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  659. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  660. if key in flashvars:
  661. max_quality = key
  662. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  663. break
  664. else:
  665. self._downloader.trouble(u'ERROR: unable to extract video URL')
  666. return
  667. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  668. if mobj is None:
  669. self._downloader.trouble(u'ERROR: unable to extract video URL')
  670. return
  671. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  672. # TODO: support choosing qualities
  673. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  674. if mobj is None:
  675. self._downloader.trouble(u'ERROR: unable to extract title')
  676. return
  677. video_title = unescapeHTML(mobj.group('title'))
  678. video_uploader = None
  679. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  680. if mobj is None:
  681. # lookin for official user
  682. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  683. if mobj_official is None:
  684. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  685. else:
  686. video_uploader = mobj_official.group(1)
  687. else:
  688. video_uploader = mobj.group(1)
  689. video_upload_date = None
  690. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  691. if mobj is not None:
  692. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  693. return [{
  694. 'id': video_id,
  695. 'url': video_url,
  696. 'uploader': video_uploader,
  697. 'upload_date': video_upload_date,
  698. 'title': video_title,
  699. 'ext': video_extension,
  700. }]
  701. class PhotobucketIE(InfoExtractor):
  702. """Information extractor for photobucket.com."""
  703. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  704. IE_NAME = u'photobucket'
  705. def __init__(self, downloader=None):
  706. InfoExtractor.__init__(self, downloader)
  707. def report_download_webpage(self, video_id):
  708. """Report webpage download."""
  709. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  710. def report_extraction(self, video_id):
  711. """Report information extraction."""
  712. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  713. def _real_extract(self, url):
  714. # Extract id from URL
  715. mobj = re.match(self._VALID_URL, url)
  716. if mobj is None:
  717. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  718. return
  719. video_id = mobj.group(1)
  720. video_extension = 'flv'
  721. # Retrieve video webpage to extract further information
  722. request = compat_urllib_request.Request(url)
  723. try:
  724. self.report_download_webpage(video_id)
  725. webpage = compat_urllib_request.urlopen(request).read()
  726. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  727. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  728. return
  729. # Extract URL, uploader, and title from webpage
  730. self.report_extraction(video_id)
  731. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  732. if mobj is None:
  733. self._downloader.trouble(u'ERROR: unable to extract media URL')
  734. return
  735. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  736. video_url = mediaURL
  737. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  738. if mobj is None:
  739. self._downloader.trouble(u'ERROR: unable to extract title')
  740. return
  741. video_title = mobj.group(1).decode('utf-8')
  742. video_uploader = mobj.group(2).decode('utf-8')
  743. return [{
  744. 'id': video_id.decode('utf-8'),
  745. 'url': video_url.decode('utf-8'),
  746. 'uploader': video_uploader,
  747. 'upload_date': None,
  748. 'title': video_title,
  749. 'ext': video_extension.decode('utf-8'),
  750. }]
  751. class YahooIE(InfoExtractor):
  752. """Information extractor for video.yahoo.com."""
  753. _WORKING = False
  754. # _VALID_URL matches all Yahoo! Video URLs
  755. # _VPAGE_URL matches only the extractable '/watch/' URLs
  756. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  757. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  758. IE_NAME = u'video.yahoo'
  759. def __init__(self, downloader=None):
  760. InfoExtractor.__init__(self, downloader)
  761. def report_download_webpage(self, video_id):
  762. """Report webpage download."""
  763. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  764. def report_extraction(self, video_id):
  765. """Report information extraction."""
  766. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  767. def _real_extract(self, url, new_video=True):
  768. # Extract ID from URL
  769. mobj = re.match(self._VALID_URL, url)
  770. if mobj is None:
  771. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  772. return
  773. video_id = mobj.group(2)
  774. video_extension = 'flv'
  775. # Rewrite valid but non-extractable URLs as
  776. # extractable English language /watch/ URLs
  777. if re.match(self._VPAGE_URL, url) is None:
  778. request = compat_urllib_request.Request(url)
  779. try:
  780. webpage = compat_urllib_request.urlopen(request).read()
  781. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  782. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  783. return
  784. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  785. if mobj is None:
  786. self._downloader.trouble(u'ERROR: Unable to extract id field')
  787. return
  788. yahoo_id = mobj.group(1)
  789. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  790. if mobj is None:
  791. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  792. return
  793. yahoo_vid = mobj.group(1)
  794. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  795. return self._real_extract(url, new_video=False)
  796. # Retrieve video webpage to extract further information
  797. request = compat_urllib_request.Request(url)
  798. try:
  799. self.report_download_webpage(video_id)
  800. webpage = compat_urllib_request.urlopen(request).read()
  801. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  802. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  803. return
  804. # Extract uploader and title from webpage
  805. self.report_extraction(video_id)
  806. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  807. if mobj is None:
  808. self._downloader.trouble(u'ERROR: unable to extract video title')
  809. return
  810. video_title = mobj.group(1).decode('utf-8')
  811. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  812. if mobj is None:
  813. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  814. return
  815. video_uploader = mobj.group(1).decode('utf-8')
  816. # Extract video thumbnail
  817. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  818. if mobj is None:
  819. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  820. return
  821. video_thumbnail = mobj.group(1).decode('utf-8')
  822. # Extract video description
  823. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  824. if mobj is None:
  825. self._downloader.trouble(u'ERROR: unable to extract video description')
  826. return
  827. video_description = mobj.group(1).decode('utf-8')
  828. if not video_description:
  829. video_description = 'No description available.'
  830. # Extract video height and width
  831. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  832. if mobj is None:
  833. self._downloader.trouble(u'ERROR: unable to extract video height')
  834. return
  835. yv_video_height = mobj.group(1)
  836. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  837. if mobj is None:
  838. self._downloader.trouble(u'ERROR: unable to extract video width')
  839. return
  840. yv_video_width = mobj.group(1)
  841. # Retrieve video playlist to extract media URL
  842. # I'm not completely sure what all these options are, but we
  843. # seem to need most of them, otherwise the server sends a 401.
  844. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  845. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  846. request = compat_urllib_request.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  847. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  848. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  849. try:
  850. self.report_download_webpage(video_id)
  851. webpage = compat_urllib_request.urlopen(request).read()
  852. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  853. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  854. return
  855. # Extract media URL from playlist XML
  856. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  857. if mobj is None:
  858. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  859. return
  860. video_url = compat_urllib_parse.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  861. video_url = unescapeHTML(video_url)
  862. return [{
  863. 'id': video_id.decode('utf-8'),
  864. 'url': video_url,
  865. 'uploader': video_uploader,
  866. 'upload_date': None,
  867. 'title': video_title,
  868. 'ext': video_extension.decode('utf-8'),
  869. 'thumbnail': video_thumbnail.decode('utf-8'),
  870. 'description': video_description,
  871. }]
  872. class VimeoIE(InfoExtractor):
  873. """Information extractor for vimeo.com."""
  874. # _VALID_URL matches Vimeo URLs
  875. _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)'
  876. IE_NAME = u'vimeo'
  877. def __init__(self, downloader=None):
  878. InfoExtractor.__init__(self, downloader)
  879. def report_download_webpage(self, video_id):
  880. """Report webpage download."""
  881. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  882. def report_extraction(self, video_id):
  883. """Report information extraction."""
  884. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  885. def _real_extract(self, url, new_video=True):
  886. # Extract ID from URL
  887. mobj = re.match(self._VALID_URL, url)
  888. if mobj is None:
  889. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  890. return
  891. video_id = mobj.group('id')
  892. if not mobj.group('proto'):
  893. url = 'https://' + url
  894. if mobj.group('direct_link'):
  895. url = 'https://vimeo.com/' + video_id
  896. # Retrieve video webpage to extract further information
  897. request = compat_urllib_request.Request(url, None, std_headers)
  898. try:
  899. self.report_download_webpage(video_id)
  900. webpage_bytes = compat_urllib_request.urlopen(request).read()
  901. webpage = webpage_bytes.decode('utf-8')
  902. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  903. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  904. return
  905. # Now we begin extracting as much information as we can from what we
  906. # retrieved. First we extract the information common to all extractors,
  907. # and latter we extract those that are Vimeo specific.
  908. self.report_extraction(video_id)
  909. # Extract the config JSON
  910. try:
  911. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  912. config = json.loads(config)
  913. except:
  914. self._downloader.trouble(u'ERROR: unable to extract info section')
  915. return
  916. # Extract title
  917. video_title = config["video"]["title"]
  918. # Extract uploader and uploader_id
  919. video_uploader = config["video"]["owner"]["name"]
  920. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1]
  921. # Extract video thumbnail
  922. video_thumbnail = config["video"]["thumbnail"]
  923. # Extract video description
  924. video_description = get_element_by_attribute("itemprop", "description", webpage)
  925. if video_description: video_description = clean_html(video_description)
  926. else: video_description = ''
  927. # Extract upload date
  928. video_upload_date = None
  929. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  930. if mobj is not None:
  931. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  932. # Vimeo specific: extract request signature and timestamp
  933. sig = config['request']['signature']
  934. timestamp = config['request']['timestamp']
  935. # Vimeo specific: extract video codec and quality information
  936. # First consider quality, then codecs, then take everything
  937. # TODO bind to format param
  938. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  939. files = { 'hd': [], 'sd': [], 'other': []}
  940. for codec_name, codec_extension in codecs:
  941. if codec_name in config["video"]["files"]:
  942. if 'hd' in config["video"]["files"][codec_name]:
  943. files['hd'].append((codec_name, codec_extension, 'hd'))
  944. elif 'sd' in config["video"]["files"][codec_name]:
  945. files['sd'].append((codec_name, codec_extension, 'sd'))
  946. else:
  947. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  948. for quality in ('hd', 'sd', 'other'):
  949. if len(files[quality]) > 0:
  950. video_quality = files[quality][0][2]
  951. video_codec = files[quality][0][0]
  952. video_extension = files[quality][0][1]
  953. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  954. break
  955. else:
  956. self._downloader.trouble(u'ERROR: no known codec found')
  957. return
  958. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  959. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  960. return [{
  961. 'id': video_id,
  962. 'url': video_url,
  963. 'uploader': video_uploader,
  964. 'uploader_id': video_uploader_id,
  965. 'upload_date': video_upload_date,
  966. 'title': video_title,
  967. 'ext': video_extension,
  968. 'thumbnail': video_thumbnail,
  969. 'description': video_description,
  970. }]
  971. class ArteTvIE(InfoExtractor):
  972. """arte.tv information extractor."""
  973. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  974. _LIVE_URL = r'index-[0-9]+\.html$'
  975. IE_NAME = u'arte.tv'
  976. def __init__(self, downloader=None):
  977. InfoExtractor.__init__(self, downloader)
  978. def report_download_webpage(self, video_id):
  979. """Report webpage download."""
  980. self._downloader.to_screen(u'[arte.tv] %s: Downloading webpage' % video_id)
  981. def report_extraction(self, video_id):
  982. """Report information extraction."""
  983. self._downloader.to_screen(u'[arte.tv] %s: Extracting information' % video_id)
  984. def fetch_webpage(self, url):
  985. request = compat_urllib_request.Request(url)
  986. try:
  987. self.report_download_webpage(url)
  988. webpage = compat_urllib_request.urlopen(request).read()
  989. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  990. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  991. return
  992. except ValueError as err:
  993. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  994. return
  995. return webpage
  996. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  997. page = self.fetch_webpage(url)
  998. mobj = re.search(regex, page, regexFlags)
  999. info = {}
  1000. if mobj is None:
  1001. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1002. return
  1003. for (i, key, err) in matchTuples:
  1004. if mobj.group(i) is None:
  1005. self._downloader.trouble(err)
  1006. return
  1007. else:
  1008. info[key] = mobj.group(i)
  1009. return info
  1010. def extractLiveStream(self, url):
  1011. video_lang = url.split('/')[-4]
  1012. info = self.grep_webpage(
  1013. url,
  1014. r'src="(.*?/videothek_js.*?\.js)',
  1015. 0,
  1016. [
  1017. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1018. ]
  1019. )
  1020. http_host = url.split('/')[2]
  1021. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  1022. info = self.grep_webpage(
  1023. next_url,
  1024. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  1025. '(http://.*?\.swf).*?' +
  1026. '(rtmp://.*?)\'',
  1027. re.DOTALL,
  1028. [
  1029. (1, 'path', u'ERROR: could not extract video path: %s' % url),
  1030. (2, 'player', u'ERROR: could not extract video player: %s' % url),
  1031. (3, 'url', u'ERROR: could not extract video url: %s' % url)
  1032. ]
  1033. )
  1034. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  1035. def extractPlus7Stream(self, url):
  1036. video_lang = url.split('/')[-3]
  1037. info = self.grep_webpage(
  1038. url,
  1039. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  1040. 0,
  1041. [
  1042. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1043. ]
  1044. )
  1045. next_url = compat_urllib_parse.unquote(info.get('url'))
  1046. info = self.grep_webpage(
  1047. next_url,
  1048. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  1049. 0,
  1050. [
  1051. (1, 'url', u'ERROR: Could not find <video> tag: %s' % url)
  1052. ]
  1053. )
  1054. next_url = compat_urllib_parse.unquote(info.get('url'))
  1055. info = self.grep_webpage(
  1056. next_url,
  1057. r'<video id="(.*?)".*?>.*?' +
  1058. '<name>(.*?)</name>.*?' +
  1059. '<dateVideo>(.*?)</dateVideo>.*?' +
  1060. '<url quality="hd">(.*?)</url>',
  1061. re.DOTALL,
  1062. [
  1063. (1, 'id', u'ERROR: could not extract video id: %s' % url),
  1064. (2, 'title', u'ERROR: could not extract video title: %s' % url),
  1065. (3, 'date', u'ERROR: could not extract video date: %s' % url),
  1066. (4, 'url', u'ERROR: could not extract video url: %s' % url)
  1067. ]
  1068. )
  1069. return {
  1070. 'id': info.get('id'),
  1071. 'url': compat_urllib_parse.unquote(info.get('url')),
  1072. 'uploader': u'arte.tv',
  1073. 'upload_date': info.get('date'),
  1074. 'title': info.get('title').decode('utf-8'),
  1075. 'ext': u'mp4',
  1076. 'format': u'NA',
  1077. 'player_url': None,
  1078. }
  1079. def _real_extract(self, url):
  1080. video_id = url.split('/')[-1]
  1081. self.report_extraction(video_id)
  1082. if re.search(self._LIVE_URL, video_id) is not None:
  1083. self.extractLiveStream(url)
  1084. return
  1085. else:
  1086. info = self.extractPlus7Stream(url)
  1087. return [info]
  1088. class GenericIE(InfoExtractor):
  1089. """Generic last-resort information extractor."""
  1090. _VALID_URL = r'.*'
  1091. IE_NAME = u'generic'
  1092. def __init__(self, downloader=None):
  1093. InfoExtractor.__init__(self, downloader)
  1094. def report_download_webpage(self, video_id):
  1095. """Report webpage download."""
  1096. if not self._downloader.params.get('test', False):
  1097. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1098. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1099. def report_extraction(self, video_id):
  1100. """Report information extraction."""
  1101. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1102. def report_following_redirect(self, new_url):
  1103. """Report information extraction."""
  1104. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1105. def _test_redirect(self, url):
  1106. """Check if it is a redirect, like url shorteners, in case restart chain."""
  1107. class HeadRequest(compat_urllib_request.Request):
  1108. def get_method(self):
  1109. return "HEAD"
  1110. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1111. """
  1112. Subclass the HTTPRedirectHandler to make it use our
  1113. HeadRequest also on the redirected URL
  1114. """
  1115. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1116. if code in (301, 302, 303, 307):
  1117. newurl = newurl.replace(' ', '%20')
  1118. newheaders = dict((k,v) for k,v in req.headers.items()
  1119. if k.lower() not in ("content-length", "content-type"))
  1120. return HeadRequest(newurl,
  1121. headers=newheaders,
  1122. origin_req_host=req.get_origin_req_host(),
  1123. unverifiable=True)
  1124. else:
  1125. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1126. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1127. """
  1128. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1129. """
  1130. def http_error_405(self, req, fp, code, msg, headers):
  1131. fp.read()
  1132. fp.close()
  1133. newheaders = dict((k,v) for k,v in req.headers.items()
  1134. if k.lower() not in ("content-length", "content-type"))
  1135. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1136. headers=newheaders,
  1137. origin_req_host=req.get_origin_req_host(),
  1138. unverifiable=True))
  1139. # Build our opener
  1140. opener = compat_urllib_request.OpenerDirector()
  1141. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1142. HTTPMethodFallback, HEADRedirectHandler,
  1143. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1144. opener.add_handler(handler())
  1145. response = opener.open(HeadRequest(url))
  1146. new_url = response.geturl()
  1147. if url == new_url:
  1148. return False
  1149. self.report_following_redirect(new_url)
  1150. self._downloader.download([new_url])
  1151. return True
  1152. def _real_extract(self, url):
  1153. if self._test_redirect(url): return
  1154. video_id = url.split('/')[-1]
  1155. try:
  1156. webpage = self._download_webpage(url, video_id)
  1157. except ValueError as err:
  1158. # since this is the last-resort InfoExtractor, if
  1159. # this error is thrown, it'll be thrown here
  1160. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1161. return
  1162. self.report_extraction(video_id)
  1163. # Start with something easy: JW Player in SWFObject
  1164. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1165. if mobj is None:
  1166. # Broaden the search a little bit
  1167. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1168. if mobj is None:
  1169. # Broaden the search a little bit: JWPlayer JS loader
  1170. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  1171. if mobj is None:
  1172. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1173. return
  1174. # It's possible that one of the regexes
  1175. # matched, but returned an empty group:
  1176. if mobj.group(1) is None:
  1177. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1178. return
  1179. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1180. video_id = os.path.basename(video_url)
  1181. # here's a fun little line of code for you:
  1182. video_extension = os.path.splitext(video_id)[1][1:]
  1183. video_id = os.path.splitext(video_id)[0]
  1184. # it's tempting to parse this further, but you would
  1185. # have to take into account all the variations like
  1186. # Video Title - Site Name
  1187. # Site Name | Video Title
  1188. # Video Title - Tagline | Site Name
  1189. # and so on and so forth; it's just not practical
  1190. mobj = re.search(r'<title>(.*)</title>', webpage)
  1191. if mobj is None:
  1192. self._downloader.trouble(u'ERROR: unable to extract title')
  1193. return
  1194. video_title = mobj.group(1)
  1195. # video uploader is domain name
  1196. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1197. if mobj is None:
  1198. self._downloader.trouble(u'ERROR: unable to extract title')
  1199. return
  1200. video_uploader = mobj.group(1)
  1201. return [{
  1202. 'id': video_id,
  1203. 'url': video_url,
  1204. 'uploader': video_uploader,
  1205. 'upload_date': None,
  1206. 'title': video_title,
  1207. 'ext': video_extension,
  1208. }]
  1209. class YoutubeSearchIE(InfoExtractor):
  1210. """Information Extractor for YouTube search queries."""
  1211. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1212. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1213. _max_youtube_results = 1000
  1214. IE_NAME = u'youtube:search'
  1215. def __init__(self, downloader=None):
  1216. InfoExtractor.__init__(self, downloader)
  1217. def report_download_page(self, query, pagenum):
  1218. """Report attempt to download search page with given number."""
  1219. query = query.decode(preferredencoding())
  1220. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1221. def _real_extract(self, query):
  1222. mobj = re.match(self._VALID_URL, query)
  1223. if mobj is None:
  1224. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1225. return
  1226. prefix, query = query.split(':')
  1227. prefix = prefix[8:]
  1228. query = query.encode('utf-8')
  1229. if prefix == '':
  1230. self._download_n_results(query, 1)
  1231. return
  1232. elif prefix == 'all':
  1233. self._download_n_results(query, self._max_youtube_results)
  1234. return
  1235. else:
  1236. try:
  1237. n = int(prefix)
  1238. if n <= 0:
  1239. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1240. return
  1241. elif n > self._max_youtube_results:
  1242. self._downloader.report_warning(u'ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1243. n = self._max_youtube_results
  1244. self._download_n_results(query, n)
  1245. return
  1246. except ValueError: # parsing prefix as integer fails
  1247. self._download_n_results(query, 1)
  1248. return
  1249. def _download_n_results(self, query, n):
  1250. """Downloads a specified number of results for a query"""
  1251. video_ids = []
  1252. pagenum = 0
  1253. limit = n
  1254. while (50 * pagenum) < limit:
  1255. self.report_download_page(query, pagenum+1)
  1256. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1257. request = compat_urllib_request.Request(result_url)
  1258. try:
  1259. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1260. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1261. self._downloader.trouble(u'ERROR: unable to download API page: %s' % compat_str(err))
  1262. return
  1263. api_response = json.loads(data)['data']
  1264. if not 'items' in api_response:
  1265. self._downloader.trouble(u'[youtube] No video results')
  1266. return
  1267. new_ids = list(video['id'] for video in api_response['items'])
  1268. video_ids += new_ids
  1269. limit = min(n, api_response['totalItems'])
  1270. pagenum += 1
  1271. if len(video_ids) > n:
  1272. video_ids = video_ids[:n]
  1273. for id in video_ids:
  1274. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1275. return
  1276. class GoogleSearchIE(InfoExtractor):
  1277. """Information Extractor for Google Video search queries."""
  1278. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1279. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1280. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1281. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1282. _max_google_results = 1000
  1283. IE_NAME = u'video.google:search'
  1284. def __init__(self, downloader=None):
  1285. InfoExtractor.__init__(self, downloader)
  1286. def report_download_page(self, query, pagenum):
  1287. """Report attempt to download playlist page with given number."""
  1288. query = query.decode(preferredencoding())
  1289. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1290. def _real_extract(self, query):
  1291. mobj = re.match(self._VALID_URL, query)
  1292. if mobj is None:
  1293. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1294. return
  1295. prefix, query = query.split(':')
  1296. prefix = prefix[8:]
  1297. query = query.encode('utf-8')
  1298. if prefix == '':
  1299. self._download_n_results(query, 1)
  1300. return
  1301. elif prefix == 'all':
  1302. self._download_n_results(query, self._max_google_results)
  1303. return
  1304. else:
  1305. try:
  1306. n = int(prefix)
  1307. if n <= 0:
  1308. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1309. return
  1310. elif n > self._max_google_results:
  1311. self._downloader.report_warning(u'gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1312. n = self._max_google_results
  1313. self._download_n_results(query, n)
  1314. return
  1315. except ValueError: # parsing prefix as integer fails
  1316. self._download_n_results(query, 1)
  1317. return
  1318. def _download_n_results(self, query, n):
  1319. """Downloads a specified number of results for a query"""
  1320. video_ids = []
  1321. pagenum = 0
  1322. while True:
  1323. self.report_download_page(query, pagenum)
  1324. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1325. request = compat_urllib_request.Request(result_url)
  1326. try:
  1327. page = compat_urllib_request.urlopen(request).read()
  1328. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1329. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1330. return
  1331. # Extract video identifiers
  1332. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1333. video_id = mobj.group(1)
  1334. if video_id not in video_ids:
  1335. video_ids.append(video_id)
  1336. if len(video_ids) == n:
  1337. # Specified n videos reached
  1338. for id in video_ids:
  1339. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1340. return
  1341. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1342. for id in video_ids:
  1343. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1344. return
  1345. pagenum = pagenum + 1
  1346. class YahooSearchIE(InfoExtractor):
  1347. """Information Extractor for Yahoo! Video search queries."""
  1348. _WORKING = False
  1349. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1350. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1351. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1352. _MORE_PAGES_INDICATOR = r'\s*Next'
  1353. _max_yahoo_results = 1000
  1354. IE_NAME = u'video.yahoo:search'
  1355. def __init__(self, downloader=None):
  1356. InfoExtractor.__init__(self, downloader)
  1357. def report_download_page(self, query, pagenum):
  1358. """Report attempt to download playlist page with given number."""
  1359. query = query.decode(preferredencoding())
  1360. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1361. def _real_extract(self, query):
  1362. mobj = re.match(self._VALID_URL, query)
  1363. if mobj is None:
  1364. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1365. return
  1366. prefix, query = query.split(':')
  1367. prefix = prefix[8:]
  1368. query = query.encode('utf-8')
  1369. if prefix == '':
  1370. self._download_n_results(query, 1)
  1371. return
  1372. elif prefix == 'all':
  1373. self._download_n_results(query, self._max_yahoo_results)
  1374. return
  1375. else:
  1376. try:
  1377. n = int(prefix)
  1378. if n <= 0:
  1379. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1380. return
  1381. elif n > self._max_yahoo_results:
  1382. self._downloader.report_warning(u'yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1383. n = self._max_yahoo_results
  1384. self._download_n_results(query, n)
  1385. return
  1386. except ValueError: # parsing prefix as integer fails
  1387. self._download_n_results(query, 1)
  1388. return
  1389. def _download_n_results(self, query, n):
  1390. """Downloads a specified number of results for a query"""
  1391. video_ids = []
  1392. already_seen = set()
  1393. pagenum = 1
  1394. while True:
  1395. self.report_download_page(query, pagenum)
  1396. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1397. request = compat_urllib_request.Request(result_url)
  1398. try:
  1399. page = compat_urllib_request.urlopen(request).read()
  1400. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1401. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1402. return
  1403. # Extract video identifiers
  1404. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1405. video_id = mobj.group(1)
  1406. if video_id not in already_seen:
  1407. video_ids.append(video_id)
  1408. already_seen.add(video_id)
  1409. if len(video_ids) == n:
  1410. # Specified n videos reached
  1411. for id in video_ids:
  1412. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1413. return
  1414. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1415. for id in video_ids:
  1416. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1417. return
  1418. pagenum = pagenum + 1
  1419. class YoutubePlaylistIE(InfoExtractor):
  1420. """Information Extractor for YouTube playlists."""
  1421. _VALID_URL = r"""(?:
  1422. (?:https?://)?
  1423. (?:\w+\.)?
  1424. youtube\.com/
  1425. (?:
  1426. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1427. \? (?:.*?&)*? (?:p|a|list)=
  1428. | user/.*?/user/
  1429. | p/
  1430. | user/.*?#[pg]/c/
  1431. )
  1432. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  1433. .*
  1434. |
  1435. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  1436. )"""
  1437. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json'
  1438. _MAX_RESULTS = 50
  1439. IE_NAME = u'youtube:playlist'
  1440. def __init__(self, downloader=None):
  1441. InfoExtractor.__init__(self, downloader)
  1442. @classmethod
  1443. def suitable(cls, url):
  1444. """Receives a URL and returns True if suitable for this IE."""
  1445. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1446. def report_download_page(self, playlist_id, pagenum):
  1447. """Report attempt to download playlist page with given number."""
  1448. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1449. def _real_extract(self, url):
  1450. # Extract playlist id
  1451. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1452. if mobj is None:
  1453. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1454. return
  1455. # Download playlist videos from API
  1456. playlist_id = mobj.group(1) or mobj.group(2)
  1457. page_num = 1
  1458. videos = []
  1459. while True:
  1460. self.report_download_page(playlist_id, page_num)
  1461. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  1462. try:
  1463. page = compat_urllib_request.urlopen(url).read().decode('utf8')
  1464. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1465. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1466. return
  1467. try:
  1468. response = json.loads(page)
  1469. except ValueError as err:
  1470. self._downloader.trouble(u'ERROR: Invalid JSON in API response: ' + compat_str(err))
  1471. return
  1472. if not 'feed' in response or not 'entry' in response['feed']:
  1473. self._downloader.trouble(u'ERROR: Got a malformed response from YouTube API')
  1474. return
  1475. videos += [ (entry['yt$position']['$t'], entry['content']['src'])
  1476. for entry in response['feed']['entry']
  1477. if 'content' in entry ]
  1478. if len(response['feed']['entry']) < self._MAX_RESULTS:
  1479. break
  1480. page_num += 1
  1481. videos = [v[1] for v in sorted(videos)]
  1482. total = len(videos)
  1483. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1484. playlistend = self._downloader.params.get('playlistend', -1)
  1485. if playlistend == -1:
  1486. videos = videos[playliststart:]
  1487. else:
  1488. videos = videos[playliststart:playlistend]
  1489. if len(videos) == total:
  1490. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos' % (playlist_id, total))
  1491. else:
  1492. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos, downloading %i' % (playlist_id, total, len(videos)))
  1493. for video in videos:
  1494. self._downloader.download([video])
  1495. return
  1496. class YoutubeChannelIE(InfoExtractor):
  1497. """Information Extractor for YouTube channels."""
  1498. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1499. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1500. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1501. IE_NAME = u'youtube:channel'
  1502. def report_download_page(self, channel_id, pagenum):
  1503. """Report attempt to download channel page with given number."""
  1504. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1505. def _real_extract(self, url):
  1506. # Extract channel id
  1507. mobj = re.match(self._VALID_URL, url)
  1508. if mobj is None:
  1509. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1510. return
  1511. # Download channel pages
  1512. channel_id = mobj.group(1)
  1513. video_ids = []
  1514. pagenum = 1
  1515. while True:
  1516. self.report_download_page(channel_id, pagenum)
  1517. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1518. request = compat_urllib_request.Request(url)
  1519. try:
  1520. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1521. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1522. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1523. return
  1524. # Extract video identifiers
  1525. ids_in_page = []
  1526. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1527. if mobj.group(1) not in ids_in_page:
  1528. ids_in_page.append(mobj.group(1))
  1529. video_ids.extend(ids_in_page)
  1530. if self._MORE_PAGES_INDICATOR not in page:
  1531. break
  1532. pagenum = pagenum + 1
  1533. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1534. for id in video_ids:
  1535. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1536. return
  1537. class YoutubeUserIE(InfoExtractor):
  1538. """Information Extractor for YouTube users."""
  1539. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1540. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1541. _GDATA_PAGE_SIZE = 50
  1542. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1543. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1544. IE_NAME = u'youtube:user'
  1545. def __init__(self, downloader=None):
  1546. InfoExtractor.__init__(self, downloader)
  1547. def report_download_page(self, username, start_index):
  1548. """Report attempt to download user page."""
  1549. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1550. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1551. def _real_extract(self, url):
  1552. # Extract username
  1553. mobj = re.match(self._VALID_URL, url)
  1554. if mobj is None:
  1555. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1556. return
  1557. username = mobj.group(1)
  1558. # Download video ids using YouTube Data API. Result size per
  1559. # query is limited (currently to 50 videos) so we need to query
  1560. # page by page until there are no video ids - it means we got
  1561. # all of them.
  1562. video_ids = []
  1563. pagenum = 0
  1564. while True:
  1565. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1566. self.report_download_page(username, start_index)
  1567. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1568. try:
  1569. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1570. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1571. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1572. return
  1573. # Extract video identifiers
  1574. ids_in_page = []
  1575. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1576. if mobj.group(1) not in ids_in_page:
  1577. ids_in_page.append(mobj.group(1))
  1578. video_ids.extend(ids_in_page)
  1579. # A little optimization - if current page is not
  1580. # "full", ie. does not contain PAGE_SIZE video ids then
  1581. # we can assume that this page is the last one - there
  1582. # are no more ids on further pages - no need to query
  1583. # again.
  1584. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1585. break
  1586. pagenum += 1
  1587. all_ids_count = len(video_ids)
  1588. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1589. playlistend = self._downloader.params.get('playlistend', -1)
  1590. if playlistend == -1:
  1591. video_ids = video_ids[playliststart:]
  1592. else:
  1593. video_ids = video_ids[playliststart:playlistend]
  1594. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1595. (username, all_ids_count, len(video_ids)))
  1596. for video_id in video_ids:
  1597. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1598. class BlipTVUserIE(InfoExtractor):
  1599. """Information Extractor for blip.tv users."""
  1600. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1601. _PAGE_SIZE = 12
  1602. IE_NAME = u'blip.tv:user'
  1603. def __init__(self, downloader=None):
  1604. InfoExtractor.__init__(self, downloader)
  1605. def report_download_page(self, username, pagenum):
  1606. """Report attempt to download user page."""
  1607. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1608. (self.IE_NAME, username, pagenum))
  1609. def _real_extract(self, url):
  1610. # Extract username
  1611. mobj = re.match(self._VALID_URL, url)
  1612. if mobj is None:
  1613. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1614. return
  1615. username = mobj.group(1)
  1616. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1617. request = compat_urllib_request.Request(url)
  1618. try:
  1619. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1620. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1621. page_base = page_base % mobj.group(1)
  1622. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1623. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1624. return
  1625. # Download video ids using BlipTV Ajax calls. Result size per
  1626. # query is limited (currently to 12 videos) so we need to query
  1627. # page by page until there are no video ids - it means we got
  1628. # all of them.
  1629. video_ids = []
  1630. pagenum = 1
  1631. while True:
  1632. self.report_download_page(username, pagenum)
  1633. url = page_base + "&page=" + str(pagenum)
  1634. request = compat_urllib_request.Request( url )
  1635. try:
  1636. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1637. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1638. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1639. return
  1640. # Extract video identifiers
  1641. ids_in_page = []
  1642. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1643. if mobj.group(1) not in ids_in_page:
  1644. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1645. video_ids.extend(ids_in_page)
  1646. # A little optimization - if current page is not
  1647. # "full", ie. does not contain PAGE_SIZE video ids then
  1648. # we can assume that this page is the last one - there
  1649. # are no more ids on further pages - no need to query
  1650. # again.
  1651. if len(ids_in_page) < self._PAGE_SIZE:
  1652. break
  1653. pagenum += 1
  1654. all_ids_count = len(video_ids)
  1655. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1656. playlistend = self._downloader.params.get('playlistend', -1)
  1657. if playlistend == -1:
  1658. video_ids = video_ids[playliststart:]
  1659. else:
  1660. video_ids = video_ids[playliststart:playlistend]
  1661. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1662. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1663. for video_id in video_ids:
  1664. self._downloader.download([u'http://blip.tv/'+video_id])
  1665. class DepositFilesIE(InfoExtractor):
  1666. """Information extractor for depositfiles.com"""
  1667. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1668. def report_download_webpage(self, file_id):
  1669. """Report webpage download."""
  1670. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1671. def report_extraction(self, file_id):
  1672. """Report information extraction."""
  1673. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1674. def _real_extract(self, url):
  1675. file_id = url.split('/')[-1]
  1676. # Rebuild url in english locale
  1677. url = 'http://depositfiles.com/en/files/' + file_id
  1678. # Retrieve file webpage with 'Free download' button pressed
  1679. free_download_indication = { 'gateway_result' : '1' }
  1680. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1681. try:
  1682. self.report_download_webpage(file_id)
  1683. webpage = compat_urllib_request.urlopen(request).read()
  1684. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1685. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % compat_str(err))
  1686. return
  1687. # Search for the real file URL
  1688. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1689. if (mobj is None) or (mobj.group(1) is None):
  1690. # Try to figure out reason of the error.
  1691. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1692. if (mobj is not None) and (mobj.group(1) is not None):
  1693. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1694. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1695. else:
  1696. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1697. return
  1698. file_url = mobj.group(1)
  1699. file_extension = os.path.splitext(file_url)[1][1:]
  1700. # Search for file title
  1701. mobj = re.search(r'<b title="(.*?)">', webpage)
  1702. if mobj is None:
  1703. self._downloader.trouble(u'ERROR: unable to extract title')
  1704. return
  1705. file_title = mobj.group(1).decode('utf-8')
  1706. return [{
  1707. 'id': file_id.decode('utf-8'),
  1708. 'url': file_url.decode('utf-8'),
  1709. 'uploader': None,
  1710. 'upload_date': None,
  1711. 'title': file_title,
  1712. 'ext': file_extension.decode('utf-8'),
  1713. }]
  1714. class FacebookIE(InfoExtractor):
  1715. """Information Extractor for Facebook"""
  1716. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1717. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1718. _NETRC_MACHINE = 'facebook'
  1719. IE_NAME = u'facebook'
  1720. def report_login(self):
  1721. """Report attempt to log in."""
  1722. self._downloader.to_screen(u'[%s] Logging in' % self.IE_NAME)
  1723. def _real_initialize(self):
  1724. if self._downloader is None:
  1725. return
  1726. useremail = None
  1727. password = None
  1728. downloader_params = self._downloader.params
  1729. # Attempt to use provided username and password or .netrc data
  1730. if downloader_params.get('username', None) is not None:
  1731. useremail = downloader_params['username']
  1732. password = downloader_params['password']
  1733. elif downloader_params.get('usenetrc', False):
  1734. try:
  1735. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1736. if info is not None:
  1737. useremail = info[0]
  1738. password = info[2]
  1739. else:
  1740. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1741. except (IOError, netrc.NetrcParseError) as err:
  1742. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  1743. return
  1744. if useremail is None:
  1745. return
  1746. # Log in
  1747. login_form = {
  1748. 'email': useremail,
  1749. 'pass': password,
  1750. 'login': 'Log+In'
  1751. }
  1752. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1753. try:
  1754. self.report_login()
  1755. login_results = compat_urllib_request.urlopen(request).read()
  1756. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1757. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1758. return
  1759. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1760. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  1761. return
  1762. def _real_extract(self, url):
  1763. mobj = re.match(self._VALID_URL, url)
  1764. if mobj is None:
  1765. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1766. return
  1767. video_id = mobj.group('ID')
  1768. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  1769. webpage = self._download_webpage(url, video_id)
  1770. BEFORE = '[["allowFullScreen","true"],["allowScriptAccess","always"],["salign","tl"],["scale","noscale"],["wmode","opaque"]].forEach(function(param) {swf.addParam(param[0], param[1]);});\n'
  1771. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  1772. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  1773. if not m:
  1774. raise ExtractorError(u'Cannot parse data')
  1775. data = dict(json.loads(m.group(1)))
  1776. params_raw = compat_urllib_parse.unquote(data['params'])
  1777. params = json.loads(params_raw)
  1778. video_url = params['hd_src']
  1779. if not video_url:
  1780. video_url = params['sd_src']
  1781. if not video_url:
  1782. raise ExtractorError(u'Cannot find video URL')
  1783. video_duration = int(params['video_duration'])
  1784. m = re.search('<h2 class="uiHeaderTitle">([^<]+)</h2>', webpage)
  1785. if not m:
  1786. raise ExtractorError(u'Cannot find title in webpage')
  1787. video_title = unescapeHTML(m.group(1))
  1788. info = {
  1789. 'id': video_id,
  1790. 'title': video_title,
  1791. 'url': video_url,
  1792. 'ext': 'mp4',
  1793. 'duration': video_duration,
  1794. 'thumbnail': params['thumbnail_src'],
  1795. }
  1796. return [info]
  1797. class BlipTVIE(InfoExtractor):
  1798. """Information extractor for blip.tv"""
  1799. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1800. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1801. IE_NAME = u'blip.tv'
  1802. def report_extraction(self, file_id):
  1803. """Report information extraction."""
  1804. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1805. def report_direct_download(self, title):
  1806. """Report information extraction."""
  1807. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1808. def _real_extract(self, url):
  1809. mobj = re.match(self._VALID_URL, url)
  1810. if mobj is None:
  1811. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1812. return
  1813. urlp = compat_urllib_parse_urlparse(url)
  1814. if urlp.path.startswith('/play/'):
  1815. request = compat_urllib_request.Request(url)
  1816. response = compat_urllib_request.urlopen(request)
  1817. redirecturl = response.geturl()
  1818. rurlp = compat_urllib_parse_urlparse(redirecturl)
  1819. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  1820. url = 'http://blip.tv/a/a-' + file_id
  1821. return self._real_extract(url)
  1822. if '?' in url:
  1823. cchar = '&'
  1824. else:
  1825. cchar = '?'
  1826. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1827. request = compat_urllib_request.Request(json_url)
  1828. request.add_header('User-Agent', 'iTunes/10.6.1')
  1829. self.report_extraction(mobj.group(1))
  1830. info = None
  1831. try:
  1832. urlh = compat_urllib_request.urlopen(request)
  1833. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1834. basename = url.split('/')[-1]
  1835. title,ext = os.path.splitext(basename)
  1836. title = title.decode('UTF-8')
  1837. ext = ext.replace('.', '')
  1838. self.report_direct_download(title)
  1839. info = {
  1840. 'id': title,
  1841. 'url': url,
  1842. 'uploader': None,
  1843. 'upload_date': None,
  1844. 'title': title,
  1845. 'ext': ext,
  1846. 'urlhandle': urlh
  1847. }
  1848. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1849. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1850. if info is None: # Regular URL
  1851. try:
  1852. json_code_bytes = urlh.read()
  1853. json_code = json_code_bytes.decode('utf-8')
  1854. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1855. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % compat_str(err))
  1856. return
  1857. try:
  1858. json_data = json.loads(json_code)
  1859. if 'Post' in json_data:
  1860. data = json_data['Post']
  1861. else:
  1862. data = json_data
  1863. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1864. video_url = data['media']['url']
  1865. umobj = re.match(self._URL_EXT, video_url)
  1866. if umobj is None:
  1867. raise ValueError('Can not determine filename extension')
  1868. ext = umobj.group(1)
  1869. info = {
  1870. 'id': data['item_id'],
  1871. 'url': video_url,
  1872. 'uploader': data['display_name'],
  1873. 'upload_date': upload_date,
  1874. 'title': data['title'],
  1875. 'ext': ext,
  1876. 'format': data['media']['mimeType'],
  1877. 'thumbnail': data['thumbnailUrl'],
  1878. 'description': data['description'],
  1879. 'player_url': data['embedUrl'],
  1880. 'user_agent': 'iTunes/10.6.1',
  1881. }
  1882. except (ValueError,KeyError) as err:
  1883. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1884. return
  1885. return [info]
  1886. class MyVideoIE(InfoExtractor):
  1887. """Information Extractor for myvideo.de."""
  1888. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1889. IE_NAME = u'myvideo'
  1890. def __init__(self, downloader=None):
  1891. InfoExtractor.__init__(self, downloader)
  1892. def report_extraction(self, video_id):
  1893. """Report information extraction."""
  1894. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1895. def _real_extract(self,url):
  1896. mobj = re.match(self._VALID_URL, url)
  1897. if mobj is None:
  1898. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1899. return
  1900. video_id = mobj.group(1)
  1901. # Get video webpage
  1902. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  1903. webpage = self._download_webpage(webpage_url, video_id)
  1904. self.report_extraction(video_id)
  1905. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/.*?\.jpg\' />',
  1906. webpage)
  1907. if mobj is None:
  1908. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1909. return
  1910. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1911. mobj = re.search('<title>([^<]+)</title>', webpage)
  1912. if mobj is None:
  1913. self._downloader.trouble(u'ERROR: unable to extract title')
  1914. return
  1915. video_title = mobj.group(1)
  1916. return [{
  1917. 'id': video_id,
  1918. 'url': video_url,
  1919. 'uploader': None,
  1920. 'upload_date': None,
  1921. 'title': video_title,
  1922. 'ext': u'flv',
  1923. }]
  1924. class ComedyCentralIE(InfoExtractor):
  1925. """Information extractor for The Daily Show and Colbert Report """
  1926. # urls can be abbreviations like :thedailyshow or :colbert
  1927. # urls for episodes like:
  1928. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1929. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1930. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1931. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1932. |(https?://)?(www\.)?
  1933. (?P<showname>thedailyshow|colbertnation)\.com/
  1934. (full-episodes/(?P<episode>.*)|
  1935. (?P<clip>
  1936. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1937. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1938. $"""
  1939. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1940. _video_extensions = {
  1941. '3500': 'mp4',
  1942. '2200': 'mp4',
  1943. '1700': 'mp4',
  1944. '1200': 'mp4',
  1945. '750': 'mp4',
  1946. '400': 'mp4',
  1947. }
  1948. _video_dimensions = {
  1949. '3500': '1280x720',
  1950. '2200': '960x540',
  1951. '1700': '768x432',
  1952. '1200': '640x360',
  1953. '750': '512x288',
  1954. '400': '384x216',
  1955. }
  1956. @classmethod
  1957. def suitable(cls, url):
  1958. """Receives a URL and returns True if suitable for this IE."""
  1959. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1960. def report_extraction(self, episode_id):
  1961. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1962. def report_config_download(self, episode_id, media_id):
  1963. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration for %s' % (episode_id, media_id))
  1964. def report_index_download(self, episode_id):
  1965. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  1966. def _print_formats(self, formats):
  1967. print('Available formats:')
  1968. for x in formats:
  1969. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  1970. def _real_extract(self, url):
  1971. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1972. if mobj is None:
  1973. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1974. return
  1975. if mobj.group('shortname'):
  1976. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  1977. url = u'http://www.thedailyshow.com/full-episodes/'
  1978. else:
  1979. url = u'http://www.colbertnation.com/full-episodes/'
  1980. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1981. assert mobj is not None
  1982. if mobj.group('clip'):
  1983. if mobj.group('showname') == 'thedailyshow':
  1984. epTitle = mobj.group('tdstitle')
  1985. else:
  1986. epTitle = mobj.group('cntitle')
  1987. dlNewest = False
  1988. else:
  1989. dlNewest = not mobj.group('episode')
  1990. if dlNewest:
  1991. epTitle = mobj.group('showname')
  1992. else:
  1993. epTitle = mobj.group('episode')
  1994. req = compat_urllib_request.Request(url)
  1995. self.report_extraction(epTitle)
  1996. try:
  1997. htmlHandle = compat_urllib_request.urlopen(req)
  1998. html = htmlHandle.read()
  1999. webpage = html.decode('utf-8')
  2000. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2001. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2002. return
  2003. if dlNewest:
  2004. url = htmlHandle.geturl()
  2005. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2006. if mobj is None:
  2007. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2008. return
  2009. if mobj.group('episode') == '':
  2010. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2011. return
  2012. epTitle = mobj.group('episode')
  2013. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  2014. if len(mMovieParams) == 0:
  2015. # The Colbert Report embeds the information in a without
  2016. # a URL prefix; so extract the alternate reference
  2017. # and then add the URL prefix manually.
  2018. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  2019. if len(altMovieParams) == 0:
  2020. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2021. return
  2022. else:
  2023. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2024. uri = mMovieParams[0][1]
  2025. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2026. self.report_index_download(epTitle)
  2027. try:
  2028. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2029. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2030. self._downloader.trouble(u'ERROR: unable to download episode index: ' + compat_str(err))
  2031. return
  2032. results = []
  2033. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2034. itemEls = idoc.findall('.//item')
  2035. for partNum,itemEl in enumerate(itemEls):
  2036. mediaId = itemEl.findall('./guid')[0].text
  2037. shortMediaId = mediaId.split(':')[-1]
  2038. showId = mediaId.split(':')[-2].replace('.com', '')
  2039. officialTitle = itemEl.findall('./title')[0].text
  2040. officialDate = itemEl.findall('./pubDate')[0].text
  2041. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2042. compat_urllib_parse.urlencode({'uri': mediaId}))
  2043. configReq = compat_urllib_request.Request(configUrl)
  2044. self.report_config_download(epTitle, shortMediaId)
  2045. try:
  2046. configXml = compat_urllib_request.urlopen(configReq).read()
  2047. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2048. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2049. return
  2050. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2051. turls = []
  2052. for rendition in cdoc.findall('.//rendition'):
  2053. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2054. turls.append(finfo)
  2055. if len(turls) == 0:
  2056. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2057. continue
  2058. if self._downloader.params.get('listformats', None):
  2059. self._print_formats([i[0] for i in turls])
  2060. return
  2061. # For now, just pick the highest bitrate
  2062. format,rtmp_video_url = turls[-1]
  2063. # Get the format arg from the arg stream
  2064. req_format = self._downloader.params.get('format', None)
  2065. # Select format if we can find one
  2066. for f,v in turls:
  2067. if f == req_format:
  2068. format, rtmp_video_url = f, v
  2069. break
  2070. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  2071. if not m:
  2072. raise ExtractorError(u'Cannot transform RTMP url')
  2073. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  2074. video_url = base + m.group('finalid')
  2075. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  2076. info = {
  2077. 'id': shortMediaId,
  2078. 'url': video_url,
  2079. 'uploader': showId,
  2080. 'upload_date': officialDate,
  2081. 'title': effTitle,
  2082. 'ext': 'mp4',
  2083. 'format': format,
  2084. 'thumbnail': None,
  2085. 'description': officialTitle,
  2086. }
  2087. results.append(info)
  2088. return results
  2089. class EscapistIE(InfoExtractor):
  2090. """Information extractor for The Escapist """
  2091. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2092. IE_NAME = u'escapist'
  2093. def report_extraction(self, showName):
  2094. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2095. def report_config_download(self, showName):
  2096. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2097. def _real_extract(self, url):
  2098. mobj = re.match(self._VALID_URL, url)
  2099. if mobj is None:
  2100. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2101. return
  2102. showName = mobj.group('showname')
  2103. videoId = mobj.group('episode')
  2104. self.report_extraction(showName)
  2105. try:
  2106. webPage = compat_urllib_request.urlopen(url)
  2107. webPageBytes = webPage.read()
  2108. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2109. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2110. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2111. self._downloader.trouble(u'ERROR: unable to download webpage: ' + compat_str(err))
  2112. return
  2113. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2114. description = unescapeHTML(descMatch.group(1))
  2115. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2116. imgUrl = unescapeHTML(imgMatch.group(1))
  2117. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2118. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2119. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2120. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2121. self.report_config_download(showName)
  2122. try:
  2123. configJSON = compat_urllib_request.urlopen(configUrl)
  2124. m = re.match(r'text/html; charset="?([^"]+)"?', configJSON.headers['Content-Type'])
  2125. configJSON = configJSON.read().decode(m.group(1) if m else 'utf-8')
  2126. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2127. self._downloader.trouble(u'ERROR: unable to download configuration: ' + compat_str(err))
  2128. return
  2129. # Technically, it's JavaScript, not JSON
  2130. configJSON = configJSON.replace("'", '"')
  2131. try:
  2132. config = json.loads(configJSON)
  2133. except (ValueError,) as err:
  2134. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + compat_str(err))
  2135. return
  2136. playlist = config['playlist']
  2137. videoUrl = playlist[1]['url']
  2138. info = {
  2139. 'id': videoId,
  2140. 'url': videoUrl,
  2141. 'uploader': showName,
  2142. 'upload_date': None,
  2143. 'title': showName,
  2144. 'ext': 'mp4',
  2145. 'thumbnail': imgUrl,
  2146. 'description': description,
  2147. 'player_url': playerUrl,
  2148. }
  2149. return [info]
  2150. class CollegeHumorIE(InfoExtractor):
  2151. """Information extractor for collegehumor.com"""
  2152. _WORKING = False
  2153. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2154. IE_NAME = u'collegehumor'
  2155. def report_manifest(self, video_id):
  2156. """Report information extraction."""
  2157. self._downloader.to_screen(u'[%s] %s: Downloading XML manifest' % (self.IE_NAME, video_id))
  2158. def report_extraction(self, video_id):
  2159. """Report information extraction."""
  2160. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2161. def _real_extract(self, url):
  2162. mobj = re.match(self._VALID_URL, url)
  2163. if mobj is None:
  2164. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2165. return
  2166. video_id = mobj.group('videoid')
  2167. info = {
  2168. 'id': video_id,
  2169. 'uploader': None,
  2170. 'upload_date': None,
  2171. }
  2172. self.report_extraction(video_id)
  2173. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2174. try:
  2175. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2176. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2177. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2178. return
  2179. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2180. try:
  2181. videoNode = mdoc.findall('./video')[0]
  2182. info['description'] = videoNode.findall('./description')[0].text
  2183. info['title'] = videoNode.findall('./caption')[0].text
  2184. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2185. manifest_url = videoNode.findall('./file')[0].text
  2186. except IndexError:
  2187. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2188. return
  2189. manifest_url += '?hdcore=2.10.3'
  2190. self.report_manifest(video_id)
  2191. try:
  2192. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2193. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2194. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2195. return
  2196. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2197. try:
  2198. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2199. node_id = media_node.attrib['url']
  2200. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2201. except IndexError as err:
  2202. self._downloader.trouble(u'\nERROR: Invalid manifest file')
  2203. return
  2204. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2205. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2206. info['url'] = url
  2207. info['ext'] = 'f4f'
  2208. return [info]
  2209. class XVideosIE(InfoExtractor):
  2210. """Information extractor for xvideos.com"""
  2211. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2212. IE_NAME = u'xvideos'
  2213. def report_extraction(self, video_id):
  2214. """Report information extraction."""
  2215. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2216. def _real_extract(self, url):
  2217. mobj = re.match(self._VALID_URL, url)
  2218. if mobj is None:
  2219. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2220. return
  2221. video_id = mobj.group(1)
  2222. webpage = self._download_webpage(url, video_id)
  2223. self.report_extraction(video_id)
  2224. # Extract video URL
  2225. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2226. if mobj is None:
  2227. self._downloader.trouble(u'ERROR: unable to extract video url')
  2228. return
  2229. video_url = compat_urllib_parse.unquote(mobj.group(1))
  2230. # Extract title
  2231. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2232. if mobj is None:
  2233. self._downloader.trouble(u'ERROR: unable to extract video title')
  2234. return
  2235. video_title = mobj.group(1)
  2236. # Extract video thumbnail
  2237. 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)
  2238. if mobj is None:
  2239. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2240. return
  2241. video_thumbnail = mobj.group(0)
  2242. info = {
  2243. 'id': video_id,
  2244. 'url': video_url,
  2245. 'uploader': None,
  2246. 'upload_date': None,
  2247. 'title': video_title,
  2248. 'ext': 'flv',
  2249. 'thumbnail': video_thumbnail,
  2250. 'description': None,
  2251. }
  2252. return [info]
  2253. class SoundcloudIE(InfoExtractor):
  2254. """Information extractor for soundcloud.com
  2255. To access the media, the uid of the song and a stream token
  2256. must be extracted from the page source and the script must make
  2257. a request to media.soundcloud.com/crossdomain.xml. Then
  2258. the media can be grabbed by requesting from an url composed
  2259. of the stream token and uid
  2260. """
  2261. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2262. IE_NAME = u'soundcloud'
  2263. def __init__(self, downloader=None):
  2264. InfoExtractor.__init__(self, downloader)
  2265. def report_resolve(self, video_id):
  2266. """Report information extraction."""
  2267. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2268. def report_extraction(self, video_id):
  2269. """Report information extraction."""
  2270. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2271. def _real_extract(self, url):
  2272. mobj = re.match(self._VALID_URL, url)
  2273. if mobj is None:
  2274. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2275. return
  2276. # extract uploader (which is in the url)
  2277. uploader = mobj.group(1)
  2278. # extract simple title (uploader + slug of song title)
  2279. slug_title = mobj.group(2)
  2280. simple_title = uploader + u'-' + slug_title
  2281. self.report_resolve('%s/%s' % (uploader, slug_title))
  2282. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  2283. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2284. request = compat_urllib_request.Request(resolv_url)
  2285. try:
  2286. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2287. info_json = info_json_bytes.decode('utf-8')
  2288. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2289. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2290. return
  2291. info = json.loads(info_json)
  2292. video_id = info['id']
  2293. self.report_extraction('%s/%s' % (uploader, slug_title))
  2294. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2295. request = compat_urllib_request.Request(streams_url)
  2296. try:
  2297. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2298. stream_json = stream_json_bytes.decode('utf-8')
  2299. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2300. self._downloader.trouble(u'ERROR: unable to download stream definitions: %s' % compat_str(err))
  2301. return
  2302. streams = json.loads(stream_json)
  2303. mediaURL = streams['http_mp3_128_url']
  2304. return [{
  2305. 'id': info['id'],
  2306. 'url': mediaURL,
  2307. 'uploader': info['user']['username'],
  2308. 'upload_date': info['created_at'],
  2309. 'title': info['title'],
  2310. 'ext': u'mp3',
  2311. 'description': info['description'],
  2312. }]
  2313. class InfoQIE(InfoExtractor):
  2314. """Information extractor for infoq.com"""
  2315. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2316. def report_extraction(self, video_id):
  2317. """Report information extraction."""
  2318. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2319. def _real_extract(self, url):
  2320. mobj = re.match(self._VALID_URL, url)
  2321. if mobj is None:
  2322. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2323. return
  2324. webpage = self._download_webpage(url, video_id=url)
  2325. self.report_extraction(url)
  2326. # Extract video URL
  2327. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2328. if mobj is None:
  2329. self._downloader.trouble(u'ERROR: unable to extract video url')
  2330. return
  2331. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  2332. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  2333. # Extract title
  2334. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2335. if mobj is None:
  2336. self._downloader.trouble(u'ERROR: unable to extract video title')
  2337. return
  2338. video_title = mobj.group(1)
  2339. # Extract description
  2340. video_description = u'No description available.'
  2341. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2342. if mobj is not None:
  2343. video_description = mobj.group(1)
  2344. video_filename = video_url.split('/')[-1]
  2345. video_id, extension = video_filename.split('.')
  2346. info = {
  2347. 'id': video_id,
  2348. 'url': video_url,
  2349. 'uploader': None,
  2350. 'upload_date': None,
  2351. 'title': video_title,
  2352. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2353. 'thumbnail': None,
  2354. 'description': video_description,
  2355. }
  2356. return [info]
  2357. class MixcloudIE(InfoExtractor):
  2358. """Information extractor for www.mixcloud.com"""
  2359. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2360. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2361. IE_NAME = u'mixcloud'
  2362. def __init__(self, downloader=None):
  2363. InfoExtractor.__init__(self, downloader)
  2364. def report_download_json(self, file_id):
  2365. """Report JSON download."""
  2366. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2367. def report_extraction(self, file_id):
  2368. """Report information extraction."""
  2369. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2370. def get_urls(self, jsonData, fmt, bitrate='best'):
  2371. """Get urls from 'audio_formats' section in json"""
  2372. file_url = None
  2373. try:
  2374. bitrate_list = jsonData[fmt]
  2375. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2376. bitrate = max(bitrate_list) # select highest
  2377. url_list = jsonData[fmt][bitrate]
  2378. except TypeError: # we have no bitrate info.
  2379. url_list = jsonData[fmt]
  2380. return url_list
  2381. def check_urls(self, url_list):
  2382. """Returns 1st active url from list"""
  2383. for url in url_list:
  2384. try:
  2385. compat_urllib_request.urlopen(url)
  2386. return url
  2387. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2388. url = None
  2389. return None
  2390. def _print_formats(self, formats):
  2391. print('Available formats:')
  2392. for fmt in formats.keys():
  2393. for b in formats[fmt]:
  2394. try:
  2395. ext = formats[fmt][b][0]
  2396. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2397. except TypeError: # we have no bitrate info
  2398. ext = formats[fmt][0]
  2399. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2400. break
  2401. def _real_extract(self, url):
  2402. mobj = re.match(self._VALID_URL, url)
  2403. if mobj is None:
  2404. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2405. return
  2406. # extract uploader & filename from url
  2407. uploader = mobj.group(1).decode('utf-8')
  2408. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2409. # construct API request
  2410. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2411. # retrieve .json file with links to files
  2412. request = compat_urllib_request.Request(file_url)
  2413. try:
  2414. self.report_download_json(file_url)
  2415. jsonData = compat_urllib_request.urlopen(request).read()
  2416. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2417. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % compat_str(err))
  2418. return
  2419. # parse JSON
  2420. json_data = json.loads(jsonData)
  2421. player_url = json_data['player_swf_url']
  2422. formats = dict(json_data['audio_formats'])
  2423. req_format = self._downloader.params.get('format', None)
  2424. bitrate = None
  2425. if self._downloader.params.get('listformats', None):
  2426. self._print_formats(formats)
  2427. return
  2428. if req_format is None or req_format == 'best':
  2429. for format_param in formats.keys():
  2430. url_list = self.get_urls(formats, format_param)
  2431. # check urls
  2432. file_url = self.check_urls(url_list)
  2433. if file_url is not None:
  2434. break # got it!
  2435. else:
  2436. if req_format not in formats:
  2437. self._downloader.trouble(u'ERROR: format is not available')
  2438. return
  2439. url_list = self.get_urls(formats, req_format)
  2440. file_url = self.check_urls(url_list)
  2441. format_param = req_format
  2442. return [{
  2443. 'id': file_id.decode('utf-8'),
  2444. 'url': file_url.decode('utf-8'),
  2445. 'uploader': uploader.decode('utf-8'),
  2446. 'upload_date': None,
  2447. 'title': json_data['name'],
  2448. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2449. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2450. 'thumbnail': json_data['thumbnail_url'],
  2451. 'description': json_data['description'],
  2452. 'player_url': player_url.decode('utf-8'),
  2453. }]
  2454. class StanfordOpenClassroomIE(InfoExtractor):
  2455. """Information extractor for Stanford's Open ClassRoom"""
  2456. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2457. IE_NAME = u'stanfordoc'
  2458. def report_download_webpage(self, objid):
  2459. """Report information extraction."""
  2460. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2461. def report_extraction(self, video_id):
  2462. """Report information extraction."""
  2463. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2464. def _real_extract(self, url):
  2465. mobj = re.match(self._VALID_URL, url)
  2466. if mobj is None:
  2467. raise ExtractorError(u'Invalid URL: %s' % url)
  2468. if mobj.group('course') and mobj.group('video'): # A specific video
  2469. course = mobj.group('course')
  2470. video = mobj.group('video')
  2471. info = {
  2472. 'id': course + '_' + video,
  2473. 'uploader': None,
  2474. 'upload_date': None,
  2475. }
  2476. self.report_extraction(info['id'])
  2477. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2478. xmlUrl = baseUrl + video + '.xml'
  2479. try:
  2480. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2481. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2482. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2483. return
  2484. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2485. try:
  2486. info['title'] = mdoc.findall('./title')[0].text
  2487. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2488. except IndexError:
  2489. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2490. return
  2491. info['ext'] = info['url'].rpartition('.')[2]
  2492. return [info]
  2493. elif mobj.group('course'): # A course page
  2494. course = mobj.group('course')
  2495. info = {
  2496. 'id': course,
  2497. 'type': 'playlist',
  2498. 'uploader': None,
  2499. 'upload_date': None,
  2500. }
  2501. coursepage = self._download_webpage(url, info['id'],
  2502. note='Downloading course info page',
  2503. errnote='Unable to download course info page')
  2504. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2505. if m:
  2506. info['title'] = unescapeHTML(m.group(1))
  2507. else:
  2508. info['title'] = info['id']
  2509. m = re.search('<description>([^<]+)</description>', coursepage)
  2510. if m:
  2511. info['description'] = unescapeHTML(m.group(1))
  2512. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2513. info['list'] = [
  2514. {
  2515. 'type': 'reference',
  2516. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2517. }
  2518. for vpage in links]
  2519. results = []
  2520. for entry in info['list']:
  2521. assert entry['type'] == 'reference'
  2522. results += self.extract(entry['url'])
  2523. return results
  2524. else: # Root page
  2525. info = {
  2526. 'id': 'Stanford OpenClassroom',
  2527. 'type': 'playlist',
  2528. 'uploader': None,
  2529. 'upload_date': None,
  2530. }
  2531. self.report_download_webpage(info['id'])
  2532. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2533. try:
  2534. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2535. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2536. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2537. return
  2538. info['title'] = info['id']
  2539. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2540. info['list'] = [
  2541. {
  2542. 'type': 'reference',
  2543. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2544. }
  2545. for cpage in links]
  2546. results = []
  2547. for entry in info['list']:
  2548. assert entry['type'] == 'reference'
  2549. results += self.extract(entry['url'])
  2550. return results
  2551. class MTVIE(InfoExtractor):
  2552. """Information extractor for MTV.com"""
  2553. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2554. IE_NAME = u'mtv'
  2555. def report_extraction(self, video_id):
  2556. """Report information extraction."""
  2557. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2558. def _real_extract(self, url):
  2559. mobj = re.match(self._VALID_URL, url)
  2560. if mobj is None:
  2561. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2562. return
  2563. if not mobj.group('proto'):
  2564. url = 'http://' + url
  2565. video_id = mobj.group('videoid')
  2566. webpage = self._download_webpage(url, video_id)
  2567. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2568. if mobj is None:
  2569. self._downloader.trouble(u'ERROR: unable to extract song name')
  2570. return
  2571. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2572. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2573. if mobj is None:
  2574. self._downloader.trouble(u'ERROR: unable to extract performer')
  2575. return
  2576. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2577. video_title = performer + ' - ' + song_name
  2578. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2579. if mobj is None:
  2580. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2581. return
  2582. mtvn_uri = mobj.group(1)
  2583. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2584. if mobj is None:
  2585. self._downloader.trouble(u'ERROR: unable to extract content id')
  2586. return
  2587. content_id = mobj.group(1)
  2588. 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
  2589. self.report_extraction(video_id)
  2590. request = compat_urllib_request.Request(videogen_url)
  2591. try:
  2592. metadataXml = compat_urllib_request.urlopen(request).read()
  2593. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2594. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % compat_str(err))
  2595. return
  2596. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2597. renditions = mdoc.findall('.//rendition')
  2598. # For now, always pick the highest quality.
  2599. rendition = renditions[-1]
  2600. try:
  2601. _,_,ext = rendition.attrib['type'].partition('/')
  2602. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2603. video_url = rendition.find('./src').text
  2604. except KeyError:
  2605. self._downloader.trouble('Invalid rendition field.')
  2606. return
  2607. info = {
  2608. 'id': video_id,
  2609. 'url': video_url,
  2610. 'uploader': performer,
  2611. 'upload_date': None,
  2612. 'title': video_title,
  2613. 'ext': ext,
  2614. 'format': format,
  2615. }
  2616. return [info]
  2617. class YoukuIE(InfoExtractor):
  2618. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2619. def report_download_webpage(self, file_id):
  2620. """Report webpage download."""
  2621. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, file_id))
  2622. def report_extraction(self, file_id):
  2623. """Report information extraction."""
  2624. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2625. def _gen_sid(self):
  2626. nowTime = int(time.time() * 1000)
  2627. random1 = random.randint(1000,1998)
  2628. random2 = random.randint(1000,9999)
  2629. return "%d%d%d" %(nowTime,random1,random2)
  2630. def _get_file_ID_mix_string(self, seed):
  2631. mixed = []
  2632. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2633. seed = float(seed)
  2634. for i in range(len(source)):
  2635. seed = (seed * 211 + 30031 ) % 65536
  2636. index = math.floor(seed / 65536 * len(source) )
  2637. mixed.append(source[int(index)])
  2638. source.remove(source[int(index)])
  2639. #return ''.join(mixed)
  2640. return mixed
  2641. def _get_file_id(self, fileId, seed):
  2642. mixed = self._get_file_ID_mix_string(seed)
  2643. ids = fileId.split('*')
  2644. realId = []
  2645. for ch in ids:
  2646. if ch:
  2647. realId.append(mixed[int(ch)])
  2648. return ''.join(realId)
  2649. def _real_extract(self, url):
  2650. mobj = re.match(self._VALID_URL, url)
  2651. if mobj is None:
  2652. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2653. return
  2654. video_id = mobj.group('ID')
  2655. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2656. request = compat_urllib_request.Request(info_url, None, std_headers)
  2657. try:
  2658. self.report_download_webpage(video_id)
  2659. jsondata = compat_urllib_request.urlopen(request).read()
  2660. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2661. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2662. return
  2663. self.report_extraction(video_id)
  2664. try:
  2665. jsonstr = jsondata.decode('utf-8')
  2666. config = json.loads(jsonstr)
  2667. video_title = config['data'][0]['title']
  2668. seed = config['data'][0]['seed']
  2669. format = self._downloader.params.get('format', None)
  2670. supported_format = list(config['data'][0]['streamfileids'].keys())
  2671. if format is None or format == 'best':
  2672. if 'hd2' in supported_format:
  2673. format = 'hd2'
  2674. else:
  2675. format = 'flv'
  2676. ext = u'flv'
  2677. elif format == 'worst':
  2678. format = 'mp4'
  2679. ext = u'mp4'
  2680. else:
  2681. format = 'flv'
  2682. ext = u'flv'
  2683. fileid = config['data'][0]['streamfileids'][format]
  2684. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2685. except (UnicodeDecodeError, ValueError, KeyError):
  2686. self._downloader.trouble(u'ERROR: unable to extract info section')
  2687. return
  2688. files_info=[]
  2689. sid = self._gen_sid()
  2690. fileid = self._get_file_id(fileid, seed)
  2691. #column 8,9 of fileid represent the segment number
  2692. #fileid[7:9] should be changed
  2693. for index, key in enumerate(keys):
  2694. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2695. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2696. info = {
  2697. 'id': '%s_part%02d' % (video_id, index),
  2698. 'url': download_url,
  2699. 'uploader': None,
  2700. 'upload_date': None,
  2701. 'title': video_title,
  2702. 'ext': ext,
  2703. }
  2704. files_info.append(info)
  2705. return files_info
  2706. class XNXXIE(InfoExtractor):
  2707. """Information extractor for xnxx.com"""
  2708. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  2709. IE_NAME = u'xnxx'
  2710. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2711. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2712. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2713. def report_webpage(self, video_id):
  2714. """Report information extraction"""
  2715. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2716. def report_extraction(self, video_id):
  2717. """Report information extraction"""
  2718. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2719. def _real_extract(self, url):
  2720. mobj = re.match(self._VALID_URL, url)
  2721. if mobj is None:
  2722. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2723. return
  2724. video_id = mobj.group(1)
  2725. self.report_webpage(video_id)
  2726. # Get webpage content
  2727. try:
  2728. webpage_bytes = compat_urllib_request.urlopen(url).read()
  2729. webpage = webpage_bytes.decode('utf-8')
  2730. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2731. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2732. return
  2733. result = re.search(self.VIDEO_URL_RE, webpage)
  2734. if result is None:
  2735. self._downloader.trouble(u'ERROR: unable to extract video url')
  2736. return
  2737. video_url = compat_urllib_parse.unquote(result.group(1))
  2738. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2739. if result is None:
  2740. self._downloader.trouble(u'ERROR: unable to extract video title')
  2741. return
  2742. video_title = result.group(1)
  2743. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2744. if result is None:
  2745. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2746. return
  2747. video_thumbnail = result.group(1)
  2748. return [{
  2749. 'id': video_id,
  2750. 'url': video_url,
  2751. 'uploader': None,
  2752. 'upload_date': None,
  2753. 'title': video_title,
  2754. 'ext': 'flv',
  2755. 'thumbnail': video_thumbnail,
  2756. 'description': None,
  2757. }]
  2758. class GooglePlusIE(InfoExtractor):
  2759. """Information extractor for plus.google.com."""
  2760. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2761. IE_NAME = u'plus.google'
  2762. def __init__(self, downloader=None):
  2763. InfoExtractor.__init__(self, downloader)
  2764. def report_extract_entry(self, url):
  2765. """Report downloading extry"""
  2766. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url)
  2767. def report_date(self, upload_date):
  2768. """Report downloading extry"""
  2769. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2770. def report_uploader(self, uploader):
  2771. """Report downloading extry"""
  2772. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader)
  2773. def report_title(self, video_title):
  2774. """Report downloading extry"""
  2775. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title)
  2776. def report_extract_vid_page(self, video_page):
  2777. """Report information extraction."""
  2778. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page)
  2779. def _real_extract(self, url):
  2780. # Extract id from URL
  2781. mobj = re.match(self._VALID_URL, url)
  2782. if mobj is None:
  2783. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  2784. return
  2785. post_url = mobj.group(0)
  2786. video_id = mobj.group(1)
  2787. video_extension = 'flv'
  2788. # Step 1, Retrieve post webpage to extract further information
  2789. self.report_extract_entry(post_url)
  2790. request = compat_urllib_request.Request(post_url)
  2791. try:
  2792. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2793. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2794. self._downloader.trouble(u'ERROR: Unable to retrieve entry webpage: %s' % compat_str(err))
  2795. return
  2796. # Extract update date
  2797. upload_date = None
  2798. pattern = 'title="Timestamp">(.*?)</a>'
  2799. mobj = re.search(pattern, webpage)
  2800. if mobj:
  2801. upload_date = mobj.group(1)
  2802. # Convert timestring to a format suitable for filename
  2803. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2804. upload_date = upload_date.strftime('%Y%m%d')
  2805. self.report_date(upload_date)
  2806. # Extract uploader
  2807. uploader = None
  2808. pattern = r'rel\="author".*?>(.*?)</a>'
  2809. mobj = re.search(pattern, webpage)
  2810. if mobj:
  2811. uploader = mobj.group(1)
  2812. self.report_uploader(uploader)
  2813. # Extract title
  2814. # Get the first line for title
  2815. video_title = u'NA'
  2816. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2817. mobj = re.search(pattern, webpage)
  2818. if mobj:
  2819. video_title = mobj.group(1)
  2820. self.report_title(video_title)
  2821. # Step 2, Stimulate clicking the image box to launch video
  2822. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2823. mobj = re.search(pattern, webpage)
  2824. if mobj is None:
  2825. self._downloader.trouble(u'ERROR: unable to extract video page URL')
  2826. video_page = mobj.group(1)
  2827. request = compat_urllib_request.Request(video_page)
  2828. try:
  2829. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2830. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2831. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2832. return
  2833. self.report_extract_vid_page(video_page)
  2834. # Extract video links on video page
  2835. """Extract video links of all sizes"""
  2836. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2837. mobj = re.findall(pattern, webpage)
  2838. if len(mobj) == 0:
  2839. self._downloader.trouble(u'ERROR: unable to extract video links')
  2840. # Sort in resolution
  2841. links = sorted(mobj)
  2842. # Choose the lowest of the sort, i.e. highest resolution
  2843. video_url = links[-1]
  2844. # Only get the url. The resolution part in the tuple has no use anymore
  2845. video_url = video_url[-1]
  2846. # Treat escaped \u0026 style hex
  2847. try:
  2848. video_url = video_url.decode("unicode_escape")
  2849. except AttributeError: # Python 3
  2850. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2851. return [{
  2852. 'id': video_id,
  2853. 'url': video_url,
  2854. 'uploader': uploader,
  2855. 'upload_date': upload_date,
  2856. 'title': video_title,
  2857. 'ext': video_extension,
  2858. }]
  2859. class NBAIE(InfoExtractor):
  2860. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*)(\?.*)?$'
  2861. IE_NAME = u'nba'
  2862. def _real_extract(self, url):
  2863. mobj = re.match(self._VALID_URL, url)
  2864. if mobj is None:
  2865. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2866. return
  2867. video_id = mobj.group(1)
  2868. if video_id.endswith('/index.html'):
  2869. video_id = video_id[:-len('/index.html')]
  2870. webpage = self._download_webpage(url, video_id)
  2871. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2872. def _findProp(rexp, default=None):
  2873. m = re.search(rexp, webpage)
  2874. if m:
  2875. return unescapeHTML(m.group(1))
  2876. else:
  2877. return default
  2878. shortened_video_id = video_id.rpartition('/')[2]
  2879. title = _findProp(r'<meta property="og:title" content="(.*?)"', shortened_video_id).replace('NBA.com: ', '')
  2880. info = {
  2881. 'id': shortened_video_id,
  2882. 'url': video_url,
  2883. 'ext': 'mp4',
  2884. 'title': title,
  2885. 'uploader_date': _findProp(r'<b>Date:</b> (.*?)</div>'),
  2886. 'description': _findProp(r'<div class="description">(.*?)</h1>'),
  2887. }
  2888. return [info]
  2889. class JustinTVIE(InfoExtractor):
  2890. """Information extractor for justin.tv and twitch.tv"""
  2891. # TODO: One broadcast may be split into multiple videos. The key
  2892. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2893. # starts at 1 and increases. Can we treat all parts as one video?
  2894. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2895. ([^/]+)(?:/b/([^/]+))?/?(?:\#.*)?$"""
  2896. _JUSTIN_PAGE_LIMIT = 100
  2897. IE_NAME = u'justin.tv'
  2898. def report_extraction(self, file_id):
  2899. """Report information extraction."""
  2900. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2901. def report_download_page(self, channel, offset):
  2902. """Report attempt to download a single page of videos."""
  2903. self._downloader.to_screen(u'[%s] %s: Downloading video information from %d to %d' %
  2904. (self.IE_NAME, channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  2905. # Return count of items, list of *valid* items
  2906. def _parse_page(self, url):
  2907. try:
  2908. urlh = compat_urllib_request.urlopen(url)
  2909. webpage_bytes = urlh.read()
  2910. webpage = webpage_bytes.decode('utf-8', 'ignore')
  2911. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2912. self._downloader.trouble(u'ERROR: unable to download video info JSON: %s' % compat_str(err))
  2913. return
  2914. response = json.loads(webpage)
  2915. if type(response) != list:
  2916. error_text = response.get('error', 'unknown error')
  2917. self._downloader.trouble(u'ERROR: Justin.tv API: %s' % error_text)
  2918. return
  2919. info = []
  2920. for clip in response:
  2921. video_url = clip['video_file_url']
  2922. if video_url:
  2923. video_extension = os.path.splitext(video_url)[1][1:]
  2924. video_date = re.sub('-', '', clip['start_time'][:10])
  2925. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  2926. video_id = clip['id']
  2927. video_title = clip.get('title', video_id)
  2928. info.append({
  2929. 'id': video_id,
  2930. 'url': video_url,
  2931. 'title': video_title,
  2932. 'uploader': clip.get('channel_name', video_uploader_id),
  2933. 'uploader_id': video_uploader_id,
  2934. 'upload_date': video_date,
  2935. 'ext': video_extension,
  2936. })
  2937. return (len(response), info)
  2938. def _real_extract(self, url):
  2939. mobj = re.match(self._VALID_URL, url)
  2940. if mobj is None:
  2941. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2942. return
  2943. api = 'http://api.justin.tv'
  2944. video_id = mobj.group(mobj.lastindex)
  2945. paged = False
  2946. if mobj.lastindex == 1:
  2947. paged = True
  2948. api += '/channel/archives/%s.json'
  2949. else:
  2950. api += '/broadcast/by_archive/%s.json'
  2951. api = api % (video_id,)
  2952. self.report_extraction(video_id)
  2953. info = []
  2954. offset = 0
  2955. limit = self._JUSTIN_PAGE_LIMIT
  2956. while True:
  2957. if paged:
  2958. self.report_download_page(video_id, offset)
  2959. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  2960. page_count, page_info = self._parse_page(page_url)
  2961. info.extend(page_info)
  2962. if not paged or page_count != limit:
  2963. break
  2964. offset += limit
  2965. return info
  2966. class FunnyOrDieIE(InfoExtractor):
  2967. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  2968. def _real_extract(self, url):
  2969. mobj = re.match(self._VALID_URL, url)
  2970. if mobj is None:
  2971. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2972. return
  2973. video_id = mobj.group('id')
  2974. webpage = self._download_webpage(url, video_id)
  2975. m = re.search(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"', webpage, re.DOTALL)
  2976. if not m:
  2977. self._downloader.trouble(u'ERROR: unable to find video information')
  2978. video_url = unescapeHTML(m.group('url'))
  2979. m = re.search(r"class='player_page_h1'>\s+<a.*?>(?P<title>.*?)</a>", webpage)
  2980. if not m:
  2981. self._downloader.trouble(u'Cannot find video title')
  2982. title = unescapeHTML(m.group('title'))
  2983. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  2984. if m:
  2985. desc = unescapeHTML(m.group('desc'))
  2986. else:
  2987. desc = None
  2988. info = {
  2989. 'id': video_id,
  2990. 'url': video_url,
  2991. 'ext': 'mp4',
  2992. 'title': title,
  2993. 'description': desc,
  2994. }
  2995. return [info]
  2996. class SteamIE(InfoExtractor):
  2997. _VALID_URL = r"""http://store.steampowered.com/
  2998. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  2999. (?P<gameID>\d+)/?
  3000. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  3001. """
  3002. @classmethod
  3003. def suitable(cls, url):
  3004. """Receives a URL and returns True if suitable for this IE."""
  3005. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3006. def _real_extract(self, url):
  3007. m = re.match(self._VALID_URL, url, re.VERBOSE)
  3008. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  3009. gameID = m.group('gameID')
  3010. videourl = 'http://store.steampowered.com/video/%s/' % gameID
  3011. webpage = self._download_webpage(videourl, gameID)
  3012. mweb = re.finditer(urlRE, webpage)
  3013. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  3014. titles = re.finditer(namesRE, webpage)
  3015. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  3016. thumbs = re.finditer(thumbsRE, webpage)
  3017. videos = []
  3018. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  3019. video_id = vid.group('videoID')
  3020. title = vtitle.group('videoName')
  3021. video_url = vid.group('videoURL')
  3022. video_thumb = thumb.group('thumbnail')
  3023. if not video_url:
  3024. self._downloader.trouble(u'ERROR: Cannot find video url for %s' % video_id)
  3025. info = {
  3026. 'id':video_id,
  3027. 'url':video_url,
  3028. 'ext': 'flv',
  3029. 'title': unescapeHTML(title),
  3030. 'thumbnail': video_thumb
  3031. }
  3032. videos.append(info)
  3033. return videos
  3034. class UstreamIE(InfoExtractor):
  3035. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  3036. IE_NAME = u'ustream'
  3037. def _real_extract(self, url):
  3038. m = re.match(self._VALID_URL, url)
  3039. video_id = m.group('videoID')
  3040. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  3041. webpage = self._download_webpage(url, video_id)
  3042. m = re.search(r'data-title="(?P<title>.+)"',webpage)
  3043. title = m.group('title')
  3044. m = re.search(r'<a class="state" data-content-type="channel" data-content-id="(?P<uploader>\d+)"',webpage)
  3045. uploader = m.group('uploader')
  3046. info = {
  3047. 'id':video_id,
  3048. 'url':video_url,
  3049. 'ext': 'flv',
  3050. 'title': title,
  3051. 'uploader': uploader
  3052. }
  3053. return [info]
  3054. class RBMARadioIE(InfoExtractor):
  3055. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  3056. def _real_extract(self, url):
  3057. m = re.match(self._VALID_URL, url)
  3058. video_id = m.group('videoID')
  3059. webpage = self._download_webpage(url, video_id)
  3060. m = re.search(r'<script>window.gon = {.*?};gon\.show=(.+?);</script>', webpage)
  3061. if not m:
  3062. raise ExtractorError(u'Cannot find metadata')
  3063. json_data = m.group(1)
  3064. try:
  3065. data = json.loads(json_data)
  3066. except ValueError as e:
  3067. raise ExtractorError(u'Invalid JSON: ' + str(e))
  3068. video_url = data['akamai_url'] + '&cbr=256'
  3069. url_parts = compat_urllib_parse_urlparse(video_url)
  3070. video_ext = url_parts.path.rpartition('.')[2]
  3071. info = {
  3072. 'id': video_id,
  3073. 'url': video_url,
  3074. 'ext': video_ext,
  3075. 'title': data['title'],
  3076. 'description': data.get('teaser_text'),
  3077. 'location': data.get('country_of_origin'),
  3078. 'uploader': data.get('host', {}).get('name'),
  3079. 'uploader_id': data.get('host', {}).get('slug'),
  3080. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  3081. 'duration': data.get('duration'),
  3082. }
  3083. return [info]
  3084. class YouPornIE(InfoExtractor):
  3085. """Information extractor for youporn.com."""
  3086. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  3087. def _print_formats(self, formats):
  3088. """Print all available formats"""
  3089. print(u'Available formats:')
  3090. print(u'ext\t\tformat')
  3091. print(u'---------------------------------')
  3092. for format in formats:
  3093. print(u'%s\t\t%s' % (format['ext'], format['format']))
  3094. def _specific(self, req_format, formats):
  3095. for x in formats:
  3096. if(x["format"]==req_format):
  3097. return x
  3098. return None
  3099. def _real_extract(self, url):
  3100. mobj = re.match(self._VALID_URL, url)
  3101. if mobj is None:
  3102. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3103. return
  3104. video_id = mobj.group('videoid')
  3105. req = compat_urllib_request.Request(url)
  3106. req.add_header('Cookie', 'age_verified=1')
  3107. webpage = self._download_webpage(req, video_id)
  3108. # Get the video title
  3109. result = re.search(r'<h1.*?>(?P<title>.*)</h1>', webpage)
  3110. if result is None:
  3111. raise ExtractorError(u'Unable to extract video title')
  3112. video_title = result.group('title').strip()
  3113. # Get the video date
  3114. result = re.search(r'Date:</label>(?P<date>.*) </li>', webpage)
  3115. if result is None:
  3116. self._downloader.report_warning(u'unable to extract video date')
  3117. upload_date = None
  3118. else:
  3119. upload_date = result.group('date').strip()
  3120. # Get the video uploader
  3121. result = re.search(r'Submitted:</label>(?P<uploader>.*)</li>', webpage)
  3122. if result is None:
  3123. self._downloader.report_warning(u'unable to extract uploader')
  3124. video_uploader = None
  3125. else:
  3126. video_uploader = result.group('uploader').strip()
  3127. video_uploader = clean_html( video_uploader )
  3128. # Get all of the formats available
  3129. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  3130. result = re.search(DOWNLOAD_LIST_RE, webpage)
  3131. if result is None:
  3132. raise ExtractorError(u'Unable to extract download list')
  3133. download_list_html = result.group('download_list').strip()
  3134. # Get all of the links from the page
  3135. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  3136. links = re.findall(LINK_RE, download_list_html)
  3137. if(len(links) == 0):
  3138. raise ExtractorError(u'ERROR: no known formats available for video')
  3139. self._downloader.to_screen(u'[youporn] Links found: %d' % len(links))
  3140. formats = []
  3141. for link in links:
  3142. # A link looks like this:
  3143. # http://cdn1.download.youporn.phncdn.com/201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4?nvb=20121113051249&nva=20121114051249&ir=1200&sr=1200&hash=014b882080310e95fb6a0
  3144. # A path looks like this:
  3145. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  3146. video_url = unescapeHTML( link )
  3147. path = compat_urllib_parse_urlparse( video_url ).path
  3148. extension = os.path.splitext( path )[1][1:]
  3149. format = path.split('/')[4].split('_')[:2]
  3150. size = format[0]
  3151. bitrate = format[1]
  3152. format = "-".join( format )
  3153. title = u'%s-%s-%s' % (video_title, size, bitrate)
  3154. formats.append({
  3155. 'id': video_id,
  3156. 'url': video_url,
  3157. 'uploader': video_uploader,
  3158. 'upload_date': upload_date,
  3159. 'title': title,
  3160. 'ext': extension,
  3161. 'format': format,
  3162. 'thumbnail': None,
  3163. 'description': None,
  3164. 'player_url': None
  3165. })
  3166. if self._downloader.params.get('listformats', None):
  3167. self._print_formats(formats)
  3168. return
  3169. req_format = self._downloader.params.get('format', None)
  3170. self._downloader.to_screen(u'[youporn] Format: %s' % req_format)
  3171. if req_format is None or req_format == 'best':
  3172. return [formats[0]]
  3173. elif req_format == 'worst':
  3174. return [formats[-1]]
  3175. elif req_format in ('-1', 'all'):
  3176. return formats
  3177. else:
  3178. format = self._specific( req_format, formats )
  3179. if result is None:
  3180. self._downloader.trouble(u'ERROR: requested format not available')
  3181. return
  3182. return [format]
  3183. class PornotubeIE(InfoExtractor):
  3184. """Information extractor for pornotube.com."""
  3185. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  3186. def _real_extract(self, url):
  3187. mobj = re.match(self._VALID_URL, url)
  3188. if mobj is None:
  3189. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3190. return
  3191. video_id = mobj.group('videoid')
  3192. video_title = mobj.group('title')
  3193. # Get webpage content
  3194. webpage = self._download_webpage(url, video_id)
  3195. # Get the video URL
  3196. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  3197. result = re.search(VIDEO_URL_RE, webpage)
  3198. if result is None:
  3199. self._downloader.trouble(u'ERROR: unable to extract video url')
  3200. return
  3201. video_url = compat_urllib_parse.unquote(result.group('url'))
  3202. #Get the uploaded date
  3203. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  3204. result = re.search(VIDEO_UPLOADED_RE, webpage)
  3205. if result is None:
  3206. self._downloader.trouble(u'ERROR: unable to extract video title')
  3207. return
  3208. upload_date = result.group('date')
  3209. info = {'id': video_id,
  3210. 'url': video_url,
  3211. 'uploader': None,
  3212. 'upload_date': upload_date,
  3213. 'title': video_title,
  3214. 'ext': 'flv',
  3215. 'format': 'flv'}
  3216. return [info]
  3217. class YouJizzIE(InfoExtractor):
  3218. """Information extractor for youjizz.com."""
  3219. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  3220. def _real_extract(self, url):
  3221. mobj = re.match(self._VALID_URL, url)
  3222. if mobj is None:
  3223. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3224. return
  3225. video_id = mobj.group('videoid')
  3226. # Get webpage content
  3227. webpage = self._download_webpage(url, video_id)
  3228. # Get the video title
  3229. result = re.search(r'<title>(?P<title>.*)</title>', webpage)
  3230. if result is None:
  3231. raise ExtractorError(u'ERROR: unable to extract video title')
  3232. video_title = result.group('title').strip()
  3233. # Get the embed page
  3234. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  3235. if result is None:
  3236. raise ExtractorError(u'ERROR: unable to extract embed page')
  3237. embed_page_url = result.group(0).strip()
  3238. video_id = result.group('videoid')
  3239. webpage = self._download_webpage(embed_page_url, video_id)
  3240. # Get the video URL
  3241. result = re.search(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);', webpage)
  3242. if result is None:
  3243. raise ExtractorError(u'ERROR: unable to extract video url')
  3244. video_url = result.group('source')
  3245. info = {'id': video_id,
  3246. 'url': video_url,
  3247. 'title': video_title,
  3248. 'ext': 'flv',
  3249. 'format': 'flv',
  3250. 'player_url': embed_page_url}
  3251. return [info]
  3252. class EightTracksIE(InfoExtractor):
  3253. IE_NAME = '8tracks'
  3254. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  3255. def _real_extract(self, url):
  3256. mobj = re.match(self._VALID_URL, url)
  3257. if mobj is None:
  3258. raise ExtractorError(u'Invalid URL: %s' % url)
  3259. playlist_id = mobj.group('id')
  3260. webpage = self._download_webpage(url, playlist_id)
  3261. m = re.search(r"PAGE.mix = (.*?);\n", webpage, flags=re.DOTALL)
  3262. if not m:
  3263. raise ExtractorError(u'Cannot find trax information')
  3264. json_like = m.group(1)
  3265. data = json.loads(json_like)
  3266. session = str(random.randint(0, 1000000000))
  3267. mix_id = data['id']
  3268. track_count = data['tracks_count']
  3269. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  3270. next_url = first_url
  3271. res = []
  3272. for i in itertools.count():
  3273. api_json = self._download_webpage(next_url, playlist_id,
  3274. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  3275. errnote=u'Failed to download song information')
  3276. api_data = json.loads(api_json)
  3277. track_data = api_data[u'set']['track']
  3278. info = {
  3279. 'id': track_data['id'],
  3280. 'url': track_data['track_file_stream_url'],
  3281. 'title': track_data['performer'] + u' - ' + track_data['name'],
  3282. 'raw_title': track_data['name'],
  3283. 'uploader_id': data['user']['login'],
  3284. 'ext': 'm4a',
  3285. }
  3286. res.append(info)
  3287. if api_data['set']['at_last_track']:
  3288. break
  3289. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  3290. return res
  3291. class KeekIE(InfoExtractor):
  3292. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  3293. IE_NAME = u'keek'
  3294. def _real_extract(self, url):
  3295. m = re.match(self._VALID_URL, url)
  3296. video_id = m.group('videoID')
  3297. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  3298. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  3299. webpage = self._download_webpage(url, video_id)
  3300. m = re.search(r'<meta property="og:title" content="(?P<title>.+)"', webpage)
  3301. title = unescapeHTML(m.group('title'))
  3302. m = re.search(r'<div class="bio-names-and-report">[\s\n]+<h4>(?P<uploader>\w+)</h4>', webpage)
  3303. uploader = unescapeHTML(m.group('uploader'))
  3304. info = {
  3305. 'id':video_id,
  3306. 'url':video_url,
  3307. 'ext': 'mp4',
  3308. 'title': title,
  3309. 'thumbnail': thumbnail,
  3310. 'uploader': uploader
  3311. }
  3312. return [info]
  3313. class TEDIE(InfoExtractor):
  3314. _VALID_URL=r'''http://www.ted.com/
  3315. (
  3316. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  3317. |
  3318. ((?P<type_talk>talks)) # We have a simple talk
  3319. )
  3320. /(?P<name>\w+) # Here goes the name and then ".html"
  3321. '''
  3322. @classmethod
  3323. def suitable(cls, url):
  3324. """Receives a URL and returns True if suitable for this IE."""
  3325. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3326. def _real_extract(self, url):
  3327. m=re.match(self._VALID_URL, url, re.VERBOSE)
  3328. if m.group('type_talk'):
  3329. return [self._talk_info(url)]
  3330. else :
  3331. playlist_id=m.group('playlist_id')
  3332. name=m.group('name')
  3333. self._downloader.to_screen(u'[%s] Getting info of playlist %s: "%s"' % (self.IE_NAME,playlist_id,name))
  3334. return self._playlist_videos_info(url,name,playlist_id)
  3335. def _talk_video_link(self,mediaSlug):
  3336. '''Returns the video link for that mediaSlug'''
  3337. return 'http://download.ted.com/talks/%s.mp4' % mediaSlug
  3338. def _playlist_videos_info(self,url,name,playlist_id=0):
  3339. '''Returns the videos of the playlist'''
  3340. video_RE=r'''
  3341. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  3342. ([.\s]*?)data-playlist_item_id="(\d+)"
  3343. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  3344. '''
  3345. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  3346. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  3347. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  3348. m_names=re.finditer(video_name_RE,webpage)
  3349. info=[]
  3350. for m_video, m_name in zip(m_videos,m_names):
  3351. video_id=m_video.group('video_id')
  3352. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  3353. info.append(self._talk_info(talk_url,video_id))
  3354. return info
  3355. def _talk_info(self, url, video_id=0):
  3356. """Return the video for the talk in the url"""
  3357. m=re.match(self._VALID_URL, url,re.VERBOSE)
  3358. videoName=m.group('name')
  3359. webpage=self._download_webpage(url, video_id, 'Downloading \"%s\" page' % videoName)
  3360. # If the url includes the language we get the title translated
  3361. title_RE=r'<h1><span id="altHeadline" >(?P<title>.*)</span></h1>'
  3362. title=re.search(title_RE, webpage).group('title')
  3363. info_RE=r'''<script\ type="text/javascript">var\ talkDetails\ =(.*?)
  3364. "id":(?P<videoID>[\d]+).*?
  3365. "mediaSlug":"(?P<mediaSlug>[\w\d]+?)"'''
  3366. thumb_RE=r'</span>[\s.]*</div>[\s.]*<img src="(?P<thumbnail>.*?)"'
  3367. thumb_match=re.search(thumb_RE,webpage)
  3368. info_match=re.search(info_RE,webpage,re.VERBOSE)
  3369. video_id=info_match.group('videoID')
  3370. mediaSlug=info_match.group('mediaSlug')
  3371. video_url=self._talk_video_link(mediaSlug)
  3372. info = {
  3373. 'id': video_id,
  3374. 'url': video_url,
  3375. 'ext': 'mp4',
  3376. 'title': title,
  3377. 'thumbnail': thumb_match.group('thumbnail')
  3378. }
  3379. return info
  3380. class MySpassIE(InfoExtractor):
  3381. _VALID_URL = r'http://www.myspass.de/.*'
  3382. def _real_extract(self, url):
  3383. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  3384. # video id is the last path element of the URL
  3385. # usually there is a trailing slash, so also try the second but last
  3386. url_path = compat_urllib_parse_urlparse(url).path
  3387. url_parent_path, video_id = os.path.split(url_path)
  3388. if not video_id:
  3389. _, video_id = os.path.split(url_parent_path)
  3390. # get metadata
  3391. metadata_url = META_DATA_URL_TEMPLATE % video_id
  3392. metadata_text = self._download_webpage(metadata_url, video_id)
  3393. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  3394. # extract values from metadata
  3395. url_flv_el = metadata.find('url_flv')
  3396. if url_flv_el is None:
  3397. self._downloader.trouble(u'ERROR: unable to extract download url')
  3398. return
  3399. video_url = url_flv_el.text
  3400. extension = os.path.splitext(video_url)[1][1:]
  3401. title_el = metadata.find('title')
  3402. if title_el is None:
  3403. self._downloader.trouble(u'ERROR: unable to extract title')
  3404. return
  3405. title = title_el.text
  3406. format_id_el = metadata.find('format_id')
  3407. if format_id_el is None:
  3408. format = ext
  3409. else:
  3410. format = format_id_el.text
  3411. description_el = metadata.find('description')
  3412. if description_el is not None:
  3413. description = description_el.text
  3414. else:
  3415. description = None
  3416. imagePreview_el = metadata.find('imagePreview')
  3417. if imagePreview_el is not None:
  3418. thumbnail = imagePreview_el.text
  3419. else:
  3420. thumbnail = None
  3421. info = {
  3422. 'id': video_id,
  3423. 'url': video_url,
  3424. 'title': title,
  3425. 'ext': extension,
  3426. 'format': format,
  3427. 'thumbnail': thumbnail,
  3428. 'description': description
  3429. }
  3430. return [info]
  3431. class SpiegelIE(InfoExtractor):
  3432. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)$'
  3433. def _real_extract(self, url):
  3434. m = re.match(self._VALID_URL, url)
  3435. video_id = m.group('videoID')
  3436. webpage = self._download_webpage(url, video_id)
  3437. m = re.search(r'<div class="spVideoTitle">(.*?)</div>', webpage)
  3438. if not m:
  3439. raise ExtractorError(u'Cannot find title')
  3440. video_title = unescapeHTML(m.group(1))
  3441. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  3442. xml_code = self._download_webpage(xml_url, video_id,
  3443. note=u'Downloading XML', errnote=u'Failed to download XML')
  3444. idoc = xml.etree.ElementTree.fromstring(xml_code)
  3445. last_type = idoc[-1]
  3446. filename = last_type.findall('./filename')[0].text
  3447. duration = float(last_type.findall('./duration')[0].text)
  3448. video_url = 'http://video2.spiegel.de/flash/' + filename
  3449. video_ext = filename.rpartition('.')[2]
  3450. info = {
  3451. 'id': video_id,
  3452. 'url': video_url,
  3453. 'ext': video_ext,
  3454. 'title': video_title,
  3455. 'duration': duration,
  3456. }
  3457. return [info]
  3458. def gen_extractors():
  3459. """ Return a list of an instance of every supported extractor.
  3460. The order does matter; the first extractor matched is the one handling the URL.
  3461. """
  3462. return [
  3463. YoutubePlaylistIE(),
  3464. YoutubeChannelIE(),
  3465. YoutubeUserIE(),
  3466. YoutubeSearchIE(),
  3467. YoutubeIE(),
  3468. MetacafeIE(),
  3469. DailymotionIE(),
  3470. GoogleSearchIE(),
  3471. PhotobucketIE(),
  3472. YahooIE(),
  3473. YahooSearchIE(),
  3474. DepositFilesIE(),
  3475. FacebookIE(),
  3476. BlipTVUserIE(),
  3477. BlipTVIE(),
  3478. VimeoIE(),
  3479. MyVideoIE(),
  3480. ComedyCentralIE(),
  3481. EscapistIE(),
  3482. CollegeHumorIE(),
  3483. XVideosIE(),
  3484. SoundcloudIE(),
  3485. InfoQIE(),
  3486. MixcloudIE(),
  3487. StanfordOpenClassroomIE(),
  3488. MTVIE(),
  3489. YoukuIE(),
  3490. XNXXIE(),
  3491. YouJizzIE(),
  3492. PornotubeIE(),
  3493. YouPornIE(),
  3494. GooglePlusIE(),
  3495. ArteTvIE(),
  3496. NBAIE(),
  3497. JustinTVIE(),
  3498. FunnyOrDieIE(),
  3499. SteamIE(),
  3500. UstreamIE(),
  3501. RBMARadioIE(),
  3502. EightTracksIE(),
  3503. KeekIE(),
  3504. TEDIE(),
  3505. MySpassIE(),
  3506. SpiegelIE(),
  3507. GenericIE()
  3508. ]