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.

1757 lines
55 KiB

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