|
| 1 | +import argparse |
| 2 | +import base64 |
| 3 | +import json |
| 4 | +import html |
| 5 | +import time |
| 6 | +from typing import Tuple, Dict, List |
| 7 | +import urllib |
| 8 | + |
| 9 | +from IPython.core.interactiveshell import InteractiveShell |
| 10 | +from IPython import get_ipython |
| 11 | +from IPython.display import display, HTML |
| 12 | + |
| 13 | +import notebook |
| 14 | + |
| 15 | +from httpdbg import httprecord |
| 16 | + |
| 17 | + |
| 18 | +def css() -> str: |
| 19 | + style = """<style> |
| 20 | +.httpdbg-block { |
| 21 | + border-style: solid !important; |
| 22 | + border-width: 1px 0px !important; |
| 23 | + border-color: rgb(124, 124, 124) !important; |
| 24 | + width: 100% !important; |
| 25 | +} |
| 26 | +
|
| 27 | +.httpdbg-url { |
| 28 | + padding: 0px 0px 0px 10px !important; |
| 29 | +} |
| 30 | +
|
| 31 | +.httpdbg-url-data { |
| 32 | + padding: 0px 0px 0px 10px !important; |
| 33 | +} |
| 34 | +
|
| 35 | +.httpdbg-url-code { |
| 36 | + padding: 0px 0px 0px 10px !important; |
| 37 | + width: 100% !important; |
| 38 | + background-color: #EEEEEE !important; |
| 39 | + cursor: default !important; |
| 40 | +} |
| 41 | +
|
| 42 | +.httpdbg-url-code > img { |
| 43 | + max-width: 50% !important; |
| 44 | + height: auto !important; |
| 45 | +} |
| 46 | +
|
| 47 | +.httpdbg-expand { |
| 48 | + cursor: pointer !important; |
| 49 | +} |
| 50 | +""" |
| 51 | + |
| 52 | + if int(notebook.__version__.split(".")[0]) < 7: |
| 53 | + style += """ |
| 54 | +
|
| 55 | +.httpdbg-expand > summary:before { |
| 56 | + content: '\\229E ' !important; |
| 57 | +} |
| 58 | +
|
| 59 | +.httpdbg-expand[open] > summary:before { |
| 60 | + content: '\\229F ' !important; |
| 61 | +} |
| 62 | + """ |
| 63 | + |
| 64 | + style += """ |
| 65 | +</style> |
| 66 | +""" |
| 67 | + |
| 68 | + return style |
| 69 | + |
| 70 | + |
| 71 | +def parse_content_type(content_type: str) -> Tuple[str, Dict[str, str]]: |
| 72 | + s = content_type.split(";") |
| 73 | + media_type = s[0] |
| 74 | + directives = {} |
| 75 | + for directive in s[1:]: |
| 76 | + sp = directive.split("=") |
| 77 | + if len(sp) == 2: |
| 78 | + directives[sp[0].strip()] = sp[1].strip() |
| 79 | + return media_type, directives |
| 80 | + |
| 81 | + |
| 82 | +def print_body(req, limit: int) -> str: |
| 83 | + if len(req.content) == 0: |
| 84 | + return "" |
| 85 | + |
| 86 | + preview = req.preview |
| 87 | + |
| 88 | + if preview.get("image"): |
| 89 | + return f"""<img src="data:{preview["content_type"]};base64,{base64.b64encode(req.content).decode("utf-8")}">""" |
| 90 | + |
| 91 | + if preview.get("text"): |
| 92 | + txt = preview["text"] |
| 93 | + try: |
| 94 | + txt = json.dumps(json.loads(preview["text"]), indent=4) |
| 95 | + except Exception: |
| 96 | + # query string |
| 97 | + try: |
| 98 | + if ( |
| 99 | + parse_content_type(req.get_header("content_type"))[0] |
| 100 | + == "application/x-www-form-urlencoded" |
| 101 | + ): |
| 102 | + qs = [] |
| 103 | + for key, value in urllib.parse.parse_qsl( |
| 104 | + req.content, strict_parsing=True |
| 105 | + ): |
| 106 | + if value: |
| 107 | + qs.append(f"{key}={value}") |
| 108 | + if qs: |
| 109 | + txt = "\n\n".join(qs) |
| 110 | + except Exception: |
| 111 | + pass |
| 112 | + |
| 113 | + return html.escape(txt)[:limit] |
| 114 | + |
| 115 | + return "<i> body data not printable </i>" |
| 116 | + |
| 117 | + |
| 118 | +def print_headers(headers: List[str], limit: int): |
| 119 | + return html.escape( |
| 120 | + "\n".join([f"{header.name}: {header.value}" for header in headers]) |
| 121 | + )[:limit] |
| 122 | + |
| 123 | + |
| 124 | +def httpdbg_magic(line, cell): |
| 125 | + args = read_args([arg for arg in line.strip().split(" ") if arg != ""]) |
| 126 | + |
| 127 | + with httprecord() as records: |
| 128 | + tbegin = time.time() |
| 129 | + get_ipython().run_cell(cell) |
| 130 | + tend = time.time() |
| 131 | + infos = css() |
| 132 | + infos += f"""<details class="httpdbg-block httpdbg-expand"><summary>[httpdbg] {len(records)} requests in {tend-tbegin:.2f} seconds</summary>""" |
| 133 | + for record in records: |
| 134 | + request_headers = print_headers(record.request.headers, args.headers) |
| 135 | + request_body = print_body( |
| 136 | + record.request, |
| 137 | + args.body, |
| 138 | + ) |
| 139 | + response_headers = print_headers(record.response.headers, args.headers) |
| 140 | + response_body = print_body( |
| 141 | + record.response, |
| 142 | + args.body, |
| 143 | + ) |
| 144 | + infos += f"""<details class="httpdbg-expand httpdbg-url"> |
| 145 | +<summary>{html.escape(str(record.status_code))} {html.escape(record.method)} {html.escape(record.url)}</summary> |
| 146 | +<details class="httpdbg-expand httpdbg-url-data"><summary>request</summary><pre class="httpdbg-url-code">{request_headers}\n\n{str(request_body)}</pre></details> |
| 147 | +<details class="httpdbg-expand httpdbg-url-data"><summary>response</summary><pre class="httpdbg-url-code">{response_headers}\n\n{str(response_body)}</pre></details> |
| 148 | +</details>""" |
| 149 | + display(HTML(infos)) |
| 150 | + |
| 151 | + |
| 152 | +def read_args(args: List[str]) -> argparse.Namespace: |
| 153 | + parser = argparse.ArgumentParser( |
| 154 | + prog="httpdbg", |
| 155 | + description="httdbg - a very simple tool to debug HTTP(S) client requests", |
| 156 | + ) |
| 157 | + |
| 158 | + parser.add_argument( |
| 159 | + "--headers", |
| 160 | + type=int, |
| 161 | + default=500, |
| 162 | + metavar=500, |
| 163 | + help="Number of characters to display for the headers.", |
| 164 | + ) |
| 165 | + |
| 166 | + parser.add_argument( |
| 167 | + "--body", |
| 168 | + type=int, |
| 169 | + default=500, |
| 170 | + metavar=500, |
| 171 | + help="Number of characters to display for the body.", |
| 172 | + ) |
| 173 | + |
| 174 | + return parser.parse_args(args) |
| 175 | + |
| 176 | + |
| 177 | +def load_ipython_extension(ipython: InteractiveShell): |
| 178 | + ipython.register_magic_function(httpdbg_magic, "cell", "httpdbg") |
| 179 | + |
| 180 | + |
| 181 | +def unload_ipython_extension(ipython): |
| 182 | + pass |
0 commit comments