-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
369 lines (309 loc) · 9.89 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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
require('dotenv').config()
const express = require('express'); // basic libs
const bodyParser = require('body-parser'); // render
const { connect } = require('./config/connect');
const { sendmail, sendnews, covid } = require('./commonfunctions/commonfunc');
const compression = require('compression')
const nocache = require('nocache');
const flash = require('connect-flash');
const session = require('cookie-session');
const cookie = require('cookie-parser');
const generateApiKey = require('generate-api-key').default;
const path = require('path');
const csrf = require('csurf');
const cookieParser = require("cookie-parser")
const appo = require('./models/apposchema')
require('events').EventEmitter.prototype._maxListeners = 900;
// models
const usersemails = require('./models/useremails'); // models
const usersSchema = require('./models/userschema'); // models
const edurls = require('./models/edurls'); // models
const api = require('./models/apis') //model
const rateLimit = require('express-rate-limit')
var limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 50
});
// routes for all action idividual
const accountRouter = require('./routes/accountrouter').Router;
const { isauthvalid } = require('./commonfunctions/commonfunc');
const { providerSchema } = require('./models/methods/provider_meth');
const { producerSchema } = require('./models/methods/producer_meth');
const apposchema = require('./models/apposchema');
// open ai
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
// ports
const port = process.env.PORT || 8080;
// start init
const app = express();
const statusMonitor = require('express-status-monitor')();
app.use(statusMonitor);
app.get('/status', statusMonitor.pageRoute)
// session
app.use(session({
secret: require('./config/connection_config').pass,
resave: false,
saveUninitialized: true,
cookie: { maxage: 6100000 }
}));
// for error flashing
app.use(flash())
app.use(cookie());
//render for htmls
app.set('view engine', 'ejs')
app.set('json spaces', 2)
//css js etc flies
app.use(express.static(__dirname + '/public'))
//no cache session cookie issue more loade time
app.use(nocache());
// compression for fast loads
app.use(compression())
//idk parseres
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser('Tatakae'));
app.use(csrf({ cookie: true }));
// parse application/json
app.use(bodyParser.json())
//account routes
app.use('/account', accountRouter)
// rate limiting
app.use(limiter);
app.set('etag', false)
app.get('/sitemap.xml', (req, res, next) => {
var fileName = 'sitemap.xml';
var options = {
root: path.join(__dirname)
};
res.sendFile(fileName, options, function (err) {
if (err) {
next(err);
} else {
console.log('Sent:', fileName);
}
});
})
app.get('/robots.txt', (req, res, next) => {
var fileName = 'robots.txt';
var options = {
root: path.join(__dirname)
};
res.sendFile(fileName, options, function (err) {
if (err) {
next(err);
} else {
console.log('Sent:', fileName);
}
});
})
// health
app.get('/health', async (req, res) => {
// GET
res.status(200).send("OK");
})
// default route
app.get('/', async (req, res) => {
// GET
const data = await sendnews();
// console.log(data.articles);
res.render('index', { data: data.articles, csrf_token: req.csrfToken() });
})
// email Register
app.post('/', async (req, res) => {
// post ajax in index.js
await connect();
// console.log(req.body)
const userData = new usersemails({
email: req.body.email,
pos: [parseFloat(req.body.lat), parseFloat(req.body.lon)],
date: req.body.date
})
var user_check = usersemails.findOne({ email: req.body.email })
if (req.body.email === user_check.email) {
console.log("error")
} else {
// subscriber added
userData.save(err => {
if (err) {
res.send({ alreadysubscribed: "404" }).status(404)
} else {
res.send({ alreadysubscribed: "200" }).status(200)
sendmail(req.body.email);
}
});
// await dis()
}
// email sent
});
// education
app.get('/education', async (req, res) => {
await connect();
// var data = edurls.findOne({});
edurls.find({}, { "_id": 0, "url": 1, "date": 1, "description": 1 }, (err, data) => {
if (err) {
res.render('error')
} else {
// console.log(data)
edurls.countDocuments({}, (err, usercount) => {
// console.log(usercount)
res.render('education', { data: data, count: usercount })
})
}
})
});
// contact
app.get('/contact', (req, res) => {
res.render('contact', { title: "Contact" })
})
// blogs
app.get('/counter', async (req, res) => {
try{
var data = await covid();
console.log(data);
}catch(e){
console.error(e);
}
await connect();
appo.find({ 'status': true }, { 'details.position': 1, '_id': 0 }, (err, result) => {
const pos = result.map(position);
// console.log(pos)
function position(item) {
return (item.details.position);
}
data = data.response;
res.render('counter', { data: data[0], appo: pos });
})
// get base india
})
// services
app.get('/services', (req, res) => {
res.render('services', { title: "Services" })
})
// about
app.get('/about', (req, res) => {
res.render('about')
})
// open ai
app.get('/help', (req, res) => {
res.render('help', { 'csrf_token': req.csrfToken() });
})
app.post('/help', async (req, res) => {
let prompt = req.body.prompt;
await openai.createCompletion({
model: "text-davinci-003",
prompt: `${prompt}`,
temperature: 0, // Higher values means the model will take more risks.
max_tokens: 2047, // The maximum number of tokens to generate in the completion. Most models have a context length of 2048 tokens (except for the newest models, which support 4096).
top_p: 1, // alternative to sampling with temperature, called nucleus sampling
frequency_penalty: 0.5, // Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
presence_penalty: 0, // Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
}).then((data) => {
console.log(data.data.choices)
res.json({ message: data.data.choices[0].text });
}).catch(err => {
console.log(err)
})
})
// apis
app.get('/api', isauthvalid, (req, res) => {
res.render('apis/api', { csrf_token: req.csrfToken() })
})
// api key genration
app.post('/api', async (req, res) => {
const key = generateApiKey({ method: 'string', min: 10, max: 20 });
const date = new Date();
const api_in = new api({
apikey: key,
date: date
})
await connect();
api_in.save(err => {
if (err) {
console.log(err);
res.send({ generated: "404" }).status(404)
} else {
res.send({ generated: "200", apikey: key }).status(200)
}
});
})
// educztion videos update api
app.get('/api/edurls/:url&:des&:apikey', async (req, res) => {
let youtube = "https://www.youtube.com/embed/"
let url = youtube + req.params.url
let apikey = req.params.apikey
let description = req.params.des
let date = new Date();
await connect();
const exsist = await api.findOne({ apikey: apikey }).lean()
// gets an object contain
// console.log(exsist)
if (exsist != null) {
// post ajax in index.js
// console.log(req.body)
const edurl = new edurls({
url: url,
description: description,
date: date
})
// save
edurl.save(err => {
if (err) {
res.send({ "msg": "Fail", "status": "already exsists", "url": url, "apikey": apikey, "err": err }).status(404)
} else {
res.send({ "msg": "Ok", "status": "200", "url": url, "apikey": apikey }).status(404)
}
});
} else {
res.json({ "msg": "Somethings Wrong" })
}
})
app.get('/api/peoples&:api', async (req, res) => {
await connect();
const apikey = req.params.api;
const exsist = await api.findOne({ apikey: apikey }).lean()
// gets an object contain
// console.log(exsist)
if (exsist != null) {
usersSchema.find().count((err, user) => {
if (err) console.log(err)
console.log(user)
providerSchema.find().count((err, provider) => {
if (err) console.log(err)
console.log(provider)
producerSchema.find().count((err, producer) => {
console.log(producer)
res.json({ users: user, provider: provider, producer: producer })
})
})
})
} else {
res.json({ msg: 'err' })
}
// await dis();
})
app.get('/api/appos&:api', async (req, res) => {
await connect();
const apikey = req.params.api;
const exsist = await api.findOne({ apikey: apikey }).lean()
// gets an object contain
// console.log(exsist)
if (exsist != null) {
apposchema.find({}, (err, docs) => {
res.json(docs)
})
} else {
res.json({ msg: 'err' })
}
// await dis();
})
//error custom
app.get("*", (req, res) => {
res.render('error')
})
app.listen(port, () => {
console.log("Started on port " + port)
});
module.exports = app