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.

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