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.

4495 lines
178 KiB

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