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.

4144 lines
165 KiB

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