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.

3564 lines
122 KiB

12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
13 years ago
13 years ago
13 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
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import datetime
  4. import netrc
  5. import os
  6. import re
  7. import socket
  8. import time
  9. import email.utils
  10. import xml.etree.ElementTree
  11. import random
  12. import math
  13. from utils import *
  14. class InfoExtractor(object):
  15. """Information Extractor class.
  16. Information extractors are the classes that, given a URL, extract
  17. information about the video (or videos) the URL refers to. This
  18. information includes the real video URL, the video title, author and
  19. others. The information is stored in a dictionary which is then
  20. passed to the FileDownloader. The FileDownloader processes this
  21. information possibly downloading the video to the file system, among
  22. other possible outcomes.
  23. The dictionaries must include the following fields:
  24. id: Video identifier.
  25. url: Final video URL.
  26. uploader: Nickname of the video uploader, unescaped.
  27. upload_date: Video upload date (YYYYMMDD).
  28. title: Video title, unescaped.
  29. ext: Video filename extension.
  30. The following fields are optional:
  31. format: The video format, defaults to ext (used for --get-format)
  32. thumbnail: Full URL to a video thumbnail image.
  33. description: One-line video description.
  34. player_url: SWF Player URL (used for rtmpdump).
  35. subtitles: The .srt file contents.
  36. urlhandle: [internal] The urlHandle to be used to download the file,
  37. like returned by urllib.request.urlopen
  38. The fields should all be Unicode strings.
  39. Subclasses of this one should re-define the _real_initialize() and
  40. _real_extract() methods and define a _VALID_URL regexp.
  41. Probably, they should also be added to the list of extractors.
  42. _real_extract() must return a *list* of information dictionaries as
  43. described above.
  44. Finally, the _WORKING attribute should be set to False for broken IEs
  45. in order to warn the users and skip the tests.
  46. """
  47. _ready = False
  48. _downloader = None
  49. _WORKING = True
  50. def __init__(self, downloader=None):
  51. """Constructor. Receives an optional downloader."""
  52. self._ready = False
  53. self.set_downloader(downloader)
  54. def suitable(self, url):
  55. """Receives a URL and returns True if suitable for this IE."""
  56. return re.match(self._VALID_URL, url) is not None
  57. def working(self):
  58. """Getter method for _WORKING."""
  59. return self._WORKING
  60. def initialize(self):
  61. """Initializes an instance (authentication, etc)."""
  62. if not self._ready:
  63. self._real_initialize()
  64. self._ready = True
  65. def extract(self, url):
  66. """Extracts URL information and returns it in list of dicts."""
  67. self.initialize()
  68. return self._real_extract(url)
  69. def set_downloader(self, downloader):
  70. """Sets the downloader for this IE."""
  71. self._downloader = downloader
  72. def _real_initialize(self):
  73. """Real initialization process. Redefine in subclasses."""
  74. pass
  75. def _real_extract(self, url):
  76. """Real extraction process. Redefine in subclasses."""
  77. pass
  78. class YoutubeIE(InfoExtractor):
  79. """Information extractor for youtube.com."""
  80. _VALID_URL = r"""^
  81. (
  82. (?:https?://)? # http(s):// (optional)
  83. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  84. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  85. (?:.*?\#/)? # handle anchor (#/) redirect urls
  86. (?!view_play_list|my_playlists|artist|playlist) # ignore playlist URLs
  87. (?: # the various things that can precede the ID:
  88. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  89. |(?: # or the v= param in all its forms
  90. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  91. (?:\?|\#!?) # the params delimiter ? or # or #!
  92. (?:.+&)? # any other preceding param (like /?s=tuff&v=xxxx)
  93. v=
  94. )
  95. )? # optional -> youtube.com/xxxx is OK
  96. )? # all until now is optional -> you can pass the naked ID
  97. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  98. (?(1).+)? # if we found the ID, everything can follow
  99. $"""
  100. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  101. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  102. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  103. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  104. _NETRC_MACHINE = 'youtube'
  105. # Listed in order of quality
  106. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  107. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  108. _video_extensions = {
  109. '13': '3gp',
  110. '17': 'mp4',
  111. '18': 'mp4',
  112. '22': 'mp4',
  113. '37': 'mp4',
  114. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  115. '43': 'webm',
  116. '44': 'webm',
  117. '45': 'webm',
  118. '46': 'webm',
  119. }
  120. _video_dimensions = {
  121. '5': '240x400',
  122. '6': '???',
  123. '13': '???',
  124. '17': '144x176',
  125. '18': '360x640',
  126. '22': '720x1280',
  127. '34': '360x640',
  128. '35': '480x854',
  129. '37': '1080x1920',
  130. '38': '3072x4096',
  131. '43': '360x640',
  132. '44': '480x854',
  133. '45': '720x1280',
  134. '46': '1080x1920',
  135. }
  136. IE_NAME = u'youtube'
  137. def suitable(self, url):
  138. """Receives a URL and returns True if suitable for this IE."""
  139. return re.match(self._VALID_URL, url, re.VERBOSE) is not None
  140. def report_lang(self):
  141. """Report attempt to set language."""
  142. self._downloader.to_screen(u'[youtube] Setting language')
  143. def report_login(self):
  144. """Report attempt to log in."""
  145. self._downloader.to_screen(u'[youtube] Logging in')
  146. def report_age_confirmation(self):
  147. """Report attempt to confirm age."""
  148. self._downloader.to_screen(u'[youtube] Confirming age')
  149. def report_video_webpage_download(self, video_id):
  150. """Report attempt to download video webpage."""
  151. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  152. def report_video_info_webpage_download(self, video_id):
  153. """Report attempt to download video info webpage."""
  154. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  155. def report_video_subtitles_download(self, video_id):
  156. """Report attempt to download video info webpage."""
  157. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles' % video_id)
  158. def report_information_extraction(self, video_id):
  159. """Report attempt to extract video information."""
  160. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  161. def report_unavailable_format(self, video_id, format):
  162. """Report extracted video URL."""
  163. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  164. def report_rtmp_download(self):
  165. """Indicate the download will use the RTMP protocol."""
  166. self._downloader.to_screen(u'[youtube] RTMP download detected')
  167. def _closed_captions_xml_to_srt(self, xml_string):
  168. srt = ''
  169. texts = re.findall(r'<text start="([\d\.]+)"( dur="([\d\.]+)")?>([^<]+)</text>', xml_string, re.MULTILINE)
  170. # TODO parse xml instead of regex
  171. for n, (start, dur_tag, dur, caption) in enumerate(texts):
  172. if not dur: dur = '4'
  173. start = float(start)
  174. end = start + float(dur)
  175. start = "%02i:%02i:%02i,%03i" %(start/(60*60), start/60%60, start%60, start%1*1000)
  176. end = "%02i:%02i:%02i,%03i" %(end/(60*60), end/60%60, end%60, end%1*1000)
  177. caption = unescapeHTML(caption)
  178. caption = unescapeHTML(caption) # double cycle, intentional
  179. srt += str(n+1) + '\n'
  180. srt += start + ' --> ' + end + '\n'
  181. srt += caption + '\n\n'
  182. return srt
  183. def _print_formats(self, formats):
  184. print('Available formats:')
  185. for x in formats:
  186. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  187. def _real_initialize(self):
  188. if self._downloader is None:
  189. return
  190. username = None
  191. password = None
  192. downloader_params = self._downloader.params
  193. # Attempt to use provided username and password or .netrc data
  194. if downloader_params.get('username', None) is not None:
  195. username = downloader_params['username']
  196. password = downloader_params['password']
  197. elif downloader_params.get('usenetrc', False):
  198. try:
  199. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  200. if info is not None:
  201. username = info[0]
  202. password = info[2]
  203. else:
  204. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  205. except (IOError, netrc.NetrcParseError) as err:
  206. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  207. return
  208. # Set language
  209. request = compat_urllib_request.Request(self._LANG_URL)
  210. try:
  211. self.report_lang()
  212. compat_urllib_request.urlopen(request).read()
  213. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  214. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % compat_str(err))
  215. return
  216. # No authentication to be performed
  217. if username is None:
  218. return
  219. # Log in
  220. login_form = {
  221. 'current_form': 'loginForm',
  222. 'next': '/',
  223. 'action_login': 'Log In',
  224. 'username': username,
  225. 'password': password,
  226. }
  227. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  228. try:
  229. self.report_login()
  230. login_results = compat_urllib_request.urlopen(request).read()
  231. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  232. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  233. return
  234. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  235. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  236. return
  237. # Confirm age
  238. age_form = {
  239. 'next_url': '/',
  240. 'action_confirm': 'Confirm',
  241. }
  242. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  243. try:
  244. self.report_age_confirmation()
  245. age_results = compat_urllib_request.urlopen(request).read()
  246. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  247. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  248. return
  249. def _real_extract(self, url):
  250. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  251. mobj = re.search(self._NEXT_URL_RE, url)
  252. if mobj:
  253. url = 'http://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  254. # Extract video id from URL
  255. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  256. if mobj is None:
  257. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  258. return
  259. video_id = mobj.group(2)
  260. # Get video webpage
  261. self.report_video_webpage_download(video_id)
  262. request = compat_urllib_request.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id)
  263. try:
  264. video_webpage = compat_urllib_request.urlopen(request).read()
  265. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  266. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  267. return
  268. # Attempt to extract SWF player URL
  269. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  270. if mobj is not None:
  271. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  272. else:
  273. player_url = None
  274. # Get video info
  275. self.report_video_info_webpage_download(video_id)
  276. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  277. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  278. % (video_id, el_type))
  279. request = compat_urllib_request.Request(video_info_url)
  280. try:
  281. video_info_webpage = compat_urllib_request.urlopen(request).read()
  282. video_info = compat_parse_qs(video_info_webpage)
  283. if 'token' in video_info:
  284. break
  285. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  286. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  287. return
  288. if 'token' not in video_info:
  289. if 'reason' in video_info:
  290. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  291. else:
  292. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  293. return
  294. # Check for "rental" videos
  295. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  296. self._downloader.trouble(u'ERROR: "rental" videos not supported')
  297. return
  298. # Start extracting information
  299. self.report_information_extraction(video_id)
  300. # uploader
  301. if 'author' not in video_info:
  302. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  303. return
  304. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  305. # title
  306. if 'title' not in video_info:
  307. self._downloader.trouble(u'ERROR: unable to extract video title')
  308. return
  309. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  310. video_title = video_title.decode('utf-8')
  311. # thumbnail image
  312. if 'thumbnail_url' not in video_info:
  313. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  314. video_thumbnail = ''
  315. else: # don't panic if we can't find it
  316. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  317. # upload date
  318. upload_date = None
  319. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  320. if mobj is not None:
  321. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  322. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  323. for expression in format_expressions:
  324. try:
  325. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  326. except:
  327. pass
  328. # description
  329. video_description = get_element_by_id("eow-description", video_webpage.decode('utf8'))
  330. if video_description: video_description = clean_html(video_description)
  331. else: video_description = ''
  332. # closed captions
  333. video_subtitles = None
  334. if self._downloader.params.get('writesubtitles', False):
  335. try:
  336. self.report_video_subtitles_download(video_id)
  337. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  338. try:
  339. srt_list = compat_urllib_request.urlopen(request).read()
  340. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  341. raise Trouble(u'WARNING: unable to download video subtitles: %s' % compat_str(err))
  342. srt_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', srt_list)
  343. srt_lang_list = dict((l[1], l[0]) for l in srt_lang_list)
  344. if not srt_lang_list:
  345. raise Trouble(u'WARNING: video has no closed captions')
  346. if self._downloader.params.get('subtitleslang', False):
  347. srt_lang = self._downloader.params.get('subtitleslang')
  348. elif 'en' in srt_lang_list:
  349. srt_lang = 'en'
  350. else:
  351. srt_lang = srt_lang_list.keys()[0]
  352. if not srt_lang in srt_lang_list:
  353. raise Trouble(u'WARNING: no closed captions found in the specified language')
  354. request = compat_urllib_request.Request('http://www.youtube.com/api/timedtext?lang=%s&name=%s&v=%s' % (srt_lang, srt_lang_list[srt_lang], video_id))
  355. try:
  356. srt_xml = compat_urllib_request.urlopen(request).read()
  357. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  358. raise Trouble(u'WARNING: unable to download video subtitles: %s' % compat_str(err))
  359. if not srt_xml:
  360. raise Trouble(u'WARNING: unable to download video subtitles')
  361. video_subtitles = self._closed_captions_xml_to_srt(srt_xml.decode('utf-8'))
  362. except Trouble as trouble:
  363. self._downloader.trouble(trouble[0])
  364. if 'length_seconds' not in video_info:
  365. self._downloader.trouble(u'WARNING: unable to extract video duration')
  366. video_duration = ''
  367. else:
  368. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  369. # token
  370. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  371. # Decide which formats to download
  372. req_format = self._downloader.params.get('format', None)
  373. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  374. self.report_rtmp_download()
  375. video_url_list = [(None, video_info['conn'][0])]
  376. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  377. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  378. url_data = [compat_parse_qs(uds) for uds in url_data_strs]
  379. url_data = filter(lambda ud: 'itag' in ud and 'url' in ud, url_data)
  380. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0]) for ud in url_data)
  381. format_limit = self._downloader.params.get('format_limit', None)
  382. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  383. if format_limit is not None and format_limit in available_formats:
  384. format_list = available_formats[available_formats.index(format_limit):]
  385. else:
  386. format_list = available_formats
  387. existing_formats = [x for x in format_list if x in url_map]
  388. if len(existing_formats) == 0:
  389. self._downloader.trouble(u'ERROR: no known formats available for video')
  390. return
  391. if self._downloader.params.get('listformats', None):
  392. self._print_formats(existing_formats)
  393. return
  394. if req_format is None or req_format == 'best':
  395. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  396. elif req_format == 'worst':
  397. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  398. elif req_format in ('-1', 'all'):
  399. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  400. else:
  401. # Specific formats. We pick the first in a slash-delimeted sequence.
  402. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  403. req_formats = req_format.split('/')
  404. video_url_list = None
  405. for rf in req_formats:
  406. if rf in url_map:
  407. video_url_list = [(rf, url_map[rf])]
  408. break
  409. if video_url_list is None:
  410. self._downloader.trouble(u'ERROR: requested format not available')
  411. return
  412. else:
  413. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  414. return
  415. results = []
  416. for format_param, video_real_url in video_url_list:
  417. # Extension
  418. video_extension = self._video_extensions.get(format_param, 'flv')
  419. video_format = '{} - {}'.format(format_param.decode('utf-8') if format_param else video_extension.decode('utf-8'),
  420. self._video_dimensions.get(format_param, '???'))
  421. results.append({
  422. 'id': video_id.decode('utf-8'),
  423. 'url': video_real_url.decode('utf-8'),
  424. 'uploader': video_uploader.decode('utf-8'),
  425. 'upload_date': upload_date,
  426. 'title': video_title,
  427. 'ext': video_extension.decode('utf-8'),
  428. 'format': video_format,
  429. 'thumbnail': video_thumbnail.decode('utf-8'),
  430. 'description': video_description,
  431. 'player_url': player_url,
  432. 'subtitles': video_subtitles,
  433. 'duration': video_duration
  434. })
  435. return results
  436. class MetacafeIE(InfoExtractor):
  437. """Information Extractor for metacafe.com."""
  438. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  439. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  440. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  441. IE_NAME = u'metacafe'
  442. def __init__(self, downloader=None):
  443. InfoExtractor.__init__(self, downloader)
  444. def report_disclaimer(self):
  445. """Report disclaimer retrieval."""
  446. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  447. def report_age_confirmation(self):
  448. """Report attempt to confirm age."""
  449. self._downloader.to_screen(u'[metacafe] Confirming age')
  450. def report_download_webpage(self, video_id):
  451. """Report webpage download."""
  452. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  453. def report_extraction(self, video_id):
  454. """Report information extraction."""
  455. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  456. def _real_initialize(self):
  457. # Retrieve disclaimer
  458. request = compat_urllib_request.Request(self._DISCLAIMER)
  459. try:
  460. self.report_disclaimer()
  461. disclaimer = compat_urllib_request.urlopen(request).read()
  462. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  463. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % compat_str(err))
  464. return
  465. # Confirm age
  466. disclaimer_form = {
  467. 'filters': '0',
  468. 'submit': "Continue - I'm over 18",
  469. }
  470. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  471. try:
  472. self.report_age_confirmation()
  473. disclaimer = compat_urllib_request.urlopen(request).read()
  474. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  475. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % compat_str(err))
  476. return
  477. def _real_extract(self, url):
  478. # Extract id and simplified title from URL
  479. mobj = re.match(self._VALID_URL, url)
  480. if mobj is None:
  481. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  482. return
  483. video_id = mobj.group(1)
  484. # Check if video comes from YouTube
  485. mobj2 = re.match(r'^yt-(.*)$', video_id)
  486. if mobj2 is not None:
  487. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  488. return
  489. # Retrieve video webpage to extract further information
  490. request = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
  491. try:
  492. self.report_download_webpage(video_id)
  493. webpage = compat_urllib_request.urlopen(request).read()
  494. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  495. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  496. return
  497. # Extract URL, uploader and title from webpage
  498. self.report_extraction(video_id)
  499. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  500. if mobj is not None:
  501. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  502. video_extension = mediaURL[-3:]
  503. # Extract gdaKey if available
  504. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  505. if mobj is None:
  506. video_url = mediaURL
  507. else:
  508. gdaKey = mobj.group(1)
  509. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  510. else:
  511. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  512. if mobj is None:
  513. self._downloader.trouble(u'ERROR: unable to extract media URL')
  514. return
  515. vardict = compat_parse_qs(mobj.group(1))
  516. if 'mediaData' not in vardict:
  517. self._downloader.trouble(u'ERROR: unable to extract media URL')
  518. return
  519. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  520. if mobj is None:
  521. self._downloader.trouble(u'ERROR: unable to extract media URL')
  522. return
  523. mediaURL = mobj.group(1).replace('\\/', '/')
  524. video_extension = mediaURL[-3:]
  525. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  526. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  527. if mobj is None:
  528. self._downloader.trouble(u'ERROR: unable to extract title')
  529. return
  530. video_title = mobj.group(1).decode('utf-8')
  531. mobj = re.search(r'submitter=(.*?);', webpage)
  532. if mobj is None:
  533. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  534. return
  535. video_uploader = mobj.group(1)
  536. return [{
  537. 'id': video_id.decode('utf-8'),
  538. 'url': video_url.decode('utf-8'),
  539. 'uploader': video_uploader.decode('utf-8'),
  540. 'upload_date': None,
  541. 'title': video_title,
  542. 'ext': video_extension.decode('utf-8'),
  543. }]
  544. class DailymotionIE(InfoExtractor):
  545. """Information Extractor for Dailymotion"""
  546. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  547. IE_NAME = u'dailymotion'
  548. def __init__(self, downloader=None):
  549. InfoExtractor.__init__(self, downloader)
  550. def report_download_webpage(self, video_id):
  551. """Report webpage download."""
  552. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  553. def report_extraction(self, video_id):
  554. """Report information extraction."""
  555. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  556. def _real_extract(self, url):
  557. # Extract id and simplified title from URL
  558. mobj = re.match(self._VALID_URL, url)
  559. if mobj is None:
  560. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  561. return
  562. video_id = mobj.group(1).split('_')[0].split('?')[0]
  563. video_extension = 'mp4'
  564. # Retrieve video webpage to extract further information
  565. request = compat_urllib_request.Request(url)
  566. request.add_header('Cookie', 'family_filter=off')
  567. try:
  568. self.report_download_webpage(video_id)
  569. webpage = compat_urllib_request.urlopen(request).read()
  570. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  571. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % compat_str(err))
  572. return
  573. # Extract URL, uploader and title from webpage
  574. self.report_extraction(video_id)
  575. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  576. if mobj is None:
  577. self._downloader.trouble(u'ERROR: unable to extract media URL')
  578. return
  579. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  580. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  581. if key in flashvars:
  582. max_quality = key
  583. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  584. break
  585. else:
  586. self._downloader.trouble(u'ERROR: unable to extract video URL')
  587. return
  588. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  589. if mobj is None:
  590. self._downloader.trouble(u'ERROR: unable to extract video URL')
  591. return
  592. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  593. # TODO: support choosing qualities
  594. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  595. if mobj is None:
  596. self._downloader.trouble(u'ERROR: unable to extract title')
  597. return
  598. video_title = unescapeHTML(mobj.group('title').decode('utf-8'))
  599. video_uploader = None
  600. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  601. if mobj is None:
  602. # lookin for official user
  603. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  604. if mobj_official is None:
  605. self._downloader.trouble(u'WARNING: unable to extract uploader nickname')
  606. else:
  607. video_uploader = mobj_official.group(1)
  608. else:
  609. video_uploader = mobj.group(1)
  610. video_upload_date = None
  611. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  612. if mobj is not None:
  613. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  614. return [{
  615. 'id': video_id.decode('utf-8'),
  616. 'url': video_url.decode('utf-8'),
  617. 'uploader': video_uploader.decode('utf-8'),
  618. 'upload_date': video_upload_date,
  619. 'title': video_title,
  620. 'ext': video_extension.decode('utf-8'),
  621. }]
  622. class GoogleIE(InfoExtractor):
  623. """Information extractor for video.google.com."""
  624. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  625. IE_NAME = u'video.google'
  626. def __init__(self, downloader=None):
  627. InfoExtractor.__init__(self, downloader)
  628. def report_download_webpage(self, video_id):
  629. """Report webpage download."""
  630. self._downloader.to_screen(u'[video.google] %s: Downloading webpage' % video_id)
  631. def report_extraction(self, video_id):
  632. """Report information extraction."""
  633. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  634. def _real_extract(self, url):
  635. # Extract id 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)
  641. video_extension = 'mp4'
  642. # Retrieve video webpage to extract further information
  643. request = compat_urllib_request.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  644. try:
  645. self.report_download_webpage(video_id)
  646. webpage = compat_urllib_request.urlopen(request).read()
  647. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  648. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  649. return
  650. # Extract URL, uploader, and title from webpage
  651. self.report_extraction(video_id)
  652. mobj = re.search(r"download_url:'([^']+)'", webpage)
  653. if mobj is None:
  654. video_extension = 'flv'
  655. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  656. if mobj is None:
  657. self._downloader.trouble(u'ERROR: unable to extract media URL')
  658. return
  659. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  660. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  661. mediaURL = mediaURL.replace('\\x26', '\x26')
  662. video_url = mediaURL
  663. mobj = re.search(r'<title>(.*)</title>', webpage)
  664. if mobj is None:
  665. self._downloader.trouble(u'ERROR: unable to extract title')
  666. return
  667. video_title = mobj.group(1).decode('utf-8')
  668. # Extract video description
  669. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  670. if mobj is None:
  671. self._downloader.trouble(u'ERROR: unable to extract video description')
  672. return
  673. video_description = mobj.group(1).decode('utf-8')
  674. if not video_description:
  675. video_description = 'No description available.'
  676. # Extract video thumbnail
  677. if self._downloader.params.get('forcethumbnail', False):
  678. request = compat_urllib_request.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  679. try:
  680. webpage = compat_urllib_request.urlopen(request).read()
  681. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  682. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  683. return
  684. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  685. if mobj is None:
  686. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  687. return
  688. video_thumbnail = mobj.group(1)
  689. else: # we need something to pass to process_info
  690. video_thumbnail = ''
  691. return [{
  692. 'id': video_id.decode('utf-8'),
  693. 'url': video_url.decode('utf-8'),
  694. 'uploader': None,
  695. 'upload_date': None,
  696. 'title': video_title,
  697. 'ext': video_extension.decode('utf-8'),
  698. }]
  699. class PhotobucketIE(InfoExtractor):
  700. """Information extractor for photobucket.com."""
  701. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  702. IE_NAME = u'photobucket'
  703. def __init__(self, downloader=None):
  704. InfoExtractor.__init__(self, downloader)
  705. def report_download_webpage(self, video_id):
  706. """Report webpage download."""
  707. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  708. def report_extraction(self, video_id):
  709. """Report information extraction."""
  710. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  711. def _real_extract(self, url):
  712. # Extract id from URL
  713. mobj = re.match(self._VALID_URL, url)
  714. if mobj is None:
  715. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  716. return
  717. video_id = mobj.group(1)
  718. video_extension = 'flv'
  719. # Retrieve video webpage to extract further information
  720. request = compat_urllib_request.Request(url)
  721. try:
  722. self.report_download_webpage(video_id)
  723. webpage = compat_urllib_request.urlopen(request).read()
  724. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  725. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  726. return
  727. # Extract URL, uploader, and title from webpage
  728. self.report_extraction(video_id)
  729. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  730. if mobj is None:
  731. self._downloader.trouble(u'ERROR: unable to extract media URL')
  732. return
  733. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  734. video_url = mediaURL
  735. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  736. if mobj is None:
  737. self._downloader.trouble(u'ERROR: unable to extract title')
  738. return
  739. video_title = mobj.group(1).decode('utf-8')
  740. video_uploader = mobj.group(2).decode('utf-8')
  741. return [{
  742. 'id': video_id.decode('utf-8'),
  743. 'url': video_url.decode('utf-8'),
  744. 'uploader': video_uploader,
  745. 'upload_date': None,
  746. 'title': video_title,
  747. 'ext': video_extension.decode('utf-8'),
  748. }]
  749. class YahooIE(InfoExtractor):
  750. """Information extractor for video.yahoo.com."""
  751. # _VALID_URL matches all Yahoo! Video URLs
  752. # _VPAGE_URL matches only the extractable '/watch/' URLs
  753. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  754. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  755. IE_NAME = u'video.yahoo'
  756. def __init__(self, downloader=None):
  757. InfoExtractor.__init__(self, downloader)
  758. def report_download_webpage(self, video_id):
  759. """Report webpage download."""
  760. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  761. def report_extraction(self, video_id):
  762. """Report information extraction."""
  763. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  764. def _real_extract(self, url, new_video=True):
  765. # Extract ID from URL
  766. mobj = re.match(self._VALID_URL, url)
  767. if mobj is None:
  768. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  769. return
  770. video_id = mobj.group(2)
  771. video_extension = 'flv'
  772. # Rewrite valid but non-extractable URLs as
  773. # extractable English language /watch/ URLs
  774. if re.match(self._VPAGE_URL, url) is None:
  775. request = compat_urllib_request.Request(url)
  776. try:
  777. webpage = compat_urllib_request.urlopen(request).read()
  778. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  779. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  780. return
  781. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  782. if mobj is None:
  783. self._downloader.trouble(u'ERROR: Unable to extract id field')
  784. return
  785. yahoo_id = mobj.group(1)
  786. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  787. if mobj is None:
  788. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  789. return
  790. yahoo_vid = mobj.group(1)
  791. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  792. return self._real_extract(url, new_video=False)
  793. # Retrieve video webpage to extract further information
  794. request = compat_urllib_request.Request(url)
  795. try:
  796. self.report_download_webpage(video_id)
  797. webpage = compat_urllib_request.urlopen(request).read()
  798. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  799. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  800. return
  801. # Extract uploader and title from webpage
  802. self.report_extraction(video_id)
  803. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  804. if mobj is None:
  805. self._downloader.trouble(u'ERROR: unable to extract video title')
  806. return
  807. video_title = mobj.group(1).decode('utf-8')
  808. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  809. if mobj is None:
  810. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  811. return
  812. video_uploader = mobj.group(1).decode('utf-8')
  813. # Extract video thumbnail
  814. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  815. if mobj is None:
  816. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  817. return
  818. video_thumbnail = mobj.group(1).decode('utf-8')
  819. # Extract video description
  820. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  821. if mobj is None:
  822. self._downloader.trouble(u'ERROR: unable to extract video description')
  823. return
  824. video_description = mobj.group(1).decode('utf-8')
  825. if not video_description:
  826. video_description = 'No description available.'
  827. # Extract video height and width
  828. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  829. if mobj is None:
  830. self._downloader.trouble(u'ERROR: unable to extract video height')
  831. return
  832. yv_video_height = mobj.group(1)
  833. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  834. if mobj is None:
  835. self._downloader.trouble(u'ERROR: unable to extract video width')
  836. return
  837. yv_video_width = mobj.group(1)
  838. # Retrieve video playlist to extract media URL
  839. # I'm not completely sure what all these options are, but we
  840. # seem to need most of them, otherwise the server sends a 401.
  841. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  842. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  843. request = compat_urllib_request.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  844. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  845. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  846. try:
  847. self.report_download_webpage(video_id)
  848. webpage = compat_urllib_request.urlopen(request).read()
  849. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  850. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  851. return
  852. # Extract media URL from playlist XML
  853. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  854. if mobj is None:
  855. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  856. return
  857. video_url = compat_urllib_parse.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  858. video_url = unescapeHTML(video_url)
  859. return [{
  860. 'id': video_id.decode('utf-8'),
  861. 'url': video_url,
  862. 'uploader': video_uploader,
  863. 'upload_date': None,
  864. 'title': video_title,
  865. 'ext': video_extension.decode('utf-8'),
  866. 'thumbnail': video_thumbnail.decode('utf-8'),
  867. 'description': video_description,
  868. }]
  869. class VimeoIE(InfoExtractor):
  870. """Information extractor for vimeo.com."""
  871. # _VALID_URL matches Vimeo URLs
  872. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?:videos?/)?([0-9]+)'
  873. IE_NAME = u'vimeo'
  874. def __init__(self, downloader=None):
  875. InfoExtractor.__init__(self, downloader)
  876. def report_download_webpage(self, video_id):
  877. """Report webpage download."""
  878. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  879. def report_extraction(self, video_id):
  880. """Report information extraction."""
  881. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  882. def _real_extract(self, url, new_video=True):
  883. # Extract ID from URL
  884. mobj = re.match(self._VALID_URL, url)
  885. if mobj is None:
  886. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  887. return
  888. video_id = mobj.group(1)
  889. # Retrieve video webpage to extract further information
  890. request = compat_urllib_request.Request(url, None, std_headers)
  891. try:
  892. self.report_download_webpage(video_id)
  893. webpage = compat_urllib_request.urlopen(request).read()
  894. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  895. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  896. return
  897. # Now we begin extracting as much information as we can from what we
  898. # retrieved. First we extract the information common to all extractors,
  899. # and latter we extract those that are Vimeo specific.
  900. self.report_extraction(video_id)
  901. # Extract the config JSON
  902. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  903. try:
  904. config = json.loads(config)
  905. except:
  906. self._downloader.trouble(u'ERROR: unable to extract info section')
  907. return
  908. # Extract title
  909. video_title = config["video"]["title"]
  910. # Extract uploader
  911. video_uploader = config["video"]["owner"]["name"]
  912. # Extract video thumbnail
  913. video_thumbnail = config["video"]["thumbnail"]
  914. # Extract video description
  915. video_description = get_element_by_id("description", webpage.decode('utf8'))
  916. if video_description: video_description = clean_html(video_description)
  917. else: video_description = ''
  918. # Extract upload date
  919. video_upload_date = None
  920. mobj = re.search(r'<span id="clip-date" style="display:none">[^:]*: (.*?)( \([^\(]*\))?</span>', webpage)
  921. if mobj is not None:
  922. video_upload_date = mobj.group(1)
  923. # Vimeo specific: extract request signature and timestamp
  924. sig = config['request']['signature']
  925. timestamp = config['request']['timestamp']
  926. # Vimeo specific: extract video codec and quality information
  927. # First consider quality, then codecs, then take everything
  928. # TODO bind to format param
  929. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  930. files = { 'hd': [], 'sd': [], 'other': []}
  931. for codec_name, codec_extension in codecs:
  932. if codec_name in config["video"]["files"]:
  933. if 'hd' in config["video"]["files"][codec_name]:
  934. files['hd'].append((codec_name, codec_extension, 'hd'))
  935. elif 'sd' in config["video"]["files"][codec_name]:
  936. files['sd'].append((codec_name, codec_extension, 'sd'))
  937. else:
  938. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  939. for quality in ('hd', 'sd', 'other'):
  940. if len(files[quality]) > 0:
  941. video_quality = files[quality][0][2]
  942. video_codec = files[quality][0][0]
  943. video_extension = files[quality][0][1]
  944. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  945. break
  946. else:
  947. self._downloader.trouble(u'ERROR: no known codec found')
  948. return
  949. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  950. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  951. return [{
  952. 'id': video_id,
  953. 'url': video_url,
  954. 'uploader': video_uploader,
  955. 'upload_date': video_upload_date,
  956. 'title': video_title,
  957. 'ext': video_extension,
  958. 'thumbnail': video_thumbnail,
  959. 'description': video_description,
  960. }]
  961. class ArteTvIE(InfoExtractor):
  962. """arte.tv information extractor."""
  963. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  964. _LIVE_URL = r'index-[0-9]+\.html$'
  965. IE_NAME = u'arte.tv'
  966. def __init__(self, downloader=None):
  967. InfoExtractor.__init__(self, downloader)
  968. def report_download_webpage(self, video_id):
  969. """Report webpage download."""
  970. self._downloader.to_screen(u'[arte.tv] %s: Downloading webpage' % video_id)
  971. def report_extraction(self, video_id):
  972. """Report information extraction."""
  973. self._downloader.to_screen(u'[arte.tv] %s: Extracting information' % video_id)
  974. def fetch_webpage(self, url):
  975. self._downloader.increment_downloads()
  976. request = compat_urllib_request.Request(url)
  977. try:
  978. self.report_download_webpage(url)
  979. webpage = compat_urllib_request.urlopen(request).read()
  980. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  981. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  982. return
  983. except ValueError as err:
  984. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  985. return
  986. return webpage
  987. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  988. page = self.fetch_webpage(url)
  989. mobj = re.search(regex, page, regexFlags)
  990. info = {}
  991. if mobj is None:
  992. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  993. return
  994. for (i, key, err) in matchTuples:
  995. if mobj.group(i) is None:
  996. self._downloader.trouble(err)
  997. return
  998. else:
  999. info[key] = mobj.group(i)
  1000. return info
  1001. def extractLiveStream(self, url):
  1002. video_lang = url.split('/')[-4]
  1003. info = self.grep_webpage(
  1004. url,
  1005. r'src="(.*?/videothek_js.*?\.js)',
  1006. 0,
  1007. [
  1008. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1009. ]
  1010. )
  1011. http_host = url.split('/')[2]
  1012. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  1013. info = self.grep_webpage(
  1014. next_url,
  1015. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  1016. '(http://.*?\.swf).*?' +
  1017. '(rtmp://.*?)\'',
  1018. re.DOTALL,
  1019. [
  1020. (1, 'path', u'ERROR: could not extract video path: %s' % url),
  1021. (2, 'player', u'ERROR: could not extract video player: %s' % url),
  1022. (3, 'url', u'ERROR: could not extract video url: %s' % url)
  1023. ]
  1024. )
  1025. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  1026. def extractPlus7Stream(self, url):
  1027. video_lang = url.split('/')[-3]
  1028. info = self.grep_webpage(
  1029. url,
  1030. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  1031. 0,
  1032. [
  1033. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1034. ]
  1035. )
  1036. next_url = compat_urllib_parse.unquote(info.get('url'))
  1037. info = self.grep_webpage(
  1038. next_url,
  1039. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  1040. 0,
  1041. [
  1042. (1, 'url', u'ERROR: Could not find <video> tag: %s' % url)
  1043. ]
  1044. )
  1045. next_url = compat_urllib_parse.unquote(info.get('url'))
  1046. info = self.grep_webpage(
  1047. next_url,
  1048. r'<video id="(.*?)".*?>.*?' +
  1049. '<name>(.*?)</name>.*?' +
  1050. '<dateVideo>(.*?)</dateVideo>.*?' +
  1051. '<url quality="hd">(.*?)</url>',
  1052. re.DOTALL,
  1053. [
  1054. (1, 'id', u'ERROR: could not extract video id: %s' % url),
  1055. (2, 'title', u'ERROR: could not extract video title: %s' % url),
  1056. (3, 'date', u'ERROR: could not extract video date: %s' % url),
  1057. (4, 'url', u'ERROR: could not extract video url: %s' % url)
  1058. ]
  1059. )
  1060. return {
  1061. 'id': info.get('id'),
  1062. 'url': compat_urllib_parse.unquote(info.get('url')),
  1063. 'uploader': u'arte.tv',
  1064. 'upload_date': info.get('date'),
  1065. 'title': info.get('title'),
  1066. 'ext': u'mp4',
  1067. 'format': u'NA',
  1068. 'player_url': None,
  1069. }
  1070. def _real_extract(self, url):
  1071. video_id = url.split('/')[-1]
  1072. self.report_extraction(video_id)
  1073. if re.search(self._LIVE_URL, video_id) is not None:
  1074. self.extractLiveStream(url)
  1075. return
  1076. else:
  1077. info = self.extractPlus7Stream(url)
  1078. return [info]
  1079. class GenericIE(InfoExtractor):
  1080. """Generic last-resort information extractor."""
  1081. _VALID_URL = r'.*'
  1082. IE_NAME = u'generic'
  1083. def __init__(self, downloader=None):
  1084. InfoExtractor.__init__(self, downloader)
  1085. def report_download_webpage(self, video_id):
  1086. """Report webpage download."""
  1087. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1088. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1089. def report_extraction(self, video_id):
  1090. """Report information extraction."""
  1091. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1092. def report_following_redirect(self, new_url):
  1093. """Report information extraction."""
  1094. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1095. def _test_redirect(self, url):
  1096. """Check if it is a redirect, like url shorteners, in case restart chain."""
  1097. class HeadRequest(compat_urllib_request.Request):
  1098. def get_method(self):
  1099. return "HEAD"
  1100. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1101. """
  1102. Subclass the HTTPRedirectHandler to make it use our
  1103. HeadRequest also on the redirected URL
  1104. """
  1105. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1106. if code in (301, 302, 303, 307):
  1107. newurl = newurl.replace(' ', '%20')
  1108. newheaders = dict((k,v) for k,v in req.headers.items()
  1109. if k.lower() not in ("content-length", "content-type"))
  1110. return HeadRequest(newurl,
  1111. headers=newheaders,
  1112. origin_req_host=req.get_origin_req_host(),
  1113. unverifiable=True)
  1114. else:
  1115. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1116. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1117. """
  1118. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1119. """
  1120. def http_error_405(self, req, fp, code, msg, headers):
  1121. fp.read()
  1122. fp.close()
  1123. newheaders = dict((k,v) for k,v in req.headers.items()
  1124. if k.lower() not in ("content-length", "content-type"))
  1125. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1126. headers=newheaders,
  1127. origin_req_host=req.get_origin_req_host(),
  1128. unverifiable=True))
  1129. # Build our opener
  1130. opener = compat_urllib_request.OpenerDirector()
  1131. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1132. HTTPMethodFallback, HEADRedirectHandler,
  1133. compat_urllib_error.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1134. opener.add_handler(handler())
  1135. response = opener.open(HeadRequest(url))
  1136. new_url = response.geturl()
  1137. if url == new_url:
  1138. return False
  1139. self.report_following_redirect(new_url)
  1140. self._downloader.download([new_url])
  1141. return True
  1142. def _real_extract(self, url):
  1143. if self._test_redirect(url): return
  1144. video_id = url.split('/')[-1]
  1145. request = compat_urllib_request.Request(url)
  1146. try:
  1147. self.report_download_webpage(video_id)
  1148. webpage = compat_urllib_request.urlopen(request).read()
  1149. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1150. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1151. return
  1152. except ValueError as err:
  1153. # since this is the last-resort InfoExtractor, if
  1154. # this error is thrown, it'll be thrown here
  1155. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1156. return
  1157. self.report_extraction(video_id)
  1158. # Start with something easy: JW Player in SWFObject
  1159. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1160. if mobj is None:
  1161. # Broaden the search a little bit
  1162. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1163. if mobj is None:
  1164. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1165. return
  1166. # It's possible that one of the regexes
  1167. # matched, but returned an empty group:
  1168. if mobj.group(1) is None:
  1169. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1170. return
  1171. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1172. video_id = os.path.basename(video_url)
  1173. # here's a fun little line of code for you:
  1174. video_extension = os.path.splitext(video_id)[1][1:]
  1175. video_id = os.path.splitext(video_id)[0]
  1176. # it's tempting to parse this further, but you would
  1177. # have to take into account all the variations like
  1178. # Video Title - Site Name
  1179. # Site Name | Video Title
  1180. # Video Title - Tagline | Site Name
  1181. # and so on and so forth; it's just not practical
  1182. mobj = re.search(r'<title>(.*)</title>', webpage)
  1183. if mobj is None:
  1184. self._downloader.trouble(u'ERROR: unable to extract title')
  1185. return
  1186. video_title = mobj.group(1).decode('utf-8')
  1187. # video uploader is domain name
  1188. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1189. if mobj is None:
  1190. self._downloader.trouble(u'ERROR: unable to extract title')
  1191. return
  1192. video_uploader = mobj.group(1).decode('utf-8')
  1193. return [{
  1194. 'id': video_id.decode('utf-8'),
  1195. 'url': video_url.decode('utf-8'),
  1196. 'uploader': video_uploader,
  1197. 'upload_date': None,
  1198. 'title': video_title,
  1199. 'ext': video_extension.decode('utf-8'),
  1200. }]
  1201. class YoutubeSearchIE(InfoExtractor):
  1202. """Information Extractor for YouTube search queries."""
  1203. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1204. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1205. _max_youtube_results = 1000
  1206. IE_NAME = u'youtube:search'
  1207. def __init__(self, downloader=None):
  1208. InfoExtractor.__init__(self, downloader)
  1209. def report_download_page(self, query, pagenum):
  1210. """Report attempt to download search page with given number."""
  1211. query = query.decode(preferredencoding())
  1212. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1213. def _real_extract(self, query):
  1214. mobj = re.match(self._VALID_URL, query)
  1215. if mobj is None:
  1216. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1217. return
  1218. prefix, query = query.split(':')
  1219. prefix = prefix[8:]
  1220. query = query.encode('utf-8')
  1221. if prefix == '':
  1222. self._download_n_results(query, 1)
  1223. return
  1224. elif prefix == 'all':
  1225. self._download_n_results(query, self._max_youtube_results)
  1226. return
  1227. else:
  1228. try:
  1229. n = int(prefix)
  1230. if n <= 0:
  1231. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1232. return
  1233. elif n > self._max_youtube_results:
  1234. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1235. n = self._max_youtube_results
  1236. self._download_n_results(query, n)
  1237. return
  1238. except ValueError: # parsing prefix as integer fails
  1239. self._download_n_results(query, 1)
  1240. return
  1241. def _download_n_results(self, query, n):
  1242. """Downloads a specified number of results for a query"""
  1243. video_ids = []
  1244. pagenum = 0
  1245. limit = n
  1246. while (50 * pagenum) < limit:
  1247. self.report_download_page(query, pagenum+1)
  1248. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1249. request = compat_urllib_request.Request(result_url)
  1250. try:
  1251. data = compat_urllib_request.urlopen(request).read()
  1252. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1253. self._downloader.trouble(u'ERROR: unable to download API page: %s' % compat_str(err))
  1254. return
  1255. api_response = json.loads(data)['data']
  1256. new_ids = list(video['id'] for video in api_response['items'])
  1257. video_ids += new_ids
  1258. limit = min(n, api_response['totalItems'])
  1259. pagenum += 1
  1260. if len(video_ids) > n:
  1261. video_ids = video_ids[:n]
  1262. for id in video_ids:
  1263. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1264. return
  1265. class GoogleSearchIE(InfoExtractor):
  1266. """Information Extractor for Google Video search queries."""
  1267. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1268. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1269. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1270. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1271. _max_google_results = 1000
  1272. IE_NAME = u'video.google:search'
  1273. def __init__(self, downloader=None):
  1274. InfoExtractor.__init__(self, downloader)
  1275. def report_download_page(self, query, pagenum):
  1276. """Report attempt to download playlist page with given number."""
  1277. query = query.decode(preferredencoding())
  1278. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1279. def _real_extract(self, query):
  1280. mobj = re.match(self._VALID_URL, query)
  1281. if mobj is None:
  1282. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1283. return
  1284. prefix, query = query.split(':')
  1285. prefix = prefix[8:]
  1286. query = query.encode('utf-8')
  1287. if prefix == '':
  1288. self._download_n_results(query, 1)
  1289. return
  1290. elif prefix == 'all':
  1291. self._download_n_results(query, self._max_google_results)
  1292. return
  1293. else:
  1294. try:
  1295. n = int(prefix)
  1296. if n <= 0:
  1297. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1298. return
  1299. elif n > self._max_google_results:
  1300. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1301. n = self._max_google_results
  1302. self._download_n_results(query, n)
  1303. return
  1304. except ValueError: # parsing prefix as integer fails
  1305. self._download_n_results(query, 1)
  1306. return
  1307. def _download_n_results(self, query, n):
  1308. """Downloads a specified number of results for a query"""
  1309. video_ids = []
  1310. pagenum = 0
  1311. while True:
  1312. self.report_download_page(query, pagenum)
  1313. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1314. request = compat_urllib_request.Request(result_url)
  1315. try:
  1316. page = compat_urllib_request.urlopen(request).read()
  1317. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1318. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1319. return
  1320. # Extract video identifiers
  1321. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1322. video_id = mobj.group(1)
  1323. if video_id not in video_ids:
  1324. video_ids.append(video_id)
  1325. if len(video_ids) == n:
  1326. # Specified n videos reached
  1327. for id in video_ids:
  1328. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1329. return
  1330. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1331. for id in video_ids:
  1332. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1333. return
  1334. pagenum = pagenum + 1
  1335. class YahooSearchIE(InfoExtractor):
  1336. """Information Extractor for Yahoo! Video search queries."""
  1337. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1338. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1339. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1340. _MORE_PAGES_INDICATOR = r'\s*Next'
  1341. _max_yahoo_results = 1000
  1342. IE_NAME = u'video.yahoo:search'
  1343. def __init__(self, downloader=None):
  1344. InfoExtractor.__init__(self, downloader)
  1345. def report_download_page(self, query, pagenum):
  1346. """Report attempt to download playlist page with given number."""
  1347. query = query.decode(preferredencoding())
  1348. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1349. def _real_extract(self, query):
  1350. mobj = re.match(self._VALID_URL, query)
  1351. if mobj is None:
  1352. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1353. return
  1354. prefix, query = query.split(':')
  1355. prefix = prefix[8:]
  1356. query = query.encode('utf-8')
  1357. if prefix == '':
  1358. self._download_n_results(query, 1)
  1359. return
  1360. elif prefix == 'all':
  1361. self._download_n_results(query, self._max_yahoo_results)
  1362. return
  1363. else:
  1364. try:
  1365. n = int(prefix)
  1366. if n <= 0:
  1367. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1368. return
  1369. elif n > self._max_yahoo_results:
  1370. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1371. n = self._max_yahoo_results
  1372. self._download_n_results(query, n)
  1373. return
  1374. except ValueError: # parsing prefix as integer fails
  1375. self._download_n_results(query, 1)
  1376. return
  1377. def _download_n_results(self, query, n):
  1378. """Downloads a specified number of results for a query"""
  1379. video_ids = []
  1380. already_seen = set()
  1381. pagenum = 1
  1382. while True:
  1383. self.report_download_page(query, pagenum)
  1384. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1385. request = compat_urllib_request.Request(result_url)
  1386. try:
  1387. page = compat_urllib_request.urlopen(request).read()
  1388. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1389. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1390. return
  1391. # Extract video identifiers
  1392. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1393. video_id = mobj.group(1)
  1394. if video_id not in already_seen:
  1395. video_ids.append(video_id)
  1396. already_seen.add(video_id)
  1397. if len(video_ids) == n:
  1398. # Specified n videos reached
  1399. for id in video_ids:
  1400. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1401. return
  1402. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1403. for id in video_ids:
  1404. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1405. return
  1406. pagenum = pagenum + 1
  1407. class YoutubePlaylistIE(InfoExtractor):
  1408. """Information Extractor for YouTube playlists."""
  1409. _VALID_URL = r'(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:(?:course|view_play_list|my_playlists|artist|playlist)\?.*?(p|a|list)=|user/.*?/user/|p/|user/.*?#[pg]/c/)(?:PL|EC)?|PL|EC)([0-9A-Za-z-_]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1410. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1411. _VIDEO_INDICATOR_TEMPLATE = r'/watch\?v=(.+?)&amp;([^&"]+&amp;)*list=.*?%s'
  1412. _MORE_PAGES_INDICATOR = r'yt-uix-pager-next'
  1413. IE_NAME = u'youtube:playlist'
  1414. def __init__(self, downloader=None):
  1415. InfoExtractor.__init__(self, downloader)
  1416. def report_download_page(self, playlist_id, pagenum):
  1417. """Report attempt to download playlist page with given number."""
  1418. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1419. def _real_extract(self, url):
  1420. # Extract playlist id
  1421. mobj = re.match(self._VALID_URL, url)
  1422. if mobj is None:
  1423. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1424. return
  1425. # Single video case
  1426. if mobj.group(3) is not None:
  1427. self._downloader.download([mobj.group(3)])
  1428. return
  1429. # Download playlist pages
  1430. # prefix is 'p' as default for playlists but there are other types that need extra care
  1431. playlist_prefix = mobj.group(1)
  1432. if playlist_prefix == 'a':
  1433. playlist_access = 'artist'
  1434. else:
  1435. playlist_prefix = 'p'
  1436. playlist_access = 'view_play_list'
  1437. playlist_id = mobj.group(2)
  1438. video_ids = []
  1439. pagenum = 1
  1440. while True:
  1441. self.report_download_page(playlist_id, pagenum)
  1442. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  1443. request = compat_urllib_request.Request(url)
  1444. try:
  1445. page = compat_urllib_request.urlopen(request).read()
  1446. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1447. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1448. return
  1449. # Extract video identifiers
  1450. ids_in_page = []
  1451. for mobj in re.finditer(self._VIDEO_INDICATOR_TEMPLATE % playlist_id, page):
  1452. if mobj.group(1) not in ids_in_page:
  1453. ids_in_page.append(mobj.group(1))
  1454. video_ids.extend(ids_in_page)
  1455. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1456. break
  1457. pagenum = pagenum + 1
  1458. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1459. playlistend = self._downloader.params.get('playlistend', -1)
  1460. if playlistend == -1:
  1461. video_ids = video_ids[playliststart:]
  1462. else:
  1463. video_ids = video_ids[playliststart:playlistend]
  1464. for id in video_ids:
  1465. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1466. return
  1467. class YoutubeChannelIE(InfoExtractor):
  1468. """Information Extractor for YouTube channels."""
  1469. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1470. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1471. _MORE_PAGES_INDICATOR = r'yt-uix-button-content">Next' # TODO
  1472. IE_NAME = u'youtube:channel'
  1473. def report_download_page(self, channel_id, pagenum):
  1474. """Report attempt to download channel page with given number."""
  1475. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1476. def _real_extract(self, url):
  1477. # Extract channel id
  1478. mobj = re.match(self._VALID_URL, url)
  1479. if mobj is None:
  1480. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1481. return
  1482. # Download channel pages
  1483. channel_id = mobj.group(1)
  1484. video_ids = []
  1485. pagenum = 1
  1486. while True:
  1487. self.report_download_page(channel_id, pagenum)
  1488. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1489. request = compat_urllib_request.Request(url)
  1490. try:
  1491. page = compat_urllib_request.urlopen(request).read()
  1492. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1493. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1494. return
  1495. # Extract video identifiers
  1496. ids_in_page = []
  1497. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1498. if mobj.group(1) not in ids_in_page:
  1499. ids_in_page.append(mobj.group(1))
  1500. video_ids.extend(ids_in_page)
  1501. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1502. break
  1503. pagenum = pagenum + 1
  1504. for id in video_ids:
  1505. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1506. return
  1507. class YoutubeUserIE(InfoExtractor):
  1508. """Information Extractor for YouTube users."""
  1509. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1510. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1511. _GDATA_PAGE_SIZE = 50
  1512. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1513. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1514. IE_NAME = u'youtube:user'
  1515. def __init__(self, downloader=None):
  1516. InfoExtractor.__init__(self, downloader)
  1517. def report_download_page(self, username, start_index):
  1518. """Report attempt to download user page."""
  1519. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1520. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1521. def _real_extract(self, url):
  1522. # Extract username
  1523. mobj = re.match(self._VALID_URL, url)
  1524. if mobj is None:
  1525. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1526. return
  1527. username = mobj.group(1)
  1528. # Download video ids using YouTube Data API. Result size per
  1529. # query is limited (currently to 50 videos) so we need to query
  1530. # page by page until there are no video ids - it means we got
  1531. # all of them.
  1532. video_ids = []
  1533. pagenum = 0
  1534. while True:
  1535. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1536. self.report_download_page(username, start_index)
  1537. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1538. try:
  1539. page = compat_urllib_request.urlopen(request).read()
  1540. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1541. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1542. return
  1543. # Extract video identifiers
  1544. ids_in_page = []
  1545. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1546. if mobj.group(1) not in ids_in_page:
  1547. ids_in_page.append(mobj.group(1))
  1548. video_ids.extend(ids_in_page)
  1549. # A little optimization - if current page is not
  1550. # "full", ie. does not contain PAGE_SIZE video ids then
  1551. # we can assume that this page is the last one - there
  1552. # are no more ids on further pages - no need to query
  1553. # again.
  1554. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1555. break
  1556. pagenum += 1
  1557. all_ids_count = len(video_ids)
  1558. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1559. playlistend = self._downloader.params.get('playlistend', -1)
  1560. if playlistend == -1:
  1561. video_ids = video_ids[playliststart:]
  1562. else:
  1563. video_ids = video_ids[playliststart:playlistend]
  1564. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1565. (username, all_ids_count, len(video_ids)))
  1566. for video_id in video_ids:
  1567. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1568. class BlipTVUserIE(InfoExtractor):
  1569. """Information Extractor for blip.tv users."""
  1570. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1571. _PAGE_SIZE = 12
  1572. IE_NAME = u'blip.tv:user'
  1573. def __init__(self, downloader=None):
  1574. InfoExtractor.__init__(self, downloader)
  1575. def report_download_page(self, username, pagenum):
  1576. """Report attempt to download user page."""
  1577. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1578. (self.IE_NAME, username, pagenum))
  1579. def _real_extract(self, url):
  1580. # Extract username
  1581. mobj = re.match(self._VALID_URL, url)
  1582. if mobj is None:
  1583. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1584. return
  1585. username = mobj.group(1)
  1586. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1587. request = compat_urllib_request.Request(url)
  1588. try:
  1589. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1590. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1591. page_base = page_base % mobj.group(1)
  1592. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1593. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  1594. return
  1595. # Download video ids using BlipTV Ajax calls. Result size per
  1596. # query is limited (currently to 12 videos) so we need to query
  1597. # page by page until there are no video ids - it means we got
  1598. # all of them.
  1599. video_ids = []
  1600. pagenum = 1
  1601. while True:
  1602. self.report_download_page(username, pagenum)
  1603. request = compat_urllib_request.Request( page_base + "&page=" + str(pagenum) )
  1604. try:
  1605. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1606. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1607. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1608. return
  1609. # Extract video identifiers
  1610. ids_in_page = []
  1611. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1612. if mobj.group(1) not in ids_in_page:
  1613. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1614. video_ids.extend(ids_in_page)
  1615. # A little optimization - if current page is not
  1616. # "full", ie. does not contain PAGE_SIZE video ids then
  1617. # we can assume that this page is the last one - there
  1618. # are no more ids on further pages - no need to query
  1619. # again.
  1620. if len(ids_in_page) < self._PAGE_SIZE:
  1621. break
  1622. pagenum += 1
  1623. all_ids_count = len(video_ids)
  1624. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1625. playlistend = self._downloader.params.get('playlistend', -1)
  1626. if playlistend == -1:
  1627. video_ids = video_ids[playliststart:]
  1628. else:
  1629. video_ids = video_ids[playliststart:playlistend]
  1630. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1631. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1632. for video_id in video_ids:
  1633. self._downloader.download([u'http://blip.tv/'+video_id])
  1634. class DepositFilesIE(InfoExtractor):
  1635. """Information extractor for depositfiles.com"""
  1636. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1637. IE_NAME = u'DepositFiles'
  1638. def __init__(self, downloader=None):
  1639. InfoExtractor.__init__(self, downloader)
  1640. def report_download_webpage(self, file_id):
  1641. """Report webpage download."""
  1642. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1643. def report_extraction(self, file_id):
  1644. """Report information extraction."""
  1645. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1646. def _real_extract(self, url):
  1647. file_id = url.split('/')[-1]
  1648. # Rebuild url in english locale
  1649. url = 'http://depositfiles.com/en/files/' + file_id
  1650. # Retrieve file webpage with 'Free download' button pressed
  1651. free_download_indication = { 'gateway_result' : '1' }
  1652. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1653. try:
  1654. self.report_download_webpage(file_id)
  1655. webpage = compat_urllib_request.urlopen(request).read()
  1656. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1657. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % compat_str(err))
  1658. return
  1659. # Search for the real file URL
  1660. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1661. if (mobj is None) or (mobj.group(1) is None):
  1662. # Try to figure out reason of the error.
  1663. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1664. if (mobj is not None) and (mobj.group(1) is not None):
  1665. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1666. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1667. else:
  1668. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1669. return
  1670. file_url = mobj.group(1)
  1671. file_extension = os.path.splitext(file_url)[1][1:]
  1672. # Search for file title
  1673. mobj = re.search(r'<b title="(.*?)">', webpage)
  1674. if mobj is None:
  1675. self._downloader.trouble(u'ERROR: unable to extract title')
  1676. return
  1677. file_title = mobj.group(1).decode('utf-8')
  1678. return [{
  1679. 'id': file_id.decode('utf-8'),
  1680. 'url': file_url.decode('utf-8'),
  1681. 'uploader': None,
  1682. 'upload_date': None,
  1683. 'title': file_title,
  1684. 'ext': file_extension.decode('utf-8'),
  1685. }]
  1686. class FacebookIE(InfoExtractor):
  1687. """Information Extractor for Facebook"""
  1688. _WORKING = False
  1689. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1690. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1691. _NETRC_MACHINE = 'facebook'
  1692. _available_formats = ['video', 'highqual', 'lowqual']
  1693. _video_extensions = {
  1694. 'video': 'mp4',
  1695. 'highqual': 'mp4',
  1696. 'lowqual': 'mp4',
  1697. }
  1698. IE_NAME = u'facebook'
  1699. def __init__(self, downloader=None):
  1700. InfoExtractor.__init__(self, downloader)
  1701. def _reporter(self, message):
  1702. """Add header and report message."""
  1703. self._downloader.to_screen(u'[facebook] %s' % message)
  1704. def report_login(self):
  1705. """Report attempt to log in."""
  1706. self._reporter(u'Logging in')
  1707. def report_video_webpage_download(self, video_id):
  1708. """Report attempt to download video webpage."""
  1709. self._reporter(u'%s: Downloading video webpage' % video_id)
  1710. def report_information_extraction(self, video_id):
  1711. """Report attempt to extract video information."""
  1712. self._reporter(u'%s: Extracting video information' % video_id)
  1713. def _parse_page(self, video_webpage):
  1714. """Extract video information from page"""
  1715. # General data
  1716. data = {'title': r'\("video_title", "(.*?)"\)',
  1717. 'description': r'<div class="datawrap">(.*?)</div>',
  1718. 'owner': r'\("video_owner_name", "(.*?)"\)',
  1719. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  1720. }
  1721. video_info = {}
  1722. for piece in data.keys():
  1723. mobj = re.search(data[piece], video_webpage)
  1724. if mobj is not None:
  1725. video_info[piece] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1726. # Video urls
  1727. video_urls = {}
  1728. for fmt in self._available_formats:
  1729. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  1730. if mobj is not None:
  1731. # URL is in a Javascript segment inside an escaped Unicode format within
  1732. # the generally utf-8 page
  1733. video_urls[fmt] = compat_urllib_parse.unquote_plus(mobj.group(1).decode("unicode_escape"))
  1734. video_info['video_urls'] = video_urls
  1735. return video_info
  1736. def _real_initialize(self):
  1737. if self._downloader is None:
  1738. return
  1739. useremail = None
  1740. password = None
  1741. downloader_params = self._downloader.params
  1742. # Attempt to use provided username and password or .netrc data
  1743. if downloader_params.get('username', None) is not None:
  1744. useremail = downloader_params['username']
  1745. password = downloader_params['password']
  1746. elif downloader_params.get('usenetrc', False):
  1747. try:
  1748. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1749. if info is not None:
  1750. useremail = info[0]
  1751. password = info[2]
  1752. else:
  1753. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1754. except (IOError, netrc.NetrcParseError) as err:
  1755. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % compat_str(err))
  1756. return
  1757. if useremail is None:
  1758. return
  1759. # Log in
  1760. login_form = {
  1761. 'email': useremail,
  1762. 'pass': password,
  1763. 'login': 'Log+In'
  1764. }
  1765. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1766. try:
  1767. self.report_login()
  1768. login_results = compat_urllib_request.urlopen(request).read()
  1769. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1770. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1771. return
  1772. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1773. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % compat_str(err))
  1774. return
  1775. def _real_extract(self, url):
  1776. mobj = re.match(self._VALID_URL, url)
  1777. if mobj is None:
  1778. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1779. return
  1780. video_id = mobj.group('ID')
  1781. # Get video webpage
  1782. self.report_video_webpage_download(video_id)
  1783. request = compat_urllib_request.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  1784. try:
  1785. page = compat_urllib_request.urlopen(request)
  1786. video_webpage = page.read()
  1787. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1788. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  1789. return
  1790. # Start extracting information
  1791. self.report_information_extraction(video_id)
  1792. # Extract information
  1793. video_info = self._parse_page(video_webpage)
  1794. # uploader
  1795. if 'owner' not in video_info:
  1796. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1797. return
  1798. video_uploader = video_info['owner']
  1799. # title
  1800. if 'title' not in video_info:
  1801. self._downloader.trouble(u'ERROR: unable to extract video title')
  1802. return
  1803. video_title = video_info['title']
  1804. video_title = video_title.decode('utf-8')
  1805. # thumbnail image
  1806. if 'thumbnail' not in video_info:
  1807. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1808. video_thumbnail = ''
  1809. else:
  1810. video_thumbnail = video_info['thumbnail']
  1811. # upload date
  1812. upload_date = None
  1813. if 'upload_date' in video_info:
  1814. upload_time = video_info['upload_date']
  1815. timetuple = email.utils.parsedate_tz(upload_time)
  1816. if timetuple is not None:
  1817. try:
  1818. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  1819. except:
  1820. pass
  1821. # description
  1822. video_description = video_info.get('description', 'No description available.')
  1823. url_map = video_info['video_urls']
  1824. if len(url_map.keys()) > 0:
  1825. # Decide which formats to download
  1826. req_format = self._downloader.params.get('format', None)
  1827. format_limit = self._downloader.params.get('format_limit', None)
  1828. if format_limit is not None and format_limit in self._available_formats:
  1829. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1830. else:
  1831. format_list = self._available_formats
  1832. existing_formats = [x for x in format_list if x in url_map]
  1833. if len(existing_formats) == 0:
  1834. self._downloader.trouble(u'ERROR: no known formats available for video')
  1835. return
  1836. if req_format is None:
  1837. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1838. elif req_format == 'worst':
  1839. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1840. elif req_format == '-1':
  1841. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1842. else:
  1843. # Specific format
  1844. if req_format not in url_map:
  1845. self._downloader.trouble(u'ERROR: requested format not available')
  1846. return
  1847. video_url_list = [(req_format, url_map[req_format])] # Specific format
  1848. results = []
  1849. for format_param, video_real_url in video_url_list:
  1850. # Extension
  1851. video_extension = self._video_extensions.get(format_param, 'mp4')
  1852. results.append({
  1853. 'id': video_id.decode('utf-8'),
  1854. 'url': video_real_url.decode('utf-8'),
  1855. 'uploader': video_uploader.decode('utf-8'),
  1856. 'upload_date': upload_date,
  1857. 'title': video_title,
  1858. 'ext': video_extension.decode('utf-8'),
  1859. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1860. 'thumbnail': video_thumbnail.decode('utf-8'),
  1861. 'description': video_description.decode('utf-8'),
  1862. })
  1863. return results
  1864. class BlipTVIE(InfoExtractor):
  1865. """Information extractor for blip.tv"""
  1866. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1867. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1868. IE_NAME = u'blip.tv'
  1869. def report_extraction(self, file_id):
  1870. """Report information extraction."""
  1871. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1872. def report_direct_download(self, title):
  1873. """Report information extraction."""
  1874. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1875. def _real_extract(self, url):
  1876. mobj = re.match(self._VALID_URL, url)
  1877. if mobj is None:
  1878. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1879. return
  1880. if '?' in url:
  1881. cchar = '&'
  1882. else:
  1883. cchar = '?'
  1884. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1885. request = compat_urllib_request.Request(json_url.encode('utf-8'))
  1886. self.report_extraction(mobj.group(1))
  1887. info = None
  1888. try:
  1889. urlh = compat_urllib_request.urlopen(request)
  1890. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1891. basename = url.split('/')[-1]
  1892. title,ext = os.path.splitext(basename)
  1893. title = title.decode('UTF-8')
  1894. ext = ext.replace('.', '')
  1895. self.report_direct_download(title)
  1896. info = {
  1897. 'id': title,
  1898. 'url': url,
  1899. 'uploader': None,
  1900. 'upload_date': None,
  1901. 'title': title,
  1902. 'ext': ext,
  1903. 'urlhandle': urlh
  1904. }
  1905. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1906. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1907. return
  1908. if info is None: # Regular URL
  1909. try:
  1910. json_code = urlh.read()
  1911. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1912. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % compat_str(err))
  1913. return
  1914. try:
  1915. json_data = json.loads(json_code)
  1916. if 'Post' in json_data:
  1917. data = json_data['Post']
  1918. else:
  1919. data = json_data
  1920. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1921. video_url = data['media']['url']
  1922. umobj = re.match(self._URL_EXT, video_url)
  1923. if umobj is None:
  1924. raise ValueError('Can not determine filename extension')
  1925. ext = umobj.group(1)
  1926. info = {
  1927. 'id': data['item_id'],
  1928. 'url': video_url,
  1929. 'uploader': data['display_name'],
  1930. 'upload_date': upload_date,
  1931. 'title': data['title'],
  1932. 'ext': ext,
  1933. 'format': data['media']['mimeType'],
  1934. 'thumbnail': data['thumbnailUrl'],
  1935. 'description': data['description'],
  1936. 'player_url': data['embedUrl']
  1937. }
  1938. except (ValueError,KeyError) as err:
  1939. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  1940. return
  1941. std_headers['User-Agent'] = 'iTunes/10.6.1'
  1942. return [info]
  1943. class MyVideoIE(InfoExtractor):
  1944. """Information Extractor for myvideo.de."""
  1945. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1946. IE_NAME = u'myvideo'
  1947. def __init__(self, downloader=None):
  1948. InfoExtractor.__init__(self, downloader)
  1949. def report_download_webpage(self, video_id):
  1950. """Report webpage download."""
  1951. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  1952. def report_extraction(self, video_id):
  1953. """Report information extraction."""
  1954. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1955. def _real_extract(self,url):
  1956. mobj = re.match(self._VALID_URL, url)
  1957. if mobj is None:
  1958. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  1959. return
  1960. video_id = mobj.group(1)
  1961. # Get video webpage
  1962. request = compat_urllib_request.Request('http://www.myvideo.de/watch/%s' % video_id)
  1963. try:
  1964. self.report_download_webpage(video_id)
  1965. webpage = compat_urllib_request.urlopen(request).read()
  1966. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1967. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  1968. return
  1969. self.report_extraction(video_id)
  1970. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  1971. webpage)
  1972. if mobj is None:
  1973. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1974. return
  1975. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1976. mobj = re.search('<title>([^<]+)</title>', webpage)
  1977. if mobj is None:
  1978. self._downloader.trouble(u'ERROR: unable to extract title')
  1979. return
  1980. video_title = mobj.group(1)
  1981. return [{
  1982. 'id': video_id,
  1983. 'url': video_url,
  1984. 'uploader': None,
  1985. 'upload_date': None,
  1986. 'title': video_title,
  1987. 'ext': u'flv',
  1988. }]
  1989. class ComedyCentralIE(InfoExtractor):
  1990. """Information extractor for The Daily Show and Colbert Report """
  1991. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  1992. IE_NAME = u'comedycentral'
  1993. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1994. _video_extensions = {
  1995. '3500': 'mp4',
  1996. '2200': 'mp4',
  1997. '1700': 'mp4',
  1998. '1200': 'mp4',
  1999. '750': 'mp4',
  2000. '400': 'mp4',
  2001. }
  2002. _video_dimensions = {
  2003. '3500': '1280x720',
  2004. '2200': '960x540',
  2005. '1700': '768x432',
  2006. '1200': '640x360',
  2007. '750': '512x288',
  2008. '400': '384x216',
  2009. }
  2010. def report_extraction(self, episode_id):
  2011. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  2012. def report_config_download(self, episode_id):
  2013. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  2014. def report_index_download(self, episode_id):
  2015. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  2016. def report_player_url(self, episode_id):
  2017. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  2018. def _print_formats(self, formats):
  2019. print('Available formats:')
  2020. for x in formats:
  2021. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  2022. def _real_extract(self, url):
  2023. mobj = re.match(self._VALID_URL, url)
  2024. if mobj is None:
  2025. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2026. return
  2027. if mobj.group('shortname'):
  2028. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  2029. url = u'http://www.thedailyshow.com/full-episodes/'
  2030. else:
  2031. url = u'http://www.colbertnation.com/full-episodes/'
  2032. mobj = re.match(self._VALID_URL, url)
  2033. assert mobj is not None
  2034. dlNewest = not mobj.group('episode')
  2035. if dlNewest:
  2036. epTitle = mobj.group('showname')
  2037. else:
  2038. epTitle = mobj.group('episode')
  2039. req = compat_urllib_request.Request(url)
  2040. self.report_extraction(epTitle)
  2041. try:
  2042. htmlHandle = compat_urllib_request.urlopen(req)
  2043. html = htmlHandle.read()
  2044. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2045. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2046. return
  2047. if dlNewest:
  2048. url = htmlHandle.geturl()
  2049. mobj = re.match(self._VALID_URL, url)
  2050. if mobj is None:
  2051. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2052. return
  2053. if mobj.group('episode') == '':
  2054. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2055. return
  2056. epTitle = mobj.group('episode')
  2057. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"', html)
  2058. if len(mMovieParams) == 0:
  2059. # The Colbert Report embeds the information in a without
  2060. # a URL prefix; so extract the alternate reference
  2061. # and then add the URL prefix manually.
  2062. altMovieParams = re.findall('data-mgid="([^"]*episode.*?:.*?)"', html)
  2063. if len(altMovieParams) == 0:
  2064. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2065. return
  2066. else:
  2067. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2068. playerUrl_raw = mMovieParams[0][0]
  2069. self.report_player_url(epTitle)
  2070. try:
  2071. urlHandle = compat_urllib_request.urlopen(playerUrl_raw)
  2072. playerUrl = urlHandle.geturl()
  2073. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2074. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + compat_str(err))
  2075. return
  2076. uri = mMovieParams[0][1]
  2077. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2078. self.report_index_download(epTitle)
  2079. try:
  2080. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2081. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2082. self._downloader.trouble(u'ERROR: unable to download episode index: ' + compat_str(err))
  2083. return
  2084. results = []
  2085. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2086. itemEls = idoc.findall('.//item')
  2087. for itemEl in itemEls:
  2088. mediaId = itemEl.findall('./guid')[0].text
  2089. shortMediaId = mediaId.split(':')[-1]
  2090. showId = mediaId.split(':')[-2].replace('.com', '')
  2091. officialTitle = itemEl.findall('./title')[0].text
  2092. officialDate = itemEl.findall('./pubDate')[0].text
  2093. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2094. compat_urllib_parse.urlencode({'uri': mediaId}))
  2095. configReq = compat_urllib_request.Request(configUrl)
  2096. self.report_config_download(epTitle)
  2097. try:
  2098. configXml = compat_urllib_request.urlopen(configReq).read()
  2099. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2100. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % compat_str(err))
  2101. return
  2102. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2103. turls = []
  2104. for rendition in cdoc.findall('.//rendition'):
  2105. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2106. turls.append(finfo)
  2107. if len(turls) == 0:
  2108. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2109. continue
  2110. if self._downloader.params.get('listformats', None):
  2111. self._print_formats([i[0] for i in turls])
  2112. return
  2113. # For now, just pick the highest bitrate
  2114. format,video_url = turls[-1]
  2115. # Get the format arg from the arg stream
  2116. req_format = self._downloader.params.get('format', None)
  2117. # Select format if we can find one
  2118. for f,v in turls:
  2119. if f == req_format:
  2120. format, video_url = f, v
  2121. break
  2122. # Patch to download from alternative CDN, which does not
  2123. # break on current RTMPDump builds
  2124. broken_cdn = "rtmpe://viacomccstrmfs.fplive.net/viacomccstrm/gsp.comedystor/"
  2125. better_cdn = "rtmpe://cp10740.edgefcs.net/ondemand/mtvnorigin/gsp.comedystor/"
  2126. if video_url.startswith(broken_cdn):
  2127. video_url = video_url.replace(broken_cdn, better_cdn)
  2128. effTitle = showId + u'-' + epTitle
  2129. info = {
  2130. 'id': shortMediaId,
  2131. 'url': video_url,
  2132. 'uploader': showId,
  2133. 'upload_date': officialDate,
  2134. 'title': effTitle,
  2135. 'ext': 'mp4',
  2136. 'format': format,
  2137. 'thumbnail': None,
  2138. 'description': officialTitle,
  2139. 'player_url': None #playerUrl
  2140. }
  2141. results.append(info)
  2142. return results
  2143. class EscapistIE(InfoExtractor):
  2144. """Information extractor for The Escapist """
  2145. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2146. IE_NAME = u'escapist'
  2147. def report_extraction(self, showName):
  2148. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2149. def report_config_download(self, showName):
  2150. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2151. def _real_extract(self, url):
  2152. mobj = re.match(self._VALID_URL, url)
  2153. if mobj is None:
  2154. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2155. return
  2156. showName = mobj.group('showname')
  2157. videoId = mobj.group('episode')
  2158. self.report_extraction(showName)
  2159. try:
  2160. webPage = compat_urllib_request.urlopen(url)
  2161. webPageBytes = webPage.read()
  2162. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2163. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2164. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2165. self._downloader.trouble(u'ERROR: unable to download webpage: ' + compat_str(err))
  2166. return
  2167. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2168. description = unescapeHTML(descMatch.group(1))
  2169. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2170. imgUrl = unescapeHTML(imgMatch.group(1))
  2171. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2172. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2173. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2174. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2175. self.report_config_download(showName)
  2176. try:
  2177. configJSON = compat_urllib_request.urlopen(configUrl).read()
  2178. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2179. self._downloader.trouble(u'ERROR: unable to download configuration: ' + compat_str(err))
  2180. return
  2181. # Technically, it's JavaScript, not JSON
  2182. configJSON = configJSON.replace("'", '"')
  2183. try:
  2184. config = json.loads(configJSON)
  2185. except (ValueError,) as err:
  2186. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + compat_str(err))
  2187. return
  2188. playlist = config['playlist']
  2189. videoUrl = playlist[1]['url']
  2190. info = {
  2191. 'id': videoId,
  2192. 'url': videoUrl,
  2193. 'uploader': showName,
  2194. 'upload_date': None,
  2195. 'title': showName,
  2196. 'ext': 'flv',
  2197. 'thumbnail': imgUrl,
  2198. 'description': description,
  2199. 'player_url': playerUrl,
  2200. }
  2201. return [info]
  2202. class CollegeHumorIE(InfoExtractor):
  2203. """Information extractor for collegehumor.com"""
  2204. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2205. IE_NAME = u'collegehumor'
  2206. def report_webpage(self, video_id):
  2207. """Report information extraction."""
  2208. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2209. def report_extraction(self, video_id):
  2210. """Report information extraction."""
  2211. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2212. def _real_extract(self, url):
  2213. mobj = re.match(self._VALID_URL, url)
  2214. if mobj is None:
  2215. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2216. return
  2217. video_id = mobj.group('videoid')
  2218. self.report_webpage(video_id)
  2219. request = compat_urllib_request.Request(url)
  2220. try:
  2221. webpage = compat_urllib_request.urlopen(request).read()
  2222. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2223. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2224. return
  2225. m = re.search(r'id="video:(?P<internalvideoid>[0-9]+)"', webpage)
  2226. if m is None:
  2227. self._downloader.trouble(u'ERROR: Cannot extract internal video ID')
  2228. return
  2229. internal_video_id = m.group('internalvideoid')
  2230. info = {
  2231. 'id': video_id,
  2232. 'internal_id': internal_video_id,
  2233. 'uploader': None,
  2234. 'upload_date': None,
  2235. }
  2236. self.report_extraction(video_id)
  2237. xmlUrl = 'http://www.collegehumor.com/moogaloop/video:' + internal_video_id
  2238. try:
  2239. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2240. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2241. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2242. return
  2243. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2244. try:
  2245. videoNode = mdoc.findall('./video')[0]
  2246. info['description'] = videoNode.findall('./description')[0].text
  2247. info['title'] = videoNode.findall('./caption')[0].text
  2248. info['url'] = videoNode.findall('./file')[0].text
  2249. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2250. info['ext'] = info['url'].rpartition('.')[2]
  2251. except IndexError:
  2252. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2253. return
  2254. return [info]
  2255. class XVideosIE(InfoExtractor):
  2256. """Information extractor for xvideos.com"""
  2257. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2258. IE_NAME = u'xvideos'
  2259. def report_webpage(self, video_id):
  2260. """Report information extraction."""
  2261. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2262. def report_extraction(self, video_id):
  2263. """Report information extraction."""
  2264. self._downloader.to_screen(u'[%s] %s: Extracting information' % (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. video_id = mobj.group(1).decode('utf-8')
  2271. self.report_webpage(video_id)
  2272. request = compat_urllib_request.Request(r'http://www.xvideos.com/video' + video_id)
  2273. try:
  2274. webpage = compat_urllib_request.urlopen(request).read()
  2275. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2276. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2277. return
  2278. self.report_extraction(video_id)
  2279. # Extract video URL
  2280. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2281. if mobj is None:
  2282. self._downloader.trouble(u'ERROR: unable to extract video url')
  2283. return
  2284. video_url = compat_urllib_parse.unquote(mobj.group(1).decode('utf-8'))
  2285. # Extract title
  2286. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2287. if mobj is None:
  2288. self._downloader.trouble(u'ERROR: unable to extract video title')
  2289. return
  2290. video_title = mobj.group(1).decode('utf-8')
  2291. # Extract video thumbnail
  2292. 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)
  2293. if mobj is None:
  2294. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2295. return
  2296. video_thumbnail = mobj.group(0).decode('utf-8')
  2297. info = {
  2298. 'id': video_id,
  2299. 'url': video_url,
  2300. 'uploader': None,
  2301. 'upload_date': None,
  2302. 'title': video_title,
  2303. 'ext': 'flv',
  2304. 'thumbnail': video_thumbnail,
  2305. 'description': None,
  2306. }
  2307. return [info]
  2308. class SoundcloudIE(InfoExtractor):
  2309. """Information extractor for soundcloud.com
  2310. To access the media, the uid of the song and a stream token
  2311. must be extracted from the page source and the script must make
  2312. a request to media.soundcloud.com/crossdomain.xml. Then
  2313. the media can be grabbed by requesting from an url composed
  2314. of the stream token and uid
  2315. """
  2316. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2317. IE_NAME = u'soundcloud'
  2318. def __init__(self, downloader=None):
  2319. InfoExtractor.__init__(self, downloader)
  2320. def report_webpage(self, video_id):
  2321. """Report information extraction."""
  2322. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2323. def report_extraction(self, video_id):
  2324. """Report information extraction."""
  2325. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2326. def _real_extract(self, url):
  2327. mobj = re.match(self._VALID_URL, url)
  2328. if mobj is None:
  2329. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2330. return
  2331. # extract uploader (which is in the url)
  2332. uploader = mobj.group(1).decode('utf-8')
  2333. # extract simple title (uploader + slug of song title)
  2334. slug_title = mobj.group(2).decode('utf-8')
  2335. simple_title = uploader + u'-' + slug_title
  2336. self.report_webpage('%s/%s' % (uploader, slug_title))
  2337. request = compat_urllib_request.Request('http://soundcloud.com/%s/%s' % (uploader, slug_title))
  2338. try:
  2339. webpage = compat_urllib_request.urlopen(request).read()
  2340. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2341. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2342. return
  2343. self.report_extraction('%s/%s' % (uploader, slug_title))
  2344. # extract uid and stream token that soundcloud hands out for access
  2345. mobj = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', webpage)
  2346. if mobj:
  2347. video_id = mobj.group(1)
  2348. stream_token = mobj.group(2)
  2349. # extract unsimplified title
  2350. mobj = re.search('"title":"(.*?)",', webpage)
  2351. if mobj:
  2352. title = mobj.group(1).decode('utf-8')
  2353. else:
  2354. title = simple_title
  2355. # construct media url (with uid/token)
  2356. mediaURL = "http://media.soundcloud.com/stream/%s?stream_token=%s"
  2357. mediaURL = mediaURL % (video_id, stream_token)
  2358. # description
  2359. description = u'No description available'
  2360. mobj = re.search('track-description-value"><p>(.*?)</p>', webpage)
  2361. if mobj:
  2362. description = mobj.group(1)
  2363. # upload date
  2364. upload_date = None
  2365. mobj = re.search("pretty-date'>on ([\w]+ [\d]+, [\d]+ \d+:\d+)</abbr></h2>", webpage)
  2366. if mobj:
  2367. try:
  2368. upload_date = datetime.datetime.strptime(mobj.group(1), '%B %d, %Y %H:%M').strftime('%Y%m%d')
  2369. except Exception as err:
  2370. self._downloader.to_stderr(compat_str(err))
  2371. # for soundcloud, a request to a cross domain is required for cookies
  2372. request = compat_urllib_request.Request('http://media.soundcloud.com/crossdomain.xml', std_headers)
  2373. return [{
  2374. 'id': video_id.decode('utf-8'),
  2375. 'url': mediaURL,
  2376. 'uploader': uploader.decode('utf-8'),
  2377. 'upload_date': upload_date,
  2378. 'title': title,
  2379. 'ext': u'mp3',
  2380. 'description': description.decode('utf-8')
  2381. }]
  2382. class InfoQIE(InfoExtractor):
  2383. """Information extractor for infoq.com"""
  2384. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2385. IE_NAME = u'infoq'
  2386. def report_webpage(self, video_id):
  2387. """Report information extraction."""
  2388. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2389. def report_extraction(self, video_id):
  2390. """Report information extraction."""
  2391. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2392. def _real_extract(self, url):
  2393. mobj = re.match(self._VALID_URL, url)
  2394. if mobj is None:
  2395. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2396. return
  2397. self.report_webpage(url)
  2398. request = compat_urllib_request.Request(url)
  2399. try:
  2400. webpage = compat_urllib_request.urlopen(request).read()
  2401. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2402. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2403. return
  2404. self.report_extraction(url)
  2405. # Extract video URL
  2406. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2407. if mobj is None:
  2408. self._downloader.trouble(u'ERROR: unable to extract video url')
  2409. return
  2410. video_url = 'rtmpe://video.infoq.com/cfx/st/' + compat_urllib_parse.unquote(mobj.group(1).decode('base64'))
  2411. # Extract title
  2412. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2413. if mobj is None:
  2414. self._downloader.trouble(u'ERROR: unable to extract video title')
  2415. return
  2416. video_title = mobj.group(1).decode('utf-8')
  2417. # Extract description
  2418. video_description = u'No description available.'
  2419. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2420. if mobj is not None:
  2421. video_description = mobj.group(1).decode('utf-8')
  2422. video_filename = video_url.split('/')[-1]
  2423. video_id, extension = video_filename.split('.')
  2424. info = {
  2425. 'id': video_id,
  2426. 'url': video_url,
  2427. 'uploader': None,
  2428. 'upload_date': None,
  2429. 'title': video_title,
  2430. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2431. 'thumbnail': None,
  2432. 'description': video_description,
  2433. }
  2434. return [info]
  2435. class MixcloudIE(InfoExtractor):
  2436. """Information extractor for www.mixcloud.com"""
  2437. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2438. IE_NAME = u'mixcloud'
  2439. def __init__(self, downloader=None):
  2440. InfoExtractor.__init__(self, downloader)
  2441. def report_download_json(self, file_id):
  2442. """Report JSON download."""
  2443. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2444. def report_extraction(self, file_id):
  2445. """Report information extraction."""
  2446. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2447. def get_urls(self, jsonData, fmt, bitrate='best'):
  2448. """Get urls from 'audio_formats' section in json"""
  2449. file_url = None
  2450. try:
  2451. bitrate_list = jsonData[fmt]
  2452. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2453. bitrate = max(bitrate_list) # select highest
  2454. url_list = jsonData[fmt][bitrate]
  2455. except TypeError: # we have no bitrate info.
  2456. url_list = jsonData[fmt]
  2457. return url_list
  2458. def check_urls(self, url_list):
  2459. """Returns 1st active url from list"""
  2460. for url in url_list:
  2461. try:
  2462. compat_urllib_request.urlopen(url)
  2463. return url
  2464. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2465. url = None
  2466. return None
  2467. def _print_formats(self, formats):
  2468. print('Available formats:')
  2469. for fmt in formats.keys():
  2470. for b in formats[fmt]:
  2471. try:
  2472. ext = formats[fmt][b][0]
  2473. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2474. except TypeError: # we have no bitrate info
  2475. ext = formats[fmt][0]
  2476. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2477. break
  2478. def _real_extract(self, url):
  2479. mobj = re.match(self._VALID_URL, url)
  2480. if mobj is None:
  2481. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2482. return
  2483. # extract uploader & filename from url
  2484. uploader = mobj.group(1).decode('utf-8')
  2485. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2486. # construct API request
  2487. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2488. # retrieve .json file with links to files
  2489. request = compat_urllib_request.Request(file_url)
  2490. try:
  2491. self.report_download_json(file_url)
  2492. jsonData = compat_urllib_request.urlopen(request).read()
  2493. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2494. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % compat_str(err))
  2495. return
  2496. # parse JSON
  2497. json_data = json.loads(jsonData)
  2498. player_url = json_data['player_swf_url']
  2499. formats = dict(json_data['audio_formats'])
  2500. req_format = self._downloader.params.get('format', None)
  2501. bitrate = None
  2502. if self._downloader.params.get('listformats', None):
  2503. self._print_formats(formats)
  2504. return
  2505. if req_format is None or req_format == 'best':
  2506. for format_param in formats.keys():
  2507. url_list = self.get_urls(formats, format_param)
  2508. # check urls
  2509. file_url = self.check_urls(url_list)
  2510. if file_url is not None:
  2511. break # got it!
  2512. else:
  2513. if req_format not in formats.keys():
  2514. self._downloader.trouble(u'ERROR: format is not available')
  2515. return
  2516. url_list = self.get_urls(formats, req_format)
  2517. file_url = self.check_urls(url_list)
  2518. format_param = req_format
  2519. return [{
  2520. 'id': file_id.decode('utf-8'),
  2521. 'url': file_url.decode('utf-8'),
  2522. 'uploader': uploader.decode('utf-8'),
  2523. 'upload_date': None,
  2524. 'title': json_data['name'],
  2525. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2526. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2527. 'thumbnail': json_data['thumbnail_url'],
  2528. 'description': json_data['description'],
  2529. 'player_url': player_url.decode('utf-8'),
  2530. }]
  2531. class StanfordOpenClassroomIE(InfoExtractor):
  2532. """Information extractor for Stanford's Open ClassRoom"""
  2533. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2534. IE_NAME = u'stanfordoc'
  2535. def report_download_webpage(self, objid):
  2536. """Report information extraction."""
  2537. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2538. def report_extraction(self, video_id):
  2539. """Report information extraction."""
  2540. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2541. def _real_extract(self, url):
  2542. mobj = re.match(self._VALID_URL, url)
  2543. if mobj is None:
  2544. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2545. return
  2546. if mobj.group('course') and mobj.group('video'): # A specific video
  2547. course = mobj.group('course')
  2548. video = mobj.group('video')
  2549. info = {
  2550. 'id': course + '_' + video,
  2551. 'uploader': None,
  2552. 'upload_date': None,
  2553. }
  2554. self.report_extraction(info['id'])
  2555. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2556. xmlUrl = baseUrl + video + '.xml'
  2557. try:
  2558. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2559. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2560. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % compat_str(err))
  2561. return
  2562. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2563. try:
  2564. info['title'] = mdoc.findall('./title')[0].text
  2565. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2566. except IndexError:
  2567. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2568. return
  2569. info['ext'] = info['url'].rpartition('.')[2]
  2570. return [info]
  2571. elif mobj.group('course'): # A course page
  2572. course = mobj.group('course')
  2573. info = {
  2574. 'id': course,
  2575. 'type': 'playlist',
  2576. 'uploader': None,
  2577. 'upload_date': None,
  2578. }
  2579. self.report_download_webpage(info['id'])
  2580. try:
  2581. coursepage = compat_urllib_request.urlopen(url).read()
  2582. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2583. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2584. return
  2585. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2586. if m:
  2587. info['title'] = unescapeHTML(m.group(1))
  2588. else:
  2589. info['title'] = info['id']
  2590. m = re.search('<description>([^<]+)</description>', coursepage)
  2591. if m:
  2592. info['description'] = unescapeHTML(m.group(1))
  2593. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2594. info['list'] = [
  2595. {
  2596. 'type': 'reference',
  2597. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2598. }
  2599. for vpage in links]
  2600. results = []
  2601. for entry in info['list']:
  2602. assert entry['type'] == 'reference'
  2603. results += self.extract(entry['url'])
  2604. return results
  2605. else: # Root page
  2606. info = {
  2607. 'id': 'Stanford OpenClassroom',
  2608. 'type': 'playlist',
  2609. 'uploader': None,
  2610. 'upload_date': None,
  2611. }
  2612. self.report_download_webpage(info['id'])
  2613. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2614. try:
  2615. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2616. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2617. self._downloader.trouble(u'ERROR: unable to download course info page: ' + compat_str(err))
  2618. return
  2619. info['title'] = info['id']
  2620. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2621. info['list'] = [
  2622. {
  2623. 'type': 'reference',
  2624. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2625. }
  2626. for cpage in links]
  2627. results = []
  2628. for entry in info['list']:
  2629. assert entry['type'] == 'reference'
  2630. results += self.extract(entry['url'])
  2631. return results
  2632. class MTVIE(InfoExtractor):
  2633. """Information extractor for MTV.com"""
  2634. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2635. IE_NAME = u'mtv'
  2636. def report_webpage(self, video_id):
  2637. """Report information extraction."""
  2638. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2639. def report_extraction(self, video_id):
  2640. """Report information extraction."""
  2641. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2642. def _real_extract(self, url):
  2643. mobj = re.match(self._VALID_URL, url)
  2644. if mobj is None:
  2645. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2646. return
  2647. if not mobj.group('proto'):
  2648. url = 'http://' + url
  2649. video_id = mobj.group('videoid')
  2650. self.report_webpage(video_id)
  2651. request = compat_urllib_request.Request(url)
  2652. try:
  2653. webpage = 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 download video webpage: %s' % compat_str(err))
  2656. return
  2657. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2658. if mobj is None:
  2659. self._downloader.trouble(u'ERROR: unable to extract song name')
  2660. return
  2661. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2662. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2663. if mobj is None:
  2664. self._downloader.trouble(u'ERROR: unable to extract performer')
  2665. return
  2666. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2667. video_title = performer + ' - ' + song_name
  2668. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2669. if mobj is None:
  2670. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  2671. return
  2672. mtvn_uri = mobj.group(1)
  2673. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2674. if mobj is None:
  2675. self._downloader.trouble(u'ERROR: unable to extract content id')
  2676. return
  2677. content_id = mobj.group(1)
  2678. 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
  2679. self.report_extraction(video_id)
  2680. request = compat_urllib_request.Request(videogen_url)
  2681. try:
  2682. metadataXml = compat_urllib_request.urlopen(request).read()
  2683. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2684. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % compat_str(err))
  2685. return
  2686. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2687. renditions = mdoc.findall('.//rendition')
  2688. # For now, always pick the highest quality.
  2689. rendition = renditions[-1]
  2690. try:
  2691. _,_,ext = rendition.attrib['type'].partition('/')
  2692. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2693. video_url = rendition.find('./src').text
  2694. except KeyError:
  2695. self._downloader.trouble('Invalid rendition field.')
  2696. return
  2697. info = {
  2698. 'id': video_id,
  2699. 'url': video_url,
  2700. 'uploader': performer,
  2701. 'upload_date': None,
  2702. 'title': video_title,
  2703. 'ext': ext,
  2704. 'format': format,
  2705. }
  2706. return [info]
  2707. class YoukuIE(InfoExtractor):
  2708. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2709. IE_NAME = u'Youku'
  2710. def __init__(self, downloader=None):
  2711. InfoExtractor.__init__(self, downloader)
  2712. def report_download_webpage(self, file_id):
  2713. """Report webpage download."""
  2714. self._downloader.to_screen(u'[Youku] %s: Downloading webpage' % file_id)
  2715. def report_extraction(self, file_id):
  2716. """Report information extraction."""
  2717. self._downloader.to_screen(u'[Youku] %s: Extracting information' % file_id)
  2718. def _gen_sid(self):
  2719. nowTime = int(time.time() * 1000)
  2720. random1 = random.randint(1000,1998)
  2721. random2 = random.randint(1000,9999)
  2722. return "%d%d%d" %(nowTime,random1,random2)
  2723. def _get_file_ID_mix_string(self, seed):
  2724. mixed = []
  2725. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2726. seed = float(seed)
  2727. for i in range(len(source)):
  2728. seed = (seed * 211 + 30031 ) % 65536
  2729. index = math.floor(seed / 65536 * len(source) )
  2730. mixed.append(source[int(index)])
  2731. source.remove(source[int(index)])
  2732. #return ''.join(mixed)
  2733. return mixed
  2734. def _get_file_id(self, fileId, seed):
  2735. mixed = self._get_file_ID_mix_string(seed)
  2736. ids = fileId.split('*')
  2737. realId = []
  2738. for ch in ids:
  2739. if ch:
  2740. realId.append(mixed[int(ch)])
  2741. return ''.join(realId)
  2742. def _real_extract(self, url):
  2743. mobj = re.match(self._VALID_URL, url)
  2744. if mobj is None:
  2745. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2746. return
  2747. video_id = mobj.group('ID')
  2748. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2749. request = compat_urllib_request.Request(info_url, None, std_headers)
  2750. try:
  2751. self.report_download_webpage(video_id)
  2752. jsondata = compat_urllib_request.urlopen(request).read()
  2753. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2754. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2755. return
  2756. self.report_extraction(video_id)
  2757. try:
  2758. config = json.loads(jsondata)
  2759. video_title = config['data'][0]['title']
  2760. seed = config['data'][0]['seed']
  2761. format = self._downloader.params.get('format', None)
  2762. supported_format = config['data'][0]['streamfileids'].keys()
  2763. if format is None or format == 'best':
  2764. if 'hd2' in supported_format:
  2765. format = 'hd2'
  2766. else:
  2767. format = 'flv'
  2768. ext = u'flv'
  2769. elif format == 'worst':
  2770. format = 'mp4'
  2771. ext = u'mp4'
  2772. else:
  2773. format = 'flv'
  2774. ext = u'flv'
  2775. fileid = config['data'][0]['streamfileids'][format]
  2776. seg_number = len(config['data'][0]['segs'][format])
  2777. keys=[]
  2778. for i in xrange(seg_number):
  2779. keys.append(config['data'][0]['segs'][format][i]['k'])
  2780. #TODO check error
  2781. #youku only could be viewed from mainland china
  2782. except:
  2783. self._downloader.trouble(u'ERROR: unable to extract info section')
  2784. return
  2785. files_info=[]
  2786. sid = self._gen_sid()
  2787. fileid = self._get_file_id(fileid, seed)
  2788. #column 8,9 of fileid represent the segment number
  2789. #fileid[7:9] should be changed
  2790. for index, key in enumerate(keys):
  2791. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2792. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2793. info = {
  2794. 'id': '%s_part%02d' % (video_id, index),
  2795. 'url': download_url,
  2796. 'uploader': None,
  2797. 'upload_date': None,
  2798. 'title': video_title,
  2799. 'ext': ext,
  2800. }
  2801. files_info.append(info)
  2802. return files_info
  2803. class XNXXIE(InfoExtractor):
  2804. """Information extractor for xnxx.com"""
  2805. _VALID_URL = r'^http://video\.xnxx\.com/video([0-9]+)/(.*)'
  2806. IE_NAME = u'xnxx'
  2807. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2808. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2809. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2810. def report_webpage(self, video_id):
  2811. """Report information extraction"""
  2812. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2813. def report_extraction(self, video_id):
  2814. """Report information extraction"""
  2815. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2816. def _real_extract(self, url):
  2817. mobj = re.match(self._VALID_URL, url)
  2818. if mobj is None:
  2819. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2820. return
  2821. video_id = mobj.group(1).decode('utf-8')
  2822. self.report_webpage(video_id)
  2823. # Get webpage content
  2824. try:
  2825. webpage = compat_urllib_request.urlopen(url).read()
  2826. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2827. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % err)
  2828. return
  2829. result = re.search(self.VIDEO_URL_RE, webpage)
  2830. if result is None:
  2831. self._downloader.trouble(u'ERROR: unable to extract video url')
  2832. return
  2833. video_url = compat_urllib_parse.unquote(result.group(1).decode('utf-8'))
  2834. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2835. if result is None:
  2836. self._downloader.trouble(u'ERROR: unable to extract video title')
  2837. return
  2838. video_title = result.group(1).decode('utf-8')
  2839. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2840. if result is None:
  2841. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2842. return
  2843. video_thumbnail = result.group(1).decode('utf-8')
  2844. return [{
  2845. 'id': video_id,
  2846. 'url': video_url,
  2847. 'uploader': None,
  2848. 'upload_date': None,
  2849. 'title': video_title,
  2850. 'ext': 'flv',
  2851. 'thumbnail': video_thumbnail,
  2852. 'description': None,
  2853. }]
  2854. class GooglePlusIE(InfoExtractor):
  2855. """Information extractor for plus.google.com."""
  2856. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:\w+/)*?(\d+)/posts/(\w+)'
  2857. IE_NAME = u'plus.google'
  2858. def __init__(self, downloader=None):
  2859. InfoExtractor.__init__(self, downloader)
  2860. def report_extract_entry(self, url):
  2861. """Report downloading extry"""
  2862. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url.decode('utf-8'))
  2863. def report_date(self, upload_date):
  2864. """Report downloading extry"""
  2865. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2866. def report_uploader(self, uploader):
  2867. """Report downloading extry"""
  2868. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader.decode('utf-8'))
  2869. def report_title(self, video_title):
  2870. """Report downloading extry"""
  2871. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title.decode('utf-8'))
  2872. def report_extract_vid_page(self, video_page):
  2873. """Report information extraction."""
  2874. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page.decode('utf-8'))
  2875. def _real_extract(self, url):
  2876. # Extract id from URL
  2877. mobj = re.match(self._VALID_URL, url)
  2878. if mobj is None:
  2879. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  2880. return
  2881. post_url = mobj.group(0)
  2882. video_id = mobj.group(2)
  2883. video_extension = 'flv'
  2884. # Step 1, Retrieve post webpage to extract further information
  2885. self.report_extract_entry(post_url)
  2886. request = compat_urllib_request.Request(post_url)
  2887. try:
  2888. webpage = compat_urllib_request.urlopen(request).read()
  2889. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2890. self._downloader.trouble(u'ERROR: Unable to retrieve entry webpage: %s' % compat_str(err))
  2891. return
  2892. # Extract update date
  2893. upload_date = None
  2894. pattern = 'title="Timestamp">(.*?)</a>'
  2895. mobj = re.search(pattern, webpage)
  2896. if mobj:
  2897. upload_date = mobj.group(1)
  2898. # Convert timestring to a format suitable for filename
  2899. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2900. upload_date = upload_date.strftime('%Y%m%d')
  2901. self.report_date(upload_date)
  2902. # Extract uploader
  2903. uploader = None
  2904. pattern = r'rel\="author".*?>(.*?)</a>'
  2905. mobj = re.search(pattern, webpage)
  2906. if mobj:
  2907. uploader = mobj.group(1)
  2908. self.report_uploader(uploader)
  2909. # Extract title
  2910. # Get the first line for title
  2911. video_title = u'NA'
  2912. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2913. mobj = re.search(pattern, webpage)
  2914. if mobj:
  2915. video_title = mobj.group(1)
  2916. self.report_title(video_title)
  2917. # Step 2, Stimulate clicking the image box to launch video
  2918. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2919. mobj = re.search(pattern, webpage)
  2920. if mobj is None:
  2921. self._downloader.trouble(u'ERROR: unable to extract video page URL')
  2922. video_page = mobj.group(1)
  2923. request = compat_urllib_request.Request(video_page)
  2924. try:
  2925. webpage = compat_urllib_request.urlopen(request).read()
  2926. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2927. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % compat_str(err))
  2928. return
  2929. self.report_extract_vid_page(video_page)
  2930. # Extract video links on video page
  2931. """Extract video links of all sizes"""
  2932. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2933. mobj = re.findall(pattern, webpage)
  2934. if len(mobj) == 0:
  2935. self._downloader.trouble(u'ERROR: unable to extract video links')
  2936. # Sort in resolution
  2937. links = sorted(mobj)
  2938. # Choose the lowest of the sort, i.e. highest resolution
  2939. video_url = links[-1]
  2940. # Only get the url. The resolution part in the tuple has no use anymore
  2941. video_url = video_url[-1]
  2942. # Treat escaped \u0026 style hex
  2943. video_url = unicode(video_url, "unicode_escape")
  2944. return [{
  2945. 'id': video_id.decode('utf-8'),
  2946. 'url': video_url,
  2947. 'uploader': uploader.decode('utf-8'),
  2948. 'upload_date': upload_date.decode('utf-8'),
  2949. 'title': video_title.decode('utf-8'),
  2950. 'ext': video_extension.decode('utf-8'),
  2951. }]