forked from Naila/Discord-chat-replica
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
96 lines (87 loc) · 2.57 KB
/
index.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
/*
* Copyright (c) 2020 Cynthia K. Rey
* Licensed under the Open Software License version 3.0
*/
const { existsSync, createReadStream } = require('fs')
const { resolve } = require('path')
const mime = require('mime-types')
const https = require('https')
const ejs = require('ejs')
const { minify } = require('html-minifier')
const markdown = require('./src/markdown')
const Formatter = require('./src/formatter')
// Stuff
const assets = require('./src/assets')
const config = require('./config')
const testData = require('./example')
require('http')
.createServer((req, res) => {
if (![ 'GET', 'POST' ].includes(req.method)) {
res.writeHead(405)
return res.end()
}
// Assets
if (req.url.startsWith('/dist/')) {
const target = req.url.split('/')[2]
const file = resolve(__dirname, 'dist', target)
if (existsSync(file) && target && target !== '.' && target !== '..') {
res.setHeader('content-type', mime.lookup(file) || 'application/octet-stream')
return createReadStream(file).pipe(res)
}
}
// Attachments
if (req.url.startsWith('/attachments/')) {
const headers = {}
if (req.headers.range) {
headers.range = req.headers.range
}
https.get({
host: 'cdn.discordapp.com',
path: req.url,
port: 443,
headers
}, resp => {
delete resp.headers['content-disposition']
res.writeHead(resp.statusCode, {
...resp.headers,
'Access-Control-Allow-Origin': '*'
})
resp.pipe(res)
})
return
}
// Serve
const handler = async (data) => {
const fm = new Formatter(data)
const formatted = await fm.format()
if (!formatted) {
res.writeHead(400)
return res.end()
}
const hostname = config.hostname ? config.hostname : `${req.headers['x-forwarded-proto'] || 'http'}://${req.headers.host}`
ejs.renderFile('./views/index.ejs', {
data: formatted,
assets,
markdown,
hostname
}, null, (err, str) => {
if (err) {
res.writeHead(500)
res.end('Internal Server Error')
console.error(err)
}
res.end(minify(str, {
collapseWhitespace: true,
removeComments: true
}))
})
}
res.setHeader('content-type', 'text/html')
if (req.method === 'POST') {
let data = ''
req.on('data', chunk => (data += chunk))
req.on('end', () => handler(JSON.parse(data)))
} else {
return handler(testData)
}
}).listen(config.port)