2021-08-05 20:57:23 +02:00
|
|
|
from abc import ABCMeta, abstractmethod
|
2014-04-27 00:07:13 +02:00
|
|
|
from itertools import chain
|
2021-09-29 20:22:19 +02:00
|
|
|
from typing import Any, Callable, Dict, Iterable, Tuple, Union
|
2019-08-31 18:21:10 +02:00
|
|
|
|
2021-09-29 20:22:19 +02:00
|
|
|
from .. import codec
|
2021-09-27 13:58:19 +02:00
|
|
|
from ..cli.constants import EMPTY_FORMAT_OPTION
|
2021-05-05 14:13:39 +02:00
|
|
|
from ..context import Environment
|
2021-08-05 20:58:43 +02:00
|
|
|
from ..constants import UTF8
|
2021-09-27 13:58:19 +02:00
|
|
|
from ..models import HTTPMessage, HTTPResponse
|
2021-05-05 14:13:39 +02:00
|
|
|
from .processing import Conversion, Formatting
|
2021-09-27 13:58:19 +02:00
|
|
|
from .utils import parse_header_content_type
|
2014-04-27 00:07:13 +02:00
|
|
|
|
|
|
|
BINARY_SUPPRESSED_NOTICE = (
|
|
|
|
b'\n'
|
|
|
|
b'+-----------------------------------------+\n'
|
|
|
|
b'| NOTE: binary data not shown in terminal |\n'
|
|
|
|
b'+-----------------------------------------+'
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-08-15 17:50:00 +02:00
|
|
|
class DataSuppressedError(Exception):
|
|
|
|
message = None
|
|
|
|
|
|
|
|
|
|
|
|
class BinarySuppressedError(DataSuppressedError):
|
2014-04-27 00:07:13 +02:00
|
|
|
"""An error indicating that the body is binary and won't be written,
|
|
|
|
e.g., for terminal output)."""
|
|
|
|
message = BINARY_SUPPRESSED_NOTICE
|
|
|
|
|
|
|
|
|
2021-08-05 20:57:23 +02:00
|
|
|
class BaseStream(metaclass=ABCMeta):
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Base HTTP message output stream class."""
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
msg: HTTPMessage,
|
2019-09-03 17:14:39 +02:00
|
|
|
with_headers=True,
|
|
|
|
with_body=True,
|
2019-08-31 18:21:10 +02:00
|
|
|
on_body_chunk_downloaded: Callable[[bytes], None] = None
|
|
|
|
):
|
2014-04-27 00:07:13 +02:00
|
|
|
"""
|
|
|
|
:param msg: a :class:`models.HTTPMessage` subclass
|
|
|
|
:param with_headers: if `True`, headers will be included
|
|
|
|
:param with_body: if `True`, body will be included
|
|
|
|
|
|
|
|
"""
|
|
|
|
assert with_headers or with_body
|
|
|
|
self.msg = msg
|
|
|
|
self.with_headers = with_headers
|
|
|
|
self.with_body = with_body
|
|
|
|
self.on_body_chunk_downloaded = on_body_chunk_downloaded
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def get_headers(self) -> bytes:
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Return the headers' bytes."""
|
2021-08-05 20:58:43 +02:00
|
|
|
return self.msg.headers.encode()
|
2014-04-27 00:07:13 +02:00
|
|
|
|
2021-08-05 20:57:23 +02:00
|
|
|
@abstractmethod
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Return an iterator over the message body."""
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def __iter__(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
"""Return an iterator over `self.msg`."""
|
|
|
|
if self.with_headers:
|
2014-04-28 23:33:30 +02:00
|
|
|
yield self.get_headers()
|
2014-04-27 00:07:13 +02:00
|
|
|
yield b'\r\n\r\n'
|
|
|
|
|
|
|
|
if self.with_body:
|
|
|
|
try:
|
2014-04-28 23:33:30 +02:00
|
|
|
for chunk in self.iter_body():
|
2014-04-27 00:07:13 +02:00
|
|
|
yield chunk
|
|
|
|
if self.on_body_chunk_downloaded:
|
|
|
|
self.on_body_chunk_downloaded(chunk)
|
2020-08-15 17:50:00 +02:00
|
|
|
except DataSuppressedError as e:
|
2014-04-27 00:07:13 +02:00
|
|
|
if self.with_headers:
|
|
|
|
yield b'\n'
|
|
|
|
yield e.message
|
|
|
|
|
|
|
|
|
|
|
|
class RawStream(BaseStream):
|
|
|
|
"""The message is streamed in chunks with no processing."""
|
|
|
|
|
|
|
|
CHUNK_SIZE = 1024 * 100
|
|
|
|
CHUNK_SIZE_BY_LINE = 1
|
|
|
|
|
|
|
|
def __init__(self, chunk_size=CHUNK_SIZE, **kwargs):
|
2019-08-30 11:32:14 +02:00
|
|
|
super().__init__(**kwargs)
|
2014-04-27 00:07:13 +02:00
|
|
|
self.chunk_size = chunk_size
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
return self.msg.iter_body(self.chunk_size)
|
|
|
|
|
|
|
|
|
|
|
|
class EncodedStream(BaseStream):
|
|
|
|
"""Encoded HTTP message stream.
|
|
|
|
|
|
|
|
The message bytes are converted to an encoding suitable for
|
|
|
|
`self.env.stdout`. Unicode errors are replaced and binary data
|
|
|
|
is suppressed. The body is always streamed by line.
|
|
|
|
|
|
|
|
"""
|
|
|
|
CHUNK_SIZE = 1
|
|
|
|
|
|
|
|
def __init__(self, env=Environment(), **kwargs):
|
2019-08-30 11:32:14 +02:00
|
|
|
super().__init__(**kwargs)
|
2014-04-27 00:07:13 +02:00
|
|
|
if env.stdout_isatty:
|
|
|
|
# Use the encoding supported by the terminal.
|
|
|
|
output_encoding = env.stdout_encoding
|
|
|
|
else:
|
|
|
|
# Preserve the message encoding.
|
|
|
|
output_encoding = self.msg.encoding
|
2021-08-05 20:58:43 +02:00
|
|
|
# Default to UTF-8 when unsure.
|
|
|
|
self.output_encoding = output_encoding or UTF8
|
2014-04-27 00:07:13 +02:00
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
for line, lf in self.msg.iter_lines(self.CHUNK_SIZE):
|
|
|
|
if b'\0' in line:
|
|
|
|
raise BinarySuppressedError()
|
2021-09-29 20:22:19 +02:00
|
|
|
line = codec.decode(line, self.msg.encoding)
|
|
|
|
yield codec.encode(line, self.output_encoding) + lf
|
2014-04-27 00:07:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
class PrettyStream(EncodedStream):
|
|
|
|
"""In addition to :class:`EncodedStream` behaviour, this stream applies
|
|
|
|
content processing.
|
|
|
|
|
|
|
|
Useful for long-lived HTTP responses that stream by lines
|
|
|
|
such as the Twitter streaming API.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
CHUNK_SIZE = 1
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def __init__(
|
|
|
|
self, conversion: Conversion,
|
|
|
|
formatting: Formatting,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2019-08-30 11:32:14 +02:00
|
|
|
super().__init__(**kwargs)
|
2014-04-28 23:33:30 +02:00
|
|
|
self.formatting = formatting
|
|
|
|
self.conversion = conversion
|
2021-09-29 20:22:19 +02:00
|
|
|
self.mime, mime_options = self._get_mime_and_options()
|
|
|
|
self.encoding = mime_options.get('charset') or ''
|
2021-09-27 13:58:19 +02:00
|
|
|
|
2021-09-29 20:22:19 +02:00
|
|
|
def _get_mime_and_options(self) -> Tuple[str, Dict[str, Any]]:
|
|
|
|
# Defaults from the `Content-Type` header.
|
|
|
|
mime, options = parse_header_content_type(self.msg.content_type)
|
|
|
|
|
|
|
|
if not isinstance(self.msg, HTTPResponse):
|
|
|
|
return mime, options
|
|
|
|
|
|
|
|
# Override from the `--response-as` option.
|
|
|
|
forced_content_type = self.formatting.options['response']['as']
|
|
|
|
if forced_content_type == EMPTY_FORMAT_OPTION:
|
|
|
|
return mime, options
|
|
|
|
|
|
|
|
forced_mime, forced_options = parse_header_content_type(forced_content_type)
|
|
|
|
return (forced_mime or mime, forced_options or options)
|
2014-04-27 00:07:13 +02:00
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def get_headers(self) -> bytes:
|
2014-04-28 23:33:30 +02:00
|
|
|
return self.formatting.format_headers(
|
2014-04-27 00:07:13 +02:00
|
|
|
self.msg.headers).encode(self.output_encoding)
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-28 23:33:30 +02:00
|
|
|
first_chunk = True
|
|
|
|
iter_lines = self.msg.iter_lines(self.CHUNK_SIZE)
|
|
|
|
for line, lf in iter_lines:
|
2014-04-27 00:07:13 +02:00
|
|
|
if b'\0' in line:
|
2014-04-28 23:33:30 +02:00
|
|
|
if first_chunk:
|
|
|
|
converter = self.conversion.get_converter(self.mime)
|
|
|
|
if converter:
|
|
|
|
body = bytearray()
|
|
|
|
# noinspection PyAssignmentToLoopOrWithParameter
|
|
|
|
for line, lf in chain([(line, lf)], iter_lines):
|
|
|
|
body.extend(line)
|
|
|
|
body.extend(lf)
|
|
|
|
self.mime, body = converter.convert(body)
|
|
|
|
assert isinstance(body, str)
|
|
|
|
yield self.process_body(body)
|
|
|
|
return
|
2014-04-27 00:07:13 +02:00
|
|
|
raise BinarySuppressedError()
|
2014-04-28 23:33:30 +02:00
|
|
|
yield self.process_body(line) + lf
|
|
|
|
first_chunk = False
|
2014-04-27 00:07:13 +02:00
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def process_body(self, chunk: Union[str, bytes]) -> bytes:
|
2014-04-28 23:33:30 +02:00
|
|
|
if not isinstance(chunk, str):
|
|
|
|
# Text when a converter has been used,
|
|
|
|
# otherwise it will always be bytes.
|
2021-09-29 20:22:19 +02:00
|
|
|
chunk = codec.decode(chunk, self.encoding)
|
2014-04-28 23:33:30 +02:00
|
|
|
chunk = self.formatting.format_body(content=chunk, mime=self.mime)
|
2021-09-29 20:22:19 +02:00
|
|
|
return codec.encode(chunk, self.output_encoding)
|
2014-04-27 00:07:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
class BufferedPrettyStream(PrettyStream):
|
|
|
|
"""The same as :class:`PrettyStream` except that the body is fully
|
|
|
|
fetched before it's processed.
|
|
|
|
|
|
|
|
Suitable regular HTTP responses.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
CHUNK_SIZE = 1024 * 10
|
|
|
|
|
2019-08-31 18:21:10 +02:00
|
|
|
def iter_body(self) -> Iterable[bytes]:
|
2014-04-27 00:07:13 +02:00
|
|
|
# Read the whole body before prettifying it,
|
|
|
|
# but bail out immediately if the body is binary.
|
2014-04-28 23:33:30 +02:00
|
|
|
converter = None
|
2014-04-27 00:07:13 +02:00
|
|
|
body = bytearray()
|
2014-04-28 23:33:30 +02:00
|
|
|
|
2014-04-27 00:07:13 +02:00
|
|
|
for chunk in self.msg.iter_body(self.CHUNK_SIZE):
|
2014-04-28 23:33:30 +02:00
|
|
|
if not converter and b'\0' in chunk:
|
|
|
|
converter = self.conversion.get_converter(self.mime)
|
|
|
|
if not converter:
|
|
|
|
raise BinarySuppressedError()
|
2014-04-27 00:07:13 +02:00
|
|
|
body.extend(chunk)
|
|
|
|
|
2014-04-28 23:33:30 +02:00
|
|
|
if converter:
|
|
|
|
self.mime, body = converter.convert(body)
|
|
|
|
|
|
|
|
yield self.process_body(body)
|