-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
270 lines (214 loc) · 6.94 KB
/
server.mjs
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
import * as path from 'path';
import express from 'express';
import compression from 'compression';
import morgan from 'morgan';
import winston from 'winston';
import {config} from './app/config.mjs';
import * as s from './app/services.mjs'
const app = express();
app.use(compression());
app.use(express.json());
app.use(express.static('public'));
// const requestFilter = (req) => {
// // Customize your condition here, for example:
// // Log only POST requests or requests to a specific path
// // return req.method === 'POST' || req.url.startsWith('/api/specific-path');
// return !req.url.startsWith('/getThumbnail');
// };
const { format } = winston;
const logger = winston.createLogger({
format: format.combine(
format.colorize(),
format.timestamp(),
format.printf((msg) => {
return `${msg.timestamp} [${msg.level}] ${msg.message}`;
})
),
transports: [new winston.transports.Console({
// format: winston.format.combine(
// winston.format((info) => {
// // Apply the filter to check if the log should be recorded
// // return requestFilter(info.req) ? info : null;
// return info
// })(),
// winston.format.colorize()
// ),
level: 'http'
})],
});
const morganMiddleware = morgan(
':method :url :status :res[content-length] - :response-time ms',
{
stream: {
write: (message) => logger.http(message.trim()),
},
}
);
app.use(morganMiddleware);
// TODO: validate request parameters in all relevant functions?
// *****************************************
// search, and thumbnails
// *****************************************
// TODO: rename this
app.get('/getAll', function(req,res){
res.json(s.search.getAllFromDefaultCollection());
});
app.get('/getThumbnail', function(req,res){
let uuid = req.query.uuid, height = +req.query.height;
// TODO: get the list of sizes from indexer / thumbnail generator
let thumbHeight = [100, 250, 500].filter(x=> x >= height)[0];
// console.log(`inputs: uuid ${uuid} height ${height}`)
let fileName = path.join(config.thumbsDir, ...Array.from(uuid).slice(0,3), `${uuid}_${thumbHeight}_fit.jpg`);
// console.log(`getting thumbnail: ${fileName}`)
res.sendFile(fileName, {root: '.'});
});
app.get('/getImage', function(req,res){
let uuid = req.query.uuid, height = +req.query.height, width = +req.query.width;
res.type('image/jpg');
// res.set({
// "Content-Disposition": `inline;filename="${filename.split(/\//).pop()}"`
// });
// s.search.getImage(uuid, width, height).pipe(res);
s.search.getImage(uuid, 1920, 1080).pipe(res);
});
app.get('/getVideo', function(req,res){
let uuid = req.query.uuid, height = +req.query.height, width = +req.query.width;
s.search.getVideo(uuid).pipe(res);
});
app.post('/search', function(req,res){
let {collection_id, searchText} = req.body;
res.json(s.search.search(collection_id, searchText));
});
app.get('/searchForExistingAlbums', function(req,res){
res.json(s.search.searchForExistingAlbums(req.query.searchStr, req.query.wantFullName))
})
// *****************************************
// collection functions
// *****************************************
app.post('/createNewCollection', function(req,res,next){
let c = req.body;
try {
let id = s.collections.createNewCollection(c)
res.json(id)
} catch (error){
next(error);
}
});
app.get('/getAllCollections', function(req,res){
res.json( s.collections.getAllCollections() )
});
// *****************************************
// indexer functions
// *****************************************
app.post('/startIndexingFirstTime', async function(req,res){
let {collection_id} = req.query;
s.indexer.indexCollection(collection_id, true);
res.sendStatus(200);
});
app.post('/indexCollection/:collection_id', function(req,res){
let collection_id = req.params.collection_id;
s.indexer.indexCollection(collection_id);
res.sendStatus(200);
});
app.get('/getIndexerStatus', function(req,res){
res.json(s.indexer.indexerStatus());
});
app.put('/pauseIndexer', function(req,res){
s.indexer.pauseIndexer();
res.sendStatus(200);
});
app.put('/resumeIndexer', function(req,res){
s.indexer.resumeIndexer();
res.sendStatus(200);
});
app.get('/getIndexerErrors', function(req,res){
res.json( s.indexer.indexerErrors )
});
app.put('/updateIndexerConcurrency/:concurrency', function(req,res,next){
let concurrency = +req.params.concurrency;
if(concurrency){
s.indexer.updateIndexerConcurrency(concurrency);
}
res.sendStatus(200);
});
app.put('/updateRating', function(req,res){
let {uuid_arr, newRating} = req.body;
try{
s.indexer.updateRating(uuid_arr, newRating);
} catch(err){
res.status(500).json({error: err.message});
return;
}
res.sendStatus(200);
});
app.put('/refreshThumbs/:uuid', async function(req,res){
await s.indexer.refreshThumbs(req.params.uuid);
res.sendStatus(200);
})
// *****************************************
// album organization
// *****************************************
app.post('/updateAlbumName', async function(req,res){
let {collection_id, currAlbumName, newAlbumName} = req.body;
try {
let updates = await s.indexer.updateAlbum(collection_id, currAlbumName, newAlbumName);
res.json(updates);
} catch (err) {
res.status(500).json(err);
}
});
app.delete('/trashItems', async function(req,res){
let {uuid_arr} = req.body;
await s.indexer.moveFileToTrash(uuid_arr);
res.sendStatus(200);
});
app.put('/moveItems', async function(req,res){
let {collection_id, uuid_arr, new_album_name} = req.body;
await s.indexer.moveItemsToAlbum(collection_id, uuid_arr, new_album_name);
res.sendStatus(200);
});
// *****************************************
// wathers
// *****************************************
// TODO Implement start and stop for individual collection
app.post('/startAllWatchers', function(req,res){
s.watcher.startWatchersForAllCollections();
res.sendStatus(200);
});
app.post('/stopAllWatchers', function(req,res){
s.watcher.stopAllWatchers();
res.sendStatus(200);
});
// TODO
// app.delete('/deleteAlbum/:albumName', function(req,res){
// let albumName = req.params.albumName;
// if(){ // album name is valid
// s.indexer.deleteAlbum(albumName);
// res.sendStatus(200);
// } else {
// ???
// }
// })
// *****************************************
// start server
// *****************************************
process.on('SIGINT', function(){
console.log('***** Interrupt signal received **** ');
handleServerShutdown();
});
process.on('SIGTERM', function(){
console.log('***** Terminate signal received **** ');
handleServerShutdown();
});
const handleServerShutdown = async function(){
await s.housekeeping.shutdownCleanup();
server.close(()=>{
console.log('app shutdown. Ending process... ');
process.exit(0);
});
}
let server = app.listen(9000, ()=>{
console.log("app started and listening in port 9000!");
// Perform startup activities
s.housekeeping.startUpActivities();
});