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.

1563 lines
47 KiB

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