This repository has been archived by the owner on Nov 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
877 lines (803 loc) · 30 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
const express = require('express');
const path = require('path');
const fs = require('fs');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const git = require('git-clone-or-pull');
const rate = require('express-rate-limit');
const mineget = require('mineget');
// Sitemap and robots.txt
const robots = require('express-robots-txt');
const {SitemapStream} = require('sitemap');
const {createGzip} = require('zlib')
// GitHub flavoured Markdown parsing
const MarkdownIt = require('markdown-it');
const hljs = require('highlight.js');
const markdown = new MarkdownIt({
html: true, xhtmlOut: true,
linkify: true, typographer: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value;
} catch (__) {}
}
return ''; // use external default escaping
}
}).use(require('markdown-it-wikilinks')({
postProcessPageName: (pageName) => {
pageName = pageName.trim()
pageName = pageName.split('/').map(require('sanitize-filename')).join('/')
pageName = pageName.replace(/ /g, '-');
return pageName
}, uriSuffix: ''
})).use(require('markdown-it-scrolltable')).use(require('markdown-it-anchor'));
// App setup
const app = express();
const host = process.env.HOST || 'localhost';
const port = process.env.PORT || 8000;
const domain = process.env.DOMAIN || 'https://william278.net';
const gtag = process.env.ANALYTICS || '';
const projects = JSON.parse(fs.readFileSync(path.join(__dirname, 'projects.json'), 'utf8'));
const platforms = JSON.parse(fs.readFileSync(path.join(__dirname, 'platforms.json'), 'utf8'));
const limiter = rate({
windowMs: 10 * 60 * 100, // 1 minute
max: 500, // Limit each IP to 1000 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
const ORGANIZATION = JSON.stringify({
"@context": "https://schema.org",
"@type": "Organization",
"url": domain,
"logo": domain + "/assets/icons/huskhelp.png",
});
// Redirect trailing forward slashes
app.use((req, res, next) => {
if (req.path.substring(-1) === '/' && req.path.length > 1) {
const query = req.url.slice(req.path.length)
const safePAge = req.path.slice(0, -1).replace(/\/+/g, '/')
res.redirect(301, safePAge + query)
} else {
next()
}
})
const content = path.join(__dirname, 'content');
const readmes = path.join(__dirname, 'readmes');
const fontawesome = path.join(__dirname, 'node_modules', '@fortawesome');
const highlighter = path.join(__dirname, 'node_modules', 'highlight.js', 'styles');
app.use(express.static(content));
app.use(express.static(fontawesome));
app.use(express.static(highlighter));
app.set('view engine', 'pug');
app.set('views', 'pages')
// Robots.txt setup
app.use(robots({
UserAgent: '*',
Disallow: '/api/',
CrawlDelay: '5',
Sitemap: domain + '/sitemap.xml',
}));
// Rate limiter setup
app.use('/api', limiter);
// Get current git head version
const version = require('child_process')
.execSync('git rev-parse HEAD')
.toString().trim().substring(0, 7);
// Returns a formatted stat
const getFormattedStat = (stat, value) => {
stat = stat.toLowerCase();
switch (stat) {
case 'total_downloads': {
return {
id: stat,
icon: 'fa-solid fa-download',
text: parseInt(value) > 1000 ? (parseInt(value) / 1000).toFixed(1) + 'k' : parseInt(value),
};
}
case 'average_rating': {
return {
id: stat,
icon: 'fa-solid fa-star',
text: parseFloat(value).toFixed(1),
};
}
case 'latest_version': {
return {
id: stat,
icon: 'fa-solid fa-code-branch',
text: value,
};
}
default: {
return undefined;
}
}
}
// Returns the readme of a project
let cachedReadmes = {};
const getProjectReadme = (project) => {
let readMeFile = project['readme'];
if (cachedReadmes[project.id]) {
return new Promise((resolve) => {
resolve(cachedReadmes[project.id]);
});
}
if (readMeFile && readMeFile.startsWith('/')) {
if (!readMeFile.endsWith('.md')) {
readMeFile += '.md';
}
if (fs.existsSync(path.join(readmes, readMeFile))) {
return new Promise((resolve) => {
cachedReadmes[project.id] = fs.readFileSync(path.join(readmes, readMeFile), 'utf8');
resolve(cachedReadmes[project.id]);
});
}
}
if (project['repository']) {
const repository = project['repository'];
// Fetch the raw readme from the repository
return fetch(repository + '/raw/master/README.md').then(res => {
if (res.status !== 200) {
throw new Error('Readme not found');
}
return res.text()
}).then(text => {
// Replace relative links with absolute links to raw repository equivalent
return text.replace(/]\((?!http)(.*?)\)/g, '](' + repository + '/raw/master/$1)');
}).then(readme => {
cachedReadmes[project.id] = readme;
return readme;
}).catch(() => {
return undefined;
});
}
return new Promise((resolve) => {
resolve(undefined);
});
};
// Returns data for a project box
const getProjectBox = (project) => {
let projectData = {};
// Prepare project name and description
projectData['id'] = project['id'];
projectData['name'] = project['name'];
projectData['description'] = project['tagline'];
// Prepare project tags
if (project['tags']) {
projectData['pills'] = project['tags'];
}
// Prepare project icon
if (project['icon']) {
if (project['icon']['svg']) {
projectData['icon'] = {
'url': '/assets/icons/' + project['icon']['svg'],
'type': 'svg'
}
} else if (project['icon']['png']) {
projectData['icon'] = {
'url': '/assets/icons/' + project['icon']['png'],
'type': 'png'
}
}
}
// Prepare platform icons
projectData['buttons'] = [];
if (project['repository']) {
projectData['buttons'].push({
'id': 'github',
'name': platforms['github']['name'],
'class': platforms['github']['icon'],
'link': project['repository']
})
}
if (project['ids']) {
Object.entries(project['ids']).forEach(entry => {
projectData['buttons'].push({
'id': entry[0],
'name': platforms[entry[0]]['name'],
'class': platforms[entry[0]]['icon'],
'link': platforms[entry[0]]['url'].toString().replace('{id}', entry[1])
});
});
}
projectData.assets = project.assets;
projectData.icons = project.icon;
// Prepare page links
projectData['links'] = [];
if (project['documentation']) {
projectData['links'].push({
'id': 'documentation',
'text': 'Docs',
'link': '/docs/' + project['id'],
})
}
if (project['readme']) {
projectData['links'].push({
'id': 'readme',
'text': 'About',
'link': '/project/' + project['id']
})
}
if (project['links']) {
for (let link of project['links']) {
projectData['links'].push({
'id': link['text'].toLowerCase(),
'text': link['text'],
'link': link['link']
})
}
}
// Prepare project stats if this is a plugin
if (project['tags'] && projectStats[project['id']]) {
if ((project['tags']).includes('plugin')) {
projectData['stats'] = {};
projectData['stats']['raw'] = projectStats[project['id']];
projectData['stats']['formatted'] = [];
for (const stat of Object.entries(projectStats[project['id']])) {
let formatted = getFormattedStat(stat[0], stat[1]);
if (formatted) {
projectData['stats']['formatted'].push(formatted);
}
}
}
}
// Set if this project has a readme
if (project['repository'] || project['readme']) {
projectData['project_page'] = '/project/' + project['id'];
}
return projectData;
};
// Prepares project box data for the homepage
const getProjectBoxes = () => {
let projectBoxData = [];
for (const project of projects) {
projectBoxData.push(getProjectBox(project));
}
return projectBoxData;
};
// Serve a page
const servePage = (req, res, page, options) => {
const data = {
'organization': ORGANIZATION,
'version': version,
'domain': domain,
'path': req.path.slice(1),
'name': 'William278.net',
'title': 'Open source Minecraft server software & game projects - William278.net',
'tagline': 'Open source Minecraft server software & game projects',
'description': 'Easily-accessible documentation and information site for all of William278\'s Minecraft plugins, projects & games',
'gtag': gtag
};
if (options) {
Object.assign(data, options);
}
res.render(page, data);
}
// Home page
app.get('/', (req, res) => {
servePage(req, res, 'home', {
'projects': getProjectBoxes()
});
});
// Redirect /project/ to the home page
app.get('/project', (req, res) => {
res.redirect('/');
});
// Terms page
app.get('/terms', (req, res) => {
servePage(req, res, 'readme', {
'markdown': markdown.render(fs.readFileSync(path.join(readmes, 'terms.md'), 'utf8'))
});
});
// Redis hosts page
app.get('/redis-hosts', (req, res) => {
servePage(req, res, 'readme', {
'markdown': markdown.render(fs.readFileSync(path.join(readmes, 'redis-hosts.md'), 'utf8'))
});
});
// Project pages
app.get('/project/:name', (req, res) => {
const project = projects.find(project => project['id'] === req.params.name);
if (!project || !(project['repository'] || project['readme'])) {
sendError(req, res, 404, 'Project not found');
return;
}
getProjectReadme(project).then(readme => {
if (!readme) {
sendError(req, res, 500, 'Server error: Unable to retrieve project README');
return;
}
servePage(req, res, 'project', {
'project': getProjectBox(project),
'name': `${project['name']} - William278.net`,
'title': `${project['tagline']} - ${project['name']} - William278.net`,
'description': `About ${project['name']} on William278.net - ${project['tagline']}`,
'markdown': markdown.render(readme)
});
});
});
// Handle new transcripts
app.get('/transcript/:id', (req, res) => {
if (!req.params.id) {
sendError(req, res, 404, 'No transcript ID specified');
return;
}
// Decode id base 64
const parsedId = Buffer.from(req.params.id, 'base64url').toString('ascii');
if (!parsedId) {
sendError(req, res, 400, 'Could not parse ID');
return;
}
// If ID has three parts separated by forward slashes and ends in .json, it's a valid ID
if (!parsedId.match(/^[0-9]{1,32}\/[0-9]{1,32}\/[a-zA-Z0-9\-_]{1,32}\.json$/)) {
sendError(req, res, 400, 'Invalid transcript ID');
return;
}
// Validate the file is from a valid channel
const allowedChannels = ['885981365491888211', '977649978270969906', '977663053179023380'];
if (parsedId.split('/')[0]) {
if (!allowedChannels.includes(parsedId.split('/')[0])) {
sendError(req, res, 403, 'Forbidden (Transcript file not from valid channel)');
return;
}
}
fetch(`https://cdn.discordapp.com/attachments/${parsedId}`).then(response => {
if (response.status === 200) {
// Get the content type. If it is application.json, it's a valid transcript
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return response.json();
}
throw new Error('Invalid content type');
} else if (response.status === 404) {
throw new Error('Could not find that transcript. It may have been deleted.');
}
throw new Error('Failed to fetch transcript');
}).then(json => {
servePage(req, res, 'transcript', {
'name': `View Transcript - William278.net`,
'title': `View HuskHelp Support Ticket Transcript - William278.net`,
'description': `Read a transcript of this HuskHelp Discord support ticket`,
'transcript': json,
'markdown': markdown,
'processor': (text) => {
// Get all matches of the <!user:NUMBER> tag
let tags = ['user', 'emote', 'role', 'channel']
for (const tag of tags) {
const matches = text.matchAll(new RegExp(`<!${tag}:(\\d+)>`, 'g'));
for (const match of matches) {
let value = json[`${tag}s`].find(list => list['id'] === match[1]);
if (value) {
switch (tag) {
case 'user':
text = text.replaceAll(match[0], `<span class="discord-tag user-tag">@${value['name']}</span>`);
break;
case 'emote':
text = text.replaceAll(match[0], `<img class="discord-emoji" src="${value['url']}" alt="${value['name']}">`);
break;
case 'role':
text = text.replaceAll(match[0], `<span class="discord-tag role-tag" style="color: #${value['color']}">@${value['name']}</span>`);
break;
case 'channel':
text = text.replaceAll(match[0], `<span class="discord-tag channel-tag">#${value['name']}</span>`);
break;
}
}
}
}
return text;
}
});
}).catch(err => {
sendError(req, res, 400, err.message);
});
});
// Handle legacy transcripts
app.get('/transcript', (req, res) => {
if (!req.url.endsWith('.html')) {
if (!fs.existsSync(req.url)) {
sendError(req, res, '404');
return;
}
return;
}
let key = Object.keys(req.query)[0];
if (key && key.length > 0) {
try {
let url = new URL(key);
if (url.hostname !== 'cdn.discordapp.com') {
sendError(req, res, '400', 'Invalid hostname.');
return;
}
} catch (error) {
sendError(req, res, '400', 'Invalid URL.');
return;
}
fetch(key).then(response => {
if (response.status !== 200) {
throw response.status;
}
if (!response.headers.get("Content-Disposition").endsWith(".html, attachment")) {
console.log("Attempted to parse an invalid html file " + response.headers.get("Content-Disposition"));
throw 400;
}
return response.text();
}).then(html => {
return html.replace("<html>", "")
.replace("</html>", "")
.replace("<!DOCTYPE html>", "");
}).then(html => {
servePage(req, res, 'legacy-transcript', {
'transcript': html,
'name': `View Transcript - William278.net`,
'title': `View HuskHelp Support Ticket Transcript (${key.split('/').pop()}) - William278.net`,
'description': `Read a transcript of this HuskHelp Discord support ticket (${key.split('/').pop()}), including messages and attachments`
});
}).catch(code => {
sendError(req, res, code, 'That transcript is invalid or has expired.');
});
return;
}
sendError(req, res, '400', 'Bad request.');
});
// Serve the documentation index
app.get('/docs', (req, res) => {
servePage(req, res, 'docs-index', {
'name': 'Documentation - William278.net',
'title': 'Documentation for HuskHomes, HuskSync & more - William278.net',
'description': 'Documentation for William278\'s various projects, including HuskHomes, HuskSync, HuskTowns & HuskChat.',
});
});
// Serve documentation pages
app.get('/docs/:name/(:page)?', (req, res) => {
// Get the project name and page specified
let projectName = (req.params['name']);
if (!projectName || projectName === '') {
sendError(req, res, '404', 'Project not found');
return;
}
projectName = projectName.toLowerCase();
let pageName = (req.params['page'])
if (!pageName || pageName === '') {
res.redirect(`/docs/${projectName}/Home`);
return;
}
// Find project with documentation by name
let project = projects.find(project => project.name.toLowerCase() === projectName);
if (!project) {
sendError(req, res, '404', 'Invalid project.');
return;
}
if (!project.documentation) {
sendError(req, res, '404', 'There are no documentation pages for this project.');
return;
}
// Send the page
let pagePath = path.join(content, `docs/${projectName.toLowerCase()}/${pageName}.md`);
if (fs.existsSync(pagePath)) {
let sidebarPath = path.join(content, `docs/${projectName.toLowerCase()}/_Sidebar.md`);
if (fs.existsSync(sidebarPath)) {
let pageTitle = pageName.replace(/-/g, ' ');
servePage(req, res, 'docs', {
'projectName': project.name,
'pageName': pageTitle,
'name': `${project.name} Docs - ${pageTitle} - William278.net`,
'navigation': markdown.render(fs.readFileSync(sidebarPath, 'utf8')),
'markdown': markdown.render(fs.readFileSync(pagePath, 'utf8')),
'title': `${project.name} Documentation - ${pageTitle} - William278.net`,
'description': `Documentation for ${project.name} - ${project['tagline']} - ${pageTitle}`,
});
}
} else {
sendError(req, res, '404', 'Documentation page not found.');
}
});
// Handle post requests to update project documentation
let searchCache = {};
app.post('/api/update-docs', (req, res) => {
const id = req.body['name'];
const repository = req.body['repository'];
if (id && repository) {
// Validate that projects contains the project
if (projects.find(project => project['repository'] === repository && project.id.toLowerCase() === id.toLowerCase())) {
updateDocs(repository, id);
res.status(200).send('OK');
searchCache = {}; // Clear the search cache
}
}
res.status(400).send('Bad request');
});
// Search for matches of the query in the read page string
const searchPage = (query, markdown) => {
let matches = [];
let regex = new RegExp(query, 'gi');
let match = regex.exec(markdown);
while (match) {
matches.push(match.index);
match = regex.exec(markdown);
}
return matches;
}
// Serves a list of search results for a query term
app.get(['/api/search-docs/(:name)?', '/api/search-docs'], (req, res) => {
const query = req.query.query;
if (!query) {
res.status(400).send('Bad request');
return;
}
// Limit query size to 32
if (query.length > 32) {
res.status(400).send('Query too long');
return;
}
let projectsToSearch = [];
const queryName = req.params.name;
if (queryName) {
const project = projects.find(project => project.name.toLowerCase() === queryName.toLowerCase());
if (!project) {
res.status(400).send('Project ' + queryName + ' not found');
return;
}
if (!project.documentation) {
res.status(400).send('No documentation found.');
return;
}
projectsToSearch.push(project);
} else {
projectsToSearch = projects.filter(project => project.documentation);
}
if (projectsToSearch.length === 0) {
res.status(400).send('No documentation found.');
return;
}
// If the query is in the cache, return the cached results
if (searchCache[query.toLowerCase()]) {
// ...But only if the query was for the same projectsToSearch
if (searchCache[query.toLowerCase()].projects.length === projectsToSearch.length) {
let sameProjects = true;
for (let i = 0; i < projectsToSearch.length; i++) {
if (searchCache[query.toLowerCase()].projects[i].name !== projectsToSearch[i].name) {
sameProjects = false;
break;
}
}
if (sameProjects) {
res.status(200).send(searchCache[query.toLowerCase()].results);
return;
}
}
}
const results = [];
for (let project of projectsToSearch) {
// List page names that end with .md from the content
const pages = fs.readdirSync(path.join(content, `docs/${project.name.toLowerCase()}`));
for (const page of pages) {
if (page.endsWith('.md')) {
// Search against the page name and content
let pageName = page.slice(0, -3);
let nameMatches = searchPage(query, pageName);
let contentMatches = searchPage(query, fs.readFileSync(path.join(content, `docs/${project.name.toLowerCase()}/${page}`), 'utf8'));
// Ignore meta pages (_Sidebar, _Footer & Home)
if (pageName.startsWith('_') || pageName === 'Home') {
continue;
}
// Add the page to the results if it contains the query
if (nameMatches.length + contentMatches.length > 0) {
results.push({
'project': project.name,
'name': pageName.replace(/-/g, ' '),
'url': `/docs/${project.name.toLowerCase()}/${pageName}`,
'name_matches': nameMatches.length,
'content_matches': contentMatches.length,
});
}
}
}
}
// Sort results by name matches first, followed by content matches
results.sort((a, b) => {
if (a.name_matches === b.name_matches) {
return b.content_matches - a.content_matches;
}
return b.name_matches - a.name_matches;
});
// Limit to first 15 results
results.splice(15);
// Cache the result for this query
searchCache[query.toLowerCase()] = {
'projects': projectsToSearch,
'results': results,
};
res.send(results);
});
// Serves a list of all projects and data
app.get('/api/projects', (req, res) => {
res.send(projects);
});
// Serves data about a specific project by name
app.get('/api/projects/:name', (req, res) => {
const name = req.params.name;
const project = projects.find(project => project.name.toLowerCase() === name.toLowerCase());
if (project) {
res.send(project);
} else {
res.status(404).send('Not found');
}
});
// Get statistics about a project
let projectStats = {};
const getProjectStats = async () => {
let stats = {};
for (const project of projects) {
if (!project.tags) continue;
if (!project.tags.includes('plugin')) continue;
if (project['ids']) {
stats[project.id] = await mineget.get(project['ids']);
}
}
return stats;
}
app.get('/api/stats', (req, res) => {
res.send(projectStats);
getProjectStats().then(stats => {
projectStats = stats;
});
});
app.get('/api/stats/:name', (req, res) => {
if (!req.params.name) {
res.status(400).send('No project specified');
return;
}
let project = projects.find(project => project.id.toLowerCase() === req.params.name.toLowerCase());
if (!project) {
res.status(404).send('Invalid project');
return;
}
if (!projectStats[project.id]) {
res.status(400).send('No stats to return for this project');
return;
}
res.send(projectStats[project.id]);
getProjectStats().then(stats => {
projectStats = stats;
});
});
// Handle sitemap requests
let cachedSitemap;
app.get('/sitemap.xml', (req, res) => {
res.header('Content-Type', 'application/xml');
res.header('Content-Encoding', 'gzip');
// Returned cached sitemap if it exists
if (cachedSitemap) {
res.send(cachedSitemap)
return;
}
// Generate sitemap
try {
const sitemapStream = new SitemapStream({
hostname: domain
});
const pipeline = sitemapStream.pipe(createGzip())
// Write pages
sitemapStream.write({
url: '/',
changefreq: 'daily',
lastmod: new Date().toISOString(),
priority: 1,
img: {
url: '/assets/icons/williamhead.png'
}
});
sitemapStream.write({
url: '/docs/',
changefreq: 'daily',
lastmod: fs.statSync(path.join('pages', 'home.pug')).mtime.toISOString(),
priority: 0.9
});
// Iterate through every .md file in the content/docs directory and subdirectories
for (const project of projects) {
if (project['repository'] && project['documentation']) {
for (const page of fs.readdirSync(path.join(content, `docs/${project.id}`))) {
if (page.endsWith('.md') && !page.startsWith('_') && page !== 'Home.md') {
let pageName = page.slice(0, -3);
if (project['icon'] && project['icon']['png']) {
sitemapStream.write({
url: `/docs/${project.id}/${pageName}`,
changefreq: 'daily',
lastmod: fs.statSync(path.join(content, `docs/${project.id}/${page}`)).mtime.toISOString(),
priority: 0.8,
img: {
url: `/assets/icons/${project.icon.png}`
}
});
} else {
sitemapStream.write({
url: `/docs/${project.id}/${pageName}`,
changefreq: 'daily',
lastmod: fs.statSync(path.join(content, `docs/${project.id}/${page}`)).mtime.toISOString(),
priority: 0.8,
});
}
}
}
}
if (project.readme || project.repository) {
if (project['icon'] && project['icon']['png']) {
sitemapStream.write({
url: `/project/${project.id}`,
changefreq: 'daily',
priority: 0.9,
img: {
url: `/assets/icons/${project['icon']['png']}`,
}
});
} else {
sitemapStream.write({
url: `/project/${project.id}`,
changefreq: 'daily',
priority: 0.9
});
}
}
}
sitemapStream.end();
pipeline.pipe(res).on('error', (error) => {
throw error;
});
} catch (error) {
console.error(error)
res.status(500).end('Internal error generating sitemap');
}
});
// Handle robots.txt
app.get('/robots.txt', (req, res) => {
res.send();
});
// Handle all other page requests
app.use((req, res) => {
sendError(req, res, '404');
});
// Display an error page with a code and description
const sendError = (req, res, code, description) => {
servePage(req, res, 'error', {
'code': code,
'details': description ? description : 'Make sure you entered the correct URL.',
'title': `Error ${code} - William278.net`,
'name': `Error ${code} - William278.net`,
'description': `Error ${code} - ${description ? description : 'Make sure you entered the correct URL.'}`,
});
}
// Updates plugin documentation
const updateDocs = (repository, id) => {
let wiki = repository + '.wiki.git';
// Check if the content /docs directory exists, if it does not create it
if (!fs.existsSync(path.join(content, 'docs'))) {
fs.mkdirSync(path.join(content, 'docs'));
}
// Pull docs from the wikis
const filePath = path.join(content, `docs/${id.toLowerCase()}`);
git(wiki, filePath, function (err) {
if (err) {
console.error('An error occurred pulling ' + wiki + ' to ' + filePath)
console.error(err);
return;
}
console.log('Updated project documentation for ' + id);
});
}
// Update all project documentation
console.log('Updating project documentation...');
projects.filter(project => project['documentation']).forEach(project => {
updateDocs(project['repository'], project['id']);
});
// Cache the project stats
console.log('Caching project stats...');
getProjectStats().then(stats => {
projectStats = stats;
}).then(() => {
console.log('Starting server...');
app.listen(port, host, () => {
console.log(`Server running at on ${host}:${port}`);
console.log('[Pterodactyl] Ready');
});
});