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.

1533 lines
46 KiB

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