From 798910205cc34395193fe53968c019c517824634 Mon Sep 17 00:00:00 2001
From: Androz 2091 <androz2091@gmail.com>
Date: Thu, 28 Nov 2024 14:41:41 +0100
Subject: [PATCH] Add support for https and wss when using domain names

Detect when using https and automatically connects using wss. Also added support for port 80/443 when using a domain name.
---
 js/src/main/scala/cs214/webapp/client/Pages.scala     | 11 +++++++++--
 .../cs214/webapp/server/web/WebServerRoutes.scala     |  2 +-
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/js/src/main/scala/cs214/webapp/client/Pages.scala b/js/src/main/scala/cs214/webapp/client/Pages.scala
index 30bf5d1..7861778 100644
--- a/js/src/main/scala/cs214/webapp/client/Pages.scala
+++ b/js/src/main/scala/cs214/webapp/client/Pages.scala
@@ -269,9 +269,16 @@ case class AppPage(appId: AppId, uiId: UIId, instanceId: InstanceId, userId: Use
       frag(header(id := "banner"), tag("section")(id := "app"))
     Requests.instanceInfo(instanceId).map: appInfo =>
       val hostName = dom.window.location.hostname
+      val protocol = if dom.window.location.protocol.startsWith("https") then "wss" else "ws"
+      val port = {
+          val p = dom.window.location.port
+          if p.length == 0 then (if protocol == "wss" then "443" else "80") else p
+      }
       val endpoint = appInfo.wsEndpoint
-        .replace("{{hostName}}", hostName)
-        .replace("{{userId}}", URLEncoder.encode(userId, "UTF-8"))
+          .replace("{{protocol}}", protocol)
+          .replace("{{hostName}}", hostName)
+          .replace("{{port}}", port)
+          .replace("{{userId}}", URLEncoder.encode(userId, "UTF-8"))
       IpBanner(appInfo.shareUrl).renderInto(target.querySelector("#banner"))
       app.init(instanceId, userId, endpoint, target.querySelector("#app"))
 
diff --git a/jvm/src/main/scala/cs214/webapp/server/web/WebServerRoutes.scala b/jvm/src/main/scala/cs214/webapp/server/web/WebServerRoutes.scala
index e42a9ac..de0b749 100644
--- a/jvm/src/main/scala/cs214/webapp/server/web/WebServerRoutes.scala
+++ b/jvm/src/main/scala/cs214/webapp/server/web/WebServerRoutes.scala
@@ -54,7 +54,7 @@ private[server] final case class WebServerRoutes()(using cc: castor.Context, log
       if WebServer.apps.contains(instanceId) then
         val app = WebServer.apps(instanceId).instance
         val shareUrl = f"http://$hostAddress:${Config.HTTP_PORT}${Endpoints.Api.root}/${app.appInfo.id}/$instanceId/"
-        val wsEndpoint = f"ws://{{hostName}}:${Config.HTTP_PORT}${Endpoints.WebSocket}/$instanceId/{{userId}}"
+        val wsEndpoint = f"{{protocol}}://{{hostName}}:{{port}}${Endpoints.WebSocket}/$instanceId/{{userId}}"
         val response = InstanceInfoResponse(instanceId, app.registeredUsers, wsEndpoint, shareUrl)
         InstanceInfoResponse.Wire.encode(response)
       else
-- 
GitLab