Skip to content

Commit

Permalink
0.11.3
Browse files Browse the repository at this point in the history
  • Loading branch information
iiPythonx committed Dec 14, 2024
1 parent f9fa056 commit f0c44ba
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 11 deletions.
2 changes: 1 addition & 1 deletion nightwatch/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "0.11.2"
__version__ = "0.11.3"

import re
HEX_COLOR_REGEX = re.compile(r"^[A-Fa-f0-9]{6}$")
24 changes: 22 additions & 2 deletions nightwatch/rics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@

from pydantic import BaseModel, Field

from requests import Session
from fastapi import FastAPI, WebSocket
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.websockets import WebSocketDisconnect, WebSocketState

from nightwatch import __version__
from nightwatch.logging import log
from nightwatch.config import fetch_config

# Load config data
Expand All @@ -23,6 +25,21 @@
app = FastAPI(openapi_url = None)
app.add_middleware(CORSMiddleware, allow_origins = ["*"], allow_methods = ["*"])

session = Session()

# Check for updates
app.state.latest_update = None
if config["enable_update_checking"] is not False:
latest = session.get("https://api.github.com/repos/iiPythonx/nightwatch/releases/latest").json()

def version(v: str) -> tuple:
return tuple(map(int, v.split(".")))

if version(latest["name"][1:]) > version(__version__):
log.info("update", f"Nightwatch {latest['name']} is now available, upgrading is recommended.")
log.info("update", f"See the changelog at {latest['html_url']}.")
app.state.latest_update = latest["name"][1:]

# Scaffold the application
app.state.clients = {}
app.state.pending_clients = {}
Expand All @@ -43,7 +60,7 @@ async def broadcast(payload: dict) -> None:

# Setup routing
class Client:
def __init__(self, websocket: WebSocket, user_data) -> None:
def __init__(self, websocket: WebSocket, user_data: dict[str, typing.Any]) -> None:
self.websocket = websocket
self.username, self.hex_code = user_data["username"], user_data["hex"]

Expand Down Expand Up @@ -95,6 +112,9 @@ async def receive(self) -> typing.Any:
except WebSocketDisconnect:
pass

except Exception:
await self.websocket.close(1002, "Some data parsing issue occured, check your payloads.")

return None

class ClientJoinModel(BaseModel):
Expand Down Expand Up @@ -185,7 +205,7 @@ async def connect_endpoint(

@app.get("/api/version")
async def route_version() -> JSONResponse:
return JSONResponse({"code": 200, "data": {"version": __version__}})
return JSONResponse({"code": 200, "data": {"version": __version__, "latest": app.state.latest_update}})

# Load additional routes
from nightwatch.rics.routing import ( # noqa: E402
Expand Down
7 changes: 3 additions & 4 deletions nightwatch/rics/routing/image_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,17 @@
import binascii

from fastapi import Response
from requests import RequestException
from fastapi.responses import JSONResponse
from requests import Session, RequestException

from nightwatch.rics import app
from nightwatch.rics import app, session
from nightwatch.logging import log

# Exceptions
class IllegalURL(Exception):
pass

# Handle image forwarding
SESSION = Session()
PROXY_SIZE_LIMIT = 10 * (1024 ** 2)

FORWARD_DOMAIN = os.getenv("DOMAIN")
Expand All @@ -40,7 +39,7 @@ async def forward_image(public_url: str) -> Response | JSONResponse:

try:
data = b""
with SESSION.get(new_url, stream = True) as response:
with session.get(new_url, stream = True) as response:
response.raise_for_status()
for chunk in response.iter_content(PROXY_SIZE_LIMIT):
data += chunk
Expand Down
1 change: 1 addition & 0 deletions nightwatch/web/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ main.loading {
flex-direction: row;
align-items: center;
justify-content: center;
text-align: center;
}

/* Random ass theming */
Expand Down
22 changes: 18 additions & 4 deletions nightwatch/web/js/flows/connection.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) 2024 iiPython

const CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const PROTOCOL_VERSION = "0.11.2";

export default class ConnectionManager {
constructor(payload, callbacks) {
Expand All @@ -24,11 +25,24 @@ export default class ConnectionManager {
this.websocket.addEventListener("message", (e) => this.#on_message(e));
this.callbacks.on_connect();
});
this.websocket.addEventListener("close", _ => console.warn("Connection closed"));
this.websocket.addEventListener("error", e => console.error(e));
this.websocket.addEventListener("close", e => this.callbacks.on_problem({ type: "generic", data: e.reason || "Connection was closed." }));
this.websocket.addEventListener("error", e => this.callbacks.on_problem({ type: "something", data: e }));
}

async #authenticate(username, hex) {
try {
const version_response = await fetch(`http${this.protocol}://${this.url}/api/version`);
if (!version_response.ok) return this.callbacks.on_problem({ type: "unknown-version" });

const info = (await version_response.json()).data;
if (PROTOCOL_VERSION.localeCompare(info.version, undefined, { numeric: true, sensitivity: "base" }) === 1) {
return this.callbacks.on_problem({ type: "outdated-version", data: { version: info.version, supported: PROTOCOL_VERSION } });
}

} catch (e) {
return this.callbacks.on_problem({ type: "unknown-version" });
}

const response = await (await fetch(
`http${this.protocol}://${this.url}/api/join`,
{
Expand Down Expand Up @@ -63,10 +77,10 @@ export default class ConnectionManager {
case "join":
case "leave":
this.callbacks.handle_member(type, data.user);
break
break;

case "problem":
console.warn({ type, data });
this.callbacks.on_problem({ type: "protocol", data });
break;
}
}
Expand Down
26 changes: 26 additions & 0 deletions nightwatch/web/js/nightwatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,31 @@ const FILE_HANDLER = new FileHandler();
const connection = new ConnectionManager(
{ username, hex, address },
{
on_problem: ({ type, data }) => {
main.classList = "loading", main.style.width = "520px";
switch (type) {
case "outdated-version":
main.innerHTML = `This client is too new to connect.<br>RICS version ${data.version}, client version >= ${data.supported}`;
break;

case "unknown-version":
main.innerHTML = `Trying to fetch the RICS version failed.<br>The server might be offline, or it might be too old.`;
break;

case "generic":
main.innerHTML = data;
break;

case "protocol":
main.innerHTML = data.message;
break;
}
if (connection.websocket.readyState === WebSocket.OPEN) {
connection.websocket.close(1000, "The client is terminating this connection due to protocol error.");
connection.callbacks.on_problem = () => {}; // Silence the close message
};
console.error(type, data);
},
on_connect: () => {
main.classList.remove("loading");
main.classList.add("full-layout");
Expand Down Expand Up @@ -182,6 +207,7 @@ const FILE_HANDLER = new FileHandler();
}
}
);
window.connection = connection;

// Handle loading spinner
main.classList.add("loading");
Expand Down

0 comments on commit f0c44ba

Please sign in to comment.