-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
175 lines (154 loc) · 4.87 KB
/
server.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
var express = require("express");
const fileUpload = require("express-fileupload");
var bodyParser = require("body-parser");
var path = require("path");
var fs = require("fs");
var app = express();
console.log(path.join(__dirname,'security/cert.key'))
const httpsOptions = {
key: fs.readFileSync(path.join(__dirname,'security/cert.key')),
cert: fs.readFileSync(path.join(__dirname,'security/cert.pem'))
}
var http = require("https").createServer(httpsOptions, app);
var io = require("socket.io")(http);
const multer = require("multer");
var serveIndex = require("serve-index");
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const generateRandom = () => Math.random().toString(36).substring(2, 15) + Math.random().toString(23).substring(2, 5);
const MIME_TYPE_MAP = {
"image/png": "png",
"image/jpeg": "jpeg",
"image/jpg": "jpg",
};
const upload = multer({
storage: multer.diskStorage({
destination(req, file, callback) {
callback(null, "./upload");
},
filename(req, file, callback) {
const ext = MIME_TYPE_MAP[file.mimetype];
callback(
null,
`${file.fieldname}_${Date.now()}_${file.originalname}.${ext}`
);
},
}),
limits: { fieldSize: 25 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const isValid = !!MIME_TYPE_MAP[file.mimetype];
let error = isValid ? null : new Error("Invalid mime type!");
cb(error, isValid);
},
});
function MessageStorage() {
const allMessages = [];
return {
find: function (conditions, callback) {
const filter = allMessages.filter((element) => {
return (
Object.keys(conditions)
.map((key) => {
return (
element.hasOwnProperty(key) && element.key === conditions[key]
);
})
.filter((e) => e).length === Object.keys(conditions).length
);
});
callback("", filter);
},
save: function (name, message, receivedAt) {
allMessages.push({
name,
receivedAt,
message,
});
},
};
}
var Message = MessageStorage();
// Serve URLs like /ftp/thing as public/ftp/thing
// The express.static serves the file contents
// The serveIndex is this module serving the directory
app.use(
"/files",
express.static(path.join(__dirname, "upload")),
serveIndex(path.join(__dirname, "upload"), { icons: true })
);
app.get("/messages", (req, res) => {
Message.find({}, (err, messages) => {
res.send(messages);
});
});
app.get("/messages/:user", (req, res) => {
var user = req.params.user;
Message.find({ name: user }, (err, messages) => {
res.send(messages);
});
});
app.post("/messages", async (req, res) => {
try {
const receivedAt = Date.now()
Message.save(req.body.name, req.body.message, receivedAt);
console.log("saved");
// var censored = await Message.findOne({message:'badword'});
// if(censored)
// await Message.remove({_id: censored.id})
// else
io.emit("message", { ...req.body, receivedAt });
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
return console.log("error", error);
} finally {
console.log("Message Posted");
}
});
app.post("/upload", fileUpload({
defCharset: 'utf8',
defParamCharset: 'utf8'
}), async function (req, res, next) {
try {
let sampleFile;
let uploadPath;
console.log("upload call");
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
sampleFile = req.files.sampleFile;
const fileFullName = Buffer.from(sampleFile.name).toString('utf-8');
const extendName = fileFullName.substring(fileFullName.lastIndexOf('.'))
const fileName = fileFullName.substring(0, fileFullName.lastIndexOf('.')).replace(/[|/\\:*?"<>]/gi, '_');
uploadPath = path.join(__dirname, "upload", `${fileName}${extendName}`);
console.log('update path', uploadPath);
// Use the mv() method to place the file somewhere on your server
sampleFile.mv(uploadPath, async function (err) {
if (err) {
console.log('upload error', err);
return res.status(500).send(err);
} else {
console.log('Upload Success', uploadPath);
return res.send("File uploaded!" + uploadPath);
}
});
} catch (error) {
console.error(error)
next(error)
}
});
app.post("/uploadPhoto", upload.array("photo", 3), function (req, res) {
if (!req.files) {
return res.status(400).send("No files were uploaded.");
} else {
res.send("File uploaded!");
}
});
io.on("connection", () => {
console.log("a user is connected");
});
var server = http.listen(process.argv[2], process.argv[3], () => {
console.log("server is running on port", server.address().port);
});