This repository has been archived by the owner on Nov 9, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathserver.js
257 lines (235 loc) · 9.8 KB
/
server.js
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
import * as cheerio from 'cheerio';
import * as Crypto from 'crypto';
import * as fs from 'fs';
import fetch from 'node-fetch';
import * as XMPP from 'node-xmpp-client';
const { Element } = XMPP;
import { XMPPClient } from './xmpp_client.js';
import { spawn } from 'child_process';
import * as url from 'url';
import { matematSummary, matematBuy } from './matemat.js';
import { getCovid } from './covid.js'
const SPACEAPI_URL = "http://spaceapi.hq.c3d2.de:3000/spaceapi.json";
const TEST_URL_REGEX = /https?:\/\/([-a-zA-Z0-9@:%_\+~#=]{1,256}\.){1,32}[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;
process.on('SIGTERM', function() {
process.exit(0);
});
if (process.argv.length < 5) {
console.error("Parameters: <my-jid> <my-password> <full-muc-jid1> [<full-muc-jid2> .. <full-muc-jidN>]");
process.exit(1);
}
const jid = process.argv[2],
pass = process.argv[3],
muc_jids = process.argv.slice(4);
const cl = new XMPPClient(jid, pass);
for(const muc_jid of muc_jids) {
cl.joinRoom(muc_jid);
}
const trimString = s => s
.replace(/\s+/g, " ")
.replace(/^\s+/, "")
.replace(/\s+$/, "");
function spaceAPI() {
return fetch(SPACEAPI_URL)
.then(res => res.json());
}
function buyMate(muc, user, item, amount) {
return matematBuy(user, item, amount)
.then(response =>
cl.sendRoomMessage(muc, `Ok, Matemat sagt: ${response}`)
)
.catch(e =>
cl.sendRoomMessage(muc, `Oops, ${e.message}`)
)
}
function correctMessage(muc, nick, regexp, replacement) {
const history = cl.getHistory(muc);
var lastMessage = "";
var foundRegexMessage = false;
for (var i = history.length; i-- > 0; ) {
if (history[i].nick === nick) {
if (foundRegexMessage) {
lastMessage = history[i].message;
break;
}
foundRegexMessage = true;
}
}
if (lastMessage === "") {
cl.sendRoomMessage(muc, `Keine letzte Nachricht…`);
} else {
const result = lastMessage.replace(regexp, replacement);
cl.sendRoomMessage(muc, `${nick} meint: ${result}`);
}
}
function fetchPageTitle(muc, url) {
if (!/^https?:\/\//.test(url)) {
var url = `http://${url}`;
}
fetch(url)
.then(res => res.text())
.then(body => {
const $ = cheerio.load(body);
var title = $('title').text().replace(/^\s+|\s+$/g, '');
if (title.length === 0) {
return;
}
if (title.length > 100) {
title = `${title.substring(0, 100)}…`;
}
cl.sendRoomMessage(muc, title);
});
}
const DEFAULT_MATE_PRICE = 1.50;
function sendBitcoinPrice(muc) {
let price = fetch("http://matemat.hq.c3d2.de/summary.json")
.then(res => res.json())
.then(json => {
let kolleMate = json.filter(value => value.name == "Kolle Mate")[0];
let price = kolleMate && kolleMate.price || DEFAULT_MATE_PRICE;
return price;
}).catch(() => DEFAULT_MATE_PRICE);
fetch("https://api.coindesk.com/v1/bpi/currentprice/euro.json")
.then(res => res.json())
.then(json => json.bpi.EUR.rate_float)
.then(euro => {
price.then(price => {
const kollemate = Math.floor(euro / price);
cl.sendRoomMessage(muc, `BTC: ${kollemate} Flaschen Kolle-Mate (${euro.toFixed(2)}€)`);
});
});
}
function sendCovidStats(location, muc) {
getCovid(location)
.then(stats => {
cl.sendRoomMessage(muc, `7-Tage-Inzidenz ${stats.name}: ${stats.y}`);
});
}
function evalNix(muc, expr) {
const nix = spawn('nix', [
'eval', '--json',
'--option', 'cores', '0',
'--option', 'restrict-eval', 'true',
'--option', 'sandbox', 'true',
'--option', 'timeout', '3',
'--option', 'max-jobs', '0',
'--option', 'allow-import-from-derivation', 'false',
'--option', 'allowed-uris', '',
'nixpkgs#legacyPackages.x86_64-linux', '--apply', `p: with p; ${expr}`
]);
nix.stdout.on('data', (data) => {
cl.sendRoomMessage(muc, `${data}`);
});
nix.stderr.on('data', (data) => {
console.log(`${data}`);
});
nix.on('close', (code) => {
if (code !== 0) {
console.log(`nix process exited with code ${code}`);
}
});
}
function sendElbePegel(muc) {
fetch("https://www.pegelonline.wsv.de/webservices/rest-api/v2/stations/DRESDEN/W/measurements.json")
.then(res => res.json())
.then(json => {
const pegel = json[json.length-1].value;
cl.sendRoomMessage(muc, `Pegel: ${pegel} cm`)
}).catch(() => {
cl.sendRoomMessage(muc, `Der Pegelstand konnte leider nicht abgerufen werden, bitte versuch es später noch einmal!`)
});
}
function fetchSchleuder(muc, nick){
const baseUrl = "https://ds.ccc.de/";
fetch(baseUrl + "download.html")
.then(res => res.text())
.then(html => {
const $ = cheerio.load(html);
const actual = $("body div[id=schleudern]").children().first();
let num = parseInt(actual.text().match(/[0-9]+/));
let url = actual.find("a").attr("href");
if ( ! /:\/\//i.test(url) ) { url = baseUrl + url; }
cl.sendRoomMessage(muc, `${nick}: Schleuder Nummer ${num} ist auf ${baseUrl} zu finden und daher min. als Print verfügbar. Somit ist Nummer ${++num} bereits in Arbeit, schreibt gerne Artikel damit sie schneller fertig wird!`);
});
}
cl.on('muc:message', (muc, nick, text) => {
var m;
if (/[^`]?[\+\?\!\/\\]hq status$/i.test(text)) {
spaceAPI().then(json => {
if (json.state &&
json.state.hasOwnProperty('open') &&
json.state.hasOwnProperty('message')) {
const open = !! json.state.hasOwnProperty('open');
cl.sendRoomMessage(muc, `${nick}: [${open ? "OPEN" : "CLOSED"}] ${json.state.message}`);
}
});
} else if (/[^`]?[\+\?\!\/\\]hq sensors$/i.test(text)) {
spaceAPI().then(json => {
const categories = Object.keys(json.sensors || {});
cl.sendRoomMessage(muc, `${nick}: +hq sensors <${categories.join(" | ")}>`);
});
} else if ((m = text.match(/[^`]?[\+\?\!\/\\]hq sensors (.+)$/))) {
const category = m[1];
spaceAPI().then(json => {
const readings = json.sensors[category];
if (!readings) {
cl.sendRoomMessage(muc, `${nick}: No such sensors`);
} else {
var text = `${nick}, ${category} sensors:`;
for(const { name, value, unit, location } of readings) {
text += `\n${name}: ${value} ${unit}`;
if (location) {
text += ` (${location})`;
}
}
cl.sendRoomMessage(muc, text);
}
});
} else if (/^hello/i.test(text) || /^hi$/i.test(text) || /^hallo/i.test(text)) {
cl.sendRoomMessage(muc, `${nick}: Hi!`);
} else if (/[^`]?[\+\?\!\/\\]hq mate$/i.test(text) || /[^`]?was gibt es\?$/i.test(text)) {
matematSummary().then(summary => {
const lines = summary
.filter(({ value }) => value > 0)
.map(({ value, name }) => `${value}× ${name}`)
.join("\n");;
cl.sendRoomMessage(muc, `Wir haben:\n${lines}`);
});
} else if ((m = text.match(/[^`]?[\+\?\!\/\\]hq mate (\d+) (.+)$/i)) || (m = text.match(/^ich kaufe (\d+) (.+)$/i))) {
buyMate(muc, nick, m[2], parseInt(m[1]));
} else if ((m = text.match(/[^`]?[\+\?\!\/\\]hq mate (.+)$/i)) || (m = text.match(/^ich kaufe eine? (.+)$/i))) {
buyMate(muc, nick, m[1], 1);
} else if (text.toLowerCase().indexOf(cl.rooms[muc].nick) !== -1) {
cl.sendRoomMessage(muc, 'I am famous!');
} else if (/[^`]?[\+\?\!\/\\](bitcoin|btc)$/i.test(text)) {
sendBitcoinPrice(muc);
} else if ((m = text.match(/[^`]?[\+\?\!\/\\]covid (.+)/))) {
sendCovidStats(m[1], muc);
} else if (/[^`]?[\+\?\!\/\\]covid/.test(text)) {
sendCovidStats(null, muc);
} else if (m = text.match(/[^`]?[\+\?\!\/\\]nix (.*)/)) {
evalNix(muc, m[1]);
} else if (m = text.match(TEST_URL_REGEX)) {
fetchPageTitle(muc, m[0]);
} else if ((/voucher/i.test(text) || /gutschein/i.test(text) || /token/i.test(text)) && (/[ck]ongress/i.test(text) || /35c3/i.test(text)) && /wiki/i.test(text)) {
cl.sendRoomMessage(muc, `${nick}: Bitte habe etwas Geduld, es gibt ja nicht unendlich viele Voucher!`)
} else if ((/voucher/i.test(text) || /gutschein/i.test(text) || /token/i.test(text)) && (/[ck]ongress/i.test(text) || /35c3/i.test(text))) {
cl.sendRoomMessage(muc, `${nick}: Bitte sieh doch im Wiki nach und koordiniere dein Anliegen dort!\nhttps://wiki.c3d2.de/35C3#Erfa-Voucher`);
} else if (/mitglied/i.test(text) || /membership/i.test(text) || ((/ccc/i.test(text) || /c3d2/i.test(text)) && /beitreten/i.test(text))) {
cl.sendRoomMessage(muc, `${nick}: Du kannst gerne den CCC Dresden unterstützen <https://c3d2.de/unterstuetzen.html>, oder Mitglied im lokalen Verein <https://c3d2.de/membership.html> bzw. im CCC eV <https://www.ccc.de/de/membership> werden.`);
} else if (/datenschleuder/i.test(text) || /schleuder/i.test(text)) {
fetchSchleuder(muc, nick);
} else if (/[^`]?[\+\?\!\/\\]elbe$/i.test(text) || /[^`]?[\+\?\!\/\\]labe$/i.test(text) || /[^`]?[\+\?\!\/\\]laba$/i.test(text) || /[^`]?[\+\?\!\/\\]łaba$/i.test(text) || /[^`]?[\+\?\!\/\\]albis$/i.test(text)) {
sendElbePegel(muc);
} else if ((m = text.match(/[^`]?s\/([^/]*)\/([^/]*)\/(\w*)$/))) {
try {
var regexp = new RegExp(m[1], m[3]);
correctMessage(muc, nick, regexp, m[2]);
} catch (e) {
console.error(e.stack);
}
}
});
cl.on('end', function() {
process.exit(1);
});