@20syldev/api 3.3.2 → 3.3.4

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