You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1533 lines
48 KiB

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