aboutsummaryrefslogtreecommitdiff
path: root/webAO/master.ts
blob: b40763de55e02bb374a038ededad27a771143768 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { safeTags } from "./encoding";

interface AOServer {
  name: string;
  description: string;
  ip: string;
  players: number;
  online: string;
  port?: number;
  ws_port?: number;
  wss_port?: number;
  asset?: string;
}

const clientVersion = process.env.npm_package_version;

// const MASTERSERVER_IP = 'master.aceattorneyonline.com:27014';
const serverlist_domain = "servers.aceattorneyonline.com";
const protocol = window.location.protocol;

const serverlist_cache_key = "masterlist";

const servers: AOServer[] = [];
servers[-1] = {
  name: "Localhost",
  description: "This is your computer on port 50001",
  ip: "127.0.0.1",
  players: 0,
  online: "Localhost",
  ws_port: 50001,
} as AOServer;

function main() {
  getServerlist().then((serverlist) => {
    processServerlist(serverlist);
  });

  addServer(servers[-1]);

  processClientVersion(clientVersion);

  getMasterVersion().then((masterVersion) => {
    processMasterVersion(masterVersion);
  });
}

main();

// Fetches the serverlist from the masterserver
// Returns a properly typed list of servers
async function getServerlist(): Promise<AOServer[]> {
  const url = `${protocol}//${serverlist_domain}/servers`;
  const response = await fetch(url);

  if (!response.ok) {
    console.error(
      `Bad status code from masterserver. status: ${response.status}, body: ${response.body}`,
    );
    document.getElementById("ms_error").style.display = "block";
    // If we get a bad status code, try to use the cached serverlist
    return getCachedServerlist();
  }

  const data = await response.json();
  const serverlist: AOServer[] = [];

  for (const item of data) {
    if (!item.name) {
      console.warn(`Server ${item} has no name, skipping`);
      continue;
    }
    if (!item.ip) {
      console.warn(`Server ${item.name} has no ip, skipping`);
      continue;
    }
    if (!item.description) {
      console.warn(`Server ${item.name} has no description`);
    }

    const newServer: AOServer = {
      name: item.name,
      description: item.description,
      ip: item.ip,
      players: item.players || 0,
      online: `Players: ${item.players}`,
    };

    if (item.ws_port) {
      newServer.ws_port = item.ws_port;
    }
    if (item.wss_port) {
      newServer.wss_port = item.wss_port;
    }

    // if none of ws_port or wss_port are defined, skip
    if (!newServer.ws_port && !newServer.wss_port) {
      console.warn(`Server ${item.name} has no websocket port, skipping`);
      continue;
    }

    serverlist.push(newServer);
  }

  // Always cache the result when we get it
  localStorage.setItem(serverlist_cache_key, JSON.stringify(serverlist));

  return serverlist;
}

function getCachedServerlist(): AOServer[] {
  // If it's not in the cache, return an empty list
  const cached = localStorage.getItem(serverlist_cache_key) || "[]";
  return JSON.parse(cached) as AOServer[];
}

// Constructs the client URL robustly, independent of domain and path
function constructClientURL(protocol: string): string {
  const clientURL = new URL(window.location.href);

  // Use the given protocol
  clientURL.protocol = protocol;

  // Remove the last part of the pathname (e.g., "index.html")
  const pathname = clientURL.pathname;
  const parts = pathname.split("/");
  parts.pop();

  // Reconstruct the pathname
  clientURL.pathname = parts.join("/");

  // If clientURL.pathname does not end with a slash, add one
  if (clientURL.pathname[clientURL.pathname.length - 1] !== "/") {
    clientURL.pathname += "/";
  }

  clientURL.pathname += "client.html";

  return clientURL.href;
}

function addServer(server: AOServer) {
  let ws_port = 0;
  let ws_protocol = "";
  let http_protocol = "";

  if (server.ws_port) {
    ws_port = server.ws_port;
    ws_protocol = "ws";
    http_protocol = "http";
  }
  if (server.wss_port && !window.navigator.userAgent.includes("Nintendo")) {
    ws_port = server.wss_port;
    ws_protocol = "wss";
    http_protocol = "https";
  }

  if (ws_port === 0 || ws_protocol === "" || http_protocol === "") {
    console.warn(`Server ${server.name} has no websocket port, skipping`);
    return;
  }

  const clientURL = constructClientURL(http_protocol);
  const connect = `${ws_protocol}://${server.ip}:${ws_port}`;
  const serverName = server.name;
  const fullClientWatchURL = `${clientURL}?mode=watch&connect=${connect}&serverName=${serverName}`;
  const fullClientJoinURL = `${clientURL}?mode=join&connect=${connect}&serverName=${serverName}`;

  servers.push(server);

  document.getElementById("masterlist").innerHTML +=
    `<details name="servers">` +
    `<summary><p>${safeTags(server.name)} (${server.players})</p>` +
    `<a class="button" href="${fullClientJoinURL}" target="_blank">Join</a>` +
    `<a class="button" href="${fullClientWatchURL}" target="_blank">Watch</a></summary>` +
    `<p>${safeTags(server.description)}</p>` +
    `</details>`;
}

function processServerlist(serverlist: AOServer[]) {
  for (let i = 0; i < serverlist.length; i++) {
    addServer(serverlist[i]);
  }
}

async function getMasterVersion(): Promise<string> {
  const url = `${protocol}//${serverlist_domain}/version`;
  const response = await fetch(url);
  if (!response.ok) {
    console.error(
      `Bad status code from masterserver version check. status: ${response.status}, body: ${response.body}`,
    );
    return "Unknown";
  }

  return await response.text();
}

function processClientVersion(data: string) {
  document.getElementById("clientinfo").innerHTML = `Client version: ${data}`;
}

function processMasterVersion(data: string) {
  document.getElementById("serverinfo").innerHTML =
    `Master server version: ${data}`;
}