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.

1528 lines
46 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import calendar
  5. import codecs
  6. import contextlib
  7. import ctypes
  8. import datetime
  9. import email.utils
  10. import errno
  11. import gzip
  12. import itertools
  13. import io
  14. import json
  15. import locale
  16. import math
  17. import os
  18. import pipes
  19. import platform
  20. import re
  21. import ssl
  22. import socket
  23. import struct
  24. import subprocess
  25. import sys
  26. import tempfile
  27. import traceback
  28. import xml.etree.ElementTree
  29. import zlib
  30. from .compat import (
  31. compat_chr,
  32. compat_getenv,
  33. compat_html_entities,
  34. compat_parse_qs,
  35. compat_str,
  36. compat_urllib_error,
  37. compat_urllib_parse,
  38. compat_urllib_parse_urlparse,
  39. compat_urllib_request,
  40. compat_urlparse,
  41. shlex_quote,
  42. )
  43. # This is not clearly defined otherwise
  44. compiled_regex_type = type(re.compile(''))
  45. std_headers = {
  46. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0 (Chrome)',
  47. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  48. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  49. 'Accept-Encoding': 'gzip, deflate',
  50. 'Accept-Language': 'en-us,en;q=0.5',
  51. }
  52. def preferredencoding():
  53. """Get preferred encoding.
  54. Returns the best encoding scheme for the system, based on
  55. locale.getpreferredencoding() and some further tweaks.
  56. """
  57. try:
  58. pref = locale.getpreferredencoding()
  59. 'TEST'.encode(pref)
  60. except:
  61. pref = 'UTF-8'
  62. return pref
  63. def write_json_file(obj, fn):
  64. """ Encode obj as JSON and write it to fn, atomically if possible """
  65. fn = encodeFilename(fn)
  66. if sys.version_info < (3, 0) and sys.platform != 'win32':
  67. encoding = get_filesystem_encoding()
  68. # os.path.basename returns a bytes object, but NamedTemporaryFile
  69. # will fail if the filename contains non ascii characters unless we
  70. # use a unicode object
  71. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  72. # the same for os.path.dirname
  73. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  74. else:
  75. path_basename = os.path.basename
  76. path_dirname = os.path.dirname
  77. args = {
  78. 'suffix': '.tmp',
  79. 'prefix': path_basename(fn) + '.',
  80. 'dir': path_dirname(fn),
  81. 'delete': False,
  82. }
  83. # In Python 2.x, json.dump expects a bytestream.
  84. # In Python 3.x, it writes to a character stream
  85. if sys.version_info < (3, 0):
  86. args['mode'] = 'wb'
  87. else:
  88. args.update({
  89. 'mode': 'w',
  90. 'encoding': 'utf-8',
  91. })
  92. tf = tempfile.NamedTemporaryFile(**args)
  93. try:
  94. with tf:
  95. json.dump(obj, tf)
  96. if sys.platform == 'win32':
  97. # Need to remove existing file on Windows, else os.rename raises
  98. # WindowsError or FileExistsError.
  99. try:
  100. os.unlink(fn)
  101. except OSError:
  102. pass
  103. os.rename(tf.name, fn)
  104. except:
  105. try:
  106. os.remove(tf.name)
  107. except OSError:
  108. pass
  109. raise
  110. if sys.version_info >= (2, 7):
  111. def find_xpath_attr(node, xpath, key, val):
  112. """ Find the xpath xpath[@key=val] """
  113. assert re.match(r'^[a-zA-Z-]+$', key)
  114. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  115. expr = xpath + "[@%s='%s']" % (key, val)
  116. return node.find(expr)
  117. else:
  118. def find_xpath_attr(node, xpath, key, val):
  119. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  120. # .//node does not match if a node is a direct child of . !
  121. if isinstance(xpath, unicode):
  122. xpath = xpath.encode('ascii')
  123. for f in node.findall(xpath):
  124. if f.attrib.get(key) == val:
  125. return f
  126. return None
  127. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  128. # the namespace parameter
  129. def xpath_with_ns(path, ns_map):
  130. components = [c.split(':') for c in path.split('/')]
  131. replaced = []
  132. for c in components:
  133. if len(c) == 1:
  134. replaced.append(c[0])
  135. else:
  136. ns, tag = c
  137. replaced.append('{%s}%s' % (ns_map[ns], tag))
  138. return '/'.join(replaced)
  139. def xpath_text(node, xpath, name=None, fatal=False):
  140. if sys.version_info < (2, 7): # Crazy 2.6
  141. xpath = xpath.encode('ascii')
  142. n = node.find(xpath)
  143. if n is None:
  144. if fatal:
  145. name = xpath if name is None else name
  146. raise ExtractorError('Could not find XML element %s' % name)
  147. else:
  148. return None
  149. return n.text
  150. def get_element_by_id(id, html):
  151. """Return the content of the tag with the specified ID in the passed HTML document"""
  152. return get_element_by_attribute("id", id, html)
  153. def get_element_by_attribute(attribute, value, html):
  154. """Return the content of the tag with the specified attribute in the passed HTML document"""
  155. m = re.search(r'''(?xs)
  156. <([a-zA-Z0-9:._-]+)
  157. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  158. \s+%s=['"]?%s['"]?
  159. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  160. \s*>
  161. (?P<content>.*?)
  162. </\1>
  163. ''' % (re.escape(attribute), re.escape(value)), html)
  164. if not m:
  165. return None
  166. res = m.group('content')
  167. if res.startswith('"') or res.startswith("'"):
  168. res = res[1:-1]
  169. return unescapeHTML(res)
  170. def clean_html(html):
  171. """Clean an HTML snippet into a readable string"""
  172. # Newline vs <br />
  173. html = html.replace('\n', ' ')
  174. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  175. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  176. # Strip html tags
  177. html = re.sub('<.*?>', '', html)
  178. # Replace html entities
  179. html = unescapeHTML(html)
  180. return html.strip()
  181. def sanitize_open(filename, open_mode):
  182. """Try to open the given filename, and slightly tweak it if this fails.
  183. Attempts to open the given filename. If this fails, it tries to change
  184. the filename slightly, step by step, until it's either able to open it
  185. or it fails and raises a final exception, like the standard open()
  186. function.
  187. It returns the tuple (stream, definitive_file_name).
  188. """
  189. try:
  190. if filename == '-':
  191. if sys.platform == 'win32':
  192. import msvcrt
  193. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  194. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  195. stream = open(encodeFilename(filename), open_mode)
  196. return (stream, filename)
  197. except (IOError, OSError) as err:
  198. if err.errno in (errno.EACCES,):
  199. raise
  200. # In case of error, try to remove win32 forbidden chars
  201. alt_filename = os.path.join(
  202. re.sub('[/<>:"\\|\\\\?\\*]', '#', path_part)
  203. for path_part in os.path.split(filename)
  204. )
  205. if alt_filename == filename:
  206. raise
  207. else:
  208. # An exception here should be caught in the caller
  209. stream = open(encodeFilename(filename), open_mode)
  210. return (stream, alt_filename)
  211. def timeconvert(timestr):
  212. """Convert RFC 2822 defined time string into system timestamp"""
  213. timestamp = None
  214. timetuple = email.utils.parsedate_tz(timestr)
  215. if timetuple is not None:
  216. timestamp = email.utils.mktime_tz(timetuple)
  217. return timestamp
  218. def sanitize_filename(s, restricted=False, is_id=False):
  219. """Sanitizes a string so it could be used as part of a filename.
  220. If restricted is set, use a stricter subset of allowed characters.
  221. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  222. """
  223. def replace_insane(char):
  224. if char == '?' or ord(char) < 32 or ord(char) == 127:
  225. return ''
  226. elif char == '"':
  227. return '' if restricted else '\''
  228. elif char == ':':
  229. return '_-' if restricted else ' -'
  230. elif char in '\\/|*<>':
  231. return '_'
  232. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  233. return '_'
  234. if restricted and ord(char) > 127:
  235. return '_'
  236. return char
  237. result = ''.join(map(replace_insane, s))
  238. if not is_id:
  239. while '__' in result:
  240. result = result.replace('__', '_')
  241. result = result.strip('_')
  242. # Common case of "Foreign band name - English song title"
  243. if restricted and result.startswith('-_'):
  244. result = result[2:]
  245. if not result:
  246. result = '_'
  247. return result
  248. def orderedSet(iterable):
  249. """ Remove all duplicates from the input iterable """
  250. res = []
  251. for el in iterable:
  252. if el not in res:
  253. res.append(el)
  254. return res
  255. def _htmlentity_transform(entity):
  256. """Transforms an HTML entity to a character."""
  257. # Known non-numeric HTML entity
  258. if entity in compat_html_entities.name2codepoint:
  259. return compat_chr(compat_html_entities.name2codepoint[entity])
  260. mobj = re.match(r'#(x?[0-9]+)', entity)
  261. if mobj is not None:
  262. numstr = mobj.group(1)
  263. if numstr.startswith('x'):
  264. base = 16
  265. numstr = '0%s' % numstr
  266. else:
  267. base = 10
  268. return compat_chr(int(numstr, base))
  269. # Unknown entity in name, return its literal representation
  270. return ('&%s;' % entity)
  271. def unescapeHTML(s):
  272. if s is None:
  273. return None
  274. assert type(s) == compat_str
  275. return re.sub(
  276. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  277. def encodeFilename(s, for_subprocess=False):
  278. """
  279. @param s The name of the file
  280. """
  281. assert type(s) == compat_str
  282. # Python 3 has a Unicode API
  283. if sys.version_info >= (3, 0):
  284. return s
  285. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  286. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  287. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  288. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  289. if not for_subprocess:
  290. return s
  291. else:
  292. # For subprocess calls, encode with locale encoding
  293. # Refer to http://stackoverflow.com/a/9951851/35070
  294. encoding = preferredencoding()
  295. else:
  296. encoding = sys.getfilesystemencoding()
  297. if encoding is None:
  298. encoding = 'utf-8'
  299. return s.encode(encoding, 'ignore')
  300. def encodeArgument(s):
  301. if not isinstance(s, compat_str):
  302. # Legacy code that uses byte strings
  303. # Uncomment the following line after fixing all post processors
  304. #assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  305. s = s.decode('ascii')
  306. return encodeFilename(s, True)
  307. def decodeOption(optval):
  308. if optval is None:
  309. return optval
  310. if isinstance(optval, bytes):
  311. optval = optval.decode(preferredencoding())
  312. assert isinstance(optval, compat_str)
  313. return optval
  314. def formatSeconds(secs):
  315. if secs > 3600:
  316. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  317. elif secs > 60:
  318. return '%d:%02d' % (secs // 60, secs % 60)
  319. else:
  320. return '%d' % secs
  321. def make_HTTPS_handler(opts_no_check_certificate, **kwargs):
  322. if sys.version_info < (3, 2):
  323. import httplib
  324. class HTTPSConnectionV3(httplib.HTTPSConnection):
  325. def __init__(self, *args, **kwargs):
  326. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  327. def connect(self):
  328. sock = socket.create_connection((self.host, self.port), self.timeout)
  329. if getattr(self, '_tunnel_host', False):
  330. self.sock = sock
  331. self._tunnel()
  332. try:
  333. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
  334. except ssl.SSLError:
  335. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  336. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  337. def https_open(self, req):
  338. return self.do_open(HTTPSConnectionV3, req)
  339. return HTTPSHandlerV3(**kwargs)
  340. elif hasattr(ssl, 'create_default_context'): # Python >= 3.4
  341. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  342. context.options &= ~ssl.OP_NO_SSLv3 # Allow older, not-as-secure SSLv3
  343. if opts_no_check_certificate:
  344. context.verify_mode = ssl.CERT_NONE
  345. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  346. else: # Python < 3.4
  347. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  348. context.verify_mode = (ssl.CERT_NONE
  349. if opts_no_check_certificate
  350. else ssl.CERT_REQUIRED)
  351. context.set_default_verify_paths()
  352. try:
  353. context.load_default_certs()
  354. except AttributeError:
  355. pass # Python < 3.4
  356. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  357. class ExtractorError(Exception):
  358. """Error during info extraction."""
  359. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  360. """ tb, if given, is the original traceback (so that it can be printed out).
  361. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  362. """
  363. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  364. expected = True
  365. if video_id is not None:
  366. msg = video_id + ': ' + msg
  367. if cause:
  368. msg += ' (caused by %r)' % cause
  369. if not expected:
  370. if ytdl_is_updateable():
  371. update_cmd = 'type youtube-dl -U to update'
  372. else:
  373. update_cmd = 'see https://yt-dl.org/update on how to update'
  374. msg += '; please report this issue on https://yt-dl.org/bug .'
  375. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  376. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  377. super(ExtractorError, self).__init__(msg)
  378. self.traceback = tb
  379. self.exc_info = sys.exc_info() # preserve original exception
  380. self.cause = cause
  381. self.video_id = video_id
  382. def format_traceback(self):
  383. if self.traceback is None:
  384. return None
  385. return ''.join(traceback.format_tb(self.traceback))
  386. class RegexNotFoundError(ExtractorError):
  387. """Error when a regex didn't match"""
  388. pass
  389. class DownloadError(Exception):
  390. """Download Error exception.
  391. This exception may be thrown by FileDownloader objects if they are not
  392. configured to continue on errors. They will contain the appropriate
  393. error message.
  394. """
  395. def __init__(self, msg, exc_info=None):
  396. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  397. super(DownloadError, self).__init__(msg)
  398. self.exc_info = exc_info
  399. class SameFileError(Exception):
  400. """Same File exception.
  401. This exception will be thrown by FileDownloader objects if they detect
  402. multiple files would have to be downloaded to the same file on disk.
  403. """
  404. pass
  405. class PostProcessingError(Exception):
  406. """Post Processing exception.
  407. This exception may be raised by PostProcessor's .run() method to
  408. indicate an error in the postprocessing task.
  409. """
  410. def __init__(self, msg):
  411. self.msg = msg
  412. class MaxDownloadsReached(Exception):
  413. """ --max-downloads limit has been reached. """
  414. pass
  415. class UnavailableVideoError(Exception):
  416. """Unavailable Format exception.
  417. This exception will be thrown when a video is requested
  418. in a format that is not available for that video.
  419. """
  420. pass
  421. class ContentTooShortError(Exception):
  422. """Content Too Short exception.
  423. This exception may be raised by FileDownloader objects when a file they
  424. download is too small for what the server announced first, indicating
  425. the connection was probably interrupted.
  426. """
  427. # Both in bytes
  428. downloaded = None
  429. expected = None
  430. def __init__(self, downloaded, expected):
  431. self.downloaded = downloaded
  432. self.expected = expected
  433. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  434. """Handler for HTTP requests and responses.
  435. This class, when installed with an OpenerDirector, automatically adds
  436. the standard headers to every HTTP request and handles gzipped and
  437. deflated responses from web servers. If compression is to be avoided in
  438. a particular request, the original request in the program code only has
  439. to include the HTTP header "Youtubedl-No-Compression", which will be
  440. removed before making the real request.
  441. Part of this code was copied from:
  442. http://techknack.net/python-urllib2-handlers/
  443. Andrew Rowls, the author of that code, agreed to release it to the
  444. public domain.
  445. """
  446. @staticmethod
  447. def deflate(data):
  448. try:
  449. return zlib.decompress(data, -zlib.MAX_WBITS)
  450. except zlib.error:
  451. return zlib.decompress(data)
  452. @staticmethod
  453. def addinfourl_wrapper(stream, headers, url, code):
  454. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  455. return compat_urllib_request.addinfourl(stream, headers, url, code)
  456. ret = compat_urllib_request.addinfourl(stream, headers, url)
  457. ret.code = code
  458. return ret
  459. def http_request(self, req):
  460. for h, v in std_headers.items():
  461. if h not in req.headers:
  462. req.add_header(h, v)
  463. if 'Youtubedl-no-compression' in req.headers:
  464. if 'Accept-encoding' in req.headers:
  465. del req.headers['Accept-encoding']
  466. del req.headers['Youtubedl-no-compression']
  467. if 'Youtubedl-user-agent' in req.headers:
  468. if 'User-agent' in req.headers:
  469. del req.headers['User-agent']
  470. req.headers['User-agent'] = req.headers['Youtubedl-user-agent']
  471. del req.headers['Youtubedl-user-agent']
  472. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  473. # Python 2.6 is brain-dead when it comes to fragments
  474. req._Request__original = req._Request__original.partition('#')[0]
  475. req._Request__r_type = req._Request__r_type.partition('#')[0]
  476. return req
  477. def http_response(self, req, resp):
  478. old_resp = resp
  479. # gzip
  480. if resp.headers.get('Content-encoding', '') == 'gzip':
  481. content = resp.read()
  482. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  483. try:
  484. uncompressed = io.BytesIO(gz.read())
  485. except IOError as original_ioerror:
  486. # There may be junk add the end of the file
  487. # See http://stackoverflow.com/q/4928560/35070 for details
  488. for i in range(1, 1024):
  489. try:
  490. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  491. uncompressed = io.BytesIO(gz.read())
  492. except IOError:
  493. continue
  494. break
  495. else:
  496. raise original_ioerror
  497. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  498. resp.msg = old_resp.msg
  499. # deflate
  500. if resp.headers.get('Content-encoding', '') == 'deflate':
  501. gz = io.BytesIO(self.deflate(resp.read()))
  502. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  503. resp.msg = old_resp.msg
  504. return resp
  505. https_request = http_request
  506. https_response = http_response
  507. def parse_iso8601(date_str, delimiter='T'):
  508. """ Return a UNIX timestamp from the given date """
  509. if date_str is None:
  510. return None
  511. m = re.search(
  512. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  513. date_str)
  514. if not m:
  515. timezone = datetime.timedelta()
  516. else:
  517. date_str = date_str[:-len(m.group(0))]
  518. if not m.group('sign'):
  519. timezone = datetime.timedelta()
  520. else:
  521. sign = 1 if m.group('sign') == '+' else -1
  522. timezone = datetime.timedelta(
  523. hours=sign * int(m.group('hours')),
  524. minutes=sign * int(m.group('minutes')))
  525. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  526. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  527. return calendar.timegm(dt.timetuple())
  528. def unified_strdate(date_str):
  529. """Return a string with the date in the format YYYYMMDD"""
  530. if date_str is None:
  531. return None
  532. upload_date = None
  533. # Replace commas
  534. date_str = date_str.replace(',', ' ')
  535. # %z (UTC offset) is only supported in python>=3.2
  536. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  537. format_expressions = [
  538. '%d %B %Y',
  539. '%d %b %Y',
  540. '%B %d %Y',
  541. '%b %d %Y',
  542. '%b %dst %Y %I:%M%p',
  543. '%b %dnd %Y %I:%M%p',
  544. '%b %dth %Y %I:%M%p',
  545. '%Y-%m-%d',
  546. '%Y/%m/%d',
  547. '%d.%m.%Y',
  548. '%d/%m/%Y',
  549. '%d/%m/%y',
  550. '%Y/%m/%d %H:%M:%S',
  551. '%d/%m/%Y %H:%M:%S',
  552. '%Y-%m-%d %H:%M:%S',
  553. '%Y-%m-%d %H:%M:%S.%f',
  554. '%d.%m.%Y %H:%M',
  555. '%d.%m.%Y %H.%M',
  556. '%Y-%m-%dT%H:%M:%SZ',
  557. '%Y-%m-%dT%H:%M:%S.%fZ',
  558. '%Y-%m-%dT%H:%M:%S.%f0Z',
  559. '%Y-%m-%dT%H:%M:%S',
  560. '%Y-%m-%dT%H:%M:%S.%f',
  561. '%Y-%m-%dT%H:%M',
  562. ]
  563. for expression in format_expressions:
  564. try:
  565. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  566. except ValueError:
  567. pass
  568. if upload_date is None:
  569. timetuple = email.utils.parsedate_tz(date_str)
  570. if timetuple:
  571. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  572. return upload_date
  573. def determine_ext(url, default_ext='unknown_video'):
  574. if url is None:
  575. return default_ext
  576. guess = url.partition('?')[0].rpartition('.')[2]
  577. if re.match(r'^[A-Za-z0-9]+$', guess):
  578. return guess
  579. else:
  580. return default_ext
  581. def subtitles_filename(filename, sub_lang, sub_format):
  582. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  583. def date_from_str(date_str):
  584. """
  585. Return a datetime object from a string in the format YYYYMMDD or
  586. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  587. today = datetime.date.today()
  588. if date_str in ('now', 'today'):
  589. return today
  590. if date_str == 'yesterday':
  591. return today - datetime.timedelta(days=1)
  592. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  593. if match is not None:
  594. sign = match.group('sign')
  595. time = int(match.group('time'))
  596. if sign == '-':
  597. time = -time
  598. unit = match.group('unit')
  599. # A bad aproximation?
  600. if unit == 'month':
  601. unit = 'day'
  602. time *= 30
  603. elif unit == 'year':
  604. unit = 'day'
  605. time *= 365
  606. unit += 's'
  607. delta = datetime.timedelta(**{unit: time})
  608. return today + delta
  609. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  610. def hyphenate_date(date_str):
  611. """
  612. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  613. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  614. if match is not None:
  615. return '-'.join(match.groups())
  616. else:
  617. return date_str
  618. class DateRange(object):
  619. """Represents a time interval between two dates"""
  620. def __init__(self, start=None, end=None):
  621. """start and end must be strings in the format accepted by date"""
  622. if start is not None:
  623. self.start = date_from_str(start)
  624. else:
  625. self.start = datetime.datetime.min.date()
  626. if end is not None:
  627. self.end = date_from_str(end)
  628. else:
  629. self.end = datetime.datetime.max.date()
  630. if self.start > self.end:
  631. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  632. @classmethod
  633. def day(cls, day):
  634. """Returns a range that only contains the given day"""
  635. return cls(day, day)
  636. def __contains__(self, date):
  637. """Check if the date is in the range"""
  638. if not isinstance(date, datetime.date):
  639. date = date_from_str(date)
  640. return self.start <= date <= self.end
  641. def __str__(self):
  642. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  643. def platform_name():
  644. """ Returns the platform name as a compat_str """
  645. res = platform.platform()
  646. if isinstance(res, bytes):
  647. res = res.decode(preferredencoding())
  648. assert isinstance(res, compat_str)
  649. return res
  650. def _windows_write_string(s, out):
  651. """ Returns True if the string was written using special methods,
  652. False if it has yet to be written out."""
  653. # Adapted from http://stackoverflow.com/a/3259271/35070
  654. import ctypes
  655. import ctypes.wintypes
  656. WIN_OUTPUT_IDS = {
  657. 1: -11,
  658. 2: -12,
  659. }
  660. try:
  661. fileno = out.fileno()
  662. except AttributeError:
  663. # If the output stream doesn't have a fileno, it's virtual
  664. return False
  665. if fileno not in WIN_OUTPUT_IDS:
  666. return False
  667. GetStdHandle = ctypes.WINFUNCTYPE(
  668. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  669. ("GetStdHandle", ctypes.windll.kernel32))
  670. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  671. WriteConsoleW = ctypes.WINFUNCTYPE(
  672. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  673. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  674. ctypes.wintypes.LPVOID)(("WriteConsoleW", ctypes.windll.kernel32))
  675. written = ctypes.wintypes.DWORD(0)
  676. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(("GetFileType", ctypes.windll.kernel32))
  677. FILE_TYPE_CHAR = 0x0002
  678. FILE_TYPE_REMOTE = 0x8000
  679. GetConsoleMode = ctypes.WINFUNCTYPE(
  680. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  681. ctypes.POINTER(ctypes.wintypes.DWORD))(
  682. ("GetConsoleMode", ctypes.windll.kernel32))
  683. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  684. def not_a_console(handle):
  685. if handle == INVALID_HANDLE_VALUE or handle is None:
  686. return True
  687. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  688. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  689. if not_a_console(h):
  690. return False
  691. def next_nonbmp_pos(s):
  692. try:
  693. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  694. except StopIteration:
  695. return len(s)
  696. while s:
  697. count = min(next_nonbmp_pos(s), 1024)
  698. ret = WriteConsoleW(
  699. h, s, count if count else 2, ctypes.byref(written), None)
  700. if ret == 0:
  701. raise OSError('Failed to write string')
  702. if not count: # We just wrote a non-BMP character
  703. assert written.value == 2
  704. s = s[1:]
  705. else:
  706. assert written.value > 0
  707. s = s[written.value:]
  708. return True
  709. def write_string(s, out=None, encoding=None):
  710. if out is None:
  711. out = sys.stderr
  712. assert type(s) == compat_str
  713. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  714. if _windows_write_string(s, out):
  715. return
  716. if ('b' in getattr(out, 'mode', '') or
  717. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  718. byt = s.encode(encoding or preferredencoding(), 'ignore')
  719. out.write(byt)
  720. elif hasattr(out, 'buffer'):
  721. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  722. byt = s.encode(enc, 'ignore')
  723. out.buffer.write(byt)
  724. else:
  725. out.write(s)
  726. out.flush()
  727. def bytes_to_intlist(bs):
  728. if not bs:
  729. return []
  730. if isinstance(bs[0], int): # Python 3
  731. return list(bs)
  732. else:
  733. return [ord(c) for c in bs]
  734. def intlist_to_bytes(xs):
  735. if not xs:
  736. return b''
  737. return struct_pack('%dB' % len(xs), *xs)
  738. # Cross-platform file locking
  739. if sys.platform == 'win32':
  740. import ctypes.wintypes
  741. import msvcrt
  742. class OVERLAPPED(ctypes.Structure):
  743. _fields_ = [
  744. ('Internal', ctypes.wintypes.LPVOID),
  745. ('InternalHigh', ctypes.wintypes.LPVOID),
  746. ('Offset', ctypes.wintypes.DWORD),
  747. ('OffsetHigh', ctypes.wintypes.DWORD),
  748. ('hEvent', ctypes.wintypes.HANDLE),
  749. ]
  750. kernel32 = ctypes.windll.kernel32
  751. LockFileEx = kernel32.LockFileEx
  752. LockFileEx.argtypes = [
  753. ctypes.wintypes.HANDLE, # hFile
  754. ctypes.wintypes.DWORD, # dwFlags
  755. ctypes.wintypes.DWORD, # dwReserved
  756. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  757. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  758. ctypes.POINTER(OVERLAPPED) # Overlapped
  759. ]
  760. LockFileEx.restype = ctypes.wintypes.BOOL
  761. UnlockFileEx = kernel32.UnlockFileEx
  762. UnlockFileEx.argtypes = [
  763. ctypes.wintypes.HANDLE, # hFile
  764. ctypes.wintypes.DWORD, # dwReserved
  765. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  766. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  767. ctypes.POINTER(OVERLAPPED) # Overlapped
  768. ]
  769. UnlockFileEx.restype = ctypes.wintypes.BOOL
  770. whole_low = 0xffffffff
  771. whole_high = 0x7fffffff
  772. def _lock_file(f, exclusive):
  773. overlapped = OVERLAPPED()
  774. overlapped.Offset = 0
  775. overlapped.OffsetHigh = 0
  776. overlapped.hEvent = 0
  777. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  778. handle = msvcrt.get_osfhandle(f.fileno())
  779. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  780. whole_low, whole_high, f._lock_file_overlapped_p):
  781. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  782. def _unlock_file(f):
  783. assert f._lock_file_overlapped_p
  784. handle = msvcrt.get_osfhandle(f.fileno())
  785. if not UnlockFileEx(handle, 0,
  786. whole_low, whole_high, f._lock_file_overlapped_p):
  787. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  788. else:
  789. import fcntl
  790. def _lock_file(f, exclusive):
  791. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  792. def _unlock_file(f):
  793. fcntl.flock(f, fcntl.LOCK_UN)
  794. class locked_file(object):
  795. def __init__(self, filename, mode, encoding=None):
  796. assert mode in ['r', 'a', 'w']
  797. self.f = io.open(filename, mode, encoding=encoding)
  798. self.mode = mode
  799. def __enter__(self):
  800. exclusive = self.mode != 'r'
  801. try:
  802. _lock_file(self.f, exclusive)
  803. except IOError:
  804. self.f.close()
  805. raise
  806. return self
  807. def __exit__(self, etype, value, traceback):
  808. try:
  809. _unlock_file(self.f)
  810. finally:
  811. self.f.close()
  812. def __iter__(self):
  813. return iter(self.f)
  814. def write(self, *args):
  815. return self.f.write(*args)
  816. def read(self, *args):
  817. return self.f.read(*args)
  818. def get_filesystem_encoding():
  819. encoding = sys.getfilesystemencoding()
  820. return encoding if encoding is not None else 'utf-8'
  821. def shell_quote(args):
  822. quoted_args = []
  823. encoding = get_filesystem_encoding()
  824. for a in args:
  825. if isinstance(a, bytes):
  826. # We may get a filename encoded with 'encodeFilename'
  827. a = a.decode(encoding)
  828. quoted_args.append(pipes.quote(a))
  829. return ' '.join(quoted_args)
  830. def takewhile_inclusive(pred, seq):
  831. """ Like itertools.takewhile, but include the latest evaluated element
  832. (the first element so that Not pred(e)) """
  833. for e in seq:
  834. yield e
  835. if not pred(e):
  836. return
  837. def smuggle_url(url, data):
  838. """ Pass additional data in a URL for internal use. """
  839. sdata = compat_urllib_parse.urlencode(
  840. {'__youtubedl_smuggle': json.dumps(data)})
  841. return url + '#' + sdata
  842. def unsmuggle_url(smug_url, default=None):
  843. if '#__youtubedl_smuggle' not in smug_url:
  844. return smug_url, default
  845. url, _, sdata = smug_url.rpartition('#')
  846. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  847. data = json.loads(jsond)
  848. return url, data
  849. def format_bytes(bytes):
  850. if bytes is None:
  851. return 'N/A'
  852. if type(bytes) is str:
  853. bytes = float(bytes)
  854. if bytes == 0.0:
  855. exponent = 0
  856. else:
  857. exponent = int(math.log(bytes, 1024.0))
  858. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  859. converted = float(bytes) / float(1024 ** exponent)
  860. return '%.2f%s' % (converted, suffix)
  861. def parse_filesize(s):
  862. if s is None:
  863. return None
  864. # The lower-case forms are of course incorrect and inofficial,
  865. # but we support those too
  866. _UNIT_TABLE = {
  867. 'B': 1,
  868. 'b': 1,
  869. 'KiB': 1024,
  870. 'KB': 1000,
  871. 'kB': 1024,
  872. 'Kb': 1000,
  873. 'MiB': 1024 ** 2,
  874. 'MB': 1000 ** 2,
  875. 'mB': 1024 ** 2,
  876. 'Mb': 1000 ** 2,
  877. 'GiB': 1024 ** 3,
  878. 'GB': 1000 ** 3,
  879. 'gB': 1024 ** 3,
  880. 'Gb': 1000 ** 3,
  881. 'TiB': 1024 ** 4,
  882. 'TB': 1000 ** 4,
  883. 'tB': 1024 ** 4,
  884. 'Tb': 1000 ** 4,
  885. 'PiB': 1024 ** 5,
  886. 'PB': 1000 ** 5,
  887. 'pB': 1024 ** 5,
  888. 'Pb': 1000 ** 5,
  889. 'EiB': 1024 ** 6,
  890. 'EB': 1000 ** 6,
  891. 'eB': 1024 ** 6,
  892. 'Eb': 1000 ** 6,
  893. 'ZiB': 1024 ** 7,
  894. 'ZB': 1000 ** 7,
  895. 'zB': 1024 ** 7,
  896. 'Zb': 1000 ** 7,
  897. 'YiB': 1024 ** 8,
  898. 'YB': 1000 ** 8,
  899. 'yB': 1024 ** 8,
  900. 'Yb': 1000 ** 8,
  901. }
  902. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  903. m = re.match(
  904. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  905. if not m:
  906. return None
  907. num_str = m.group('num').replace(',', '.')
  908. mult = _UNIT_TABLE[m.group('unit')]
  909. return int(float(num_str) * mult)
  910. def get_term_width():
  911. columns = compat_getenv('COLUMNS', None)
  912. if columns:
  913. return int(columns)
  914. try:
  915. sp = subprocess.Popen(
  916. ['stty', 'size'],
  917. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  918. out, err = sp.communicate()
  919. return int(out.split()[1])
  920. except:
  921. pass
  922. return None
  923. def month_by_name(name):
  924. """ Return the number of a month by (locale-independently) English name """
  925. ENGLISH_NAMES = [
  926. 'January', 'February', 'March', 'April', 'May', 'June',
  927. 'July', 'August', 'September', 'October', 'November', 'December']
  928. try:
  929. return ENGLISH_NAMES.index(name) + 1
  930. except ValueError:
  931. return None
  932. def fix_xml_ampersands(xml_str):
  933. """Replace all the '&' by '&amp;' in XML"""
  934. return re.sub(
  935. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  936. '&amp;',
  937. xml_str)
  938. def setproctitle(title):
  939. assert isinstance(title, compat_str)
  940. try:
  941. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  942. except OSError:
  943. return
  944. title_bytes = title.encode('utf-8')
  945. buf = ctypes.create_string_buffer(len(title_bytes))
  946. buf.value = title_bytes
  947. try:
  948. libc.prctl(15, buf, 0, 0, 0)
  949. except AttributeError:
  950. return # Strange libc, just skip this
  951. def remove_start(s, start):
  952. if s.startswith(start):
  953. return s[len(start):]
  954. return s
  955. def remove_end(s, end):
  956. if s.endswith(end):
  957. return s[:-len(end)]
  958. return s
  959. def url_basename(url):
  960. path = compat_urlparse.urlparse(url).path
  961. return path.strip('/').split('/')[-1]
  962. class HEADRequest(compat_urllib_request.Request):
  963. def get_method(self):
  964. return "HEAD"
  965. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  966. if get_attr:
  967. if v is not None:
  968. v = getattr(v, get_attr, None)
  969. if v == '':
  970. v = None
  971. return default if v is None else (int(v) * invscale // scale)
  972. def str_or_none(v, default=None):
  973. return default if v is None else compat_str(v)
  974. def str_to_int(int_str):
  975. """ A more relaxed version of int_or_none """
  976. if int_str is None:
  977. return None
  978. int_str = re.sub(r'[,\.\+]', '', int_str)
  979. return int(int_str)
  980. def float_or_none(v, scale=1, invscale=1, default=None):
  981. return default if v is None else (float(v) * invscale / scale)
  982. def parse_duration(s):
  983. if s is None:
  984. return None
  985. s = s.strip()
  986. m = re.match(
  987. r'''(?ix)T?
  988. (?:
  989. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  990. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  991. (?:
  992. (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?
  993. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  994. )?
  995. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  996. )$''', s)
  997. if not m:
  998. return None
  999. res = 0
  1000. if m.group('only_mins'):
  1001. return float_or_none(m.group('only_mins'), invscale=60)
  1002. if m.group('only_hours'):
  1003. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1004. if m.group('secs'):
  1005. res += int(m.group('secs'))
  1006. if m.group('mins'):
  1007. res += int(m.group('mins')) * 60
  1008. if m.group('hours'):
  1009. res += int(m.group('hours')) * 60 * 60
  1010. if m.group('ms'):
  1011. res += float(m.group('ms'))
  1012. return res
  1013. def prepend_extension(filename, ext):
  1014. name, real_ext = os.path.splitext(filename)
  1015. return '{0}.{1}{2}'.format(name, ext, real_ext)
  1016. def check_executable(exe, args=[]):
  1017. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1018. args can be a list of arguments for a short output (like -version) """
  1019. try:
  1020. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1021. except OSError:
  1022. return False
  1023. return exe
  1024. def get_exe_version(exe, args=['--version'],
  1025. version_re=r'version\s+([0-9._-a-zA-Z]+)',
  1026. unrecognized='present'):
  1027. """ Returns the version of the specified executable,
  1028. or False if the executable is not present """
  1029. try:
  1030. out, err = subprocess.Popen(
  1031. [exe] + args,
  1032. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1033. except OSError:
  1034. return False
  1035. firstline = out.partition(b'\n')[0].decode('ascii', 'ignore')
  1036. m = re.search(version_re, firstline)
  1037. if m:
  1038. return m.group(1)
  1039. else:
  1040. return unrecognized
  1041. class PagedList(object):
  1042. def __len__(self):
  1043. # This is only useful for tests
  1044. return len(self.getslice())
  1045. class OnDemandPagedList(PagedList):
  1046. def __init__(self, pagefunc, pagesize):
  1047. self._pagefunc = pagefunc
  1048. self._pagesize = pagesize
  1049. def getslice(self, start=0, end=None):
  1050. res = []
  1051. for pagenum in itertools.count(start // self._pagesize):
  1052. firstid = pagenum * self._pagesize
  1053. nextfirstid = pagenum * self._pagesize + self._pagesize
  1054. if start >= nextfirstid:
  1055. continue
  1056. page_results = list(self._pagefunc(pagenum))
  1057. startv = (
  1058. start % self._pagesize
  1059. if firstid <= start < nextfirstid
  1060. else 0)
  1061. endv = (
  1062. ((end - 1) % self._pagesize) + 1
  1063. if (end is not None and firstid <= end <= nextfirstid)
  1064. else None)
  1065. if startv != 0 or endv is not None:
  1066. page_results = page_results[startv:endv]
  1067. res.extend(page_results)
  1068. # A little optimization - if current page is not "full", ie. does
  1069. # not contain page_size videos then we can assume that this page
  1070. # is the last one - there are no more ids on further pages -
  1071. # i.e. no need to query again.
  1072. if len(page_results) + startv < self._pagesize:
  1073. break
  1074. # If we got the whole page, but the next page is not interesting,
  1075. # break out early as well
  1076. if end == nextfirstid:
  1077. break
  1078. return res
  1079. class InAdvancePagedList(PagedList):
  1080. def __init__(self, pagefunc, pagecount, pagesize):
  1081. self._pagefunc = pagefunc
  1082. self._pagecount = pagecount
  1083. self._pagesize = pagesize
  1084. def getslice(self, start=0, end=None):
  1085. res = []
  1086. start_page = start // self._pagesize
  1087. end_page = (
  1088. self._pagecount if end is None else (end // self._pagesize + 1))
  1089. skip_elems = start - start_page * self._pagesize
  1090. only_more = None if end is None else end - start
  1091. for pagenum in range(start_page, end_page):
  1092. page = list(self._pagefunc(pagenum))
  1093. if skip_elems:
  1094. page = page[skip_elems:]
  1095. skip_elems = None
  1096. if only_more is not None:
  1097. if len(page) < only_more:
  1098. only_more -= len(page)
  1099. else:
  1100. page = page[:only_more]
  1101. res.extend(page)
  1102. break
  1103. res.extend(page)
  1104. return res
  1105. def uppercase_escape(s):
  1106. unicode_escape = codecs.getdecoder('unicode_escape')
  1107. return re.sub(
  1108. r'\\U[0-9a-fA-F]{8}',
  1109. lambda m: unicode_escape(m.group(0))[0],
  1110. s)
  1111. def escape_rfc3986(s):
  1112. """Escape non-ASCII characters as suggested by RFC 3986"""
  1113. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1114. s = s.encode('utf-8')
  1115. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1116. def escape_url(url):
  1117. """Escape URL as suggested by RFC 3986"""
  1118. url_parsed = compat_urllib_parse_urlparse(url)
  1119. return url_parsed._replace(
  1120. path=escape_rfc3986(url_parsed.path),
  1121. params=escape_rfc3986(url_parsed.params),
  1122. query=escape_rfc3986(url_parsed.query),
  1123. fragment=escape_rfc3986(url_parsed.fragment)
  1124. ).geturl()
  1125. try:
  1126. struct.pack('!I', 0)
  1127. except TypeError:
  1128. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1129. def struct_pack(spec, *args):
  1130. if isinstance(spec, compat_str):
  1131. spec = spec.encode('ascii')
  1132. return struct.pack(spec, *args)
  1133. def struct_unpack(spec, *args):
  1134. if isinstance(spec, compat_str):
  1135. spec = spec.encode('ascii')
  1136. return struct.unpack(spec, *args)
  1137. else:
  1138. struct_pack = struct.pack
  1139. struct_unpack = struct.unpack
  1140. def read_batch_urls(batch_fd):
  1141. def fixup(url):
  1142. if not isinstance(url, compat_str):
  1143. url = url.decode('utf-8', 'replace')
  1144. BOM_UTF8 = '\xef\xbb\xbf'
  1145. if url.startswith(BOM_UTF8):
  1146. url = url[len(BOM_UTF8):]
  1147. url = url.strip()
  1148. if url.startswith(('#', ';', ']')):
  1149. return False
  1150. return url
  1151. with contextlib.closing(batch_fd) as fd:
  1152. return [url for url in map(fixup, fd) if url]
  1153. def urlencode_postdata(*args, **kargs):
  1154. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1155. try:
  1156. etree_iter = xml.etree.ElementTree.Element.iter
  1157. except AttributeError: # Python <=2.6
  1158. etree_iter = lambda n: n.findall('.//*')
  1159. def parse_xml(s):
  1160. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1161. def doctype(self, name, pubid, system):
  1162. pass # Ignore doctypes
  1163. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1164. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1165. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1166. # Fix up XML parser in Python 2.x
  1167. if sys.version_info < (3, 0):
  1168. for n in etree_iter(tree):
  1169. if n.text is not None:
  1170. if not isinstance(n.text, compat_str):
  1171. n.text = n.text.decode('utf-8')
  1172. return tree
  1173. US_RATINGS = {
  1174. 'G': 0,
  1175. 'PG': 10,
  1176. 'PG-13': 13,
  1177. 'R': 16,
  1178. 'NC': 18,
  1179. }
  1180. def parse_age_limit(s):
  1181. if s is None:
  1182. return None
  1183. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1184. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1185. def strip_jsonp(code):
  1186. return re.sub(
  1187. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1188. def js_to_json(code):
  1189. def fix_kv(m):
  1190. v = m.group(0)
  1191. if v in ('true', 'false', 'null'):
  1192. return v
  1193. if v.startswith('"'):
  1194. return v
  1195. if v.startswith("'"):
  1196. v = v[1:-1]
  1197. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1198. '\\\\': '\\\\',
  1199. "\\'": "'",
  1200. '"': '\\"',
  1201. }[m.group(0)], v)
  1202. return '"%s"' % v
  1203. res = re.sub(r'''(?x)
  1204. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1205. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1206. [a-zA-Z_][a-zA-Z_0-9]*
  1207. ''', fix_kv, code)
  1208. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1209. return res
  1210. def qualities(quality_ids):
  1211. """ Get a numeric quality value out of a list of possible values """
  1212. def q(qid):
  1213. try:
  1214. return quality_ids.index(qid)
  1215. except ValueError:
  1216. return -1
  1217. return q
  1218. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1219. def limit_length(s, length):
  1220. """ Add ellipses to overly long strings """
  1221. if s is None:
  1222. return None
  1223. ELLIPSES = '...'
  1224. if len(s) > length:
  1225. return s[:length - len(ELLIPSES)] + ELLIPSES
  1226. return s
  1227. def version_tuple(v):
  1228. return tuple(int(e) for e in re.split(r'[-.]', v))
  1229. def is_outdated_version(version, limit, assume_new=True):
  1230. if not version:
  1231. return not assume_new
  1232. try:
  1233. return version_tuple(version) < version_tuple(limit)
  1234. except ValueError:
  1235. return not assume_new
  1236. def ytdl_is_updateable():
  1237. """ Returns if youtube-dl can be updated with -U """
  1238. from zipimport import zipimporter
  1239. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1240. def args_to_str(args):
  1241. # Get a short string representation for a subprocess command
  1242. return ' '.join(shlex_quote(a) for a in args)