Skip to content

Commit

Permalink
add image proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
iiPythonx committed Nov 24, 2024
1 parent 8e5586e commit 0fe65a3
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 545 deletions.
43 changes: 42 additions & 1 deletion nightwatch/server/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,60 @@
# Modules
import os
import asyncio
from http import HTTPStatus

from requests import Session
from requests.exceptions import RequestException
from websockets.http11 import Response
from websockets.asyncio.server import serve
from websockets.datastructures import Headers

from . import connection

from nightwatch import __version__
from nightwatch.logging import log

# Handle proxying images
SESSION = Session()
PROXY_SIZE_LIMIT = 10 * (1024 ** 2)
PROXY_ALLOWED_SUFFIX = ["avif", "avifs", "apng", "png", "jpeg", "jpg", "jfif", "webp", "ico", "gif", "svg"]

def proxy_handler(connection, request):
if request.path != "/gateway":
if not request.path.startswith("/proxy"):
return connection.respond(HTTPStatus.NOT_FOUND, "Nightwatch: Specified content was not found.\n")

url = request.path[6:].lstrip("/")
if not (url.strip() and "." in url):
return connection.respond(HTTPStatus.BAD_REQUEST, "Nightwatch: Specified URI is incorrect.\n")

paths = url.split("/")
if len(paths) < 2 or "." not in paths[-1] or paths[-1].split(".")[-1] not in PROXY_ALLOWED_SUFFIX:
return connection.respond(HTTPStatus.BAD_REQUEST, "Nightwatch: Specified URI is incorrect.\n")

log.info("proxy", f"Proxying to https://{url}")
try:
data = b""
with SESSION.get(f"https://{url}", headers = {"User-Agent": request.headers.get("User-Agent", "")}, stream = True) as response:
response.raise_for_status()
for chunk in response.iter_content(PROXY_SIZE_LIMIT):
data += chunk
if len(data) >= PROXY_SIZE_LIMIT:
return connection.respond(HTTPStatus.BAD_REQUEST, "Nightwatch: Specified URI contains data above size limit.")

return Response(response.status_code, "OK", Headers([
(k, v)
for k, v in response.headers.items()
]), data)

except RequestException:
return connection.respond(HTTPStatus.BAD_REQUEST, "Nightwatch: Failed to contact the specified URI.")

# Entrypoint
async def main() -> None:
host, port = os.getenv("HOST", "localhost"), int(os.getenv("PORT", 8000))
log.info("ws", f"Nightwatch v{__version__} running on ws://{host}:{port}/")
async with serve(connection, host, port):
async with serve(connection, host, port, process_request = proxy_handler):
await asyncio.Future()

if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions nightwatch/web/js/nightwatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const leftmark_rules = [
{ regex: /__(.*?)__/g, replace: "<u>$1</u>" },
{ regex: /~~(.*?)~~/g, replace: "<s>$1</s>" },
{ regex: /\*(.*?)\*/g, replace: "<em>$1</em>" },
{ regex: /\[(.*?)\]\((.*?)\)/g, replace: `<a href = "$2">$1</a>` }
{ regex: /\[(.*?)\]\((.*?)\)/g, replace: `<a href = "$2" target = "_blank" rel = "noreferrer">$1</a>` }
];

function leftmark(content) {
Expand Down Expand Up @@ -88,7 +88,7 @@ const NOTIFICATION_SFX = new Audio("/audio/notification.mp3");
// Construct text/attachment
let attachment = message.text, classlist = "message-content";
if (attachment.match(/^https:\/\/[\w\d./-]+.(?:avifs?|a?png|jpe?g|jfif|webp|ico|gif|svg)(?:\?.+)?$/)) {
attachment = `<img src = "${attachment}">`;
attachment = `<img src = "https://${address}/proxy/${attachment.slice(8)}">`;
classlist += " has-image";
} else {

Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies = [
"nanoid>=2.0.0",
"orjson>=3.10.11",
"readchar>=4.2.1",
"requests>=2.32.3",
"urwid>=2.6.16",
"websockets>=14.1",
]
Expand Down
Loading

0 comments on commit 0fe65a3

Please sign in to comment.