add support for view-source scheme

This commit is contained in:
Matthew Welch 2025-02-09 15:45:11 -08:00
parent 9e0192fe52
commit 08282b6f6b
2 changed files with 33 additions and 7 deletions

View File

@ -9,9 +9,16 @@ SUPPORTED_SCHEMES = [
"http", "http",
"https", "https",
"file", "file",
"data" "data",
"view-source",
] ]
ENTITIES = {
"&lt;": "<",
"&gt;": ">",
"&amp;": "&",
}
DEFAULT_FILE = "default.html" DEFAULT_FILE = "default.html"
@ -27,6 +34,7 @@ class URL:
self.media_type = "" self.media_type = ""
self.media_encoding = "" self.media_encoding = ""
self.data = "" self.data = ""
self.view_source: bool = False
if url_string is not None: if url_string is not None:
parse_url(url_string, self) parse_url(url_string, self)
@ -142,6 +150,9 @@ def parse_url(url_string: str, url: URL | None = None) -> tuple[URL, bool]:
try: try:
url.scheme, url_string = url_string.split(":", 1) url.scheme, url_string = url_string.split(":", 1)
assert url.scheme in SUPPORTED_SCHEMES assert url.scheme in SUPPORTED_SCHEMES
if url.scheme == "view-source":
url.view_source = True
url.scheme, url_string = url_string.split(":", 1)
if url_string.startswith("//"): if url_string.startswith("//"):
has_authority = True has_authority = True
@ -210,15 +221,28 @@ def parse_url(url_string: str, url: URL | None = None) -> tuple[URL, bool]:
return url, False return url, False
def show(body: str) -> None: def show(body: str, view_source: bool = False) -> None:
if view_source:
print(body)
return
in_tag = False in_tag = False
for char in body: i = 0
if char == "<": while i < len(body):
if body[i] == "<":
in_tag = True in_tag = True
elif char == ">": elif body[i] == ">":
in_tag = False in_tag = False
elif body[i] == "&" and not in_tag:
index = body.find(";", i, i + 10)
if index >= 0 and body[i:index+1] in ENTITIES:
print(ENTITIES[body[i:index+1]], end="")
i = index +1
continue
else:
print(body[i], end="")
elif not in_tag: elif not in_tag:
print(char, end="") print(body[i], end="")
i += 1
def load(url_string: str): def load(url_string: str):
@ -230,7 +254,7 @@ def load(url_string: str):
url, _ = parse_url(f"file://{default}") url, _ = parse_url(f"file://{default}")
body = Request(url).send_request() body = Request(url).send_request()
show(body) show(body, url.view_source)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -6,5 +6,7 @@
</head> </head>
<body> <body>
<p>Test</p> <p>Test</p>
<p>'&amp;lt;div&amp;gt;&amp;lt;/div&amp;gt;'</p>
<p>&lt;div&gt;&lt;/div&gt;</p>
</body> </body>
</html> </html>