aboutsummaryrefslogtreecommitdiff
path: root/webAO/master.ts
blob: bfd5d343b195e1c5463cf281173724ad2f6e1a1e (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
import { safeTags } from './encoding';

declare global {
    interface Window {
        setServ: (ID: number) => void;
    }
}

interface AOServer {
    name: string,
    description: string,
    ip: string,
    players: number,
    port?: number,
    ws_port?: number,
    wss_port?: number,
    assets?: string,
    online?: 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 host = window.location.host;

const serverlist_cache_key = 'masterlist';

const servers: AOServer[] = [];
servers[-2] = {
    name: 'Singleplayer',
    description: 'Build cases, try out new things',
    ip: '127.0.0.1',
    port: 50001,
    assets: '',
    online: 'Online: 0/1',
    players: 0,
};
servers[-1] = {
    name: 'Localhost',
    description: 'This is your computer on port 50001',
    ip: '127.0.0.1',
    port: 50001,
    assets: '',
    online: 'Offline',
    players: 0,
};


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

    processClientVersion(clientVersion);

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

main();

export function setServ(ID: number) {
    const server = servers[ID];
    const onlineStr = server.online;
    const serverDesc = safeTags(server.description);
    document.getElementById('serverdescription_content').innerHTML = `<b>${onlineStr}</b><br>${serverDesc}`;
}
window.setServ = setServ;


// 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, skipping`);
            continue;
        }

        const newServer: AOServer = {
            name: item.name,
            description: item.description,
            ip: item.ip,
            players: item.players || 0,
        }

        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
        // Note that this is not an error condition, as many servers only has port (TCP) enabled
        // Which means they don't support webAO
        if (!newServer.ws_port && !newServer.wss_port) {
            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[];
}

function processServerlist(serverlist: AOServer[]) {
    for (let i = 0; i < serverlist.length; i++) {
        const server = serverlist[i];
        let port = 0;
        let ws_protocol = '';
        let http_protocol = '';
        let domain = '';

        if (server.ws_port) {
            port = server.ws_port;
            ws_protocol = 'ws';
            http_protocol = 'http';
            domain = 'insecure';
        }
        if (server.wss_port) {
            port = server.wss_port;
            ws_protocol = 'wss';
            http_protocol = 'https';
            domain = 'web';
        }
        if (port === 0 || protocol === '') {
            console.warn(`Server ${server.name} has no websocket port, skipping`)
            continue;
        }

        // Replace the first element of the domain with the correct subdomain
        const domainElements = window.location.hostname.split('.');
        domainElements[0] = domain;
        let hostname = domainElements.join('.');

        if (window.location.port) {
            hostname += `:${window.location.port}`;
        }

        const clientURL: string = `${http_protocol}://${hostname}/client.html`;
        const connect = `${ws_protocol}://${server.ip}:${port}`;
        const serverName = server.name;
        server.online = `Players: ${server.players}`;
        servers.push(server);

        document.getElementById('masterlist').innerHTML
            += `<li id="server${i}" onmouseover="setServ(${i})"><p>${safeTags(server.name)} (${server.players})</p>`
            + `<a class="button" href="${clientURL}?mode=watch&connect=${connect}&serverName=${serverName}" target="_blank">Watch</a>`
            + `<a class="button" href="${clientURL}?mode=join&connect=${connect}&serverName=${serverName}" target="_blank">Join</a></li>`;
    }
}

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}`;
}