common.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. from __future__ import unicode_literals
  2. import base64
  3. import datetime
  4. import hashlib
  5. import json
  6. import netrc
  7. import os
  8. import re
  9. import socket
  10. import sys
  11. import time
  12. import xml.etree.ElementTree
  13. from ..utils import (
  14. compat_http_client,
  15. compat_urllib_error,
  16. compat_urllib_parse_urlparse,
  17. compat_urlparse,
  18. compat_str,
  19. clean_html,
  20. compiled_regex_type,
  21. ExtractorError,
  22. int_or_none,
  23. RegexNotFoundError,
  24. sanitize_filename,
  25. unescapeHTML,
  26. )
  27. _NO_DEFAULT = object()
  28. class InfoExtractor(object):
  29. """Information Extractor class.
  30. Information extractors are the classes that, given a URL, extract
  31. information about the video (or videos) the URL refers to. This
  32. information includes the real video URL, the video title, author and
  33. others. The information is stored in a dictionary which is then
  34. passed to the FileDownloader. The FileDownloader processes this
  35. information possibly downloading the video to the file system, among
  36. other possible outcomes.
  37. The dictionaries must include the following fields:
  38. id: Video identifier.
  39. title: Video title, unescaped.
  40. Additionally, it must contain either a formats entry or a url one:
  41. formats: A list of dictionaries for each format available, ordered
  42. from worst to best quality.
  43. Potential fields:
  44. * url Mandatory. The URL of the video file
  45. * ext Will be calculated from url if missing
  46. * format A human-readable description of the format
  47. ("mp4 container with h264/opus").
  48. Calculated from the format_id, width, height.
  49. and format_note fields if missing.
  50. * format_id A short description of the format
  51. ("mp4_h264_opus" or "19").
  52. Technically optional, but strongly recommended.
  53. * format_note Additional info about the format
  54. ("3D" or "DASH video")
  55. * width Width of the video, if known
  56. * height Height of the video, if known
  57. * resolution Textual description of width and height
  58. * tbr Average bitrate of audio and video in KBit/s
  59. * abr Average audio bitrate in KBit/s
  60. * acodec Name of the audio codec in use
  61. * asr Audio sampling rate in Hertz
  62. * vbr Average video bitrate in KBit/s
  63. * vcodec Name of the video codec in use
  64. * container Name of the container format
  65. * filesize The number of bytes, if known in advance
  66. * filesize_approx An estimate for the number of bytes
  67. * player_url SWF Player URL (used for rtmpdump).
  68. * protocol The protocol that will be used for the actual
  69. download, lower-case.
  70. "http", "https", "rtsp", "rtmp", "m3u8" or so.
  71. * preference Order number of this format. If this field is
  72. present and not None, the formats get sorted
  73. by this field, regardless of all other values.
  74. -1 for default (order by other properties),
  75. -2 or smaller for less than default.
  76. * quality Order number of the video quality of this
  77. format, irrespective of the file format.
  78. -1 for default (order by other properties),
  79. -2 or smaller for less than default.
  80. * http_referer HTTP Referer header value to set.
  81. * http_method HTTP method to use for the download.
  82. * http_headers A dictionary of additional HTTP headers
  83. to add to the request.
  84. * http_post_data Additional data to send with a POST
  85. request.
  86. url: Final video URL.
  87. ext: Video filename extension.
  88. format: The video format, defaults to ext (used for --get-format)
  89. player_url: SWF Player URL (used for rtmpdump).
  90. The following fields are optional:
  91. display_id An alternative identifier for the video, not necessarily
  92. unique, but available before title. Typically, id is
  93. something like "4234987", title "Dancing naked mole rats",
  94. and display_id "dancing-naked-mole-rats"
  95. thumbnails: A list of dictionaries, with the following entries:
  96. * "url"
  97. * "width" (optional, int)
  98. * "height" (optional, int)
  99. * "resolution" (optional, string "{width}x{height"},
  100. deprecated)
  101. thumbnail: Full URL to a video thumbnail image.
  102. description: One-line video description.
  103. uploader: Full name of the video uploader.
  104. timestamp: UNIX timestamp of the moment the video became available.
  105. upload_date: Video upload date (YYYYMMDD).
  106. If not explicitly set, calculated from timestamp.
  107. uploader_id: Nickname or id of the video uploader.
  108. location: Physical location where the video was filmed.
  109. subtitles: The subtitle file contents as a dictionary in the format
  110. {language: subtitles}.
  111. duration: Length of the video in seconds, as an integer.
  112. view_count: How many users have watched the video on the platform.
  113. like_count: Number of positive ratings of the video
  114. dislike_count: Number of negative ratings of the video
  115. comment_count: Number of comments on the video
  116. age_limit: Age restriction for the video, as an integer (years)
  117. webpage_url: The url to the video webpage, if given to youtube-dl it
  118. should allow to get the same result again. (It will be set
  119. by YoutubeDL if it's missing)
  120. categories: A list of categories that the video falls in, for example
  121. ["Sports", "Berlin"]
  122. is_live: True, False, or None (=unknown). Whether this video is a
  123. live stream that goes on instead of a fixed-length video.
  124. Unless mentioned otherwise, the fields should be Unicode strings.
  125. Subclasses of this one should re-define the _real_initialize() and
  126. _real_extract() methods and define a _VALID_URL regexp.
  127. Probably, they should also be added to the list of extractors.
  128. Finally, the _WORKING attribute should be set to False for broken IEs
  129. in order to warn the users and skip the tests.
  130. """
  131. _ready = False
  132. _downloader = None
  133. _WORKING = True
  134. def __init__(self, downloader=None):
  135. """Constructor. Receives an optional downloader."""
  136. self._ready = False
  137. self.set_downloader(downloader)
  138. @classmethod
  139. def suitable(cls, url):
  140. """Receives a URL and returns True if suitable for this IE."""
  141. # This does not use has/getattr intentionally - we want to know whether
  142. # we have cached the regexp for *this* class, whereas getattr would also
  143. # match the superclass
  144. if '_VALID_URL_RE' not in cls.__dict__:
  145. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  146. return cls._VALID_URL_RE.match(url) is not None
  147. @classmethod
  148. def working(cls):
  149. """Getter method for _WORKING."""
  150. return cls._WORKING
  151. def initialize(self):
  152. """Initializes an instance (authentication, etc)."""
  153. if not self._ready:
  154. self._real_initialize()
  155. self._ready = True
  156. def extract(self, url):
  157. """Extracts URL information and returns it in list of dicts."""
  158. self.initialize()
  159. return self._real_extract(url)
  160. def set_downloader(self, downloader):
  161. """Sets the downloader for this IE."""
  162. self._downloader = downloader
  163. def _real_initialize(self):
  164. """Real initialization process. Redefine in subclasses."""
  165. pass
  166. def _real_extract(self, url):
  167. """Real extraction process. Redefine in subclasses."""
  168. pass
  169. @classmethod
  170. def ie_key(cls):
  171. """A string for getting the InfoExtractor with get_info_extractor"""
  172. return cls.__name__[:-2]
  173. @property
  174. def IE_NAME(self):
  175. return type(self).__name__[:-2]
  176. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  177. """ Returns the response handle """
  178. if note is None:
  179. self.report_download_webpage(video_id)
  180. elif note is not False:
  181. if video_id is None:
  182. self.to_screen('%s' % (note,))
  183. else:
  184. self.to_screen('%s: %s' % (video_id, note))
  185. try:
  186. return self._downloader.urlopen(url_or_request)
  187. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  188. if errnote is False:
  189. return False
  190. if errnote is None:
  191. errnote = 'Unable to download webpage'
  192. errmsg = '%s: %s' % (errnote, compat_str(err))
  193. if fatal:
  194. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  195. else:
  196. self._downloader.report_warning(errmsg)
  197. return False
  198. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  199. """ Returns a tuple (page content as string, URL handle) """
  200. # Strip hashes from the URL (#1038)
  201. if isinstance(url_or_request, (compat_str, str)):
  202. url_or_request = url_or_request.partition('#')[0]
  203. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal)
  204. if urlh is False:
  205. assert not fatal
  206. return False
  207. content_type = urlh.headers.get('Content-Type', '')
  208. webpage_bytes = urlh.read()
  209. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  210. if m:
  211. encoding = m.group(1)
  212. else:
  213. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  214. webpage_bytes[:1024])
  215. if m:
  216. encoding = m.group(1).decode('ascii')
  217. elif webpage_bytes.startswith(b'\xff\xfe'):
  218. encoding = 'utf-16'
  219. else:
  220. encoding = 'utf-8'
  221. if self._downloader.params.get('dump_intermediate_pages', False):
  222. try:
  223. url = url_or_request.get_full_url()
  224. except AttributeError:
  225. url = url_or_request
  226. self.to_screen('Dumping request to ' + url)
  227. dump = base64.b64encode(webpage_bytes).decode('ascii')
  228. self._downloader.to_screen(dump)
  229. if self._downloader.params.get('write_pages', False):
  230. try:
  231. url = url_or_request.get_full_url()
  232. except AttributeError:
  233. url = url_or_request
  234. basen = '%s_%s' % (video_id, url)
  235. if len(basen) > 240:
  236. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  237. basen = basen[:240 - len(h)] + h
  238. raw_filename = basen + '.dump'
  239. filename = sanitize_filename(raw_filename, restricted=True)
  240. self.to_screen('Saving request to ' + filename)
  241. with open(filename, 'wb') as outf:
  242. outf.write(webpage_bytes)
  243. try:
  244. content = webpage_bytes.decode(encoding, 'replace')
  245. except LookupError:
  246. content = webpage_bytes.decode('utf-8', 'replace')
  247. if ('<title>Access to this site is blocked</title>' in content and
  248. 'Websense' in content[:512]):
  249. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  250. blocked_iframe = self._html_search_regex(
  251. r'<iframe src="([^"]+)"', content,
  252. 'Websense information URL', default=None)
  253. if blocked_iframe:
  254. msg += ' Visit %s for more details' % blocked_iframe
  255. raise ExtractorError(msg, expected=True)
  256. return (content, urlh)
  257. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True):
  258. """ Returns the data of the page as a string """
  259. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal)
  260. if res is False:
  261. return res
  262. else:
  263. content, _ = res
  264. return content
  265. def _download_xml(self, url_or_request, video_id,
  266. note='Downloading XML', errnote='Unable to download XML',
  267. transform_source=None, fatal=True):
  268. """Return the xml as an xml.etree.ElementTree.Element"""
  269. xml_string = self._download_webpage(
  270. url_or_request, video_id, note, errnote, fatal=fatal)
  271. if xml_string is False:
  272. return xml_string
  273. if transform_source:
  274. xml_string = transform_source(xml_string)
  275. return xml.etree.ElementTree.fromstring(xml_string.encode('utf-8'))
  276. def _download_json(self, url_or_request, video_id,
  277. note='Downloading JSON metadata',
  278. errnote='Unable to download JSON metadata',
  279. transform_source=None,
  280. fatal=True):
  281. json_string = self._download_webpage(
  282. url_or_request, video_id, note, errnote, fatal=fatal)
  283. if (not fatal) and json_string is False:
  284. return None
  285. if transform_source:
  286. json_string = transform_source(json_string)
  287. try:
  288. return json.loads(json_string)
  289. except ValueError as ve:
  290. raise ExtractorError('Failed to download JSON', cause=ve)
  291. def report_warning(self, msg, video_id=None):
  292. idstr = '' if video_id is None else '%s: ' % video_id
  293. self._downloader.report_warning(
  294. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  295. def to_screen(self, msg):
  296. """Print msg to screen, prefixing it with '[ie_name]'"""
  297. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  298. def report_extraction(self, id_or_name):
  299. """Report information extraction."""
  300. self.to_screen('%s: Extracting information' % id_or_name)
  301. def report_download_webpage(self, video_id):
  302. """Report webpage download."""
  303. self.to_screen('%s: Downloading webpage' % video_id)
  304. def report_age_confirmation(self):
  305. """Report attempt to confirm age."""
  306. self.to_screen('Confirming age')
  307. def report_login(self):
  308. """Report attempt to log in."""
  309. self.to_screen('Logging in')
  310. #Methods for following #608
  311. @staticmethod
  312. def url_result(url, ie=None, video_id=None):
  313. """Returns a url that points to a page that should be processed"""
  314. #TODO: ie should be the class used for getting the info
  315. video_info = {'_type': 'url',
  316. 'url': url,
  317. 'ie_key': ie}
  318. if video_id is not None:
  319. video_info['id'] = video_id
  320. return video_info
  321. @staticmethod
  322. def playlist_result(entries, playlist_id=None, playlist_title=None):
  323. """Returns a playlist"""
  324. video_info = {'_type': 'playlist',
  325. 'entries': entries}
  326. if playlist_id:
  327. video_info['id'] = playlist_id
  328. if playlist_title:
  329. video_info['title'] = playlist_title
  330. return video_info
  331. def _search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
  332. """
  333. Perform a regex search on the given string, using a single or a list of
  334. patterns returning the first matching group.
  335. In case of failure return a default value or raise a WARNING or a
  336. RegexNotFoundError, depending on fatal, specifying the field name.
  337. """
  338. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  339. mobj = re.search(pattern, string, flags)
  340. else:
  341. for p in pattern:
  342. mobj = re.search(p, string, flags)
  343. if mobj:
  344. break
  345. if os.name != 'nt' and sys.stderr.isatty():
  346. _name = '\033[0;34m%s\033[0m' % name
  347. else:
  348. _name = name
  349. if mobj:
  350. # return the first matching group
  351. return next(g for g in mobj.groups() if g is not None)
  352. elif default is not _NO_DEFAULT:
  353. return default
  354. elif fatal:
  355. raise RegexNotFoundError('Unable to extract %s' % _name)
  356. else:
  357. self._downloader.report_warning('unable to extract %s; '
  358. 'please report this issue on http://yt-dl.org/bug' % _name)
  359. return None
  360. def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0):
  361. """
  362. Like _search_regex, but strips HTML tags and unescapes entities.
  363. """
  364. res = self._search_regex(pattern, string, name, default, fatal, flags)
  365. if res:
  366. return clean_html(res).strip()
  367. else:
  368. return res
  369. def _get_login_info(self):
  370. """
  371. Get the the login info as (username, password)
  372. It will look in the netrc file using the _NETRC_MACHINE value
  373. If there's no info available, return (None, None)
  374. """
  375. if self._downloader is None:
  376. return (None, None)
  377. username = None
  378. password = None
  379. downloader_params = self._downloader.params
  380. # Attempt to use provided username and password or .netrc data
  381. if downloader_params.get('username', None) is not None:
  382. username = downloader_params['username']
  383. password = downloader_params['password']
  384. elif downloader_params.get('usenetrc', False):
  385. try:
  386. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  387. if info is not None:
  388. username = info[0]
  389. password = info[2]
  390. else:
  391. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  392. except (IOError, netrc.NetrcParseError) as err:
  393. self._downloader.report_warning('parsing .netrc: %s' % compat_str(err))
  394. return (username, password)
  395. def _get_tfa_info(self):
  396. """
  397. Get the two-factor authentication info
  398. TODO - asking the user will be required for sms/phone verify
  399. currently just uses the command line option
  400. If there's no info available, return None
  401. """
  402. if self._downloader is None:
  403. return None
  404. downloader_params = self._downloader.params
  405. if downloader_params.get('twofactor', None) is not None:
  406. return downloader_params['twofactor']
  407. return None
  408. # Helper functions for extracting OpenGraph info
  409. @staticmethod
  410. def _og_regexes(prop):
  411. content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')'
  412. property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop)
  413. template = r'<meta[^>]+?%s[^>]+?%s'
  414. return [
  415. template % (property_re, content_re),
  416. template % (content_re, property_re),
  417. ]
  418. def _og_search_property(self, prop, html, name=None, **kargs):
  419. if name is None:
  420. name = 'OpenGraph %s' % prop
  421. escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs)
  422. if escaped is None:
  423. return None
  424. return unescapeHTML(escaped)
  425. def _og_search_thumbnail(self, html, **kargs):
  426. return self._og_search_property('image', html, 'thumbnail url', fatal=False, **kargs)
  427. def _og_search_description(self, html, **kargs):
  428. return self._og_search_property('description', html, fatal=False, **kargs)
  429. def _og_search_title(self, html, **kargs):
  430. return self._og_search_property('title', html, **kargs)
  431. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  432. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  433. if secure:
  434. regexes = self._og_regexes('video:secure_url') + regexes
  435. return self._html_search_regex(regexes, html, name, **kargs)
  436. def _og_search_url(self, html, **kargs):
  437. return self._og_search_property('url', html, **kargs)
  438. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  439. if display_name is None:
  440. display_name = name
  441. return self._html_search_regex(
  442. r'''(?ix)<meta
  443. (?=[^>]+(?:itemprop|name|property)=["\']?%s["\']?)
  444. [^>]+content=["\']([^"\']+)["\']''' % re.escape(name),
  445. html, display_name, fatal=fatal, **kwargs)
  446. def _dc_search_uploader(self, html):
  447. return self._html_search_meta('dc.creator', html, 'uploader')
  448. def _rta_search(self, html):
  449. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  450. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  451. r' content="RTA-5042-1996-1400-1577-RTA"',
  452. html):
  453. return 18
  454. return 0
  455. def _media_rating_search(self, html):
  456. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  457. rating = self._html_search_meta('rating', html)
  458. if not rating:
  459. return None
  460. RATING_TABLE = {
  461. 'safe for kids': 0,
  462. 'general': 8,
  463. '14 years': 14,
  464. 'mature': 17,
  465. 'restricted': 19,
  466. }
  467. return RATING_TABLE.get(rating.lower(), None)
  468. def _twitter_search_player(self, html):
  469. return self._html_search_meta('twitter:player', html,
  470. 'twitter card player')
  471. def _sort_formats(self, formats):
  472. if not formats:
  473. raise ExtractorError('No video formats found')
  474. def _formats_key(f):
  475. # TODO remove the following workaround
  476. from ..utils import determine_ext
  477. if not f.get('ext') and 'url' in f:
  478. f['ext'] = determine_ext(f['url'])
  479. preference = f.get('preference')
  480. if preference is None:
  481. proto = f.get('protocol')
  482. if proto is None:
  483. proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme
  484. preference = 0 if proto in ['http', 'https'] else -0.1
  485. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  486. preference -= 0.5
  487. if f.get('vcodec') == 'none': # audio only
  488. if self._downloader.params.get('prefer_free_formats'):
  489. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  490. else:
  491. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  492. ext_preference = 0
  493. try:
  494. audio_ext_preference = ORDER.index(f['ext'])
  495. except ValueError:
  496. audio_ext_preference = -1
  497. else:
  498. if self._downloader.params.get('prefer_free_formats'):
  499. ORDER = ['flv', 'mp4', 'webm']
  500. else:
  501. ORDER = ['webm', 'flv', 'mp4']
  502. try:
  503. ext_preference = ORDER.index(f['ext'])
  504. except ValueError:
  505. ext_preference = -1
  506. audio_ext_preference = 0
  507. return (
  508. preference,
  509. f.get('quality') if f.get('quality') is not None else -1,
  510. f.get('height') if f.get('height') is not None else -1,
  511. f.get('width') if f.get('width') is not None else -1,
  512. ext_preference,
  513. f.get('tbr') if f.get('tbr') is not None else -1,
  514. f.get('vbr') if f.get('vbr') is not None else -1,
  515. f.get('abr') if f.get('abr') is not None else -1,
  516. audio_ext_preference,
  517. f.get('filesize') if f.get('filesize') is not None else -1,
  518. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  519. f.get('format_id'),
  520. )
  521. formats.sort(key=_formats_key)
  522. def http_scheme(self):
  523. """ Either "https:" or "https:", depending on the user's preferences """
  524. return (
  525. 'http:'
  526. if self._downloader.params.get('prefer_insecure', False)
  527. else 'https:')
  528. def _proto_relative_url(self, url, scheme=None):
  529. if url is None:
  530. return url
  531. if url.startswith('//'):
  532. if scheme is None:
  533. scheme = self.http_scheme()
  534. return scheme + url
  535. else:
  536. return url
  537. def _sleep(self, timeout, video_id, msg_template=None):
  538. if msg_template is None:
  539. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  540. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  541. self.to_screen(msg)
  542. time.sleep(timeout)
  543. def _extract_f4m_formats(self, manifest_url, video_id):
  544. manifest = self._download_xml(
  545. manifest_url, video_id, 'Downloading f4m manifest',
  546. 'Unable to download f4m manifest')
  547. formats = []
  548. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  549. for i, media_el in enumerate(media_nodes):
  550. tbr = int_or_none(media_el.attrib.get('bitrate'))
  551. format_id = 'f4m-%d' % (i if tbr is None else tbr)
  552. formats.append({
  553. 'format_id': format_id,
  554. 'url': manifest_url,
  555. 'ext': 'flv',
  556. 'tbr': tbr,
  557. 'width': int_or_none(media_el.attrib.get('width')),
  558. 'height': int_or_none(media_el.attrib.get('height')),
  559. })
  560. self._sort_formats(formats)
  561. return formats
  562. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  563. entry_protocol='m3u8', preference=None):
  564. formats = [{
  565. 'format_id': 'm3u8-meta',
  566. 'url': m3u8_url,
  567. 'ext': ext,
  568. 'protocol': 'm3u8',
  569. 'preference': -1,
  570. 'resolution': 'multiple',
  571. 'format_note': 'Quality selection URL',
  572. }]
  573. format_url = lambda u: (
  574. u
  575. if re.match(r'^https?://', u)
  576. else compat_urlparse.urljoin(m3u8_url, u))
  577. m3u8_doc = self._download_webpage(m3u8_url, video_id)
  578. last_info = None
  579. kv_rex = re.compile(
  580. r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)')
  581. for line in m3u8_doc.splitlines():
  582. if line.startswith('#EXT-X-STREAM-INF:'):
  583. last_info = {}
  584. for m in kv_rex.finditer(line):
  585. v = m.group('val')
  586. if v.startswith('"'):
  587. v = v[1:-1]
  588. last_info[m.group('key')] = v
  589. elif line.startswith('#') or not line.strip():
  590. continue
  591. else:
  592. if last_info is None:
  593. formats.append({'url': format_url(line)})
  594. continue
  595. tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000)
  596. f = {
  597. 'format_id': 'm3u8-%d' % (tbr if tbr else len(formats)),
  598. 'url': format_url(line.strip()),
  599. 'tbr': tbr,
  600. 'ext': ext,
  601. 'protocol': entry_protocol,
  602. 'preference': preference,
  603. }
  604. codecs = last_info.get('CODECS')
  605. if codecs:
  606. # TODO: looks like video codec is not always necessarily goes first
  607. va_codecs = codecs.split(',')
  608. if va_codecs[0]:
  609. f['vcodec'] = va_codecs[0].partition('.')[0]
  610. if len(va_codecs) > 1 and va_codecs[1]:
  611. f['acodec'] = va_codecs[1].partition('.')[0]
  612. resolution = last_info.get('RESOLUTION')
  613. if resolution:
  614. width_str, height_str = resolution.split('x')
  615. f['width'] = int(width_str)
  616. f['height'] = int(height_str)
  617. formats.append(f)
  618. last_info = {}
  619. self._sort_formats(formats)
  620. return formats
  621. def _live_title(self, name):
  622. """ Generate the title for a live video """
  623. now = datetime.datetime.now()
  624. now_str = now.strftime("%Y-%m-%d %H:%M")
  625. return name + ' ' + now_str
  626. class SearchInfoExtractor(InfoExtractor):
  627. """
  628. Base class for paged search queries extractors.
  629. They accept urls in the format _SEARCH_KEY(|all|[0-9]):{query}
  630. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  631. """
  632. @classmethod
  633. def _make_valid_url(cls):
  634. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  635. @classmethod
  636. def suitable(cls, url):
  637. return re.match(cls._make_valid_url(), url) is not None
  638. def _real_extract(self, query):
  639. mobj = re.match(self._make_valid_url(), query)
  640. if mobj is None:
  641. raise ExtractorError('Invalid search query "%s"' % query)
  642. prefix = mobj.group('prefix')
  643. query = mobj.group('query')
  644. if prefix == '':
  645. return self._get_n_results(query, 1)
  646. elif prefix == 'all':
  647. return self._get_n_results(query, self._MAX_RESULTS)
  648. else:
  649. n = int(prefix)
  650. if n <= 0:
  651. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  652. elif n > self._MAX_RESULTS:
  653. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  654. n = self._MAX_RESULTS
  655. return self._get_n_results(query, n)
  656. def _get_n_results(self, query, n):
  657. """Get a specified number of results for a query"""
  658. raise NotImplementedError("This method must be implemented by subclasses")
  659. @property
  660. def SEARCH_KEY(self):
  661. return self._SEARCH_KEY