@20syldev/api 3.2.5 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app.js CHANGED
@@ -1,1122 +1,1156 @@
1
- import cors from 'cors';
2
- import dotenv from 'dotenv';
3
- import express from 'express';
4
- import fetch from 'node-fetch';
5
- import ical from 'ical.js';
6
- import { createCanvas } from 'canvas';
7
- import { randomBytes, getHashes, createHash } from 'crypto';
8
- import { urlencoded, json } from 'express';
9
- import { factorial } from 'mathjs';
10
- import { dirname, join } from 'path';
11
- import { toDataURL } from 'qrcode';
12
- import { fileURLToPath } from 'url';
13
- import { v4 } from 'uuid';
14
-
15
- const __filename = fileURLToPath(import.meta.url);
16
- const __dirname = dirname(__filename);
17
- const app = express();
18
-
19
- // Define allowed versions & endpoints for each version
20
- const versions = ['v1', 'v2', 'v3'];
21
- const endpoints = {
22
- v1: ['algorithms', 'captcha', 'color', 'convert', 'domain', 'infos', 'personal', 'qrcode', 'token', 'username', 'website'],
23
- v2: ['algorithms', 'captcha', 'chat', 'color', 'convert', 'domain', 'hash', 'infos', 'personal', 'qrcode', 'tic-tac-toe', 'token', 'username', 'website'],
24
- v3: ['algorithms', 'captcha', 'chat', 'color', 'convert', 'domain', 'hash', 'hyperplanning', 'infos', 'levenshtein', 'personal', 'qrcode', 'tic-tac-toe', 'time', 'token', 'username', 'website']
25
- };
26
-
27
- // Arrowed functions (formatting, math & random)
28
- const formatDate = d => new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().replace('Z', '');
29
- const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
30
- const genID = () => {
31
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
32
- return Array.from(randomBytes(5)).map(b => chars[b % chars.length]).join('');
33
- };
34
- const genIP = () => `${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`;
35
- const genToken = (chars, length) => Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
36
- const random = (arr) => arr[Math.floor(Math.random() * arr.length)];
37
-
38
- // Store data
39
- const logs = [], chat = [], privateChats = {}, sessions = {}, rateLimits = {}, games = {};
40
-
41
- // Define global variables
42
- let contributions, lastFetch = 0, requests = 0, resetTime = Date.now() + 10000;
43
-
44
- // ----------- ----------- MAIN FUNCTIONS ----------- ----------- //
45
-
46
- /**
47
- * Check the game result of a Tic-Tac-Toe game.
48
- *
49
- * @param {Array} moves - The moves of the game.
50
- * @returns {Object} - The result of the game.
51
- */
52
- function checkGame(moves) {
53
- let board = Array(3).fill().map(() => Array(3).fill(null));
54
- let playerSymbols = {};
55
- let playersOrder = [];
56
-
57
- moves.forEach(({ username, move }) => {
58
- if (!playerSymbols[username]) {
59
- playersOrder.push(username);
60
- playerSymbols[username] = playersOrder.length === 1 ? 'X' : 'O';
61
- }
62
- let [row, col] = move.split('-').map(Number);
63
- board[row - 1][col - 1] = playerSymbols[username];
64
- });
65
-
66
- const checkWinner = (symbol) => {
67
- for (let i = 0; i < 3; i++) {
68
- if (board[i][0] === symbol && board[i][1] === symbol && board[i][2] === symbol) return true;
69
- if (board[0][i] === symbol && board[1][i] === symbol && board[2][i] === symbol) return true;
70
- }
71
- if (board[0][0] === symbol && board[1][1] === symbol && board[2][2] === symbol) return true;
72
- if (board[0][2] === symbol && board[1][1] === symbol && board[2][0] === symbol) return true;
73
- return false;
74
- };
75
-
76
- let winner = Object.keys(playerSymbols).find(player => checkWinner(playerSymbols[player]));
77
- let isTie = !winner && moves.length === 9;
78
- let loser = winner && playersOrder.length === 2 ? playersOrder.find(player => player !== winner) : null;
79
-
80
- return { winner, loser, tie: isTie };
81
- }
82
-
83
- // ----------- ----------- MIDDLEWARES SETUP ----------- ----------- //
84
-
85
- dotenv.config();
86
-
87
- // CORS & Express setup
88
- app.use(cors({ methods: ['GET', 'POST'] }));
89
- app.use(urlencoded({ extended: true }));
90
- app.use(json());
91
-
92
- // Set favicon for API
93
- app.use('/favicon.ico', express.static(join(__dirname, 'src', 'favicon.ico')));
94
-
95
- // Display robots.txt
96
- app.use('/robots.txt', express.static(join(__dirname, 'robots.txt')));
97
-
98
- // Return formatted JSON
99
- app.use((req, res, next) => {
100
- res.setHeader('Content-Type', 'application/json');
101
- res.jsonResponse = (data) => {
102
- res.send(JSON.stringify(data, null, 2));
103
- };
104
- next();
105
- });
106
-
107
- // Too many requests
108
- app.use((req, res, next) => {
109
- if (Date.now() > resetTime) requests = 0, resetTime = Date.now() + 10000;
110
- if (++requests > 1000) return res.status(429).jsonResponse({ message: 'Too Many Requests' });
111
- next();
112
- });
113
-
114
- // Save and send logs
115
- app.use((req, res, next) => {
116
- if (req.method === 'HEAD') return next();
117
- if (req.originalUrl === '/logs') return next();
118
-
119
- const startTime = Date.now();
120
-
121
- res.on('finish', () => {
122
- logs.push({
123
- timestamp: new Date().toISOString(),
124
- method: req.method,
125
- url: req.originalUrl,
126
- status: res.statusCode === 304 ? 200 : res.statusCode,
127
- duration: `${Date.now() - startTime}ms`,
128
- platform: req.headers['sec-ch-ua-platform']?.replace(/"/g, ''),
129
- });
130
- if (logs.length > 1000) logs.shift();
131
- console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} ${res.statusCode} - ${Date.now() - startTime}ms`);
132
- });
133
- next();
134
- });
135
-
136
- // Internal Server Error
137
- app.use((err, req, res, next) => {
138
- console.error(err.stack);
139
- res.status(500).jsonResponse({
140
- message: 'Internal Server Error',
141
- error: err.message,
142
- documentation: 'https://docs.sylvain.pro',
143
- status: '500'
144
- });
145
- });
146
-
147
- // Check if version exists
148
- app.use('/:version', (req, res, next) => {
149
- const { version } = req.params;
150
- const latest = versions[versions.length - 1];
151
- const endpoint = req.originalUrl.split('/').slice(2).join('/');
152
-
153
- if (['latest', 'fr', 'en'].includes(version)) {
154
- return res.redirect(endpoint ? `/${latest}/${endpoint}` : `/${latest}`);
155
- }
156
-
157
- if (!versions.includes(version) && version !== 'logs') {
158
- return res.status(404).jsonResponse({
159
- message: 'Not Found',
160
- error: `Invalid API version (${version}).`,
161
- documentation: `https://docs.sylvain.pro/${versions.at(-1)}`,
162
- status: '404'
163
- });
164
- }
165
- next();
166
- });
167
-
168
- // Check if endpoint exists
169
- app.use('/:version/:endpoint', (req, res, next) => {
170
- const { version, endpoint } = req.params;
171
-
172
- if (!versions.includes(version) || !endpoints[version].includes(endpoint)) {
173
- return res.status(404).jsonResponse({
174
- message: 'Not Found',
175
- error: `Endpoint '${endpoint}' does not exist in ${version}.`,
176
- documentation: `https://docs.sylvain.pro/${versions.at(-1)}`,
177
- status: '404'
178
- });
179
- }
180
- next();
181
- });
182
-
183
- // ----------- ----------- MAIN ENDPOINTS ----------- ----------- //
184
-
185
- // Main route
186
- app.get('/', (req, res) => {
187
- res.setHeader('Content-Type', 'application/json');
188
- res.jsonResponse({
189
- documentation: 'https://docs.sylvain.pro',
190
- latest: 'https://api.sylvain.pro/latest',
191
- logs: 'https://api.sylvain.pro/logs',
192
- versions: {
193
- v1: 'https://api.sylvain.pro/v1',
194
- v2: 'https://api.sylvain.pro/v2',
195
- v3: 'https://api.sylvain.pro/v3'
196
- }
197
- });
198
- });
199
-
200
- // Display v1 endpoints
201
- app.get('/v1', (req, res) => {
202
- res.jsonResponse({
203
- version: 'v1',
204
- documentation: 'https://docs.sylvain.pro/v1',
205
- endpoints: {
206
- get: {
207
- algorithm: '/v1/algorithms?method={algorithm}&value={value}(&value2={value2})',
208
- captcha: '/v1/captcha?text={text}',
209
- color: '/v1/color',
210
- convert: '/v1/convert?value={value}&from={unit}&to={unit}',
211
- domain: '/v1/domain',
212
- infos: '/v1/infos',
213
- personal: '/v1/personal',
214
- qrcode: '/v1/qrcode?url={URL}',
215
- username: '/v1/username'
216
- },
217
- post: {
218
- token: '/v1/token'
219
- }
220
- }
221
- });
222
- });
223
-
224
- // Display v2 endpoints
225
- app.get('/v2', (req, res) => {
226
- res.jsonResponse({
227
- version: 'v2',
228
- documentation: 'https://docs.sylvain.pro/v2',
229
- endpoints: {
230
- get: {
231
- algorithm: '/v2/algorithms?method={algorithm}&value={value}(&value2={value2})',
232
- captcha: '/v2/captcha?text={text}',
233
- chat: '/v2/chat',
234
- color: '/v2/color',
235
- convert: '/v2/convert?value={value}&from={unit}&to={unit}',
236
- domain: '/v2/domain',
237
- infos: '/v2/infos',
238
- personal: '/v2/personal',
239
- qrcode: '/v2/qrcode?url={URL}',
240
- username: '/v2/username'
241
- },
242
- post: {
243
- chat: {
244
- chat: '/v2/chat',
245
- private: '/v2/chat/private'
246
- },
247
- hash: '/v2/hash',
248
- tic_tac_toe: {
249
- tic_tac_toe: '/v2/tic-tac-toe',
250
- fetch: '/v2/tic-tac-toe/fetch'
251
- },
252
- token: '/v2/token'
253
- }
254
- }
255
- });
256
- });
257
-
258
- // Display v3 endpoints
259
- app.get('/v3', (req, res) => {
260
- res.jsonResponse({
261
- version: 'v3',
262
- documentation: 'https://docs.sylvain.pro/v3',
263
- endpoints: {
264
- get: {
265
- algorithm: '/v3/algorithms?method={algorithm}&value={value}(&value2={value2})',
266
- captcha: '/v3/captcha?text={text}',
267
- chat: '/v3/chat',
268
- color: '/v3/color',
269
- convert: '/v3/convert?value={value}&from={unit}&to={unit}',
270
- domain: '/v3/domain',
271
- infos: '/v3/infos',
272
- levenshtein: '/v3/levenshtein?str1={string}&str2={string}',
273
- personal: '/v3/personal',
274
- qrcode: '/v3/qrcode?url={URL}',
275
- time: '/v3/time(?type={type}&start={timestamp}&end={timestamp}&format={format}&timezone={timezone})',
276
- username: '/v3/username'
277
- },
278
- post: {
279
- chat: {
280
- chat: '/v3/chat',
281
- private: '/v3/chat/private'
282
- },
283
- hash: '/v3/hash',
284
- hyperplanning: '/v3/hyperplanning',
285
- tic_tac_toe: {
286
- tic_tac_toe: '/v3/tic-tac-toe',
287
- fetch: '/v3/tic-tac-toe/fetch'
288
- },
289
- token: '/v3/token'
290
- }
291
- }
292
- });
293
- });
294
-
295
- // Display logs
296
- app.get('/logs', (req, res) => res.jsonResponse(logs));
297
-
298
- // ----------- ----------- GET ENDPOINTS ----------- ----------- //
299
-
300
- // Algorithms
301
- app.get('/:version/algorithms', (req, res) => {
302
- const { method, value, value2 } = req.query;
303
- const { version } = req.params;
304
-
305
- if (!['anagram', 'bubblesort', 'factorial', 'fibonacci', 'gcd', 'isprime', 'palindrome', 'primefactors', 'primelist', 'reverse'].includes(method)) {
306
- return res.jsonResponse({
307
- error: 'Please provide a valid algorithm (?method={algorithm})',
308
- documentation: `https://docs.sylvain.pro/${version}/algorithms`
309
- });
310
- }
311
- if (!value) return res.jsonResponse({ error: 'Please provide a valid value (&value={value})' });
312
-
313
- if (method === 'anagram') {
314
- if (!value2) return res.jsonResponse({ error: 'Please provide a second value (&value2={value})' });
315
- return res.jsonResponse({ answer: value.split('').sort().join('') === value2.split('').sort().join('') });
316
- }
317
-
318
- if (method === 'bubblesort') {
319
- const arr = value.split(',').map(Number);
320
- const n = arr.length;
321
- for (let i = 0; i < n-1; i++) {
322
- for (let j = 0; j < n-i-1; j++) {
323
- if (arr[j] > arr[j + 1]) [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
324
- }
325
- }
326
- return res.jsonResponse({ answer: arr });
327
- }
328
-
329
- if (method === 'factorial') {
330
- if (isNaN(value) || value < 0 || value > 170) return res.jsonResponse({ error: 'Please provide a valid number between 0 and 170.' });
331
- return res.jsonResponse({ answer: factorial(value) });
332
- }
333
-
334
- if (method === 'fibonacci') {
335
- let fib = [0, 1];
336
- for (let i = 2; i < parseInt(value); i++) fib.push(fib[i - 1] + fib[i - 2]);
337
- return res.jsonResponse({ answer: fib.slice(0, parseInt(value)) });
338
- }
339
-
340
- if (method === 'gcd') {
341
- if (!value2) return res.jsonResponse({ error: 'Please provide a second value (&value2={value})' });
342
- if (isNaN(value) || isNaN(value2)) return res.jsonResponse({ error: 'Invalid numbers.' });
343
- return res.jsonResponse({ answer: gcd(value, value2) });
344
- }
345
-
346
- if (method === 'isprime') {
347
- let isPrime = true;
348
- if (isNaN(value) || value < 1) return res.jsonResponse({ error: 'Please provide a valid number greater than or equal to 1.' });
349
- for (let i = 2; i <= Math.sqrt(value); i++) {
350
- if (value % i === 0) {
351
- isPrime = false;
352
- break;
353
- }
354
- }
355
- return res.jsonResponse({ answer: isPrime });
356
- }
357
-
358
- if (method === 'palindrome') return res.jsonResponse({ answer: value === value.split('').reverse().join('') });
359
-
360
- if (method === 'primefactors') {
361
- let num = value;
362
- let factors = [];
363
- if (isNaN(num) || num < 2 || num > 100000) return res.jsonResponse({ error: 'Please provide a valid number between 2 and 100 000.' });
364
- for (let i = 2; i <= num; i++) {
365
- while (num % i === 0) {
366
- factors.push(i);
367
- num /= i;
368
- }
369
- }
370
- return res.jsonResponse({ answer: factors });
371
- }
372
-
373
- if (method === 'primelist') {
374
- const primes = [];
375
- if (isNaN(value) || value < 2 || value > 10000) return res.jsonResponse({ error: 'Please provide a valid number between 2 and 10 000.' });
376
- for (let i = 2; i <= value; i++) {
377
- let isPrime = true;
378
- for (let j = 2; j <= Math.sqrt(i); j++) {
379
- if (i % j === 0) {
380
- isPrime = false;
381
- break;
382
- }
383
- }
384
- if (isPrime) primes.push(i);
385
- }
386
- return res.jsonResponse({ answer: primes });
387
- }
388
-
389
- if (method === 'reverse') return res.jsonResponse({ answer: value.split('').reverse().join('') });
390
- });
391
-
392
- // Generate captcha
393
- app.get('/:version/captcha', (req, res) => {
394
- const captcha = req.query.text;
395
-
396
- if (!captcha) return res.jsonResponse({ error: 'Please provide a valid argument (?text={text})' });
397
-
398
- const size = 60, font = '60px Comic Sans Ms', width = captcha.length * size, height = 120;
399
- const canvas = createCanvas(width, height), ctx = canvas.getContext('2d');
400
-
401
- ctx.fillStyle = 'white';
402
- ctx.fillRect(0, 0, width, height);
403
-
404
- for (let i = 0; i < 20; i++) {
405
- ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
406
- ctx.beginPath();
407
- ctx.moveTo(Math.random() * width, Math.random() * height);
408
- ctx.lineTo(Math.random() * width, Math.random() * height);
409
- ctx.lineWidth = Math.random() * 2;
410
- ctx.stroke();
411
- }
412
-
413
- let x = (canvas.width + 20 - width) / 2;
414
- for (let i = 0; i < captcha.length; i++) {
415
- const offsetX = Math.cos(i * 0.3) * 10, y = height / 2.5 + Math.floor(Math.random() * (height / 2));
416
-
417
- ctx.font = font;
418
- ctx.fillStyle = `rgb(${Math.floor(Math.random() * 192)}, ${Math.floor(Math.random() * 192)}, ${Math.floor(Math.random() * 192)})`;
419
-
420
- ctx.save();
421
- ctx.translate(x + size / 2, y);
422
- ctx.rotate((Math.random() - 0.5) * 0.5);
423
- ctx.fillText(captcha[i], -size / 2 + offsetX, 0);
424
- ctx.restore();
425
-
426
- x += size;
427
- }
428
-
429
- for (let i = 0; i < 200; i++) {
430
- ctx.fillStyle = 'black';
431
- ctx.fillRect(Math.floor(Math.random() * width), Math.floor(Math.random() * height), 1.2, 1.2);
432
- }
433
-
434
- res.set('Content-Type', 'image/png');
435
- res.send(canvas.toBuffer('image/png'));
436
- });
437
-
438
- // Display stored data
439
- app.get('/:version/chat', (req, res) => {
440
- if (chat.length > 0) res.jsonResponse(chat);
441
- else res.jsonResponse({ error: 'No messages stored.' });
442
- });
443
-
444
- // GET private chat error
445
- app.get('/:version/chat/private', (req, res) => {
446
- res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
447
- });
448
-
449
- // Generate color
450
- app.get('/:version/color', (req, res) => {
451
- const r = Math.floor(Math.random() * 256), g = Math.floor(Math.random() * 256), b = Math.floor(Math.random() * 256);
452
- const hsl = (() => {
453
- const r1 = r / 255, g1 = g / 255, b1 = b / 255, max = Math.max(r1, g1, b1), min = Math.min(r1, g1, b1), l = (max + min) / 2;
454
- if (max === min) return [0, 0, l * 100];
455
- const d = max - min, s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
456
- let h = { [r1]: (g1 - b1) / d + (g1 < b1 ? 6 : 0), [g1]: (b1 - r1) / d + 2, [b1]: (r1 - g1) / d + 4 }[max];
457
- return [h * 60 % 360, s * 100, l * 100];
458
- })();
459
- const hsv = (() => {
460
- const max = Math.max(r, g, b), min = Math.min(r, g, b), v = max / 255, s = max ? (max - min) / max : 0;
461
- let h = max === min ? 0 : { [r]: (g - b) / (max - min), [g]: 2 + (b - r) / (max - min), [b]: 4 + (r - g) / (max - min) }[max];
462
- return [h * 60 % 360, s * 100, v * 100];
463
- })();
464
- const hwb = (() => {
465
- const [h] = hsv, whiteness = Math.min(r, g, b) / 255, blackness = 1 - Math.max(r, g, b) / 255;
466
- return [h, whiteness * 100, blackness * 100];
467
- })();
468
- const cmyk = (() => {
469
- const k = 1 - Math.max(r, g, b) / 255, c = (1 - r / 255 - k) / (1 - k) || 0, m = (1 - g / 255 - k) / (1 - k) || 0, y = (1 - b / 255 - k) / (1 - k) || 0;
470
- return [c, m, y, k].map(x => x * 100);
471
- })();
472
- res.jsonResponse({
473
- hex: `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`,
474
- rgb: `rgb(${r}, ${g}, ${b})`,
475
- hsl: `hsl(${hsl[0].toFixed(1)}, ${hsl[1].toFixed(1)}%, ${hsl[2].toFixed(1)}%)`,
476
- hsv: `hsv(${hsv[0].toFixed(1)}, ${hsv[1].toFixed(1)}%, ${hsv[2].toFixed(1)}%)`,
477
- hwb: `hwb(${hwb[0].toFixed(1)}, ${hwb[1].toFixed(1)}%, ${hwb[2].toFixed(1)}%)`,
478
- cmyk: `cmyk(${cmyk.map(x => x.toFixed(1)).join('%, ')}%)`
479
- });
480
- });
481
-
482
- // Convert units
483
- app.get('/:version/convert', (req, res) => {
484
- const { value, from, to } = req.query;
485
-
486
- if (!value || isNaN(value)) return res.jsonResponse({ error: 'Please provide a valid value (?value={value})' });
487
- if (!from) return res.jsonResponse({ error: 'Please provide a valid source unit (&from={unit})' });
488
- if (!to) return res.jsonResponse({ error: 'Please provide a valid target unit (&to={unit})' });
489
-
490
- const conversions = {
491
- celsius: { fahrenheit: (val) => (val * 9) / 5 + 32, kelvin: (val) => val + 273.15 },
492
- fahrenheit: { celsius: (val) => ((val - 32) * 5) / 9, kelvin: (val) => ((val - 32) * 5) / 9 + 273.15 },
493
- kelvin: { celsius: (val) => val - 273.15, fahrenheit: (val) => ((val - 273.15) * 9) / 5 + 32 },
494
- };
495
-
496
- const convert = conversions[from.toLowerCase()]?.[to.toLowerCase()];
497
- if (!convert) return res.jsonResponse({ error: 'Invalid conversion units.' });
498
-
499
- res.jsonResponse({ from, to, value: parseFloat(value), result: convert(parseFloat(value)) });
500
- });
501
-
502
- // Generate domain informations
503
- app.get('/:version/domain', (req, res) => {
504
- const subdomains = ['fr.', 'en.', 'docs.', 'api.', 'projects.', 'app.', 'web.', 'info.', 'dev.', 'shop.', 'blog.', 'support.', 'mail.', 'forum.'];
505
- const domains = ['example', 'site', 'test', 'demo', 'page', 'store', 'portfolio', 'platform', 'hub', 'network', 'service', 'cloud', 'solutions', 'company'];
506
- const tlds = ['.com', '.fr', '.eu', '.dev', '.net', '.org', '.io', '.tech', '.biz', '.info', '.co', '.app', '.store', '.online', '.shop', '.tv'];
507
-
508
- const domain = `${random(domains)}${random(tlds)}`;
509
- const fulldomain = `${random(subdomains)}${domain}`;
510
-
511
- const ips = Array.from({ length: Math.floor(Math.random() * 3) + 1 }, genIP);
512
- const dns = Array.from({ length: Math.floor(Math.random() * 5) + 1 }, genIP);
513
-
514
- res.jsonResponse({
515
- domain,
516
- full_domain: fulldomain,
517
- ip_address: ips,
518
- ssl_certified: Math.random() > 0.5,
519
- hosting_provider: random(['AWS', 'Bluehost', 'DigitalOcean', 'GitHub', 'HostGator', 'Render', 'SiteGround']),
520
- dns_servers: dns,
521
- dns_provider: random(['AWS Route 53', 'Cloudflare', 'GoDaddy', 'Google DNS', 'Namecheap']),
522
- traffic: `${Math.floor(Math.random() * 10000)} visits/day`,
523
- seo_score: Math.floor(Math.random() * 100),
524
- page_rank: Math.floor(Math.random() * 10),
525
- country: random(['Australia', 'Canada', 'France', 'Germany', 'India', 'Japan', 'UK', 'USA']),
526
- website_type: random(['Blog', 'Community', 'Corporate', 'Educational', 'E-commerce', 'Personal', 'Portfolio']),
527
- random_name: domain.split('.')[0],
528
- random_subdomain: fulldomain.split('.')[0],
529
- random_tld: domain.split('.').pop(),
530
- backlinks_count: Math.floor(Math.random() * 1000),
531
- creation_date: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
532
- expiration_date: new Date(Date.now() + Math.floor(Math.random() * 10000000000)).toISOString(),
533
- });
534
- });
535
-
536
- // GET planning error
537
- app.get('/:version/hyperplanning', (req, res) => {
538
- res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
539
- });
540
-
541
- // GET hash error
542
- app.get('/:version/hash', (req, res) => {
543
- res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
544
- });
545
-
546
- // Display API informations
547
- app.get('/:version/infos', (req, res) => {
548
- res.jsonResponse({
549
- endpoints: endpoints[versions.at(-1)].length,
550
- last_version: versions.at(-1),
551
- documentation: 'https://docs.sylvain.pro',
552
- github: 'https://github.com/20syldev/api',
553
- creation: 'November 25th 2024',
554
- });
555
- });
556
-
557
- // Calculate Levenshtein distance
558
- app.get('/:version/levenshtein', (req, res) => {
559
- const { str1, str2 } = req.query;
560
-
561
- if (!str1 || typeof str1 !== 'string') return res.jsonResponse({ error: 'Please provide a first string (?str1={string})' });
562
- if (!str2 || typeof str2 !== 'string') return res.jsonResponse({ error: 'Please provide a second string (&str2={string})' });
563
-
564
- if (str1.length > 1000) return res.jsonResponse({ error: 'First string exceeds 1000 characters.' });
565
- if (str2.length > 1000) return res.jsonResponse({ error: 'Second string exceeds 1000 characters.' });
566
-
567
- const lev = (a, b) => {
568
- const m = Array.from({ length: a.length + 1 }, (_, i) => [i]);
569
- for (let j = 0; j <= b.length; j++) m[0][j] = j;
570
- for (let i = 1; i <= a.length; i++)
571
- for (let j = 1; j <= b.length; j++)
572
- m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (a[i - 1] !== b[j - 1]));
573
-
574
- return m[a.length][b.length];
575
- };
576
-
577
- res.jsonResponse({ str1, str2, distance: lev(str1, str2) });
578
- });
579
-
580
- // Generate personal data
581
- app.get('/:version/personal', (req, res) => {
582
- const people = [
583
- { name: 'John Doe', social: 'john_doe', email: 'john@example.com', country: 'US' },
584
- { name: 'Jane Martin', social: 'jane_martin', email: 'jane@example.com', country: 'FR' },
585
- { name: 'Michael Johnson', social: 'mike_johnson', email: 'michael@example.com', country: 'UK' },
586
- { name: 'Emily Davis', social: 'emily_davis', email: 'emily@example.com', country: 'ES' },
587
- { name: 'Alexis Barbos', social: 'alexis_barbos', email: 'alexis@example.com', country: 'DE' },
588
- { name: 'Sarah Williams', social: 'sarah_williams', email: 'sarah@example.com', country: 'IT' },
589
- { name: 'Daniel Brown', social: 'daniel_brown', email: 'daniel@example.com', country: 'JP' },
590
- { name: 'Sophia Wilson', social: 'sophia_wilson', email: 'sophia@example.com', country: 'BR' },
591
- { name: 'James Taylor', social: 'james_taylor', email: 'james@example.com', country: 'CA' },
592
- { name: 'Olivia Thomas', social: 'olivia_thomas', email: 'olivia@example.com', country: 'AU' }
593
- ];
594
-
595
- const countries = {
596
- US: { tel: '123-456-7890', code: '1', lang: 'English' },
597
- FR: { tel: '06 78 90 12 34', code: '33', lang: 'French' },
598
- UK: { tel: '7911 123456', code: '44', lang: 'English' },
599
- ES: { tel: '678 901 234', code: '34', lang: 'Spanish' },
600
- DE: { tel: '163 555 1584', code: '49', lang: 'German' },
601
- IT: { tel: '345 678 9012', code: '39', lang: 'Italian' },
602
- JP: { tel: '080-1234-5678', code: '81', lang: 'Japanese' },
603
- BR: { tel: '(11) 98765-4321', code: '55', lang: 'Portuguese' },
604
- CA: { tel: '416-123-4567', code: '1', lang: 'English' },
605
- AU: { tel: '0412 345 678', code: '61', lang: 'English' }
606
- };
607
-
608
- const jobs = ['Writer', 'Artist', 'Musician', 'Explorer', 'Scientist', 'Engineer', 'Athlete', 'Doctor'];
609
- const hobbies = ['Reading', 'Traveling', 'Gaming', 'Cooking', 'Fitness', 'Music', 'Photography', 'Writing'];
610
- const cities = ['New York', 'Paris', 'London', 'Madrid', 'Berlin', 'Rome', 'Tokyo', 'Los Angeles', 'Sydney', 'São Paulo', 'Toronto'];
611
- const streets = ['Main St', '2nd Ave', 'Broadway', 'Park Lane', 'Elm St', 'Sunset Blvd', 'Maple St', 'Highland Rd'];
612
-
613
- const card = Array.from({ length: 4 }, () => Math.floor(Math.random() * 9000) + 1000).join(' ');
614
- const cvc = Math.floor(Math.random() * 900) + 100;
615
- const expiration = `${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}/${(new Date().getFullYear() + Math.floor(Math.random() * 3)).toString().slice(-2)}`;
616
-
617
- const person = random(people);
618
- const social = person.social;
619
- const country = person.country;
620
- const phone = countries[country].tel;
621
- const lang = countries[country].lang;
622
-
623
- const age = Math.floor(Math.random() * 50) + 18;
624
- const birthday = new Date(Date.now() - Math.floor((Math.random() * 50 + 18) * 365.25 * 24 * 60 * 60 * 1000)).toISOString();
625
-
626
- let emergencyContacts = [], yearIncome = Math.floor(Math.random() * 100000), subscriptions = [], pets = [], vehicles = [];
627
- let civilStatus = 'Single';
628
- let children = 0;
629
-
630
- if (age >= 21 && Math.random() > 0.7) civilStatus = 'Married';
631
-
632
- if (civilStatus === 'Married' && age >= 25) children = Math.floor(Math.random() * 4);
633
-
634
- while (emergencyContacts.length < Math.floor(Math.random() * 3) + 1) {
635
- let emergencyContact = random(people);
636
- while (emergencyContact.email === person.email || emergencyContacts.some(e => e.email === emergencyContact.email)) {
637
- emergencyContact = random(people);
638
- }
639
- emergencyContacts.push({
640
- name: emergencyContact.name,
641
- relationship: random(['Spouse', 'Parent', 'Sibling', 'Friend']),
642
- phone: `+${countries[country].code} ${countries[country].tel}`
643
- });
644
- }
645
-
646
- while (subscriptions.length < Math.floor(Math.random() * 3) + 1) {
647
- let subscription = random(['Netflix', 'Spotify', 'Amazon Prime', 'Disney+', 'Hulu']);
648
- if (!subscriptions.includes(subscription)) subscriptions.push(subscription);
649
- }
650
-
651
- while (pets.length < Math.floor(Math.random() * 3) + 1) {
652
- let pet = random(['Dog', 'Cat', 'Fish', 'Bird', 'None']);
653
- if (!pets.includes(pet)) pets.push(pet);
654
- }
655
-
656
- while (vehicles.length < Math.floor(Math.random() * 3) + 1) {
657
- let vehicle = random(['Car', 'Bike', 'Motorcycle', 'Bus', 'None']);
658
- if (!vehicles.includes(vehicle)) vehicles.push(vehicle);
659
- }
660
-
661
- res.jsonResponse({
662
- name: person.name,
663
- email: person.email,
664
- localisation: country,
665
- phone: `+${countries[country].code} ${phone}`,
666
- job: random(jobs),
667
- hobbies: random(hobbies),
668
- language: lang,
669
- card,
670
- cvc,
671
- expiration,
672
- address: `${Math.floor(Math.random() * 9999)} ${random(streets)}, ${random(cities)}`,
673
- birthday,
674
- civil_status: civilStatus,
675
- children,
676
- vehicle: vehicles,
677
- social_profiles: {
678
- twitter: `@${social}`,
679
- facebook: `facebook.com/${social}`,
680
- linkedin: `linkedin.com/in/${social}`,
681
- instagram: `instagram.com/${social}`
682
- },
683
- year_income: `${yearIncome} USD/year`,
684
- month_income: `${(yearIncome / 12).toFixed(2)} USD/month`,
685
- education: random(['High School', 'Bachelor\'s', 'Master\'s', 'PhD']),
686
- work_experience: `${Math.floor(Math.random() * 20)} years`,
687
- health_status: random(['Healthy', 'Minor Issues', 'Chronic Conditions']),
688
- emergency_contacts: emergencyContacts,
689
- subscriptions,
690
- pets,
691
- });
692
- });
693
-
694
- // Generate QR Code
695
- app.get('/:version/qrcode', async (req, res) => {
696
- const { url } = req.query;
697
-
698
- if (!url) return res.jsonResponse({ error: 'Please provide a valid url (?url={URL})' });
699
-
700
- try { res.jsonResponse({ qr: await toDataURL(url) }); }
701
- catch { res.jsonResponse({ error: 'Error generating QR code.' }); }
702
- });
703
-
704
- // GET tic-tac-toe game error
705
- app.get('/:version/tic-tac-toe', (req, res) => {
706
- res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
707
- });
708
-
709
- // GET tic-tac-toe fetch error
710
- app.get('/:version/tic-tac-toe/fetch', (req, res) => {
711
- res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
712
- });
713
-
714
- // Display or generate time informations
715
- app.get('/:version/time', (req, res) => {
716
- const { type = 'live', start, end, format, timezone } = req.query;
717
-
718
- const validFormats = ['iso', 'utc', 'timestamp', 'locale', 'date', 'time', 'year', 'month', 'day', 'hour', 'minute', 'second', 'ms', 'dayOfWeek', 'dayOfYear', 'weekNumber', 'timezone', 'timezoneOffset'];
719
- const validTimezones = ['UTC', 'America/New_York', 'Europe/Paris', 'Asia/Tokyo', 'Australia/Sydney'];
720
-
721
- if (type !== 'live' && type !== 'random') return res.jsonResponse({ error: 'Please provide a valid type (?type={type})' });
722
- if (start && !Date.parse(start)) return res.jsonResponse({ error: 'Please provide a valid start date (?start={YYYY-MM-DD})' });
723
- if (end && !Date.parse(end)) return res.jsonResponse({ error: 'Please provide a valid end date (?end={YYYY-MM-DD})' });
724
- if (format && !validFormats.includes(format)) return res.jsonResponse({ error: 'Please provide a valid format (?format={format})' });
725
- if (timezone && !validTimezones.includes(timezone)) return res.jsonResponse({ error: 'Please provide a valid timezone (?timezone={timezone})' });
726
-
727
- const getTimeFormats = (date, timezoneOption) => {
728
- return {
729
- iso: date.toISOString(),
730
- utc: date.toUTCString(),
731
- timestamp: date.getTime(),
732
- locale: date.toLocaleString('en-US', { timeZone: timezoneOption, timeZoneName: 'long' }),
733
- date: date.toLocaleDateString('en-US', { timeZone: timezoneOption }),
734
- time: date.toLocaleTimeString('en-US', { timeZone: timezoneOption }),
735
- year: date.getFullYear(),
736
- month: date.getMonth() + 1,
737
- day: date.getDate(),
738
- hour: date.getHours(),
739
- minute: date.getMinutes(),
740
- second: date.getSeconds(),
741
- ms: date.getMilliseconds(),
742
- dayOfWeek: date.getDay(),
743
- dayOfYear: Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 86400000),
744
- weekNumber: Math.ceil((((date - new Date(date.getFullYear(), 0, 0)) / 86400000) + 1) / 7),
745
- timezone: timezoneOption,
746
- timezoneOffset: date.getTimezoneOffset()
747
- };
748
- };
749
-
750
- if (type === 'random') {
751
- const startDate = new Date(start || '1900-01-01').getTime();
752
- const endDate = new Date(end || '2100-12-31').getTime();
753
- const randomDate = new Date(start ? startDate : startDate + Math.random() * (endDate - startDate));
754
- const timezoneOption = timezone || validTimezones[Math.floor(Math.random() * 5)];
755
- const formats = getTimeFormats(randomDate, timezoneOption);
756
-
757
- return res.jsonResponse(format && formats[format] ? { date: formats[format] } : formats);
758
- }
759
-
760
- const now = new Date();
761
- const timezoneOption = timezone || 'UTC';
762
- const formats = getTimeFormats(now, timezoneOption);
763
-
764
- res.jsonResponse(format && formats[format] ? { date: formats[format] } : formats);
765
- });
766
-
767
- // GET token error
768
- app.get('/:version/token', (req, res) => {
769
- res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
770
- });
771
-
772
- // Generate username
773
- app.get('/:version/username', (req, res) => {
774
- const adj = ['Happy', 'Silly', 'Clever', 'Creative', 'Brave', 'Gentle', 'Kind', 'Funny', 'Wise', 'Charming', 'Sincere', 'Resourceful', 'Patient', 'Energetic', 'Adventurous', 'Ambitious', 'Courageous', 'Courteous', 'Determined'];
775
- const ani = ['Cat', 'Dog', 'Tiger', 'Elephant', 'Monkey', 'Penguin', 'Dolphin', 'Lion', 'Bear', 'Fox', 'Owl', 'Giraffe', 'Zebra', 'Koala', 'Rabbit', 'Squirrel', 'Panda', 'Horse', 'Wolf', 'Eagle'];
776
- const job = ['Writer', 'Artist', 'Musician', 'Explorer', 'Scientist', 'Engineer', 'Athlete', 'Chef', 'Doctor', 'Teacher', 'Lawyer', 'Entrepreneur', 'Actor', 'Dancer', 'Photographer', 'Architect', 'Pilot', 'Designer', 'Journalist', 'Veterinarian'];
777
-
778
- const nombre = Math.floor(Math.random() * 100);
779
- const choix = {
780
- adj_num: () => random(adj) + nombre,
781
- ani_num: () => random(ani) + nombre,
782
- pro_num: () => random(job) + nombre,
783
- adj_ani: () => random(adj) + random(ani),
784
- adj_ani_num: () => random(adj) + random(ani) + nombre,
785
- adj_pro: () => random(adj) + random(job),
786
- pro_ani: () => random(job) + random(ani),
787
- pro_ani_num: () => random(job) + random(ani) + nombre
788
- };
789
-
790
- const username = choix[random(Object.keys(choix))]();
791
- res.jsonResponse({ adjective: adj, animal: ani, job, number: nombre, username });
792
- });
793
-
794
- // Display informations for owner's website
795
- app.get('/:version/website', async (req, res) => {
796
- const currentTime = Date.now();
797
-
798
- if (currentTime - lastFetch >= 10 * 60 * 1000) {
799
- try {
800
- const username = '20syldev';
801
- const token = process.env.STATS5;
802
- const today = new Date().toISOString().split('T')[0];
803
- const monthFirst = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0];
804
- const lastYear = new Date(new Date().setFullYear(new Date().getFullYear() - 1)).toISOString().split('T')[0];
805
-
806
- const query = `
807
- {
808
- user(login: "${username}") {
809
- contributionsCollection(from: "${today}T00:00:00Z") {
810
- contributionCalendar {
811
- totalContributions
812
- }
813
- }
814
- contributions_month: contributionsCollection(from: "${monthFirst}T00:00:00Z") {
815
- contributionCalendar {
816
- totalContributions
817
- }
818
- }
819
- contributions_year: contributionsCollection(from: "${lastYear}T00:00:00Z") {
820
- contributionCalendar {
821
- totalContributions
822
- }
823
- }
824
- }
825
- }`;
826
-
827
- const apiResponse = await fetch('https://api.github.com/graphql', {
828
- method: 'POST',
829
- headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
830
- body: JSON.stringify({ query })
831
- });
832
-
833
- if (!apiResponse.ok) throw new Error('Error fetching data.');
834
-
835
- const data = await apiResponse.json();
836
- const user = data?.data?.user;
837
-
838
- contributions = {
839
- today: user?.contributionsCollection?.contributionCalendar?.totalContributions || 0,
840
- month: user?.contributions_month?.contributionCalendar?.totalContributions || 0,
841
- year: user?.contributions_year?.contributionCalendar?.totalContributions || 0,
842
- };
843
-
844
- lastFetch = currentTime;
845
- } catch { contributions = { today: 0, month: 0, year: 0 }; }
846
- }
847
-
848
- res.jsonResponse({
849
- versions: {
850
- api: process.env.API,
851
- cdn: process.env.CDN,
852
- coop_api: process.env.COOP_API,
853
- coop_status: process.env.COOP_STATUS,
854
- chat: process.env.CHAT,
855
- digit: process.env.DIGIT,
856
- doc_coopbot: process.env.DOC_COOPBOT,
857
- docs: process.env.DOCS,
858
- donut: process.env.DONUT,
859
- drawio_plugin: process.env.DRAWIO_PLUGIN,
860
- flowers: process.env.FLOWERS,
861
- gemsync: process.env.GEMSYNC,
862
- gitsite: process.env.GITSITE,
863
- logs: process.env.LOGS,
864
- logvault: process.env.LOGVAULT,
865
- minify: process.env.MINIFY,
866
- morpion: process.env.MORPION,
867
- nitrogen: process.env.NITROGEN,
868
- old_database: process.env.OLD_DATABASE,
869
- php: process.env.PHP,
870
- ping: process.env.PING,
871
- portfolio: process.env.PORTFOLIO,
872
- python_api: process.env.PYTHON_API,
873
- readme: process.env.README,
874
- terminal: process.env.TERMINAL,
875
- wrkit: process.env.WRKIT,
876
- zpki: process.env.ZPKI
877
- },
878
- patched_projects: process.env.PATCH !== undefined ? process.env.PATCH.split(' ') : [],
879
- updated_projects: process.env.RECENT !== undefined ? process.env.RECENT.split(' ') : [],
880
- new_projects: process.env.NEW !== undefined ? process.env.NEW.split(' ') : [],
881
- sub_domains: process.env.DOMAINS !== undefined ? process.env.DOMAINS.split(' ') : [],
882
- stats: {
883
- os: process.env.STATS1,
884
- front: process.env.STATS2,
885
- back: process.env.STATS3,
886
- projects: process.env.STATS4,
887
- today: contributions.today.toString(),
888
- this_month: contributions.month.toString(),
889
- last_year: contributions.year.toString(),
890
- },
891
- notif_tag: process.env.TAG,
892
- active: process.env.ACTIVE
893
- });
894
- });
895
-
896
- // ----------- ----------- POST ENDPOINTS ----------- ----------- //
897
-
898
- // Store chat messages
899
- app.post('/:version/chat', (req, res) => {
900
- const { username, message, timestamp, session, token } = req.body;
901
-
902
- if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
903
- if (!message) return res.jsonResponse({ error: 'Please provide a message (&message={message})' });
904
- if (!session) return res.jsonResponse({ error: 'Please provide a valid session ID (&session={ID})' });
905
-
906
- const u = username.toLowerCase(), now = Date.now();
907
- const msg = { username, message, timestamp: timestamp || new Date().toISOString() };
908
-
909
- rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
910
- if (rateLimits[u].length > 50) {
911
- const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
912
- return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
913
- }
914
- rateLimits[u].push(now);
915
-
916
- if (sessions[u] && sessions[u].user !== session) return res.jsonResponse({ error: 'Session ID mismatch' });
917
-
918
- if (token) {
919
- privateChats[token] = privateChats[token] || [];
920
- privateChats[token].push(msg);
921
- setTimeout(() => { delete privateChats[token]; }, 3600000);
922
- } else {
923
- chat.push(msg);
924
- setTimeout(() => chat.splice(chat.indexOf(msg), 1), 3600000);
925
- }
926
-
927
- sessions[u] = sessions[u] || { user: session, last: now };
928
- sessions[u].last = now;
929
-
930
- setTimeout(() => { if (now - sessions[u].last >= 3600000) delete sessions[u]; }, 3600000);
931
-
932
- res.jsonResponse({ message: 'Message sent successfully' });
933
- });
934
-
935
- // Display a private chat with a token
936
- app.post('/:version/chat/private', (req, res) => {
937
- const { username, token } = req.body;
938
-
939
- if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
940
- if (!token) return res.jsonResponse({ error: 'Please provide a valid token (&token={key}).' });
941
-
942
- const u = username.toLowerCase(), now = Date.now();
943
-
944
- rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
945
- if (rateLimits[u].length > 50) {
946
- const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
947
- return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
948
- }
949
- rateLimits[u].push(now);
950
-
951
- if (privateChats[token]) return res.jsonResponse(privateChats[token]);
952
-
953
- return res.jsonResponse({ error: 'Invalid or expired token.' });
954
- });
955
-
956
- // Generate hash
957
- app.post('/:version/hash', (req, res) => {
958
- const { text, method } = req.body;
959
- const { version } = req.params;
960
-
961
- if (!text) return res.jsonResponse({ error: 'Please provide a text (?text={text})' });
962
- if (!method) return res.jsonResponse({
963
- error: 'Please provide a valid hash algorithm (?method={algorithm})',
964
- documentation: `https://docs.sylvain.pro/${version}/hash`
965
- });
966
-
967
- const methods = getHashes();
968
- if (!methods.includes(method)) return res.jsonResponse({ error: `Unsupported method. Use one of: ${methods.join(', ')}` });
969
-
970
- const hash = createHash(method).update(text).digest('hex');
971
- res.jsonResponse({ method, hash });
972
- });
973
-
974
- // Display a planning from an ICS file
975
- app.post('/:version/hyperplanning', async (req, res) => {
976
- const { url, detail } = req.body;
977
-
978
- if (!url) return res.jsonResponse({ error: 'Please provide a valid ICS file URL.' });
979
-
980
- try {
981
- const response = await fetch(url);
982
- if (!response.ok || !(response.headers.get('content-type') || '').includes('text/calendar')) return res.jsonResponse({ error: 'Invalid ICS file format.' });
983
-
984
- const events = new ical.Component(ical.parse(await response.text()))
985
- .getAllSubcomponents('vevent')
986
- .map(e => {
987
- const evt = new ical.Event(e);
988
- const summary = evt.summary.split(' ').filter(part => part !== '-');
989
- const start = formatDate(evt.startDate.toJSDate());
990
- const end = formatDate(evt.endDate.toJSDate());
991
-
992
- if (detail === 'full') {
993
- const desc = evt.description.split('\n').map(l => l.trim());
994
- const extract = (p) => (desc.find(l => l.startsWith(p)) || '').replace(p, '').trim();
995
-
996
- return {
997
- summary,
998
- subject: extract('Matière :'),
999
- teacher: extract('Enseignant :'),
1000
- classes: extract('Promotions :').split(', ').map(c => c.trim()),
1001
- type: extract('Salle :') || undefined,
1002
- start,
1003
- end
1004
- };
1005
- }
1006
- if (detail === 'list') return { summary, start, end };
1007
-
1008
- return { summary: evt.summary, start, end };
1009
- })
1010
- .sort((a, b) => new Date(a.start) - new Date(b.start))
1011
- .filter(e => new Date(e.end) >= new Date());
1012
-
1013
- res.jsonResponse(events);
1014
- } catch { res.jsonResponse({ error: 'Failed to parse ICS file.' }); }
1015
- });
1016
-
1017
- // Store tic tac toe games
1018
- app.post('/:version/tic-tac-toe', (req, res) => {
1019
- const { username, move, session, game } = req.body;
1020
-
1021
- if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
1022
- if (!move) return res.jsonResponse({ error: 'Please provide a valid move (&move={move})' });
1023
- if (!session) return res.jsonResponse({ error: 'Please provide a valid session ID (&session={ID})' });
1024
- if (!game) return res.jsonResponse({ error: 'Please provide a valid game ID (&game={ID})' });
1025
-
1026
- const u = username.toLowerCase(), now = Date.now();
1027
- const play = { username, move, session };
1028
- const validMoves = ['1-1', '1-2', '1-3', '2-1', '2-2', '2-3', '3-1', '3-2', '3-3'];
1029
-
1030
- if (!validMoves.includes(move)) return res.jsonResponse({ error: 'Invalid move. Please provide a valid move (e.g., 1-1, 2-2, 3-3).' });
1031
-
1032
- rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
1033
- if (rateLimits[u].length > 50) {
1034
- const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
1035
- return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
1036
- }
1037
- rateLimits[u].push(now);
1038
-
1039
- if (sessions[u] && sessions[u].user !== session) return res.jsonResponse({ error: 'Session ID mismatch' });
1040
-
1041
- games[game] = games[game] || [];
1042
-
1043
- const players = [...new Set(games[game].map(play => play.username))];
1044
- if (players.length >= 2 && !players.includes(username)) return res.jsonResponse({ error: 'Game is full, you can only watch.' });
1045
- if (games[game].length > 0 && games[game][games[game].length - 1].username === username) return res.jsonResponse({ error: 'Please wait for the other player to make a move.' });
1046
- if (games[game].some(play => play.move === move)) return res.jsonResponse({ error: 'Move already made. Please choose a different move.' });
1047
-
1048
- games[game].push(play);
1049
-
1050
- const result = checkGame(games[game]);
1051
- if (result.winner || result.tie) {
1052
- setTimeout(() => delete games[game], 600000);
1053
- return res.jsonResponse({
1054
- message: `Move sent successfully. ${result.winner ? result.winner + ' wins. ' + result.loser + ' loses.' : 'It\'s a tie.'}`,
1055
- ...result
1056
- });
1057
- }
1058
- if (!result.winner && !result.tie) setTimeout(() => delete games[game], 3600000);
1059
-
1060
- sessions[u] = sessions[u] || { user: session, last: now };
1061
- sessions[u].last = now;
1062
-
1063
- setTimeout(() => { if (now - sessions[u].last >= 3600000) delete sessions[u]; }, 3600000);
1064
-
1065
- res.jsonResponse({ message: 'Move sent successfully' });
1066
- });
1067
-
1068
- // Display a tic tac toe game with a token
1069
- app.post('/:version/tic-tac-toe/fetch', (req, res) => {
1070
- const { username, game } = req.body;
1071
-
1072
- if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
1073
-
1074
- const ID = game || genID();
1075
- const u = username.toLowerCase(), now = Date.now();
1076
-
1077
- rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
1078
- if (rateLimits[u].length > 50) {
1079
- const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
1080
- return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
1081
- }
1082
- rateLimits[u].push(now);
1083
-
1084
- if (!games[ID]) games[ID] = [];
1085
-
1086
- const data = games[ID];
1087
- const last = data.length ? data[data.length - 1].username : null;
1088
- const players = [...new Set(data.map(p => p.username))];
1089
- const turn = players.find(p => p !== last);
1090
- const result = data.length ? checkGame(data) : {};
1091
-
1092
- res.jsonResponse({ game: data, turn, ID, ...result });
1093
- });
1094
-
1095
- // Generate Token
1096
- app.post('/:version/token', (req, res) => {
1097
- let { len, type } = req.body;
1098
-
1099
- len = parseInt(len || 24, 10);
1100
- type = type ? type.toLowerCase() : 'alpha';
1101
-
1102
- if (isNaN(len) || len < 0) return res.jsonResponse({ error: 'Invalid number.' });
1103
- if (len > 4096) return res.jsonResponse({ error: 'Length cannot exceed 4096.' });
1104
- if (len < 12) return res.jsonResponse({ error: 'Length cannot be less than 12.' });
1105
-
1106
- const token = {
1107
- alpha: genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', len),
1108
- alphanum: genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', len),
1109
- base64: randomBytes(len).toString('base64').slice(0, len),
1110
- hex: randomBytes(len).toString('hex').slice(0, len),
1111
- num: genToken('0123456789', len),
1112
- punct: genToken('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', len),
1113
- urlsafe: genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_', len),
1114
- uuid: v4().replace(/-/g, '').slice(0, len)
1115
- }[type] || genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', len);
1116
-
1117
- res.jsonResponse({ token });
1118
- });
1119
-
1120
- // ----------- ----------- SERVER SETUP ----------- ----------- //
1121
-
1122
- app.listen(3000, () => console.log('API is running on\n - http://127.0.0.1:3000\n - http://localhost:3000'));
1
+ import cors from 'cors';
2
+ import dotenv from 'dotenv';
3
+ import express from 'express';
4
+ import fetch from 'node-fetch';
5
+ import ical from 'ical.js';
6
+ import { createCanvas } from 'canvas';
7
+ import { randomBytes, getHashes, createHash } from 'crypto';
8
+ import { urlencoded, json } from 'express';
9
+ import { factorial } from 'mathjs';
10
+ import { dirname, join } from 'path';
11
+ import { toDataURL } from 'qrcode';
12
+ import { fileURLToPath } from 'url';
13
+ import { v4 } from 'uuid';
14
+
15
+ const __filename = fileURLToPath(import.meta.url);
16
+ const __dirname = dirname(__filename);
17
+ const app = express();
18
+
19
+ // Define allowed versions & endpoints for each version
20
+ const versions = ['v1', 'v2', 'v3'];
21
+ const endpoints = {
22
+ v1: ['algorithms', 'captcha', 'color', 'convert', 'domain', 'infos', 'personal', 'qrcode', 'token', 'username', 'website'],
23
+ v2: ['algorithms', 'captcha', 'chat', 'color', 'convert', 'domain', 'hash', 'infos', 'personal', 'qrcode', 'tic-tac-toe', 'token', 'username', 'website'],
24
+ v3: ['algorithms', 'captcha', 'chat', 'color', 'convert', 'domain', 'hash', 'hyperplanning', 'infos', 'levenshtein', 'personal', 'qrcode', 'tic-tac-toe', 'time', 'token', 'username', 'website']
25
+ };
26
+
27
+ // Arrowed functions (formatting, math & random)
28
+ const formatDate = d => new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().replace('Z', '');
29
+ const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
30
+ const genID = () => {
31
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
32
+ return Array.from(randomBytes(5)).map(b => chars[b % chars.length]).join('');
33
+ };
34
+ const genIP = () => `${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`;
35
+ const genToken = (chars, length) => Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
36
+ const random = (arr) => arr[Math.floor(Math.random() * arr.length)];
37
+
38
+ // Store data
39
+ const logs = [], chat = [], privateChats = {}, sessions = {}, rateLimits = {}, ipLimits = {}, games = {};
40
+
41
+ // Define global variables
42
+ let contributions, lastFetch = 0, requests = 0, requestLimit = 50, globalLimit = 10000, resetTime = Date.now() + 60000;
43
+
44
+ // ----------- ----------- MAIN FUNCTIONS ----------- ----------- //
45
+
46
+ /**
47
+ * Check the game result of a Tic-Tac-Toe game.
48
+ *
49
+ * @param {Array} moves - The moves of the game.
50
+ * @returns {Object} - The result of the game.
51
+ */
52
+ function checkGame(moves) {
53
+ let board = Array(3).fill().map(() => Array(3).fill(null));
54
+ let playerSymbols = {};
55
+ let playersOrder = [];
56
+
57
+ moves.forEach(({ username, move }) => {
58
+ if (!playerSymbols[username]) {
59
+ playersOrder.push(username);
60
+ playerSymbols[username] = playersOrder.length === 1 ? 'X' : 'O';
61
+ }
62
+ let [row, col] = move.split('-').map(Number);
63
+ board[row - 1][col - 1] = playerSymbols[username];
64
+ });
65
+
66
+ const checkWinner = (symbol) => {
67
+ for (let i = 0; i < 3; i++) {
68
+ if (board[i][0] === symbol && board[i][1] === symbol && board[i][2] === symbol) return true;
69
+ if (board[0][i] === symbol && board[1][i] === symbol && board[2][i] === symbol) return true;
70
+ }
71
+ if (board[0][0] === symbol && board[1][1] === symbol && board[2][2] === symbol) return true;
72
+ if (board[0][2] === symbol && board[1][1] === symbol && board[2][0] === symbol) return true;
73
+ return false;
74
+ };
75
+
76
+ let winner = Object.keys(playerSymbols).find(player => checkWinner(playerSymbols[player]));
77
+ let isTie = !winner && moves.length === 9;
78
+ let loser = winner && playersOrder.length === 2 ? playersOrder.find(player => player !== winner) : null;
79
+
80
+ return { winner, loser, tie: isTie };
81
+ }
82
+
83
+ // ----------- ----------- MIDDLEWARES SETUP ----------- ----------- //
84
+
85
+ dotenv.config();
86
+
87
+ // CORS & Express setup
88
+ app.set('trust proxy', 1);
89
+ app.use(cors({ methods: ['GET', 'POST'] }));
90
+ app.use(urlencoded({ extended: true }));
91
+ app.use(json());
92
+
93
+ // Set favicon for API
94
+ app.use('/favicon.ico', express.static(join(__dirname, 'src', 'favicon.ico')));
95
+
96
+ // Display robots.txt
97
+ app.use('/robots.txt', express.static(join(__dirname, 'robots.txt')));
98
+
99
+ // Return formatted JSON
100
+ app.use((req, res, next) => {
101
+ res.setHeader('Content-Type', 'application/json');
102
+ res.jsonResponse = (data) => {
103
+ res.send(JSON.stringify(data, null, 2));
104
+ };
105
+ next();
106
+ });
107
+
108
+ // Too many requests
109
+ app.use((req, res, next) => {
110
+ const ip = req.headers['cf-connecting-ip'] || req.socket.remoteAddress;
111
+ const now = Date.now();
112
+ const token = req.headers.authorization?.split(' ')[1] || '';
113
+
114
+ const unlimited = process.env.UNLIMITED_TOKEN_LIST?.split(' ') || [];
115
+ const pro = process.env.PRO_TOKEN_LIST?.split(' ') || [];
116
+ const advanced = process.env.ADVANCED_TOKEN_LIST?.split(' ') || [];
117
+
118
+ if (token && ![...unlimited, ...pro, ...advanced].includes(token) || token === 'undefined') {
119
+ return res.status(401).jsonResponse({
120
+ message: 'Unauthorized',
121
+ error: 'Invalid token.',
122
+ status: '401'
123
+ });
124
+ }
125
+
126
+ if (unlimited.includes(token) && !unlimited.includes('undefined')) requestLimit = Infinity;
127
+ else if (pro.includes(token) && !pro.includes('undefined')) requestLimit = 100;
128
+ else if (advanced.includes(token) && !advanced.includes('undefined')) requestLimit = 75;
129
+
130
+ if (unlimited.includes(token)) return next();
131
+
132
+ if (now > resetTime) requests = 0, resetTime = now + 60000;
133
+ if (++requests > Math.max(globalLimit / Math.max(1, Object.keys(ipLimits).length), requestLimit)) {
134
+ return res.status(429).jsonResponse({ message: 'Too Many Requests' });
135
+ }
136
+
137
+ if (!ipLimits[ip]) ipLimits[ip] = [];
138
+ ipLimits[ip] = ipLimits[ip].filter(t => now - t < 60000);
139
+
140
+ if (ipLimits[ip].length >= requestLimit) return res.status(429).jsonResponse({ message: 'Too Many Requests (IP limited)' });
141
+
142
+ ipLimits[ip].push(now);
143
+ next();
144
+ });
145
+
146
+ // Save and send logs
147
+ app.use((req, res, next) => {
148
+ if (req.method === 'HEAD') return next();
149
+ if (req.originalUrl === '/logs') return next();
150
+
151
+ const ip = req.headers['cf-connecting-ip'] || req.socket.remoteAddress;
152
+
153
+ const startTime = Date.now();
154
+ const timestamp = new Date().toISOString();
155
+ const method = req.method;
156
+ const url = req.originalUrl;
157
+ const status = res.statusCode === 304 ? 200 : res.statusCode;
158
+ const duration = `${Date.now() - startTime}ms`;
159
+ const platform = req.headers['sec-ch-ua-platform']?.replace(/"/g, '');
160
+
161
+ res.on('finish', () => {
162
+ logs.push({ timestamp, method, url, status, duration, platform });
163
+ console.log(`[${new Date().toISOString()}] ${method} ${url} ${res.statusCode} - ${duration} - ${ip}`);
164
+ if (logs.length > 1000) logs.shift();
165
+ });
166
+ next();
167
+ });
168
+
169
+ // Internal Server Error
170
+ app.use((err, req, res, next) => {
171
+ console.error(err.stack);
172
+ res.status(500).jsonResponse({
173
+ message: 'Internal Server Error',
174
+ error: err.message,
175
+ documentation: 'https://docs.sylvain.pro',
176
+ status: '500'
177
+ });
178
+ });
179
+
180
+ // Check if version exists
181
+ app.use('/:version', (req, res, next) => {
182
+ const { version } = req.params;
183
+ const latest = versions[versions.length - 1];
184
+ const endpoint = req.originalUrl.split('/').slice(2).join('/');
185
+
186
+ if (['latest', 'fr', 'en'].includes(version)) {
187
+ return res.redirect(endpoint ? `/${latest}/${endpoint}` : `/${latest}`);
188
+ }
189
+
190
+ if (!versions.includes(version) && version !== 'logs') {
191
+ return res.status(404).jsonResponse({
192
+ message: 'Not Found',
193
+ error: `Invalid API version (${version}).`,
194
+ documentation: `https://docs.sylvain.pro/${versions.at(-1)}`,
195
+ status: '404'
196
+ });
197
+ }
198
+ next();
199
+ });
200
+
201
+ // Check if endpoint exists
202
+ app.use('/:version/:endpoint', (req, res, next) => {
203
+ const { version, endpoint } = req.params;
204
+
205
+ if (!versions.includes(version) || !endpoints[version].includes(endpoint)) {
206
+ return res.status(404).jsonResponse({
207
+ message: 'Not Found',
208
+ error: `Endpoint '${endpoint}' does not exist in ${version}.`,
209
+ documentation: `https://docs.sylvain.pro/${versions.at(-1)}`,
210
+ status: '404'
211
+ });
212
+ }
213
+ next();
214
+ });
215
+
216
+ // ----------- ----------- MAIN ENDPOINTS ----------- ----------- //
217
+
218
+ // Main route
219
+ app.get('/', (req, res) => {
220
+ res.setHeader('Content-Type', 'application/json');
221
+ res.jsonResponse({
222
+ documentation: 'https://docs.sylvain.pro',
223
+ latest: 'https://api.sylvain.pro/latest',
224
+ logs: 'https://api.sylvain.pro/logs',
225
+ versions: {
226
+ v1: 'https://api.sylvain.pro/v1',
227
+ v2: 'https://api.sylvain.pro/v2',
228
+ v3: 'https://api.sylvain.pro/v3'
229
+ }
230
+ });
231
+ });
232
+
233
+ // Display v1 endpoints
234
+ app.get('/v1', (req, res) => {
235
+ res.jsonResponse({
236
+ version: 'v1',
237
+ documentation: 'https://docs.sylvain.pro/v1',
238
+ endpoints: {
239
+ get: {
240
+ algorithm: '/v1/algorithms?method={algorithm}&value={value}(&value2={value2})',
241
+ captcha: '/v1/captcha?text={text}',
242
+ color: '/v1/color',
243
+ convert: '/v1/convert?value={value}&from={unit}&to={unit}',
244
+ domain: '/v1/domain',
245
+ infos: '/v1/infos',
246
+ personal: '/v1/personal',
247
+ qrcode: '/v1/qrcode?url={URL}',
248
+ username: '/v1/username'
249
+ },
250
+ post: {
251
+ token: '/v1/token'
252
+ }
253
+ }
254
+ });
255
+ });
256
+
257
+ // Display v2 endpoints
258
+ app.get('/v2', (req, res) => {
259
+ res.jsonResponse({
260
+ version: 'v2',
261
+ documentation: 'https://docs.sylvain.pro/v2',
262
+ endpoints: {
263
+ get: {
264
+ algorithm: '/v2/algorithms?method={algorithm}&value={value}(&value2={value2})',
265
+ captcha: '/v2/captcha?text={text}',
266
+ chat: '/v2/chat',
267
+ color: '/v2/color',
268
+ convert: '/v2/convert?value={value}&from={unit}&to={unit}',
269
+ domain: '/v2/domain',
270
+ infos: '/v2/infos',
271
+ personal: '/v2/personal',
272
+ qrcode: '/v2/qrcode?url={URL}',
273
+ username: '/v2/username'
274
+ },
275
+ post: {
276
+ chat: {
277
+ chat: '/v2/chat',
278
+ private: '/v2/chat/private'
279
+ },
280
+ hash: '/v2/hash',
281
+ tic_tac_toe: {
282
+ tic_tac_toe: '/v2/tic-tac-toe',
283
+ fetch: '/v2/tic-tac-toe/fetch'
284
+ },
285
+ token: '/v2/token'
286
+ }
287
+ }
288
+ });
289
+ });
290
+
291
+ // Display v3 endpoints
292
+ app.get('/v3', (req, res) => {
293
+ res.jsonResponse({
294
+ version: 'v3',
295
+ documentation: 'https://docs.sylvain.pro/v3',
296
+ endpoints: {
297
+ get: {
298
+ algorithm: '/v3/algorithms?method={algorithm}&value={value}(&value2={value2})',
299
+ captcha: '/v3/captcha?text={text}',
300
+ chat: '/v3/chat',
301
+ color: '/v3/color',
302
+ convert: '/v3/convert?value={value}&from={unit}&to={unit}',
303
+ domain: '/v3/domain',
304
+ infos: '/v3/infos',
305
+ levenshtein: '/v3/levenshtein?str1={string}&str2={string}',
306
+ personal: '/v3/personal',
307
+ qrcode: '/v3/qrcode?url={URL}',
308
+ time: '/v3/time(?type={type}&start={timestamp}&end={timestamp}&format={format}&timezone={timezone})',
309
+ username: '/v3/username'
310
+ },
311
+ post: {
312
+ chat: {
313
+ chat: '/v3/chat',
314
+ private: '/v3/chat/private'
315
+ },
316
+ hash: '/v3/hash',
317
+ hyperplanning: '/v3/hyperplanning',
318
+ tic_tac_toe: {
319
+ tic_tac_toe: '/v3/tic-tac-toe',
320
+ fetch: '/v3/tic-tac-toe/fetch'
321
+ },
322
+ token: '/v3/token'
323
+ }
324
+ }
325
+ });
326
+ });
327
+
328
+ // Display logs
329
+ app.get('/logs', (req, res) => res.jsonResponse(logs));
330
+
331
+ // ----------- ----------- GET ENDPOINTS ----------- ----------- //
332
+
333
+ // Algorithms
334
+ app.get('/:version/algorithms', (req, res) => {
335
+ const { method, value, value2 } = req.query;
336
+ const { version } = req.params;
337
+
338
+ if (!['anagram', 'bubblesort', 'factorial', 'fibonacci', 'gcd', 'isprime', 'palindrome', 'primefactors', 'primelist', 'reverse'].includes(method)) {
339
+ return res.jsonResponse({
340
+ error: 'Please provide a valid algorithm (?method={algorithm})',
341
+ documentation: `https://docs.sylvain.pro/${version}/algorithms`
342
+ });
343
+ }
344
+ if (!value) return res.jsonResponse({ error: 'Please provide a valid value (&value={value})' });
345
+
346
+ if (method === 'anagram') {
347
+ if (!value2) return res.jsonResponse({ error: 'Please provide a second value (&value2={value})' });
348
+ return res.jsonResponse({ answer: value.split('').sort().join('') === value2.split('').sort().join('') });
349
+ }
350
+
351
+ if (method === 'bubblesort') {
352
+ const arr = value.split(',').map(Number);
353
+ const n = arr.length;
354
+ for (let i = 0; i < n-1; i++) {
355
+ for (let j = 0; j < n-i-1; j++) {
356
+ if (arr[j] > arr[j + 1]) [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
357
+ }
358
+ }
359
+ return res.jsonResponse({ answer: arr });
360
+ }
361
+
362
+ if (method === 'factorial') {
363
+ if (isNaN(value) || value < 0 || value > 170) return res.jsonResponse({ error: 'Please provide a valid number between 0 and 170.' });
364
+ return res.jsonResponse({ answer: factorial(value) });
365
+ }
366
+
367
+ if (method === 'fibonacci') {
368
+ let fib = [0, 1];
369
+ if (isNaN(value) || value < 0 || value > 1000) return res.jsonResponse({ error: 'Please provide a valid number between 0 and 1000.' });
370
+ for (let i = 2; i < parseInt(value); i++) fib.push(fib[i - 1] + fib[i - 2]);
371
+ return res.jsonResponse({ answer: fib.slice(0, parseInt(value)) });
372
+ }
373
+
374
+ if (method === 'gcd') {
375
+ if (!value2) return res.jsonResponse({ error: 'Please provide a second value (&value2={value})' });
376
+ if (isNaN(value) || isNaN(value2)) return res.jsonResponse({ error: 'Invalid numbers.' });
377
+ return res.jsonResponse({ answer: gcd(value, value2) });
378
+ }
379
+
380
+ if (method === 'isprime') {
381
+ let isPrime = true;
382
+ if (isNaN(value) || value < 1) return res.jsonResponse({ error: 'Please provide a valid number greater than or equal to 1.' });
383
+ for (let i = 2; i <= Math.sqrt(value); i++) {
384
+ if (value % i === 0) {
385
+ isPrime = false;
386
+ break;
387
+ }
388
+ }
389
+ return res.jsonResponse({ answer: isPrime });
390
+ }
391
+
392
+ if (method === 'palindrome') return res.jsonResponse({ answer: value === value.split('').reverse().join('') });
393
+
394
+ if (method === 'primefactors') {
395
+ let num = value;
396
+ let factors = [];
397
+ if (isNaN(num) || num < 2 || num > 100000) return res.jsonResponse({ error: 'Please provide a valid number between 2 and 100 000.' });
398
+ for (let i = 2; i <= num; i++) {
399
+ while (num % i === 0) {
400
+ factors.push(i);
401
+ num /= i;
402
+ }
403
+ }
404
+ return res.jsonResponse({ answer: factors });
405
+ }
406
+
407
+ if (method === 'primelist') {
408
+ const primes = [];
409
+ if (isNaN(value) || value < 2 || value > 10000) return res.jsonResponse({ error: 'Please provide a valid number between 2 and 10 000.' });
410
+ for (let i = 2; i <= value; i++) {
411
+ let isPrime = true;
412
+ for (let j = 2; j <= Math.sqrt(i); j++) {
413
+ if (i % j === 0) {
414
+ isPrime = false;
415
+ break;
416
+ }
417
+ }
418
+ if (isPrime) primes.push(i);
419
+ }
420
+ return res.jsonResponse({ answer: primes });
421
+ }
422
+
423
+ if (method === 'reverse') return res.jsonResponse({ answer: value.split('').reverse().join('') });
424
+ });
425
+
426
+ // Generate captcha
427
+ app.get('/:version/captcha', (req, res) => {
428
+ const captcha = req.query.text;
429
+
430
+ if (!captcha) return res.jsonResponse({ error: 'Please provide a valid argument (?text={text})' });
431
+
432
+ const size = 60, font = '60px Comic Sans Ms', width = captcha.length * size, height = 120;
433
+ const canvas = createCanvas(width, height), ctx = canvas.getContext('2d');
434
+
435
+ ctx.fillStyle = 'white';
436
+ ctx.fillRect(0, 0, width, height);
437
+
438
+ for (let i = 0; i < 20; i++) {
439
+ ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
440
+ ctx.beginPath();
441
+ ctx.moveTo(Math.random() * width, Math.random() * height);
442
+ ctx.lineTo(Math.random() * width, Math.random() * height);
443
+ ctx.lineWidth = Math.random() * 2;
444
+ ctx.stroke();
445
+ }
446
+
447
+ let x = (canvas.width + 20 - width) / 2;
448
+ for (let i = 0; i < captcha.length; i++) {
449
+ const offsetX = Math.cos(i * 0.3) * 10, y = height / 2.5 + Math.floor(Math.random() * (height / 2));
450
+
451
+ ctx.font = font;
452
+ ctx.fillStyle = `rgb(${Math.floor(Math.random() * 192)}, ${Math.floor(Math.random() * 192)}, ${Math.floor(Math.random() * 192)})`;
453
+
454
+ ctx.save();
455
+ ctx.translate(x + size / 2, y);
456
+ ctx.rotate((Math.random() - 0.5) * 0.5);
457
+ ctx.fillText(captcha[i], -size / 2 + offsetX, 0);
458
+ ctx.restore();
459
+
460
+ x += size;
461
+ }
462
+
463
+ for (let i = 0; i < 200; i++) {
464
+ ctx.fillStyle = 'black';
465
+ ctx.fillRect(Math.floor(Math.random() * width), Math.floor(Math.random() * height), 1.2, 1.2);
466
+ }
467
+
468
+ res.set('Content-Type', 'image/png');
469
+ res.send(canvas.toBuffer('image/png'));
470
+ });
471
+
472
+ // Display stored data
473
+ app.get('/:version/chat', (req, res) => {
474
+ if (chat.length > 0) res.jsonResponse(chat);
475
+ else res.jsonResponse({ error: 'No messages stored.' });
476
+ });
477
+
478
+ // GET private chat error
479
+ app.get('/:version/chat/private', (req, res) => {
480
+ res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
481
+ });
482
+
483
+ // Generate color
484
+ app.get('/:version/color', (req, res) => {
485
+ const r = Math.floor(Math.random() * 256), g = Math.floor(Math.random() * 256), b = Math.floor(Math.random() * 256);
486
+ const hsl = (() => {
487
+ const r1 = r / 255, g1 = g / 255, b1 = b / 255, max = Math.max(r1, g1, b1), min = Math.min(r1, g1, b1), l = (max + min) / 2;
488
+ if (max === min) return [0, 0, l * 100];
489
+ const d = max - min, s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
490
+ let h = { [r1]: (g1 - b1) / d + (g1 < b1 ? 6 : 0), [g1]: (b1 - r1) / d + 2, [b1]: (r1 - g1) / d + 4 }[max];
491
+ return [h * 60 % 360, s * 100, l * 100];
492
+ })();
493
+ const hsv = (() => {
494
+ const max = Math.max(r, g, b), min = Math.min(r, g, b), v = max / 255, s = max ? (max - min) / max : 0;
495
+ let h = max === min ? 0 : { [r]: (g - b) / (max - min), [g]: 2 + (b - r) / (max - min), [b]: 4 + (r - g) / (max - min) }[max];
496
+ return [h * 60 % 360, s * 100, v * 100];
497
+ })();
498
+ const hwb = (() => {
499
+ const [h] = hsv, whiteness = Math.min(r, g, b) / 255, blackness = 1 - Math.max(r, g, b) / 255;
500
+ return [h, whiteness * 100, blackness * 100];
501
+ })();
502
+ const cmyk = (() => {
503
+ const k = 1 - Math.max(r, g, b) / 255, c = (1 - r / 255 - k) / (1 - k) || 0, m = (1 - g / 255 - k) / (1 - k) || 0, y = (1 - b / 255 - k) / (1 - k) || 0;
504
+ return [c, m, y, k].map(x => x * 100);
505
+ })();
506
+ res.jsonResponse({
507
+ hex: `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`,
508
+ rgb: `rgb(${r}, ${g}, ${b})`,
509
+ hsl: `hsl(${hsl[0].toFixed(1)}, ${hsl[1].toFixed(1)}%, ${hsl[2].toFixed(1)}%)`,
510
+ hsv: `hsv(${hsv[0].toFixed(1)}, ${hsv[1].toFixed(1)}%, ${hsv[2].toFixed(1)}%)`,
511
+ hwb: `hwb(${hwb[0].toFixed(1)}, ${hwb[1].toFixed(1)}%, ${hwb[2].toFixed(1)}%)`,
512
+ cmyk: `cmyk(${cmyk.map(x => x.toFixed(1)).join('%, ')}%)`
513
+ });
514
+ });
515
+
516
+ // Convert units
517
+ app.get('/:version/convert', (req, res) => {
518
+ const { value, from, to } = req.query;
519
+
520
+ if (!value || isNaN(value)) return res.jsonResponse({ error: 'Please provide a valid value (?value={value})' });
521
+ if (!from) return res.jsonResponse({ error: 'Please provide a valid source unit (&from={unit})' });
522
+ if (!to) return res.jsonResponse({ error: 'Please provide a valid target unit (&to={unit})' });
523
+
524
+ const conversions = {
525
+ celsius: { fahrenheit: (val) => (val * 9) / 5 + 32, kelvin: (val) => val + 273.15 },
526
+ fahrenheit: { celsius: (val) => ((val - 32) * 5) / 9, kelvin: (val) => ((val - 32) * 5) / 9 + 273.15 },
527
+ kelvin: { celsius: (val) => val - 273.15, fahrenheit: (val) => ((val - 273.15) * 9) / 5 + 32 },
528
+ };
529
+
530
+ const convert = conversions[from.toLowerCase()]?.[to.toLowerCase()];
531
+ if (!convert) return res.jsonResponse({ error: 'Invalid conversion units.' });
532
+
533
+ res.jsonResponse({ from, to, value: parseFloat(value), result: convert(parseFloat(value)) });
534
+ });
535
+
536
+ // Generate domain informations
537
+ app.get('/:version/domain', (req, res) => {
538
+ const subdomains = ['fr.', 'en.', 'docs.', 'api.', 'projects.', 'app.', 'web.', 'info.', 'dev.', 'shop.', 'blog.', 'support.', 'mail.', 'forum.'];
539
+ const domains = ['example', 'site', 'test', 'demo', 'page', 'store', 'portfolio', 'platform', 'hub', 'network', 'service', 'cloud', 'solutions', 'company'];
540
+ const tlds = ['.com', '.fr', '.eu', '.dev', '.net', '.org', '.io', '.tech', '.biz', '.info', '.co', '.app', '.store', '.online', '.shop', '.tv'];
541
+
542
+ const domain = `${random(domains)}${random(tlds)}`;
543
+ const fulldomain = `${random(subdomains)}${domain}`;
544
+
545
+ const ips = Array.from({ length: Math.floor(Math.random() * 3) + 1 }, genIP);
546
+ const dns = Array.from({ length: Math.floor(Math.random() * 5) + 1 }, genIP);
547
+
548
+ res.jsonResponse({
549
+ domain,
550
+ full_domain: fulldomain,
551
+ ip_address: ips,
552
+ ssl_certified: Math.random() > 0.5,
553
+ hosting_provider: random(['AWS', 'Bluehost', 'DigitalOcean', 'GitHub', 'HostGator', 'Render', 'SiteGround']),
554
+ dns_servers: dns,
555
+ dns_provider: random(['AWS Route 53', 'Cloudflare', 'GoDaddy', 'Google DNS', 'Namecheap']),
556
+ traffic: `${Math.floor(Math.random() * 10000)} visits/day`,
557
+ seo_score: Math.floor(Math.random() * 100),
558
+ page_rank: Math.floor(Math.random() * 10),
559
+ country: random(['Australia', 'Canada', 'France', 'Germany', 'India', 'Japan', 'UK', 'USA']),
560
+ website_type: random(['Blog', 'Community', 'Corporate', 'Educational', 'E-commerce', 'Personal', 'Portfolio']),
561
+ random_name: domain.split('.')[0],
562
+ random_subdomain: fulldomain.split('.')[0],
563
+ random_tld: domain.split('.').pop(),
564
+ backlinks_count: Math.floor(Math.random() * 1000),
565
+ creation_date: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
566
+ expiration_date: new Date(Date.now() + Math.floor(Math.random() * 10000000000)).toISOString(),
567
+ });
568
+ });
569
+
570
+ // GET planning error
571
+ app.get('/:version/hyperplanning', (req, res) => {
572
+ res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
573
+ });
574
+
575
+ // GET hash error
576
+ app.get('/:version/hash', (req, res) => {
577
+ res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
578
+ });
579
+
580
+ // Display API informations
581
+ app.get('/:version/infos', (req, res) => {
582
+ res.jsonResponse({
583
+ endpoints: endpoints[versions.at(-1)].length,
584
+ last_version: versions.at(-1),
585
+ documentation: 'https://docs.sylvain.pro',
586
+ github: 'https://github.com/20syldev/api',
587
+ creation: 'November 25th 2024',
588
+ });
589
+ });
590
+
591
+ // Calculate Levenshtein distance
592
+ app.get('/:version/levenshtein', (req, res) => {
593
+ const { str1, str2 } = req.query;
594
+
595
+ if (!str1 || typeof str1 !== 'string') return res.jsonResponse({ error: 'Please provide a first string (?str1={string})' });
596
+ if (!str2 || typeof str2 !== 'string') return res.jsonResponse({ error: 'Please provide a second string (&str2={string})' });
597
+
598
+ if (str1.length > 1000) return res.jsonResponse({ error: 'First string exceeds 1000 characters.' });
599
+ if (str2.length > 1000) return res.jsonResponse({ error: 'Second string exceeds 1000 characters.' });
600
+
601
+ const lev = (a, b) => {
602
+ const m = Array.from({ length: a.length + 1 }, (_, i) => [i]);
603
+ for (let j = 0; j <= b.length; j++) m[0][j] = j;
604
+ for (let i = 1; i <= a.length; i++)
605
+ for (let j = 1; j <= b.length; j++)
606
+ m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (a[i - 1] !== b[j - 1]));
607
+
608
+ return m[a.length][b.length];
609
+ };
610
+
611
+ res.jsonResponse({ str1, str2, distance: lev(str1, str2) });
612
+ });
613
+
614
+ // Generate personal data
615
+ app.get('/:version/personal', (req, res) => {
616
+ const people = [
617
+ { name: 'John Doe', social: 'john_doe', email: 'john@example.com', country: 'US' },
618
+ { name: 'Jane Martin', social: 'jane_martin', email: 'jane@example.com', country: 'FR' },
619
+ { name: 'Michael Johnson', social: 'mike_johnson', email: 'michael@example.com', country: 'UK' },
620
+ { name: 'Emily Davis', social: 'emily_davis', email: 'emily@example.com', country: 'ES' },
621
+ { name: 'Alexis Barbos', social: 'alexis_barbos', email: 'alexis@example.com', country: 'DE' },
622
+ { name: 'Sarah Williams', social: 'sarah_williams', email: 'sarah@example.com', country: 'IT' },
623
+ { name: 'Daniel Brown', social: 'daniel_brown', email: 'daniel@example.com', country: 'JP' },
624
+ { name: 'Sophia Wilson', social: 'sophia_wilson', email: 'sophia@example.com', country: 'BR' },
625
+ { name: 'James Taylor', social: 'james_taylor', email: 'james@example.com', country: 'CA' },
626
+ { name: 'Olivia Thomas', social: 'olivia_thomas', email: 'olivia@example.com', country: 'AU' }
627
+ ];
628
+
629
+ const countries = {
630
+ US: { tel: '123-456-7890', code: '1', lang: 'English' },
631
+ FR: { tel: '06 78 90 12 34', code: '33', lang: 'French' },
632
+ UK: { tel: '7911 123456', code: '44', lang: 'English' },
633
+ ES: { tel: '678 901 234', code: '34', lang: 'Spanish' },
634
+ DE: { tel: '163 555 1584', code: '49', lang: 'German' },
635
+ IT: { tel: '345 678 9012', code: '39', lang: 'Italian' },
636
+ JP: { tel: '080-1234-5678', code: '81', lang: 'Japanese' },
637
+ BR: { tel: '(11) 98765-4321', code: '55', lang: 'Portuguese' },
638
+ CA: { tel: '416-123-4567', code: '1', lang: 'English' },
639
+ AU: { tel: '0412 345 678', code: '61', lang: 'English' }
640
+ };
641
+
642
+ const jobs = ['Writer', 'Artist', 'Musician', 'Explorer', 'Scientist', 'Engineer', 'Athlete', 'Doctor'];
643
+ const hobbies = ['Reading', 'Traveling', 'Gaming', 'Cooking', 'Fitness', 'Music', 'Photography', 'Writing'];
644
+ const cities = ['New York', 'Paris', 'London', 'Madrid', 'Berlin', 'Rome', 'Tokyo', 'Los Angeles', 'Sydney', 'São Paulo', 'Toronto'];
645
+ const streets = ['Main St', '2nd Ave', 'Broadway', 'Park Lane', 'Elm St', 'Sunset Blvd', 'Maple St', 'Highland Rd'];
646
+
647
+ const card = Array.from({ length: 4 }, () => Math.floor(Math.random() * 9000) + 1000).join(' ');
648
+ const cvc = Math.floor(Math.random() * 900) + 100;
649
+ const expiration = `${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}/${(new Date().getFullYear() + Math.floor(Math.random() * 3)).toString().slice(-2)}`;
650
+
651
+ const person = random(people);
652
+ const social = person.social;
653
+ const country = person.country;
654
+ const phone = countries[country].tel;
655
+ const lang = countries[country].lang;
656
+
657
+ const age = Math.floor(Math.random() * 50) + 18;
658
+ const birthday = new Date(Date.now() - Math.floor((Math.random() * 50 + 18) * 365.25 * 24 * 60 * 60 * 1000)).toISOString();
659
+
660
+ let emergencyContacts = [], yearIncome = Math.floor(Math.random() * 100000), subscriptions = [], pets = [], vehicles = [];
661
+ let civilStatus = 'Single';
662
+ let children = 0;
663
+
664
+ if (age >= 21 && Math.random() > 0.7) civilStatus = 'Married';
665
+
666
+ if (civilStatus === 'Married' && age >= 25) children = Math.floor(Math.random() * 4);
667
+
668
+ while (emergencyContacts.length < Math.floor(Math.random() * 3) + 1) {
669
+ let emergencyContact = random(people);
670
+ while (emergencyContact.email === person.email || emergencyContacts.some(e => e.email === emergencyContact.email)) {
671
+ emergencyContact = random(people);
672
+ }
673
+ emergencyContacts.push({
674
+ name: emergencyContact.name,
675
+ relationship: random(['Spouse', 'Parent', 'Sibling', 'Friend']),
676
+ phone: `+${countries[country].code} ${countries[country].tel}`
677
+ });
678
+ }
679
+
680
+ while (subscriptions.length < Math.floor(Math.random() * 3) + 1) {
681
+ let subscription = random(['Netflix', 'Spotify', 'Amazon Prime', 'Disney+', 'Hulu']);
682
+ if (!subscriptions.includes(subscription)) subscriptions.push(subscription);
683
+ }
684
+
685
+ while (pets.length < Math.floor(Math.random() * 3) + 1) {
686
+ let pet = random(['Dog', 'Cat', 'Fish', 'Bird', 'None']);
687
+ if (!pets.includes(pet)) pets.push(pet);
688
+ }
689
+
690
+ while (vehicles.length < Math.floor(Math.random() * 3) + 1) {
691
+ let vehicle = random(['Car', 'Bike', 'Motorcycle', 'Bus', 'None']);
692
+ if (!vehicles.includes(vehicle)) vehicles.push(vehicle);
693
+ }
694
+
695
+ res.jsonResponse({
696
+ name: person.name,
697
+ email: person.email,
698
+ localisation: country,
699
+ phone: `+${countries[country].code} ${phone}`,
700
+ job: random(jobs),
701
+ hobbies: random(hobbies),
702
+ language: lang,
703
+ card,
704
+ cvc,
705
+ expiration,
706
+ address: `${Math.floor(Math.random() * 9999)} ${random(streets)}, ${random(cities)}`,
707
+ birthday,
708
+ civil_status: civilStatus,
709
+ children,
710
+ vehicle: vehicles,
711
+ social_profiles: {
712
+ twitter: `@${social}`,
713
+ facebook: `facebook.com/${social}`,
714
+ linkedin: `linkedin.com/in/${social}`,
715
+ instagram: `instagram.com/${social}`
716
+ },
717
+ year_income: `${yearIncome} USD/year`,
718
+ month_income: `${(yearIncome / 12).toFixed(2)} USD/month`,
719
+ education: random(['High School', 'Bachelor\'s', 'Master\'s', 'PhD']),
720
+ work_experience: `${Math.floor(Math.random() * 20)} years`,
721
+ health_status: random(['Healthy', 'Minor Issues', 'Chronic Conditions']),
722
+ emergency_contacts: emergencyContacts,
723
+ subscriptions,
724
+ pets,
725
+ });
726
+ });
727
+
728
+ // Generate QR Code
729
+ app.get('/:version/qrcode', async (req, res) => {
730
+ const { url } = req.query;
731
+
732
+ if (!url) return res.jsonResponse({ error: 'Please provide a valid url (?url={URL})' });
733
+
734
+ try { res.jsonResponse({ qr: await toDataURL(url) }); }
735
+ catch { res.jsonResponse({ error: 'Error generating QR code.' }); }
736
+ });
737
+
738
+ // GET tic-tac-toe game error
739
+ app.get('/:version/tic-tac-toe', (req, res) => {
740
+ res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
741
+ });
742
+
743
+ // GET tic-tac-toe fetch error
744
+ app.get('/:version/tic-tac-toe/fetch', (req, res) => {
745
+ res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
746
+ });
747
+
748
+ // Display or generate time informations
749
+ app.get('/:version/time', (req, res) => {
750
+ const { type = 'live', start, end, format, timezone } = req.query;
751
+
752
+ const validFormats = ['iso', 'utc', 'timestamp', 'locale', 'date', 'time', 'year', 'month', 'day', 'hour', 'minute', 'second', 'ms', 'dayOfWeek', 'dayOfYear', 'weekNumber', 'timezone', 'timezoneOffset'];
753
+ const validTimezones = ['UTC', 'America/New_York', 'Europe/Paris', 'Asia/Tokyo', 'Australia/Sydney'];
754
+
755
+ if (type !== 'live' && type !== 'random') return res.jsonResponse({ error: 'Please provide a valid type (?type={type})' });
756
+ if (start && !Date.parse(start)) return res.jsonResponse({ error: 'Please provide a valid start date (?start={YYYY-MM-DD})' });
757
+ if (end && !Date.parse(end)) return res.jsonResponse({ error: 'Please provide a valid end date (?end={YYYY-MM-DD})' });
758
+ if (format && !validFormats.includes(format)) return res.jsonResponse({ error: 'Please provide a valid format (?format={format})' });
759
+ if (timezone && !validTimezones.includes(timezone)) return res.jsonResponse({ error: 'Please provide a valid timezone (?timezone={timezone})' });
760
+
761
+ const getTimeFormats = (date, timezoneOption) => {
762
+ return {
763
+ iso: date.toISOString(),
764
+ utc: date.toUTCString(),
765
+ timestamp: date.getTime(),
766
+ locale: date.toLocaleString('en-US', { timeZone: timezoneOption, timeZoneName: 'long' }),
767
+ date: date.toLocaleDateString('en-US', { timeZone: timezoneOption }),
768
+ time: date.toLocaleTimeString('en-US', { timeZone: timezoneOption }),
769
+ year: date.getFullYear(),
770
+ month: date.getMonth() + 1,
771
+ day: date.getDate(),
772
+ hour: date.getHours(),
773
+ minute: date.getMinutes(),
774
+ second: date.getSeconds(),
775
+ ms: date.getMilliseconds(),
776
+ dayOfWeek: date.getDay(),
777
+ dayOfYear: Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 86400000),
778
+ weekNumber: Math.ceil((((date - new Date(date.getFullYear(), 0, 0)) / 86400000) + 1) / 7),
779
+ timezone: timezoneOption,
780
+ timezoneOffset: date.getTimezoneOffset()
781
+ };
782
+ };
783
+
784
+ if (type === 'random') {
785
+ const startDate = new Date(start || '1900-01-01').getTime();
786
+ const endDate = new Date(end || '2100-12-31').getTime();
787
+ const randomDate = new Date(start ? startDate : startDate + Math.random() * (endDate - startDate));
788
+ const timezoneOption = timezone || validTimezones[Math.floor(Math.random() * 5)];
789
+ const formats = getTimeFormats(randomDate, timezoneOption);
790
+
791
+ return res.jsonResponse(format && formats[format] ? { date: formats[format] } : formats);
792
+ }
793
+
794
+ const now = new Date();
795
+ const timezoneOption = timezone || 'UTC';
796
+ const formats = getTimeFormats(now, timezoneOption);
797
+
798
+ res.jsonResponse(format && formats[format] ? { date: formats[format] } : formats);
799
+ });
800
+
801
+ // GET token error
802
+ app.get('/:version/token', (req, res) => {
803
+ res.jsonResponse({ error: 'This endpoint only supports POST requests.' });
804
+ });
805
+
806
+ // Generate username
807
+ app.get('/:version/username', (req, res) => {
808
+ const adj = ['Happy', 'Silly', 'Clever', 'Creative', 'Brave', 'Gentle', 'Kind', 'Funny', 'Wise', 'Charming', 'Sincere', 'Resourceful', 'Patient', 'Energetic', 'Adventurous', 'Ambitious', 'Courageous', 'Courteous', 'Determined'];
809
+ const ani = ['Cat', 'Dog', 'Tiger', 'Elephant', 'Monkey', 'Penguin', 'Dolphin', 'Lion', 'Bear', 'Fox', 'Owl', 'Giraffe', 'Zebra', 'Koala', 'Rabbit', 'Squirrel', 'Panda', 'Horse', 'Wolf', 'Eagle'];
810
+ const job = ['Writer', 'Artist', 'Musician', 'Explorer', 'Scientist', 'Engineer', 'Athlete', 'Chef', 'Doctor', 'Teacher', 'Lawyer', 'Entrepreneur', 'Actor', 'Dancer', 'Photographer', 'Architect', 'Pilot', 'Designer', 'Journalist', 'Veterinarian'];
811
+
812
+ const nombre = Math.floor(Math.random() * 100);
813
+ const choix = {
814
+ adj_num: () => random(adj) + nombre,
815
+ ani_num: () => random(ani) + nombre,
816
+ pro_num: () => random(job) + nombre,
817
+ adj_ani: () => random(adj) + random(ani),
818
+ adj_ani_num: () => random(adj) + random(ani) + nombre,
819
+ adj_pro: () => random(adj) + random(job),
820
+ pro_ani: () => random(job) + random(ani),
821
+ pro_ani_num: () => random(job) + random(ani) + nombre
822
+ };
823
+
824
+ const username = choix[random(Object.keys(choix))]();
825
+ res.jsonResponse({ adjective: adj, animal: ani, job, number: nombre, username });
826
+ });
827
+
828
+ // Display informations for owner's website
829
+ app.get('/:version/website', async (req, res) => {
830
+ const currentTime = Date.now();
831
+
832
+ if (currentTime - lastFetch >= 10 * 60 * 1000) {
833
+ try {
834
+ const username = '20syldev';
835
+ const token = process.env.STATS5;
836
+ const today = new Date().toISOString().split('T')[0];
837
+ const monthFirst = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0];
838
+ const lastYear = new Date(new Date().setFullYear(new Date().getFullYear() - 1)).toISOString().split('T')[0];
839
+
840
+ const query = `
841
+ {
842
+ user(login: "${username}") {
843
+ contributionsCollection(from: "${today}T00:00:00Z") {
844
+ contributionCalendar {
845
+ totalContributions
846
+ }
847
+ }
848
+ contributions_month: contributionsCollection(from: "${monthFirst}T00:00:00Z") {
849
+ contributionCalendar {
850
+ totalContributions
851
+ }
852
+ }
853
+ contributions_year: contributionsCollection(from: "${lastYear}T00:00:00Z") {
854
+ contributionCalendar {
855
+ totalContributions
856
+ }
857
+ }
858
+ }
859
+ }`;
860
+
861
+ const apiResponse = await fetch('https://api.github.com/graphql', {
862
+ method: 'POST',
863
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
864
+ body: JSON.stringify({ query })
865
+ });
866
+
867
+ if (!apiResponse.ok) throw new Error('Error fetching data.');
868
+
869
+ const data = await apiResponse.json();
870
+ const user = data?.data?.user;
871
+
872
+ contributions = {
873
+ today: user?.contributionsCollection?.contributionCalendar?.totalContributions || 0,
874
+ month: user?.contributions_month?.contributionCalendar?.totalContributions || 0,
875
+ year: user?.contributions_year?.contributionCalendar?.totalContributions || 0,
876
+ };
877
+
878
+ lastFetch = currentTime;
879
+ } catch { contributions = { today: 0, month: 0, year: 0 }; }
880
+ }
881
+
882
+ res.jsonResponse({
883
+ versions: {
884
+ api: process.env.API,
885
+ cdn: process.env.CDN,
886
+ coop_api: process.env.COOP_API,
887
+ coop_status: process.env.COOP_STATUS,
888
+ chat: process.env.CHAT,
889
+ digit: process.env.DIGIT,
890
+ doc_coopbot: process.env.DOC_COOPBOT,
891
+ docs: process.env.DOCS,
892
+ donut: process.env.DONUT,
893
+ drawio_plugin: process.env.DRAWIO_PLUGIN,
894
+ flowers: process.env.FLOWERS,
895
+ gemsync: process.env.GEMSYNC,
896
+ gitsite: process.env.GITSITE,
897
+ logs: process.env.LOGS,
898
+ logvault: process.env.LOGVAULT,
899
+ minify: process.env.MINIFY,
900
+ morpion: process.env.MORPION,
901
+ nitrogen: process.env.NITROGEN,
902
+ old_database: process.env.OLD_DATABASE,
903
+ php: process.env.PHP,
904
+ ping: process.env.PING,
905
+ portfolio: process.env.PORTFOLIO,
906
+ python_api: process.env.PYTHON_API,
907
+ readme: process.env.README,
908
+ terminal: process.env.TERMINAL,
909
+ wrkit: process.env.WRKIT,
910
+ zpki: process.env.ZPKI
911
+ },
912
+ patched_projects: process.env.PATCH?.split(' ') || [],
913
+ updated_projects: process.env.RECENT?.split(' ') || [],
914
+ new_projects: process.env.NEW?.split(' ') || [],
915
+ sub_domains: process.env.DOMAINS?.split(' ') || [],
916
+ stats: {
917
+ os: process.env.STATS1,
918
+ front: process.env.STATS2,
919
+ back: process.env.STATS3,
920
+ projects: process.env.STATS4,
921
+ today: contributions.today.toString(),
922
+ this_month: contributions.month.toString(),
923
+ last_year: contributions.year.toString(),
924
+ },
925
+ notif_tag: process.env.TAG,
926
+ active: process.env.ACTIVE
927
+ });
928
+ });
929
+
930
+ // ----------- ----------- POST ENDPOINTS ----------- ----------- //
931
+
932
+ // Store chat messages
933
+ app.post('/:version/chat', (req, res) => {
934
+ const { username, message, timestamp, session, token } = req.body;
935
+
936
+ if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
937
+ if (!message) return res.jsonResponse({ error: 'Please provide a message (&message={message})' });
938
+ if (!session) return res.jsonResponse({ error: 'Please provide a valid session ID (&session={ID})' });
939
+
940
+ const u = username.toLowerCase(), now = Date.now();
941
+ const msg = { username, message, timestamp: timestamp || new Date().toISOString() };
942
+
943
+ rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
944
+ if (rateLimits[u].length > 50) {
945
+ const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
946
+ return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
947
+ }
948
+ rateLimits[u].push(now);
949
+
950
+ if (sessions[u] && sessions[u].user !== session) return res.jsonResponse({ error: 'Session ID mismatch' });
951
+
952
+ if (token) {
953
+ privateChats[token] = privateChats[token] || [];
954
+ privateChats[token].push(msg);
955
+ setTimeout(() => { delete privateChats[token]; }, 3600000);
956
+ } else {
957
+ chat.push(msg);
958
+ setTimeout(() => chat.splice(chat.indexOf(msg), 1), 3600000);
959
+ }
960
+
961
+ sessions[u] = sessions[u] || { user: session, last: now };
962
+ sessions[u].last = now;
963
+
964
+ setTimeout(() => { if (now - sessions[u].last >= 3600000) delete sessions[u]; }, 3600000);
965
+
966
+ res.jsonResponse({ message: 'Message sent successfully' });
967
+ });
968
+
969
+ // Display a private chat with a token
970
+ app.post('/:version/chat/private', (req, res) => {
971
+ const { username, token } = req.body;
972
+
973
+ if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
974
+ if (!token) return res.jsonResponse({ error: 'Please provide a valid token (&token={key}).' });
975
+
976
+ const u = username.toLowerCase(), now = Date.now();
977
+
978
+ rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
979
+ if (rateLimits[u].length > 50) {
980
+ const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
981
+ return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
982
+ }
983
+ rateLimits[u].push(now);
984
+
985
+ if (privateChats[token]) return res.jsonResponse(privateChats[token]);
986
+
987
+ return res.jsonResponse({ error: 'Invalid or expired token.' });
988
+ });
989
+
990
+ // Generate hash
991
+ app.post('/:version/hash', (req, res) => {
992
+ const { text, method } = req.body;
993
+ const { version } = req.params;
994
+
995
+ if (!text) return res.jsonResponse({ error: 'Please provide a text (?text={text})' });
996
+ if (!method) return res.jsonResponse({
997
+ error: 'Please provide a valid hash algorithm (?method={algorithm})',
998
+ documentation: `https://docs.sylvain.pro/${version}/hash`
999
+ });
1000
+
1001
+ const methods = getHashes();
1002
+ if (!methods.includes(method)) return res.jsonResponse({ error: `Unsupported method. Use one of: ${methods.join(', ')}` });
1003
+
1004
+ const hash = createHash(method).update(text).digest('hex');
1005
+ res.jsonResponse({ method, hash });
1006
+ });
1007
+
1008
+ // Display a planning from an ICS file
1009
+ app.post('/:version/hyperplanning', async (req, res) => {
1010
+ const { url, detail } = req.body;
1011
+
1012
+ if (!url) return res.jsonResponse({ error: 'Please provide a valid ICS file URL.' });
1013
+
1014
+ try {
1015
+ const response = await fetch(url);
1016
+ if (!response.ok || !(response.headers.get('content-type') || '').includes('text/calendar')) return res.jsonResponse({ error: 'Invalid ICS file format.' });
1017
+
1018
+ const events = new ical.Component(ical.parse(await response.text()))
1019
+ .getAllSubcomponents('vevent')
1020
+ .map(e => {
1021
+ const evt = new ical.Event(e);
1022
+ const summary = evt.summary.split(' ').filter(part => part !== '-');
1023
+ const start = formatDate(evt.startDate.toJSDate());
1024
+ const end = formatDate(evt.endDate.toJSDate());
1025
+
1026
+ if (detail === 'full') {
1027
+ const desc = evt.description.split('\n').map(l => l.trim());
1028
+ const extract = (p) => (desc.find(l => l.startsWith(p)) || '').replace(p, '').trim();
1029
+
1030
+ return {
1031
+ summary,
1032
+ subject: extract('Matière :'),
1033
+ teacher: extract('Enseignant :'),
1034
+ classes: extract('Promotions :').split(', ').map(c => c.trim()),
1035
+ type: extract('Salle :') || undefined,
1036
+ start,
1037
+ end
1038
+ };
1039
+ }
1040
+ if (detail === 'list') return { summary, start, end };
1041
+
1042
+ return { summary: evt.summary, start, end };
1043
+ })
1044
+ .sort((a, b) => new Date(a.start) - new Date(b.start))
1045
+ .filter(e => new Date(e.end) >= new Date());
1046
+
1047
+ res.jsonResponse(events);
1048
+ } catch { res.jsonResponse({ error: 'Failed to parse ICS file.' }); }
1049
+ });
1050
+
1051
+ // Store tic tac toe games
1052
+ app.post('/:version/tic-tac-toe', (req, res) => {
1053
+ const { username, move, session, game } = req.body;
1054
+
1055
+ if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
1056
+ if (!move) return res.jsonResponse({ error: 'Please provide a valid move (&move={move})' });
1057
+ if (!session) return res.jsonResponse({ error: 'Please provide a valid session ID (&session={ID})' });
1058
+ if (!game) return res.jsonResponse({ error: 'Please provide a valid game ID (&game={ID})' });
1059
+
1060
+ const u = username.toLowerCase(), now = Date.now();
1061
+ const play = { username, move, session };
1062
+ const validMoves = ['1-1', '1-2', '1-3', '2-1', '2-2', '2-3', '3-1', '3-2', '3-3'];
1063
+
1064
+ if (!validMoves.includes(move)) return res.jsonResponse({ error: 'Invalid move. Please provide a valid move (e.g., 1-1, 2-2, 3-3).' });
1065
+
1066
+ rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
1067
+ if (rateLimits[u].length > 50) {
1068
+ const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
1069
+ return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
1070
+ }
1071
+ rateLimits[u].push(now);
1072
+
1073
+ if (sessions[u] && sessions[u].user !== session) return res.jsonResponse({ error: 'Session ID mismatch' });
1074
+
1075
+ games[game] = games[game] || [];
1076
+
1077
+ const players = [...new Set(games[game].map(play => play.username))];
1078
+ if (players.length >= 2 && !players.includes(username)) return res.jsonResponse({ error: 'Game is full, you can only watch.' });
1079
+ if (games[game].length > 0 && games[game][games[game].length - 1].username === username) return res.jsonResponse({ error: 'Please wait for the other player to make a move.' });
1080
+ if (games[game].some(play => play.move === move)) return res.jsonResponse({ error: 'Move already made. Please choose a different move.' });
1081
+
1082
+ games[game].push(play);
1083
+
1084
+ const result = checkGame(games[game]);
1085
+ if (result.winner || result.tie) {
1086
+ setTimeout(() => delete games[game], 600000);
1087
+ return res.jsonResponse({
1088
+ message: `Move sent successfully. ${result.winner ? result.winner + ' wins. ' + result.loser + ' loses.' : 'It\'s a tie.'}`,
1089
+ ...result
1090
+ });
1091
+ }
1092
+ if (!result.winner && !result.tie) setTimeout(() => delete games[game], 3600000);
1093
+
1094
+ sessions[u] = sessions[u] || { user: session, last: now };
1095
+ sessions[u].last = now;
1096
+
1097
+ setTimeout(() => { if (now - sessions[u].last >= 3600000) delete sessions[u]; }, 3600000);
1098
+
1099
+ res.jsonResponse({ message: 'Move sent successfully' });
1100
+ });
1101
+
1102
+ // Display a tic tac toe game with a token
1103
+ app.post('/:version/tic-tac-toe/fetch', (req, res) => {
1104
+ const { username, game } = req.body;
1105
+
1106
+ if (!username) return res.jsonResponse({ error: 'Please provide a username (?username={username})' });
1107
+
1108
+ const ID = game || genID();
1109
+ const u = username.toLowerCase(), now = Date.now();
1110
+
1111
+ rateLimits[u] = (rateLimits[u] || []).filter(ts => now - ts < 10000);
1112
+ if (rateLimits[u].length > 50) {
1113
+ const remainingTime = Math.ceil((rateLimits[u][0] + 10000 - now) / 1000);
1114
+ return res.jsonResponse({ error: `Rate limit exceeded. Try again in ${remainingTime} seconds.` });
1115
+ }
1116
+ rateLimits[u].push(now);
1117
+
1118
+ if (!games[ID]) games[ID] = [];
1119
+
1120
+ const data = games[ID];
1121
+ const last = data.length ? data[data.length - 1].username : null;
1122
+ const players = [...new Set(data.map(p => p.username))];
1123
+ const turn = players.find(p => p !== last);
1124
+ const result = data.length ? checkGame(data) : {};
1125
+
1126
+ res.jsonResponse({ game: data, turn, ID, ...result });
1127
+ });
1128
+
1129
+ // Generate Token
1130
+ app.post('/:version/token', (req, res) => {
1131
+ let { len, type } = req.body;
1132
+
1133
+ len = parseInt(len || 24, 10);
1134
+ type = type ? type.toLowerCase() : 'alpha';
1135
+
1136
+ if (isNaN(len) || len < 0) return res.jsonResponse({ error: 'Invalid number.' });
1137
+ if (len > 4096) return res.jsonResponse({ error: 'Length cannot exceed 4096.' });
1138
+ if (len < 12) return res.jsonResponse({ error: 'Length cannot be less than 12.' });
1139
+
1140
+ const token = {
1141
+ alpha: genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', len),
1142
+ alphanum: genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', len),
1143
+ base64: randomBytes(len).toString('base64').slice(0, len),
1144
+ hex: randomBytes(len).toString('hex').slice(0, len),
1145
+ num: genToken('0123456789', len),
1146
+ punct: genToken('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', len),
1147
+ urlsafe: genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_', len),
1148
+ uuid: v4().replace(/-/g, '').slice(0, len)
1149
+ }[type] || genToken('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', len);
1150
+
1151
+ res.jsonResponse({ token });
1152
+ });
1153
+
1154
+ // ----------- ----------- SERVER SETUP ----------- ----------- //
1155
+
1156
+ app.listen(3000, () => console.log('API is running on\n - http://127.0.0.1:3000\n - http://localhost:3000'));