/
index.js
217 lines (189 loc) · 6.68 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
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
const version_id = "1.0.1";
const express = require('express');
const session = require('express-session');
const app = express();
const fs = require('fs');
const sqlite3 = require('sqlite3').verbose();
const compression = require('compression');
const helmet = require('helmet');
const { MulterError } = require('multer');
const environment = require('./environment.js');
if (!environment.debug) {
// Activate SSL for img.ryandw11.com
const https = require('https');
const privateKey = fs.readFileSync('../privkey.pem', 'utf8');
const certificate = fs.readFileSync('../fullchain.pem', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(8443, () => console.log('Server running on port 8443...'));
} else {
app.listen(8080, () => console.log("Sever running debug on port 8080..."));
}
// Setup the handlebars template engine.
const hbs = require('express-handlebars').engine({
defaultLayout: 'main',
extname: '.hbs',
helpers: {
static(path) {
return path;
},
escapeJSString(str) {
if (!str) {
return null;
}
return jsesc(str, {
escapeEverything: true,
wrap: true
});
},
// Custom functionality that allows a basic if statement.
ifEq(a, b, opts) {
if(a == null || b == null)
return opts.inverse(this);
if (a == b)
return opts.fn(this);
else
return opts.inverse(this);
},
// Highlights a specific set of characters in a string.
surrWord(input, search) {
input = input.replace("<", "<").replace(">", ">");
let index = input.toLowerCase().indexOf(search.toLowerCase());
if (index < 0) {
return input.slice(0, 200);
}
let sectionOne = Math.max(0, index - 50);
let sectionTwo = Math.min(input.length, index + 50);
return (sectionOne != 0 ? "..." : "") + input.slice(sectionOne, index) + `<strong>${input.slice(index, index + search.length)}</strong>` + input.slice(index + search.length, sectionTwo) + (sectionTwo != input.length ? "..." : "");
}
}
});
app.use(helmet());
app.engine('hbs', hbs);
app.set('view engine', 'hbs');
app.use(express.static(__dirname + '/public'));
if (!environment.debug) {
app.enable('view cache');
app.use(compression());
}
// let RedisStore = require('connect-redis')(session);
// let redisClient = redis.createClient();
app.use(session({
secret: 'a^fewfjwiofh-6Jfjsc&3+mca**fj4$$mcsjiog#4$',
resave: false,
saveUninitialized: true,
// Two Weeks
cookie: {
maxAge: 1.21e+9,
// Enable secure mode if not in debug.
secure: !environment.debug
}
// store: new RedisStore({ client: redisClient }),
}));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
/*
* Setup SQL
*/
const db = new sqlite3.Database('./data/images.db');
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS images (
id INTEGER PRIMARY KEY,
file_id VARCHAR(40) NOT NULL,
uuid VARCHAR(40) NOT NULL,
name VARCHAR(40) NOT NULL,
caption VARCHAR(100) NOT NULL,
unlisted INTEGER NOT NULL,
author_id VARCHAR(40) NOT NULL,
file VARCHAR(40) NOT NULL,
date DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
user_id VARCHAR(40) NOT NULL,
user_name VARCHAR(40) NOT NULL,
password VARCHAR(100) NOT NULL,
current_session VARCHAR(40),
session_creation BIGINT,
date DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
db.run(`CREATE TABLE IF NOT EXISTS 'Ryandw11Images' (
id INTEGER PRIMARY KEY,
version_id VARCHAR(40) NOT NULL
)`, () => {
// Check to see if the table exists.
db.all(`SELECT * FROM 'Ryandw11Images'`, (err, rows) => {
if(rows.length < 1){
// Insert the current version number into the table.
db.run(`INSERT INTO 'Ryandw11Images' (version_id) VALUES ('${version_id}')`);
}
})
});
// Check to see if private exists. If it does not, add it.
// TODO:: Remove this after a few versions.
db.get(`SELECT unlisted FROM images`, (err, sel) => {
if(sel !== undefined) return;
console.log("Detected older version. Updating Database!");
db.run(`ALTER TABLE images ADD unlisted INTEGER NOT NULL DEFAULT 0`, (err) => {
if(err != null){
console.log("Fatal error occured! Could not update database!");
console.log(err);
return;
}
console.log("Updated database to the recent version!");
});
})
});
/*
* Setup Routes
*
*/
if(environment.isRegistrationAllowed)
console.log("Running Ryandw11 Images with Registration Allowed!");
console.log(`There are ${environment.admins.length} admins.`);
const main_router = require('./main_router.js');
const account_router = require('./account_router.js');
const handler_router = require('./handler_router.js');
const api_router = require('./api_router.js');
const admin_router = require('./admin_router.js');
app.use('/', main_router(db, environment));
app.use('/auth', account_router(db, environment));
app.use('/handle', handler_router(db, environment));
app.use('/api/v1', api_router(db, environment));
app.use('/admin', admin_router(db, environment));
// This handles errors within the program.
app.use((err, req, res, next) => {
// If it is a Multer error, redirect to the upload page with an error.
if(err instanceof MulterError) {
res.redirect("/upload?err=6");
return;
}
function getThemeNumber(req) {
if(req.session == null || req.session == undefined)
return 0;
if (req.session.theme != null) {
return req.session.theme;
}
return 0;
}
console.log("A critical error has occured:");
console.error(err.stack);
// Render the error page.
res.status(500).render("error", {debug: environment.debug, error: err.stack, session: req.session, theme: getThemeNumber(req)});
});
app.post('/theme', (req, res) => {
let data = req.body.theme;
switch (data) {
case "0":
req.session.theme = 0;
break;
case "1":
req.session.theme = 1;
break;
default:
req.session.theme = 0;
break;
}
// Go back to the previous page.
res.redirect('back');
});