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.

4403 lines
174 KiB

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