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.

1474 lines
46 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 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. '%Y/%m/%d',
  708. '%d.%m.%Y',
  709. '%d/%m/%Y',
  710. '%Y/%m/%d %H:%M:%S',
  711. '%Y-%m-%d %H:%M:%S',
  712. '%d.%m.%Y %H:%M',
  713. '%d.%m.%Y %H.%M',
  714. '%Y-%m-%dT%H:%M:%SZ',
  715. '%Y-%m-%dT%H:%M:%S.%fZ',
  716. '%Y-%m-%dT%H:%M:%S.%f0Z',
  717. '%Y-%m-%dT%H:%M:%S',
  718. '%Y-%m-%dT%H:%M:%S.%f',
  719. '%Y-%m-%dT%H:%M',
  720. ]
  721. for expression in format_expressions:
  722. try:
  723. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  724. except ValueError:
  725. pass
  726. if upload_date is None:
  727. timetuple = email.utils.parsedate_tz(date_str)
  728. if timetuple:
  729. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  730. return upload_date
  731. def determine_ext(url, default_ext=u'unknown_video'):
  732. if url is None:
  733. return default_ext
  734. guess = url.partition(u'?')[0].rpartition(u'.')[2]
  735. if re.match(r'^[A-Za-z0-9]+$', guess):
  736. return guess
  737. else:
  738. return default_ext
  739. def subtitles_filename(filename, sub_lang, sub_format):
  740. return filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  741. def date_from_str(date_str):
  742. """
  743. Return a datetime object from a string in the format YYYYMMDD or
  744. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  745. today = datetime.date.today()
  746. if date_str == 'now'or date_str == 'today':
  747. return today
  748. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  749. if match is not None:
  750. sign = match.group('sign')
  751. time = int(match.group('time'))
  752. if sign == '-':
  753. time = -time
  754. unit = match.group('unit')
  755. #A bad aproximation?
  756. if unit == 'month':
  757. unit = 'day'
  758. time *= 30
  759. elif unit == 'year':
  760. unit = 'day'
  761. time *= 365
  762. unit += 's'
  763. delta = datetime.timedelta(**{unit: time})
  764. return today + delta
  765. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  766. def hyphenate_date(date_str):
  767. """
  768. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  769. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  770. if match is not None:
  771. return '-'.join(match.groups())
  772. else:
  773. return date_str
  774. class DateRange(object):
  775. """Represents a time interval between two dates"""
  776. def __init__(self, start=None, end=None):
  777. """start and end must be strings in the format accepted by date"""
  778. if start is not None:
  779. self.start = date_from_str(start)
  780. else:
  781. self.start = datetime.datetime.min.date()
  782. if end is not None:
  783. self.end = date_from_str(end)
  784. else:
  785. self.end = datetime.datetime.max.date()
  786. if self.start > self.end:
  787. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  788. @classmethod
  789. def day(cls, day):
  790. """Returns a range that only contains the given day"""
  791. return cls(day,day)
  792. def __contains__(self, date):
  793. """Check if the date is in the range"""
  794. if not isinstance(date, datetime.date):
  795. date = date_from_str(date)
  796. return self.start <= date <= self.end
  797. def __str__(self):
  798. return '%s - %s' % ( self.start.isoformat(), self.end.isoformat())
  799. def platform_name():
  800. """ Returns the platform name as a compat_str """
  801. res = platform.platform()
  802. if isinstance(res, bytes):
  803. res = res.decode(preferredencoding())
  804. assert isinstance(res, compat_str)
  805. return res
  806. def _windows_write_string(s, out):
  807. """ Returns True if the string was written using special methods,
  808. False if it has yet to be written out."""
  809. # Adapted from http://stackoverflow.com/a/3259271/35070
  810. import ctypes
  811. import ctypes.wintypes
  812. WIN_OUTPUT_IDS = {
  813. 1: -11,
  814. 2: -12,
  815. }
  816. try:
  817. fileno = out.fileno()
  818. except AttributeError:
  819. # If the output stream doesn't have a fileno, it's virtual
  820. return False
  821. if fileno not in WIN_OUTPUT_IDS:
  822. return False
  823. GetStdHandle = ctypes.WINFUNCTYPE(
  824. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  825. ("GetStdHandle", ctypes.windll.kernel32))
  826. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  827. WriteConsoleW = ctypes.WINFUNCTYPE(
  828. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  829. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  830. ctypes.wintypes.LPVOID)(("WriteConsoleW", ctypes.windll.kernel32))
  831. written = ctypes.wintypes.DWORD(0)
  832. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)(("GetFileType", ctypes.windll.kernel32))
  833. FILE_TYPE_CHAR = 0x0002
  834. FILE_TYPE_REMOTE = 0x8000
  835. GetConsoleMode = ctypes.WINFUNCTYPE(
  836. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  837. ctypes.POINTER(ctypes.wintypes.DWORD))(
  838. ("GetConsoleMode", ctypes.windll.kernel32))
  839. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  840. def not_a_console(handle):
  841. if handle == INVALID_HANDLE_VALUE or handle is None:
  842. return True
  843. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
  844. or GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  845. if not_a_console(h):
  846. return False
  847. def next_nonbmp_pos(s):
  848. try:
  849. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  850. except StopIteration:
  851. return len(s)
  852. while s:
  853. count = min(next_nonbmp_pos(s), 1024)
  854. ret = WriteConsoleW(
  855. h, s, count if count else 2, ctypes.byref(written), None)
  856. if ret == 0:
  857. raise OSError('Failed to write string')
  858. if not count: # We just wrote a non-BMP character
  859. assert written.value == 2
  860. s = s[1:]
  861. else:
  862. assert written.value > 0
  863. s = s[written.value:]
  864. return True
  865. def write_string(s, out=None, encoding=None):
  866. if out is None:
  867. out = sys.stderr
  868. assert type(s) == compat_str
  869. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  870. if _windows_write_string(s, out):
  871. return
  872. if ('b' in getattr(out, 'mode', '') or
  873. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  874. byt = s.encode(encoding or preferredencoding(), 'ignore')
  875. out.write(byt)
  876. elif hasattr(out, 'buffer'):
  877. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  878. byt = s.encode(enc, 'ignore')
  879. out.buffer.write(byt)
  880. else:
  881. out.write(s)
  882. out.flush()
  883. def bytes_to_intlist(bs):
  884. if not bs:
  885. return []
  886. if isinstance(bs[0], int): # Python 3
  887. return list(bs)
  888. else:
  889. return [ord(c) for c in bs]
  890. def intlist_to_bytes(xs):
  891. if not xs:
  892. return b''
  893. if isinstance(chr(0), bytes): # Python 2
  894. return ''.join([chr(x) for x in xs])
  895. else:
  896. return bytes(xs)
  897. def get_cachedir(params={}):
  898. cache_root = os.environ.get('XDG_CACHE_HOME',
  899. os.path.expanduser('~/.cache'))
  900. return params.get('cachedir', os.path.join(cache_root, 'youtube-dl'))
  901. # Cross-platform file locking
  902. if sys.platform == 'win32':
  903. import ctypes.wintypes
  904. import msvcrt
  905. class OVERLAPPED(ctypes.Structure):
  906. _fields_ = [
  907. ('Internal', ctypes.wintypes.LPVOID),
  908. ('InternalHigh', ctypes.wintypes.LPVOID),
  909. ('Offset', ctypes.wintypes.DWORD),
  910. ('OffsetHigh', ctypes.wintypes.DWORD),
  911. ('hEvent', ctypes.wintypes.HANDLE),
  912. ]
  913. kernel32 = ctypes.windll.kernel32
  914. LockFileEx = kernel32.LockFileEx
  915. LockFileEx.argtypes = [
  916. ctypes.wintypes.HANDLE, # hFile
  917. ctypes.wintypes.DWORD, # dwFlags
  918. ctypes.wintypes.DWORD, # dwReserved
  919. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  920. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  921. ctypes.POINTER(OVERLAPPED) # Overlapped
  922. ]
  923. LockFileEx.restype = ctypes.wintypes.BOOL
  924. UnlockFileEx = kernel32.UnlockFileEx
  925. UnlockFileEx.argtypes = [
  926. ctypes.wintypes.HANDLE, # hFile
  927. ctypes.wintypes.DWORD, # dwReserved
  928. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  929. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  930. ctypes.POINTER(OVERLAPPED) # Overlapped
  931. ]
  932. UnlockFileEx.restype = ctypes.wintypes.BOOL
  933. whole_low = 0xffffffff
  934. whole_high = 0x7fffffff
  935. def _lock_file(f, exclusive):
  936. overlapped = OVERLAPPED()
  937. overlapped.Offset = 0
  938. overlapped.OffsetHigh = 0
  939. overlapped.hEvent = 0
  940. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  941. handle = msvcrt.get_osfhandle(f.fileno())
  942. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  943. whole_low, whole_high, f._lock_file_overlapped_p):
  944. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  945. def _unlock_file(f):
  946. assert f._lock_file_overlapped_p
  947. handle = msvcrt.get_osfhandle(f.fileno())
  948. if not UnlockFileEx(handle, 0,
  949. whole_low, whole_high, f._lock_file_overlapped_p):
  950. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  951. else:
  952. import fcntl
  953. def _lock_file(f, exclusive):
  954. fcntl.lockf(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  955. def _unlock_file(f):
  956. fcntl.lockf(f, fcntl.LOCK_UN)
  957. class locked_file(object):
  958. def __init__(self, filename, mode, encoding=None):
  959. assert mode in ['r', 'a', 'w']
  960. self.f = io.open(filename, mode, encoding=encoding)
  961. self.mode = mode
  962. def __enter__(self):
  963. exclusive = self.mode != 'r'
  964. try:
  965. _lock_file(self.f, exclusive)
  966. except IOError:
  967. self.f.close()
  968. raise
  969. return self
  970. def __exit__(self, etype, value, traceback):
  971. try:
  972. _unlock_file(self.f)
  973. finally:
  974. self.f.close()
  975. def __iter__(self):
  976. return iter(self.f)
  977. def write(self, *args):
  978. return self.f.write(*args)
  979. def read(self, *args):
  980. return self.f.read(*args)
  981. def shell_quote(args):
  982. quoted_args = []
  983. encoding = sys.getfilesystemencoding()
  984. if encoding is None:
  985. encoding = 'utf-8'
  986. for a in args:
  987. if isinstance(a, bytes):
  988. # We may get a filename encoded with 'encodeFilename'
  989. a = a.decode(encoding)
  990. quoted_args.append(pipes.quote(a))
  991. return u' '.join(quoted_args)
  992. def takewhile_inclusive(pred, seq):
  993. """ Like itertools.takewhile, but include the latest evaluated element
  994. (the first element so that Not pred(e)) """
  995. for e in seq:
  996. yield e
  997. if not pred(e):
  998. return
  999. def smuggle_url(url, data):
  1000. """ Pass additional data in a URL for internal use. """
  1001. sdata = compat_urllib_parse.urlencode(
  1002. {u'__youtubedl_smuggle': json.dumps(data)})
  1003. return url + u'#' + sdata
  1004. def unsmuggle_url(smug_url, default=None):
  1005. if not '#__youtubedl_smuggle' in smug_url:
  1006. return smug_url, default
  1007. url, _, sdata = smug_url.rpartition(u'#')
  1008. jsond = compat_parse_qs(sdata)[u'__youtubedl_smuggle'][0]
  1009. data = json.loads(jsond)
  1010. return url, data
  1011. def format_bytes(bytes):
  1012. if bytes is None:
  1013. return u'N/A'
  1014. if type(bytes) is str:
  1015. bytes = float(bytes)
  1016. if bytes == 0.0:
  1017. exponent = 0
  1018. else:
  1019. exponent = int(math.log(bytes, 1024.0))
  1020. suffix = [u'B', u'KiB', u'MiB', u'GiB', u'TiB', u'PiB', u'EiB', u'ZiB', u'YiB'][exponent]
  1021. converted = float(bytes) / float(1024 ** exponent)
  1022. return u'%.2f%s' % (converted, suffix)
  1023. def get_term_width():
  1024. columns = os.environ.get('COLUMNS', None)
  1025. if columns:
  1026. return int(columns)
  1027. try:
  1028. sp = subprocess.Popen(
  1029. ['stty', 'size'],
  1030. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1031. out, err = sp.communicate()
  1032. return int(out.split()[1])
  1033. except:
  1034. pass
  1035. return None
  1036. def month_by_name(name):
  1037. """ Return the number of a month by (locale-independently) English name """
  1038. ENGLISH_NAMES = [
  1039. u'January', u'February', u'March', u'April', u'May', u'June',
  1040. u'July', u'August', u'September', u'October', u'November', u'December']
  1041. try:
  1042. return ENGLISH_NAMES.index(name) + 1
  1043. except ValueError:
  1044. return None
  1045. def fix_xml_ampersands(xml_str):
  1046. """Replace all the '&' by '&amp;' in XML"""
  1047. return re.sub(
  1048. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1049. u'&amp;',
  1050. xml_str)
  1051. def setproctitle(title):
  1052. assert isinstance(title, compat_str)
  1053. try:
  1054. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  1055. except OSError:
  1056. return
  1057. title_bytes = title.encode('utf-8')
  1058. buf = ctypes.create_string_buffer(len(title_bytes))
  1059. buf.value = title_bytes
  1060. try:
  1061. libc.prctl(15, buf, 0, 0, 0)
  1062. except AttributeError:
  1063. return # Strange libc, just skip this
  1064. def remove_start(s, start):
  1065. if s.startswith(start):
  1066. return s[len(start):]
  1067. return s
  1068. def url_basename(url):
  1069. path = compat_urlparse.urlparse(url).path
  1070. return path.strip(u'/').split(u'/')[-1]
  1071. class HEADRequest(compat_urllib_request.Request):
  1072. def get_method(self):
  1073. return "HEAD"
  1074. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1075. if get_attr:
  1076. if v is not None:
  1077. v = getattr(v, get_attr, None)
  1078. if v == '':
  1079. v = None
  1080. return default if v is None else (int(v) * invscale // scale)
  1081. def str_or_none(v, default=None):
  1082. return default if v is None else compat_str(v)
  1083. def str_to_int(int_str):
  1084. if int_str is None:
  1085. return None
  1086. int_str = re.sub(r'[,\.]', u'', int_str)
  1087. return int(int_str)
  1088. def float_or_none(v, scale=1, invscale=1, default=None):
  1089. return default if v is None else (float(v) * invscale / scale)
  1090. def parse_duration(s):
  1091. if s is None:
  1092. return None
  1093. m = re.match(
  1094. r'(?:(?:(?P<hours>[0-9]+)[:h])?(?P<mins>[0-9]+)[:m])?(?P<secs>[0-9]+)s?(?::[0-9]+)?$', s)
  1095. if not m:
  1096. return None
  1097. res = int(m.group('secs'))
  1098. if m.group('mins'):
  1099. res += int(m.group('mins')) * 60
  1100. if m.group('hours'):
  1101. res += int(m.group('hours')) * 60 * 60
  1102. return res
  1103. def prepend_extension(filename, ext):
  1104. name, real_ext = os.path.splitext(filename)
  1105. return u'{0}.{1}{2}'.format(name, ext, real_ext)
  1106. def check_executable(exe, args=[]):
  1107. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1108. args can be a list of arguments for a short output (like -version) """
  1109. try:
  1110. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1111. except OSError:
  1112. return False
  1113. return exe
  1114. class PagedList(object):
  1115. def __init__(self, pagefunc, pagesize):
  1116. self._pagefunc = pagefunc
  1117. self._pagesize = pagesize
  1118. def __len__(self):
  1119. # This is only useful for tests
  1120. return len(self.getslice())
  1121. def getslice(self, start=0, end=None):
  1122. res = []
  1123. for pagenum in itertools.count(start // self._pagesize):
  1124. firstid = pagenum * self._pagesize
  1125. nextfirstid = pagenum * self._pagesize + self._pagesize
  1126. if start >= nextfirstid:
  1127. continue
  1128. page_results = list(self._pagefunc(pagenum))
  1129. startv = (
  1130. start % self._pagesize
  1131. if firstid <= start < nextfirstid
  1132. else 0)
  1133. endv = (
  1134. ((end - 1) % self._pagesize) + 1
  1135. if (end is not None and firstid <= end <= nextfirstid)
  1136. else None)
  1137. if startv != 0 or endv is not None:
  1138. page_results = page_results[startv:endv]
  1139. res.extend(page_results)
  1140. # A little optimization - if current page is not "full", ie. does
  1141. # not contain page_size videos then we can assume that this page
  1142. # is the last one - there are no more ids on further pages -
  1143. # i.e. no need to query again.
  1144. if len(page_results) + startv < self._pagesize:
  1145. break
  1146. # If we got the whole page, but the next page is not interesting,
  1147. # break out early as well
  1148. if end == nextfirstid:
  1149. break
  1150. return res
  1151. def uppercase_escape(s):
  1152. unicode_escape = codecs.getdecoder('unicode_escape')
  1153. return re.sub(
  1154. r'\\U[0-9a-fA-F]{8}',
  1155. lambda m: unicode_escape(m.group(0))[0],
  1156. s)
  1157. try:
  1158. struct.pack(u'!I', 0)
  1159. except TypeError:
  1160. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1161. def struct_pack(spec, *args):
  1162. if isinstance(spec, compat_str):
  1163. spec = spec.encode('ascii')
  1164. return struct.pack(spec, *args)
  1165. def struct_unpack(spec, *args):
  1166. if isinstance(spec, compat_str):
  1167. spec = spec.encode('ascii')
  1168. return struct.unpack(spec, *args)
  1169. else:
  1170. struct_pack = struct.pack
  1171. struct_unpack = struct.unpack
  1172. def read_batch_urls(batch_fd):
  1173. def fixup(url):
  1174. if not isinstance(url, compat_str):
  1175. url = url.decode('utf-8', 'replace')
  1176. BOM_UTF8 = u'\xef\xbb\xbf'
  1177. if url.startswith(BOM_UTF8):
  1178. url = url[len(BOM_UTF8):]
  1179. url = url.strip()
  1180. if url.startswith(('#', ';', ']')):
  1181. return False
  1182. return url
  1183. with contextlib.closing(batch_fd) as fd:
  1184. return [url for url in map(fixup, fd) if url]
  1185. def urlencode_postdata(*args, **kargs):
  1186. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1187. def parse_xml(s):
  1188. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1189. def doctype(self, name, pubid, system):
  1190. pass # Ignore doctypes
  1191. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1192. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1193. return xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1194. if sys.version_info < (3, 0) and sys.platform == 'win32':
  1195. def compat_getpass(prompt, *args, **kwargs):
  1196. if isinstance(prompt, compat_str):
  1197. prompt = prompt.encode(preferredencoding())
  1198. return getpass.getpass(prompt, *args, **kwargs)
  1199. else:
  1200. compat_getpass = getpass.getpass
  1201. US_RATINGS = {
  1202. 'G': 0,
  1203. 'PG': 10,
  1204. 'PG-13': 13,
  1205. 'R': 16,
  1206. 'NC': 18,
  1207. }
  1208. def strip_jsonp(code):
  1209. return re.sub(r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?\s*$', r'\1', code)
  1210. def qualities(quality_ids):
  1211. """ Get a numeric quality value out of a list of possible values """
  1212. def q(qid):
  1213. try:
  1214. return quality_ids.index(qid)
  1215. except ValueError:
  1216. return -1
  1217. return q
  1218. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1219. try:
  1220. subprocess_check_output = subprocess.check_output
  1221. except AttributeError:
  1222. def subprocess_check_output(*args, **kwargs):
  1223. assert 'input' not in kwargs
  1224. p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
  1225. output, _ = p.communicate()
  1226. ret = p.poll()
  1227. if ret:
  1228. raise subprocess.CalledProcessError(ret, p.args, output=output)
  1229. return output