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.

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