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.

1545 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 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. # 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 hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  323. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  324. if opts_no_check_certificate:
  325. context.verify_mode = ssl.CERT_NONE
  326. try:
  327. return compat_urllib_request.HTTPSHandler(context=context, **kwargs)
  328. except TypeError:
  329. # Python 2.7.8
  330. # (create_default_context present but HTTPSHandler has no context=)
  331. pass
  332. if sys.version_info < (3, 2):
  333. import httplib
  334. class HTTPSConnectionV3(httplib.HTTPSConnection):
  335. def __init__(self, *args, **kwargs):
  336. httplib.HTTPSConnection.__init__(self, *args, **kwargs)
  337. def connect(self):
  338. sock = socket.create_connection((self.host, self.port), self.timeout)
  339. if getattr(self, '_tunnel_host', False):
  340. self.sock = sock
  341. self._tunnel()
  342. try:
  343. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)
  344. except ssl.SSLError:
  345. self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
  346. class HTTPSHandlerV3(compat_urllib_request.HTTPSHandler):
  347. def https_open(self, req):
  348. return self.do_open(HTTPSConnectionV3, req)
  349. return HTTPSHandlerV3(**kwargs)
  350. else: # Python < 3.4
  351. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  352. context.verify_mode = (ssl.CERT_NONE
  353. if opts_no_check_certificate
  354. else ssl.CERT_REQUIRED)
  355. context.set_default_verify_paths()
  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, day_first=True):
  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. # Remove AM/PM + timezone
  538. date_str = re.sub(r'(?i)\s*(?:AM|PM)\s+[A-Z]+', '', date_str)
  539. format_expressions = [
  540. '%d %B %Y',
  541. '%d %b %Y',
  542. '%B %d %Y',
  543. '%b %d %Y',
  544. '%b %dst %Y %I:%M%p',
  545. '%b %dnd %Y %I:%M%p',
  546. '%b %dth %Y %I:%M%p',
  547. '%Y-%m-%d',
  548. '%Y/%m/%d',
  549. '%d.%m.%Y',
  550. '%d/%m/%Y',
  551. '%d/%m/%y',
  552. '%Y/%m/%d %H:%M:%S',
  553. '%Y-%m-%d %H:%M:%S',
  554. '%Y-%m-%d %H:%M:%S.%f',
  555. '%d.%m.%Y %H:%M',
  556. '%d.%m.%Y %H.%M',
  557. '%Y-%m-%dT%H:%M:%SZ',
  558. '%Y-%m-%dT%H:%M:%S.%fZ',
  559. '%Y-%m-%dT%H:%M:%S.%f0Z',
  560. '%Y-%m-%dT%H:%M:%S',
  561. '%Y-%m-%dT%H:%M:%S.%f',
  562. '%Y-%m-%dT%H:%M',
  563. ]
  564. if day_first:
  565. format_expressions.extend([
  566. '%d/%m/%Y %H:%M:%S',
  567. ])
  568. else:
  569. format_expressions.extend([
  570. '%m/%d/%Y %H:%M:%S',
  571. ])
  572. for expression in format_expressions:
  573. try:
  574. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  575. except ValueError:
  576. pass
  577. if upload_date is None:
  578. timetuple = email.utils.parsedate_tz(date_str)
  579. if timetuple:
  580. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  581. return upload_date
  582. def determine_ext(url, default_ext='unknown_video'):
  583. if url is None:
  584. return default_ext
  585. guess = url.partition('?')[0].rpartition('.')[2]
  586. if re.match(r'^[A-Za-z0-9]+$', guess):
  587. return guess
  588. else:
  589. return default_ext
  590. def subtitles_filename(filename, sub_lang, sub_format):
  591. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  592. def date_from_str(date_str):
  593. """
  594. Return a datetime object from a string in the format YYYYMMDD or
  595. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  596. today = datetime.date.today()
  597. if date_str in ('now', 'today'):
  598. return today
  599. if date_str == 'yesterday':
  600. return today - datetime.timedelta(days=1)
  601. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  602. if match is not None:
  603. sign = match.group('sign')
  604. time = int(match.group('time'))
  605. if sign == '-':
  606. time = -time
  607. unit = match.group('unit')
  608. # A bad aproximation?
  609. if unit == 'month':
  610. unit = 'day'
  611. time *= 30
  612. elif unit == 'year':
  613. unit = 'day'
  614. time *= 365
  615. unit += 's'
  616. delta = datetime.timedelta(**{unit: time})
  617. return today + delta
  618. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  619. def hyphenate_date(date_str):
  620. """
  621. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  622. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  623. if match is not None:
  624. return '-'.join(match.groups())
  625. else:
  626. return date_str
  627. class DateRange(object):
  628. """Represents a time interval between two dates"""
  629. def __init__(self, start=None, end=None):
  630. """start and end must be strings in the format accepted by date"""
  631. if start is not None:
  632. self.start = date_from_str(start)
  633. else:
  634. self.start = datetime.datetime.min.date()
  635. if end is not None:
  636. self.end = date_from_str(end)
  637. else:
  638. self.end = datetime.datetime.max.date()
  639. if self.start > self.end:
  640. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  641. @classmethod
  642. def day(cls, day):
  643. """Returns a range that only contains the given day"""
  644. return cls(day, day)
  645. def __contains__(self, date):
  646. """Check if the date is in the range"""
  647. if not isinstance(date, datetime.date):
  648. date = date_from_str(date)
  649. return self.start <= date <= self.end
  650. def __str__(self):
  651. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  652. def platform_name():
  653. """ Returns the platform name as a compat_str """
  654. res = platform.platform()
  655. if isinstance(res, bytes):
  656. res = res.decode(preferredencoding())
  657. assert isinstance(res, compat_str)
  658. return res
  659. def _windows_write_string(s, out):
  660. """ Returns True if the string was written using special methods,
  661. False if it has yet to be written out."""
  662. # Adapted from http://stackoverflow.com/a/3259271/35070
  663. import ctypes
  664. import ctypes.wintypes
  665. WIN_OUTPUT_IDS = {
  666. 1: -11,
  667. 2: -12,
  668. }
  669. try:
  670. fileno = out.fileno()
  671. except AttributeError:
  672. # If the output stream doesn't have a fileno, it's virtual
  673. return False
  674. if fileno not in WIN_OUTPUT_IDS:
  675. return False
  676. GetStdHandle = ctypes.WINFUNCTYPE(
  677. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  678. (b"GetStdHandle", ctypes.windll.kernel32))
  679. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  680. WriteConsoleW = ctypes.WINFUNCTYPE(
  681. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  682. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  683. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  684. written = ctypes.wintypes.DWORD(0)
  685. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  686. FILE_TYPE_CHAR = 0x0002
  687. FILE_TYPE_REMOTE = 0x8000
  688. GetConsoleMode = ctypes.WINFUNCTYPE(
  689. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  690. ctypes.POINTER(ctypes.wintypes.DWORD))(
  691. (b"GetConsoleMode", ctypes.windll.kernel32))
  692. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  693. def not_a_console(handle):
  694. if handle == INVALID_HANDLE_VALUE or handle is None:
  695. return True
  696. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  697. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  698. if not_a_console(h):
  699. return False
  700. def next_nonbmp_pos(s):
  701. try:
  702. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  703. except StopIteration:
  704. return len(s)
  705. while s:
  706. count = min(next_nonbmp_pos(s), 1024)
  707. ret = WriteConsoleW(
  708. h, s, count if count else 2, ctypes.byref(written), None)
  709. if ret == 0:
  710. raise OSError('Failed to write string')
  711. if not count: # We just wrote a non-BMP character
  712. assert written.value == 2
  713. s = s[1:]
  714. else:
  715. assert written.value > 0
  716. s = s[written.value:]
  717. return True
  718. def write_string(s, out=None, encoding=None):
  719. if out is None:
  720. out = sys.stderr
  721. assert type(s) == compat_str
  722. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  723. if _windows_write_string(s, out):
  724. return
  725. if ('b' in getattr(out, 'mode', '') or
  726. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  727. byt = s.encode(encoding or preferredencoding(), 'ignore')
  728. out.write(byt)
  729. elif hasattr(out, 'buffer'):
  730. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  731. byt = s.encode(enc, 'ignore')
  732. out.buffer.write(byt)
  733. else:
  734. out.write(s)
  735. out.flush()
  736. def bytes_to_intlist(bs):
  737. if not bs:
  738. return []
  739. if isinstance(bs[0], int): # Python 3
  740. return list(bs)
  741. else:
  742. return [ord(c) for c in bs]
  743. def intlist_to_bytes(xs):
  744. if not xs:
  745. return b''
  746. return struct_pack('%dB' % len(xs), *xs)
  747. # Cross-platform file locking
  748. if sys.platform == 'win32':
  749. import ctypes.wintypes
  750. import msvcrt
  751. class OVERLAPPED(ctypes.Structure):
  752. _fields_ = [
  753. ('Internal', ctypes.wintypes.LPVOID),
  754. ('InternalHigh', ctypes.wintypes.LPVOID),
  755. ('Offset', ctypes.wintypes.DWORD),
  756. ('OffsetHigh', ctypes.wintypes.DWORD),
  757. ('hEvent', ctypes.wintypes.HANDLE),
  758. ]
  759. kernel32 = ctypes.windll.kernel32
  760. LockFileEx = kernel32.LockFileEx
  761. LockFileEx.argtypes = [
  762. ctypes.wintypes.HANDLE, # hFile
  763. ctypes.wintypes.DWORD, # dwFlags
  764. ctypes.wintypes.DWORD, # dwReserved
  765. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  766. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  767. ctypes.POINTER(OVERLAPPED) # Overlapped
  768. ]
  769. LockFileEx.restype = ctypes.wintypes.BOOL
  770. UnlockFileEx = kernel32.UnlockFileEx
  771. UnlockFileEx.argtypes = [
  772. ctypes.wintypes.HANDLE, # hFile
  773. ctypes.wintypes.DWORD, # dwReserved
  774. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  775. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  776. ctypes.POINTER(OVERLAPPED) # Overlapped
  777. ]
  778. UnlockFileEx.restype = ctypes.wintypes.BOOL
  779. whole_low = 0xffffffff
  780. whole_high = 0x7fffffff
  781. def _lock_file(f, exclusive):
  782. overlapped = OVERLAPPED()
  783. overlapped.Offset = 0
  784. overlapped.OffsetHigh = 0
  785. overlapped.hEvent = 0
  786. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  787. handle = msvcrt.get_osfhandle(f.fileno())
  788. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  789. whole_low, whole_high, f._lock_file_overlapped_p):
  790. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  791. def _unlock_file(f):
  792. assert f._lock_file_overlapped_p
  793. handle = msvcrt.get_osfhandle(f.fileno())
  794. if not UnlockFileEx(handle, 0,
  795. whole_low, whole_high, f._lock_file_overlapped_p):
  796. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  797. else:
  798. import fcntl
  799. def _lock_file(f, exclusive):
  800. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  801. def _unlock_file(f):
  802. fcntl.flock(f, fcntl.LOCK_UN)
  803. class locked_file(object):
  804. def __init__(self, filename, mode, encoding=None):
  805. assert mode in ['r', 'a', 'w']
  806. self.f = io.open(filename, mode, encoding=encoding)
  807. self.mode = mode
  808. def __enter__(self):
  809. exclusive = self.mode != 'r'
  810. try:
  811. _lock_file(self.f, exclusive)
  812. except IOError:
  813. self.f.close()
  814. raise
  815. return self
  816. def __exit__(self, etype, value, traceback):
  817. try:
  818. _unlock_file(self.f)
  819. finally:
  820. self.f.close()
  821. def __iter__(self):
  822. return iter(self.f)
  823. def write(self, *args):
  824. return self.f.write(*args)
  825. def read(self, *args):
  826. return self.f.read(*args)
  827. def get_filesystem_encoding():
  828. encoding = sys.getfilesystemencoding()
  829. return encoding if encoding is not None else 'utf-8'
  830. def shell_quote(args):
  831. quoted_args = []
  832. encoding = get_filesystem_encoding()
  833. for a in args:
  834. if isinstance(a, bytes):
  835. # We may get a filename encoded with 'encodeFilename'
  836. a = a.decode(encoding)
  837. quoted_args.append(pipes.quote(a))
  838. return ' '.join(quoted_args)
  839. def takewhile_inclusive(pred, seq):
  840. """ Like itertools.takewhile, but include the latest evaluated element
  841. (the first element so that Not pred(e)) """
  842. for e in seq:
  843. yield e
  844. if not pred(e):
  845. return
  846. def smuggle_url(url, data):
  847. """ Pass additional data in a URL for internal use. """
  848. sdata = compat_urllib_parse.urlencode(
  849. {'__youtubedl_smuggle': json.dumps(data)})
  850. return url + '#' + sdata
  851. def unsmuggle_url(smug_url, default=None):
  852. if '#__youtubedl_smuggle' not in smug_url:
  853. return smug_url, default
  854. url, _, sdata = smug_url.rpartition('#')
  855. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  856. data = json.loads(jsond)
  857. return url, data
  858. def format_bytes(bytes):
  859. if bytes is None:
  860. return 'N/A'
  861. if type(bytes) is str:
  862. bytes = float(bytes)
  863. if bytes == 0.0:
  864. exponent = 0
  865. else:
  866. exponent = int(math.log(bytes, 1024.0))
  867. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  868. converted = float(bytes) / float(1024 ** exponent)
  869. return '%.2f%s' % (converted, suffix)
  870. def parse_filesize(s):
  871. if s is None:
  872. return None
  873. # The lower-case forms are of course incorrect and inofficial,
  874. # but we support those too
  875. _UNIT_TABLE = {
  876. 'B': 1,
  877. 'b': 1,
  878. 'KiB': 1024,
  879. 'KB': 1000,
  880. 'kB': 1024,
  881. 'Kb': 1000,
  882. 'MiB': 1024 ** 2,
  883. 'MB': 1000 ** 2,
  884. 'mB': 1024 ** 2,
  885. 'Mb': 1000 ** 2,
  886. 'GiB': 1024 ** 3,
  887. 'GB': 1000 ** 3,
  888. 'gB': 1024 ** 3,
  889. 'Gb': 1000 ** 3,
  890. 'TiB': 1024 ** 4,
  891. 'TB': 1000 ** 4,
  892. 'tB': 1024 ** 4,
  893. 'Tb': 1000 ** 4,
  894. 'PiB': 1024 ** 5,
  895. 'PB': 1000 ** 5,
  896. 'pB': 1024 ** 5,
  897. 'Pb': 1000 ** 5,
  898. 'EiB': 1024 ** 6,
  899. 'EB': 1000 ** 6,
  900. 'eB': 1024 ** 6,
  901. 'Eb': 1000 ** 6,
  902. 'ZiB': 1024 ** 7,
  903. 'ZB': 1000 ** 7,
  904. 'zB': 1024 ** 7,
  905. 'Zb': 1000 ** 7,
  906. 'YiB': 1024 ** 8,
  907. 'YB': 1000 ** 8,
  908. 'yB': 1024 ** 8,
  909. 'Yb': 1000 ** 8,
  910. }
  911. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  912. m = re.match(
  913. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  914. if not m:
  915. return None
  916. num_str = m.group('num').replace(',', '.')
  917. mult = _UNIT_TABLE[m.group('unit')]
  918. return int(float(num_str) * mult)
  919. def get_term_width():
  920. columns = compat_getenv('COLUMNS', None)
  921. if columns:
  922. return int(columns)
  923. try:
  924. sp = subprocess.Popen(
  925. ['stty', 'size'],
  926. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  927. out, err = sp.communicate()
  928. return int(out.split()[1])
  929. except:
  930. pass
  931. return None
  932. def month_by_name(name):
  933. """ Return the number of a month by (locale-independently) English name """
  934. ENGLISH_NAMES = [
  935. 'January', 'February', 'March', 'April', 'May', 'June',
  936. 'July', 'August', 'September', 'October', 'November', 'December']
  937. try:
  938. return ENGLISH_NAMES.index(name) + 1
  939. except ValueError:
  940. return None
  941. def fix_xml_ampersands(xml_str):
  942. """Replace all the '&' by '&amp;' in XML"""
  943. return re.sub(
  944. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  945. '&amp;',
  946. xml_str)
  947. def setproctitle(title):
  948. assert isinstance(title, compat_str)
  949. try:
  950. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  951. except OSError:
  952. return
  953. title_bytes = title.encode('utf-8')
  954. buf = ctypes.create_string_buffer(len(title_bytes))
  955. buf.value = title_bytes
  956. try:
  957. libc.prctl(15, buf, 0, 0, 0)
  958. except AttributeError:
  959. return # Strange libc, just skip this
  960. def remove_start(s, start):
  961. if s.startswith(start):
  962. return s[len(start):]
  963. return s
  964. def remove_end(s, end):
  965. if s.endswith(end):
  966. return s[:-len(end)]
  967. return s
  968. def url_basename(url):
  969. path = compat_urlparse.urlparse(url).path
  970. return path.strip('/').split('/')[-1]
  971. class HEADRequest(compat_urllib_request.Request):
  972. def get_method(self):
  973. return "HEAD"
  974. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  975. if get_attr:
  976. if v is not None:
  977. v = getattr(v, get_attr, None)
  978. if v == '':
  979. v = None
  980. return default if v is None else (int(v) * invscale // scale)
  981. def str_or_none(v, default=None):
  982. return default if v is None else compat_str(v)
  983. def str_to_int(int_str):
  984. """ A more relaxed version of int_or_none """
  985. if int_str is None:
  986. return None
  987. int_str = re.sub(r'[,\.\+]', '', int_str)
  988. return int(int_str)
  989. def float_or_none(v, scale=1, invscale=1, default=None):
  990. return default if v is None else (float(v) * invscale / scale)
  991. def parse_duration(s):
  992. if s is None:
  993. return None
  994. s = s.strip()
  995. m = re.match(
  996. r'''(?ix)T?
  997. (?:
  998. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  999. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1000. (?:
  1001. (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)?
  1002. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1003. )?
  1004. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1005. )$''', s)
  1006. if not m:
  1007. return None
  1008. res = 0
  1009. if m.group('only_mins'):
  1010. return float_or_none(m.group('only_mins'), invscale=60)
  1011. if m.group('only_hours'):
  1012. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1013. if m.group('secs'):
  1014. res += int(m.group('secs'))
  1015. if m.group('mins'):
  1016. res += int(m.group('mins')) * 60
  1017. if m.group('hours'):
  1018. res += int(m.group('hours')) * 60 * 60
  1019. if m.group('ms'):
  1020. res += float(m.group('ms'))
  1021. return res
  1022. def prepend_extension(filename, ext):
  1023. name, real_ext = os.path.splitext(filename)
  1024. return '{0}.{1}{2}'.format(name, ext, real_ext)
  1025. def check_executable(exe, args=[]):
  1026. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1027. args can be a list of arguments for a short output (like -version) """
  1028. try:
  1029. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1030. except OSError:
  1031. return False
  1032. return exe
  1033. def get_exe_version(exe, args=['--version'],
  1034. version_re=None, unrecognized='present'):
  1035. """ Returns the version of the specified executable,
  1036. or False if the executable is not present """
  1037. try:
  1038. out, _ = subprocess.Popen(
  1039. [exe] + args,
  1040. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1041. except OSError:
  1042. return False
  1043. if isinstance(out, bytes): # Python 2.x
  1044. out = out.decode('ascii', 'ignore')
  1045. return detect_exe_version(out, version_re, unrecognized)
  1046. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1047. assert isinstance(output, compat_str)
  1048. if version_re is None:
  1049. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1050. m = re.search(version_re, output)
  1051. if m:
  1052. return m.group(1)
  1053. else:
  1054. return unrecognized
  1055. class PagedList(object):
  1056. def __len__(self):
  1057. # This is only useful for tests
  1058. return len(self.getslice())
  1059. class OnDemandPagedList(PagedList):
  1060. def __init__(self, pagefunc, pagesize):
  1061. self._pagefunc = pagefunc
  1062. self._pagesize = pagesize
  1063. def getslice(self, start=0, end=None):
  1064. res = []
  1065. for pagenum in itertools.count(start // self._pagesize):
  1066. firstid = pagenum * self._pagesize
  1067. nextfirstid = pagenum * self._pagesize + self._pagesize
  1068. if start >= nextfirstid:
  1069. continue
  1070. page_results = list(self._pagefunc(pagenum))
  1071. startv = (
  1072. start % self._pagesize
  1073. if firstid <= start < nextfirstid
  1074. else 0)
  1075. endv = (
  1076. ((end - 1) % self._pagesize) + 1
  1077. if (end is not None and firstid <= end <= nextfirstid)
  1078. else None)
  1079. if startv != 0 or endv is not None:
  1080. page_results = page_results[startv:endv]
  1081. res.extend(page_results)
  1082. # A little optimization - if current page is not "full", ie. does
  1083. # not contain page_size videos then we can assume that this page
  1084. # is the last one - there are no more ids on further pages -
  1085. # i.e. no need to query again.
  1086. if len(page_results) + startv < self._pagesize:
  1087. break
  1088. # If we got the whole page, but the next page is not interesting,
  1089. # break out early as well
  1090. if end == nextfirstid:
  1091. break
  1092. return res
  1093. class InAdvancePagedList(PagedList):
  1094. def __init__(self, pagefunc, pagecount, pagesize):
  1095. self._pagefunc = pagefunc
  1096. self._pagecount = pagecount
  1097. self._pagesize = pagesize
  1098. def getslice(self, start=0, end=None):
  1099. res = []
  1100. start_page = start // self._pagesize
  1101. end_page = (
  1102. self._pagecount if end is None else (end // self._pagesize + 1))
  1103. skip_elems = start - start_page * self._pagesize
  1104. only_more = None if end is None else end - start
  1105. for pagenum in range(start_page, end_page):
  1106. page = list(self._pagefunc(pagenum))
  1107. if skip_elems:
  1108. page = page[skip_elems:]
  1109. skip_elems = None
  1110. if only_more is not None:
  1111. if len(page) < only_more:
  1112. only_more -= len(page)
  1113. else:
  1114. page = page[:only_more]
  1115. res.extend(page)
  1116. break
  1117. res.extend(page)
  1118. return res
  1119. def uppercase_escape(s):
  1120. unicode_escape = codecs.getdecoder('unicode_escape')
  1121. return re.sub(
  1122. r'\\U[0-9a-fA-F]{8}',
  1123. lambda m: unicode_escape(m.group(0))[0],
  1124. s)
  1125. def escape_rfc3986(s):
  1126. """Escape non-ASCII characters as suggested by RFC 3986"""
  1127. if sys.version_info < (3, 0) and isinstance(s, unicode):
  1128. s = s.encode('utf-8')
  1129. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1130. def escape_url(url):
  1131. """Escape URL as suggested by RFC 3986"""
  1132. url_parsed = compat_urllib_parse_urlparse(url)
  1133. return url_parsed._replace(
  1134. path=escape_rfc3986(url_parsed.path),
  1135. params=escape_rfc3986(url_parsed.params),
  1136. query=escape_rfc3986(url_parsed.query),
  1137. fragment=escape_rfc3986(url_parsed.fragment)
  1138. ).geturl()
  1139. try:
  1140. struct.pack('!I', 0)
  1141. except TypeError:
  1142. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1143. def struct_pack(spec, *args):
  1144. if isinstance(spec, compat_str):
  1145. spec = spec.encode('ascii')
  1146. return struct.pack(spec, *args)
  1147. def struct_unpack(spec, *args):
  1148. if isinstance(spec, compat_str):
  1149. spec = spec.encode('ascii')
  1150. return struct.unpack(spec, *args)
  1151. else:
  1152. struct_pack = struct.pack
  1153. struct_unpack = struct.unpack
  1154. def read_batch_urls(batch_fd):
  1155. def fixup(url):
  1156. if not isinstance(url, compat_str):
  1157. url = url.decode('utf-8', 'replace')
  1158. BOM_UTF8 = '\xef\xbb\xbf'
  1159. if url.startswith(BOM_UTF8):
  1160. url = url[len(BOM_UTF8):]
  1161. url = url.strip()
  1162. if url.startswith(('#', ';', ']')):
  1163. return False
  1164. return url
  1165. with contextlib.closing(batch_fd) as fd:
  1166. return [url for url in map(fixup, fd) if url]
  1167. def urlencode_postdata(*args, **kargs):
  1168. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1169. try:
  1170. etree_iter = xml.etree.ElementTree.Element.iter
  1171. except AttributeError: # Python <=2.6
  1172. etree_iter = lambda n: n.findall('.//*')
  1173. def parse_xml(s):
  1174. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1175. def doctype(self, name, pubid, system):
  1176. pass # Ignore doctypes
  1177. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1178. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1179. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1180. # Fix up XML parser in Python 2.x
  1181. if sys.version_info < (3, 0):
  1182. for n in etree_iter(tree):
  1183. if n.text is not None:
  1184. if not isinstance(n.text, compat_str):
  1185. n.text = n.text.decode('utf-8')
  1186. return tree
  1187. US_RATINGS = {
  1188. 'G': 0,
  1189. 'PG': 10,
  1190. 'PG-13': 13,
  1191. 'R': 16,
  1192. 'NC': 18,
  1193. }
  1194. def parse_age_limit(s):
  1195. if s is None:
  1196. return None
  1197. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1198. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1199. def strip_jsonp(code):
  1200. return re.sub(
  1201. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1202. def js_to_json(code):
  1203. def fix_kv(m):
  1204. v = m.group(0)
  1205. if v in ('true', 'false', 'null'):
  1206. return v
  1207. if v.startswith('"'):
  1208. return v
  1209. if v.startswith("'"):
  1210. v = v[1:-1]
  1211. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1212. '\\\\': '\\\\',
  1213. "\\'": "'",
  1214. '"': '\\"',
  1215. }[m.group(0)], v)
  1216. return '"%s"' % v
  1217. res = re.sub(r'''(?x)
  1218. "(?:[^"\\]*(?:\\\\|\\")?)*"|
  1219. '(?:[^'\\]*(?:\\\\|\\')?)*'|
  1220. [a-zA-Z_][a-zA-Z_0-9]*
  1221. ''', fix_kv, code)
  1222. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1223. return res
  1224. def qualities(quality_ids):
  1225. """ Get a numeric quality value out of a list of possible values """
  1226. def q(qid):
  1227. try:
  1228. return quality_ids.index(qid)
  1229. except ValueError:
  1230. return -1
  1231. return q
  1232. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1233. def limit_length(s, length):
  1234. """ Add ellipses to overly long strings """
  1235. if s is None:
  1236. return None
  1237. ELLIPSES = '...'
  1238. if len(s) > length:
  1239. return s[:length - len(ELLIPSES)] + ELLIPSES
  1240. return s
  1241. def version_tuple(v):
  1242. return tuple(int(e) for e in re.split(r'[-.]', v))
  1243. def is_outdated_version(version, limit, assume_new=True):
  1244. if not version:
  1245. return not assume_new
  1246. try:
  1247. return version_tuple(version) < version_tuple(limit)
  1248. except ValueError:
  1249. return not assume_new
  1250. def ytdl_is_updateable():
  1251. """ Returns if youtube-dl can be updated with -U """
  1252. from zipimport import zipimporter
  1253. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1254. def args_to_str(args):
  1255. # Get a short string representation for a subprocess command
  1256. return ' '.join(shlex_quote(a) for a in args)