-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
203 lines (181 loc) · 6.23 KB
/
main.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
if(process.env.NODE_ENV != 'production')
{
require('dotenv').config();
}
const express = require('express');
const app = express();
const path = require('path');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const ejsMate = require('ejs-mate');
const bodyParser = require('body-parser');
const cors = require('cors');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const maptilerClient = require("@maptiler/client");
const csv = require('csv-parser');
const fs = require('fs');
maptilerClient.config.apiKey = process.env.MAPTILER_API_KEY;
const Mines = require('./models/mines');
const User = require('./models/user');
const places = require('./data/india-places');
const marketplaceRoutes = require('./marketplace/marketplace');
const authRoutes = require('./auth/auth');
const isAuthenticated = require('./auth/auth');
app.engine('ejs', ejsMate);
app.set("view engine", "ejs");
app.set('views', path.join(__dirname, 'pages'));
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static('pages'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(cors());
app.use(session({
secret: 'keyboard cat', // Replace with a strong secret key
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: 'mongodb://localhost:27017/mines' }),
cookie: { maxAge: 1000 * 60 * 60 * 24 } // Session expires after 1 day
}));
app.use(async (req, res, next) => {
if (req.session.userId) {
try {
const user = await User.findById(req.session.userId);
res.locals.currentUser = user;
} catch (err) {
console.error(err);
}
} else {
res.locals.currentUser = null;
}
next();
});
mongoose.connect('mongodb://localhost:27017/mines', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("MONGO CONNECTION OPEN!!!");
})
.catch(err => {
console.log("OH NO MONGO CONNECTION ERROR!!!!");
console.log(err);
});
app.use('/', authRoutes);
app.get("/home", (req, res) => {
res.render("home");
})
app.get("/about", (req, res) => {
res.render("aboutus");
})
app.get("/suggest", (req, res) => {
res.render("suggest");
})
app.post("/index", isAuthenticated, async (req, res) => {
try {
const geox = (req.body.Mine.district +", " + req.body.Mine.state);
console.log(geox)
const geoData = await maptilerClient.geocoding.forward((geox), { limit: 1 });
const mineData = req.body.Mine;
const mine = new Mines(mineData);
mine.geometry = geoData.features[0].geometry;
await mine.save();
res.redirect("/index");
} catch (err) {
console.error("Error adding mine:", err);
res.status(500).send("Internal Server Error");
}
});
app.get("/index", async (req, res) => {
try {
const user = await User.findById(req.session.userId);
if (!user) {
return res.redirect('/login');
}
const mines = await Mines.find({});
res.render("index", { mines });
} catch (err) {
console.error("Error fetching mines:", err);
res.status(500).send("Internal Server Error");
}
});
app.get("/calculate",(req, res) => {
res.render("calculate", {places});
});
app.get("/index/:id/suggestions",(req, res) => {
res.render("suggestions");
});
app.get("/index/:id", async (req, res) => {
try {
const data = [];
const mines = await Mines.findById(req.params.id);
if (!mines) {
return res.status(404).send("Mine not found");
}
fs.createReadStream('./mine_data3.csv')
.pipe(csv())
.on('data', (row) => {
data.push(row);
})
.on('end', () => {
res.render('show', { mines, mineData: data });
});
} catch (err) {
console.error("Error fetching mine:", err);
res.status(500).send("Internal Server Error");
}
});
app.delete("/index/:id", async (req, res) => {
try {
const mines = await Mines.findByIdAndDelete(req.params.id);
if (!mines) {
return res.status(404).send("Mine not found");
}
res.redirect("/index");
} catch (err) {
console.error("Error deleting mine:", err);
res.status(500).send("Internal Server Error");
}
});
app.put("/index/:id", async (req, res) => {
try {
const geox = (req.body.Mine.district +", " + req.body.Mine.state);
const mines = await Mines.findByIdAndUpdate(req.params.id, req.body.Mine, { new: true });
const geoData = await maptilerClient.geocoding.forward((geox), { limit: 1 });
mines.geometry = geoData.features[0].geometry;
if (!mines) {
return res.status(404).send("Mine not found");
}
await mines.save();
res.redirect(`/index/${mines.id}`);
} catch (err) {
console.error("Error updating mine:", err);
res.status(500).send("Internal Server Error");
}
});
app.get("/index/:id/edit", async (req, res) => {
try {
const mines = await Mines.findById(req.params.id);
if (!mines) {
return res.status(404).send("Mine not found");
}
res.render("edit", { mines, places });
} catch (err) {
console.error("Error fetching mine for edit:", err);
res.status(500).send("Internal Server Error");
}
});
app.get('/getCities', (req, res) => {
try {
const state = req.query.state;
const selectedState = places.states.find(s => s.name === state);
const cities = selectedState ? selectedState.districts.map(d => d.name) : [];
res.json(cities);
} catch (err) {
console.error("Error fetching cities:", err);
res.status(500).send("Internal Server Error");
}
});
app.use('/marketplace', marketplaceRoutes);
app.listen("3000", () => {
console.log("SERVER RUNNING.....................");
});