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.

4454 lines
176 KiB

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