-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
265 lines (240 loc) · 11.4 KB
/
index.html
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Use minimum-scale=1 to enable GPU rasterization -->
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0, maximum-scale=1, minimum-scale=1">
<meta name="Description" content="CCMap Live Snitches">
<title>CCMap Live Snitches</title>
<meta property="og:type" content="object" />
<meta property="og:url" content="https://ccmap.github.io/snitch-live" />
<meta property="og:site_name" content="CCMap" />
<meta property="og:title" content="CCMap" />
<meta property="og:description" content="CCMap Live Snitches" />
<meta property="og:image" content="https://gamepedia.cursecdn.com/minecraft_gamepedia/9/9b/Note_Block.png" />
<link rel="icon" type="image/png" href="https://gamepedia.cursecdn.com/minecraft_gamepedia/9/9b/Note_Block.png" />
</head>
<body>
<div id="app-root">
Loading...
</div>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.css" />
<link rel="stylesheet" type="text/css" href="https://ccmap.github.io/beta/style.css" />
<script src="https://ccmap.github.io/beta/js/bundle.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/discordjs/discord.js@webpack/discord.stable.min.js"></script>
<script type="text/javascript">
var config = {
defaultCollectionUrls: [
{ source: "https://ccmap.github.io/data/political.civmap.json", enabled_presentation: false },
{ source: "https://ccmap.github.io/data/settlements.civmap.json", enabled_presentation: false },
{ source: "https://ccmap.github.io/data/rails.civmap.json", enabled_presentation: false },
],
initialState: {
mapConfig: {
borderApothem: 13000,
tilesRoot: 'https://raw.githubusercontent.com/ccmap/tiles/master/',
basemaps: {
terrain: { name: 'Terrain', id: 'terrain', bgColor: '#000' },
biome: { name: 'Biome', id: 'biome', bgColor: '#000' },
height: { name: 'Height', id: 'height', bgColor: '#888' },
simple: { name: 'Land/Water', id: 'simple', bgColor: '#888' },
night: { name: 'Night', id: 'night', bgColor: '#000', isDefault: true },
light: { name: 'Light', id: 'light', bgColor: '#000' },
},
},
},
};
window.civMapApi = CivMap.start(config);
function createSnitchLiveCollection() {
var collectionId = 'civmap:collection/snitch-live';
try {
if (window.civMapApi.store.getState().collections[collectionId]) return collectionId;
} catch (e) {
// ignore missing collection
}
window.civMapApi.store.dispatch({
type: "CREATE_COLLECTION",
collectionId: collectionId,
collection: {
id: collectionId,
name: "Live Snitch alerts",
persistent: false,
enabled_presentation: true,
presentations: {
"Live Snitch alerts": {
name: "Live Snitch alerts",
style_base: {
icon_size: 24,
icon: "$icon",
},
},
},
},
});
return collectionId;
};
var latestPlayerUpdates = {}; // name -> timestamp
function handleSnitchAlert(alert) {
if (alert.snitch.location.world !== 'world') return; // wrong dimension
if (latestPlayerUpdates[alert.player] > alert.time) return; // old update
latestPlayerUpdates[alert.player] = alert.time;
console.log('Snitch alert:', alert.player, alert.action, alert.snitch.name, alert.snitch.location);
var timestr = new Date(alert.time).toISOString().replace('T', ' ').substring(0, 19);
var collectionId = createSnitchLiveCollection();
window.civMapApi.store.dispatch({
type: "UPDATE_FEATURE_IN_COLLECTION",
collectionId: collectionId,
feature: {
collectionId: collectionId,
id: "civmap:feature/snitch-live/" + alert.player,
name: alert.player,
// label: `${alert.player} ${timestr.substr(11)}\nat ${alert.snitch.name}`,
x: alert.snitch.location.x,
y: alert.snitch.location.y,
z: alert.snitch.location.z,
player: alert.player,
action: alert.action,
snitch: alert.snitch.name,
group: alert.snitch.group,
type: alert.snitch.type,
time: timestr,
timestamp: alert.time,
image: 'https://minotar.net/avatar/' + alert.player + '/256.png',
icon: 'https://minotar.net/avatar/' + alert.player + '/48.png',
}
})
}
var currentWS;
function connectKira(token, groups) {
url = 'wss://mc.civclassic.com:14314/?apiVersion=1&applicationId=ccmap.github.io/snitch-live:v1&apiToken=' + encodeURIComponent(token);
if (currentWS) currentWS.close();
console.log('Connecting to Kira');
var ws = new WebSocket(url);
var currentWS = ws;
var retriesLeft = 3;
function retry() {
if (retriesLeft <= 0) {
alert(`Kira API connection failed three times. Disabling live snitch overlay. Reload page to re-enable.`);
return;
}
retriesLeft -= 1;
connectKira(token, url);
}
ws.onopen = function (event) {
console.log('Connected to Kira.');
retriesLeft = 3;
};
ws.onerror = function (event) {
console.error('Socket error:', event);
retry();
};
ws.onclose = function (event) {
console.error('Socket closed:', event);
retry();
};
ws.onmessage = function onmessage(event) {
var payload;
try {
payload = JSON.parse(event.data);
} catch (e) {
console.error('Could not parse Kira API message:', event.data);
return;
}
if (payload.type !== 'data') return; // unknown event
var alerts = payload['snitch-alerts'];
if (!alerts || !alerts.forEach) return; // no snitch alerts given, or wrong format
alerts.forEach(function (alert) {
if (groups && groups.length > 0 && groups.includes
&& !groups.includes(alert.snitch.group)) {
return;
}
handleSnitchAlert(alert);
});
};
}
// group, player, action, snitch, x, y, z
var snitchKiraRegexp = /^`\[..:..:..\]` `\[([^ ]+)\]` \*\*([^ ]+)\*\* (is|logged in|logged out) at ([^ ]*) \(([-0-9]+),([-0-9]+),([-0-9]+)\)/;
// player, action, snitch, x, y, z
var snitchChatLogRegexp = /\b([^ ]+) (entered|logged in to|logged out in) snitch at ([^ ]*) \[.+ ([-0-9]+) ([-0-9]+) ([-0-9]+)\]/;
var currentDiscord;
function connectDiscord(token, preloadChannels) {
if (currentDiscord) currentDiscord.destroy();
console.log('Connecting to Discord');
const discord = new Discord.Client();
currentDiscord = discord;
if (!preloadChannels || !preloadChannels.forEach) {
preloadChannels = [533255321414795267]; // Kira bot id
}
var retriesLeft = 3;
function retry() {
if (retriesLeft <= 0) {
alert(`Discord connection failed three times. Disabling live snitch overlay. Reload page to re-enable.`);
return;
}
retriesLeft -= 1;
connectDiscord(token);
}
function handleMessageForSnitchAlert(msg) {
if (preloadChannels.length > 0
&& !preloadChannels.includes(msg.channel.id)
&& !preloadChannels.includes(msg.author.id)) return;
var match = snitchKiraRegexp.exec(msg.content);
if (!match) return; // not a snitch alert
var [_fullmatch, group, player, action, snitch, x, y, z] = match;
handleSnitchAlert({
time: msg.createdTimestamp,
player: player,
action: 'ENTRY', // TODO from action var
snitch: {
location: {
x: parseInt(x),
y: parseInt(y),
z: parseInt(z),
world: 'world',
},
name: snitch,
group: group,
type: null,
},
});
}
discord.on('error', function (event) {
console.error('Discord error:', event);
retry();
});
discord.on('disconnect', function (event) {
console.error('Discord closed:', event);
retry();
});
discord.on('ready', function () {
console.log(`Connected to Discord as ${discord.user.tag}`);
retriesLeft = 3;
preloadChannels.forEach(function (channelId) {
var channel = discord.channels.get(channelId);
console.log('Loading last 100 msgs from', channel.name, 'in', channel.guild.name);
channel.fetchMessages({ limit: 100 }).then(function (msgs) {
msgs.forEach(handleMessageForSnitchAlert);
}).catch(console.error);
});
});
discord.on('message', function (msg) {
handleMessageForSnitchAlert(msg);
});
discord.login(token);
}
// you can also add space-separated discord channel/user ids after the discord token to accept alerts only from those channels/users
// similarly, you can add space-separated namelayer group names after the kira token to accept alerts only from those groups
var token = window.location.hash ? decodeURI(window.location.hash.substr(1)) :
prompt("Enter Kira API token or Discord token to show live snitches:");
if (token) {
var splits = token.split(' ');
token = splits[0];
var filter = splits.slice(1);
if (token.length === 64 && !token.includes('.')) connectKira(token, filter);
else connectDiscord(token, filter);
}
else alert('No token given. Disabling live snitch overlay.');
</script>
</body>
</html>