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.

4477 lines
178 KiB

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