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.

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