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.

4204 lines
167 KiB

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