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