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.

4222 lines
167 KiB

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