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.

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