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.

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