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.

1465 lines
46 KiB

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