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.

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