forked from dynastic/place
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
188 lines (165 loc) · 7.14 KB
/
app.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
const mongoose = require("mongoose");
mongoose.promise = global.Promise;
const recaptcha = require("express-recaptcha");
const readline = require("readline").createInterface({input: process.stdin, output: process.stdout});
const util = require("util");
const PaintingManager = require("./util/PaintingManager");
const HTTPServer = require("./util/HTTPServer");
const WebsocketServer = require("./util/WebsocketServer");
const ResponseFactory = require("./util/ResponseFactory");
const TemporaryUserInfo = require("./util/TemporaryUserInfo");
const LeaderboardManager = require("./util/LeaderboardManager");
const UserActivityManager = require("./util/UserActivityManager");
const ModuleManager = require("./util/ModuleManager");
const PixelNotificationManager = require("./util/PixelNotificationManager");
const JavaScriptProcessor = require("./util/JavaScriptProcessor");
const ChangelogManager = require("./util/ChangelogManager");
const User = require("./models/user");
const fs = require("fs");
const path = require("path");
var app = {};
app.logger = require('./util/logger');
app.loadConfig = (path = "./config/config") => {
delete require.cache[require.resolve(path)];
var oldConfig = app.config;
app.config = require(path);
app.colours = [... new Set((app.config.colours || ["#FFFFFF", "#E4E4E4", "#888888", "#222222", "#FFA7D1", "#E50000", "#E59500", "#A06A42", "#E5D900", "#94E044", "#02BE01", "#00D3DD", "#0083C7", "#0000EA", "#CF6EE4", "#820080"]).map((c) => c.toUpperCase()))];
if(!app.config.siteName) app.config.siteName = "MineBBS像素画板";
if(!app.config.enableChangelogs) app.config.enableChangelogs = true;
if(!app.config.boardSize) app.config.boardSize = 800; // default to 1600 if not specified in config
if(oldConfig && (oldConfig.secret != app.config.secret || oldConfig.database != app.config.database || oldConfig.boardSize != app.config.boardSize)) {
app.logger.log("配置", "我们正在停止 Place 服务器,因为数据库 URL、密码和/或板图像大小已更改,这将需要重新启动整个服务器。");
process.exit(0);
}
if(oldConfig && (oldConfig.oauth != app.config.oauth)) {
app.stopServer();
app.recreateServer();
app.restartServer();
app.recreateRoutes();
}
if(oldConfig && (oldConfig.port != app.config.port || oldConfig.onlyListenLocal != app.config.onlyListenLocal)) app.restartServer();
}
app.loadConfig();
app.temporaryUserInfo = TemporaryUserInfo;
app.responseFactory = (req, res) => new ResponseFactory(app, req, res);
app.pixelNotificationManager = new PixelNotificationManager(app);
app.changelogManager = new ChangelogManager(app);
app.reportError = app.logger.capture;
app.moduleManager = new ModuleManager(app);
app.moduleManager.loadAll();
// Create .place-data folder
app.dataFolder = path.resolve(__dirname, ".place-data");
if (!fs.existsSync(app.dataFolder)) fs.mkdirSync(app.dataFolder);
// Get image handler
app.paintingManager = PaintingManager(app);
app.logger.info('启动', "从数据库加载图像中…");
app.paintingManager.loadImageFromDatabase().then((image) => {
app.paintingManager.startTimer();
app.logger.info('启动', "从数据库成功加载图像。");
}).catch((err) => {
app.logger.capture("从数据库加载图像时出错:" + err);
});
app.leaderboardManager = LeaderboardManager(app);
app.userActivityController = UserActivityManager(app);
app.enableCaptcha = false;
if(typeof app.config.recaptcha !== "undefined") {
if(typeof app.config.recaptcha.siteKey !== "undefined" && typeof app.config.recaptcha.secretKey !== "undefined") {
app.enableCaptcha = app.config.recaptcha.siteKey != "" && app.config.recaptcha.secretKey != "";
}
}
if(app.enableCaptcha) {
// Set up reCaptcha
recaptcha.init(app.config.recaptcha.siteKey, app.config.recaptcha.secretKey);
app.recaptcha = recaptcha;
}
app.adminMiddleware = (req, res, next) => {
if(!req.user || !req.user.admin) return res.status(403).redirect("/?admindenied=1");
next();
};
app.modMiddleware = (req, res, next) => {
if(!req.user || !(req.user.admin || req.user.moderator)) return res.status(403).redirect("/?moddenied=1");
next();
};
app.recreateServer = () => {
app.httpServer = new HTTPServer(app);
app.server = app.httpServer.httpServer;
app.websocketServer = new WebsocketServer(app, app.server);
}
app.recreateServer();
async function connectToDb() {
try {
await mongoose.connect(app.config.database, { useNewUrlParser: true,
useUnifiedTopology: true,
family: 4});
} catch (error) {
console.log(error);
}
if (mongoose.connection.readyState === 1) {
console.log("成功连接至数据库");
}
}
connectToDb().then(function(data) {
console.log(data);
});
const handlePendingDeletions = () => {
setInterval(() => {
const now = new Date();
User.remove({ deletionDate: { $lte: now } }, function(err, result) {
if (err) { console.error(err); return }
if (result.n) app.logger.log('删除者', `已删除 ${result.n} 用户。`);
});
}, 30 * Math.pow(10, 3));
}
mongoose.connection.on('error', err => {
app.logger.log('数据库连接', err);
});
mongoose.connection.once('connected', () => {
handlePendingDeletions();
});
// Process JS
app.javascriptProcessor = new JavaScriptProcessor(app);
app.javascriptProcessor.processJavaScript();
app.stopServer = () => {
if(app.server.listening) {
app.logger.log('关闭', "正在关闭服务器…")
app.server.close();
setImmediate(function() { app.server.emit("close"); });
}
}
app.restartServer = () => {
app.stopServer();
app.server.listen(process.env.PORT || app.config.port, (process.env.ONLY_LISTEN_LOCAL ? process.env.ONLY_LISTEN_LOCAL === true : app.config.onlyListenLocal) ? "127.0.0.1" : null, null, () => {
app.logger.log('启动', `已启动Place服务器于端口 ${app.config.port}${app.config.onlyListenLocal ? " (仅在本地监听)" : ""}.`);
});
}
app.restartServer();
app.recreateRoutes = () => {
app.moduleManager.fireWhenLoaded((manager) => {
function initializeServer(directories, routes = []) {
app.httpServer.setupRoutes(directories, routes);
}
function continueWithServer(directories = []) {
manager.getRoutesToRegister().then((routes) => initializeServer(directories, routes)).catch((err) => app.logger.capture(err))//initializeServer(directories));
}
manager.getAllPublicDirectoriesToRegister().then((directories) => continueWithServer(directories)).catch((err) => continueWithServer());
});
}
app.recreateRoutes();
readline.on('line', i => {
try {
var output = eval(i)
output instanceof Promise
? output.then(a => {
console.log('承诺已解决')
console.log(util.inspect(a, {depth: 0}))
}).catch(e => {
console.log('承诺被拒绝')
console.log(e.stack)
})
: output instanceof Object
? console.log(util.inspect(output, {depth: 0}))
: console.log(output)
} catch (err) {
console.log(err.stack)
}
})