-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.js
More file actions
135 lines (106 loc) · 3.8 KB
/
app.js
File metadata and controls
135 lines (106 loc) · 3.8 KB
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
require('dotenv').config();
const config = require('./config'),
cors = require('cors'),
express = require('express'),
exphbs = require('express-handlebars'),
getDayjs = require('./services/dayjs-wrapper'),
jsonStore = require('./services/json-store'),
mongodb = require('./services/mongodb'),
stats = require('./services/stats'),
morgan = require('morgan'),
removeExpiredSubscriptions = require('./services/remove-expired-subscriptions'),
websocket = require('./services/websocket');
let app, hbs, server, dayjs;
console.log(`${config.appName} ${config.appVersion}`);
// Schedule cleanup tasks
function scheduleCleanupTasks() {
// Run subscription cleanup every 24 hours
setInterval(async() => {
try {
console.log('Running scheduled subscription cleanup...');
await removeExpiredSubscriptions();
} catch (error) {
console.error('Error in scheduled subscription cleanup:', error);
}
}, 24 * 60 * 60 * 1000); // 24 hours in milliseconds
}
morgan.format('mydate', () => {
return new Date().toLocaleTimeString('en-US', { hour12: false, fractionalSecondDigits: 3 }).replace(/:/g, ':');
});
// Initialize dayjs at startup
async function initializeDayjs() {
dayjs = await getDayjs();
}
app = express();
app.set('trust proxy', true);
app.use(morgan('[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'));
app.use(cors());
// Configure handlebars template engine to work with dayjs
hbs = exphbs.create({
helpers: {
formatDate: (datetime, format) => {
return dayjs(datetime).format(format);
}
}
});
// Configure express to use handlebars
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// Handle static files in public directory
app.use(express.static('public', {
dotfiles: 'ignore',
maxAge: '1d'
}));
// Load controllers
app.use(require('./controllers'));
// Start server
async function seedJsonStore() {
const db = mongodb.get('rsscloud');
const resources = await db.collection('resources').find({}).toArray();
const subscriptions = await db.collection('subscriptions').find({}).toArray();
for (const resource of resources) {
jsonStore.setResource(resource._id, resource);
}
for (const sub of subscriptions) {
jsonStore.setSubscriptions(sub._id, sub.pleaseNotify || []);
}
jsonStore.flush();
}
async function gracefulShutdown() {
jsonStore.shutdown();
await mongodb.closeAll();
process.exit();
}
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
async function startServer() {
await initializeDayjs();
await mongodb.connect('rsscloud', config.mongodbUri);
jsonStore.initialize(config.dataFilePath);
await seedJsonStore();
// Start cleanup scheduling
scheduleCleanupTasks();
// Generate stats on startup, then schedule periodic regeneration
stats.generateStats().catch(err => console.error('Error generating initial stats:', err));
stats.scheduleStatsGeneration();
server = app.listen(config.port, () => {
app.locals.host = config.domain;
app.locals.port = server.address().port;
if (app.locals.host.indexOf(':') > -1) {
app.locals.host = '[' + app.locals.host + ']';
}
// Initialize WebSocket server for /wsLog
websocket.initialize(server);
console.log(`Listening at http://${app.locals.host}:${app.locals.port}`);
})
.on('error', (error) => {
switch (error.code) {
case 'EADDRINUSE':
console.log(`Error: Port ${config.port} is already in use.`);
break;
default:
console.log(error.code);
}
});
}
startServer().catch(console.error);