const express = require('express'); const mongoose = require('mongoose'); var rpguser_data = require('./models/rpguserlist'); var rpgcategory_data = require("./models/rpgcategorylist"); var rpgcategoryuser_data = require("./models/rpgcategoryuserlist"); const fetch = require('node-fetch'); var path = require('path'); var keys = require('./keysfile'); var multer = require('multer'); var fs = require('fs'); const { response } = require('express'); var ACCESS_TOKEN = 'pk.eyJ1IjoiZW5zby1pbW1lcnNpdmUiLCJhIjoiY2toMW01ODE4MTk0NzJxbnZyYzhsMHB1cyJ9.02d-FQX0o80XjwRPNQXzoA'; var client = require('twilio')(keys.twilio.accountSid, keys.twilio.authToken, { lazyLoading: true }); const app = express(); app.use(express.json()); const port = process.env.PORT || 8080; mongoose.Promise = global.Promise; mongoose.connect("mongodb://localhost:27017/rpgheritagewalk", { }); const isNullOrUndefined = (val) => val === null || val === undefined || val === '' || val.length===0; function randomString(length, chars) { var result = ''; for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))]; return result; }; app.get('/server', function (req, res) { res.send("Server work"); }); app.post("/addrpgcategory", async function (req, res) { var Category = req.body.Category; if (isNullOrUndefined(Category)) { res.status(409).send({ msg: "Empty Category Found" }); } else { await new rpgcategory_data({ Category: Category }).save(); res.status(200).send({ msg: "Category added successfully" }); } }); app.post("/addrpgcategoryuser", async function (req, res) { var Userid = req.body.Userid; var Categories = req.body.Categories; var MapId = req.body.MapId; var MapName = req.body.MapName; var Rating = req.body.Rating; var NoofPOIVisited = req.body.NoofPOIVisited; var TotalNoOfPOI = req.body.TotalNoOfPOI; var Language = req.body.Language; var result = await rpgcategoryuser_data.findOne({ Userid: Userid }); if (isNullOrUndefined(result)) { await new rpgcategoryuser_data({ Categories: Categories, MapId: MapId, Userid: Userid, MapName: MapName, Rating: Rating, NoofPOIVisited: NoofPOIVisited, TotalNoOfPOI: TotalNoOfPOI, Language: Language }).save(); res.status(200).send({ msg: "Data added successfully" }); } else { await rpgcategoryuser_data.updateOne({ $set: { Categories: Categories, MapId: MapId, MapName: MapName, Rating: Rating, NoofPOIVisited: NoofPOIVisited, TotalNoOfPOI: TotalNoOfPOI, Language: Language } }); res.status(200).send({ msg: "Data Updated successfully" }); } }); app.post('/getuserlocation', async function (req, res) { var latitude = req.body.latitude; var longitude = req.body.longitude; var url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + longitude + ', ' + latitude + '.json?access_token=' + ACCESS_TOKEN; await fetch(url).then((resp) => { return resp.json() }).then((resp) => { var geoData = resp.features[0].context; var region, city, postcode; for (i = 0; i < geoData.length; i++) { if (geoData[i].id.indexOf('region') >= 0) { region = geoData[i].text; } if (geoData[i].id.indexOf('place') >= 0) { city = geoData[i].text; } if (geoData[i].id.indexOf('postcode') >= 0) { postcode = geoData[i].text; } } if (isNullOrUndefined(region) && isNullOrUndefined(city)) { res.status(404).send({ geoData: "Map Detail Not found" }); } else { res.status(200).send({ geoData: { region, city, postcode } }); } }).catch((err) => { res.status(404).send({ geoData: "Map Detail Not found" }); }) }) app.post('/getrpguser', async function (req, res) { var Email = req.body.Email; var result = await rpguser_data.findOne({ Email: Email }); var categoryresult = await rpgcategoryuser_data.findOne({ Userid: Email }); if (isNullOrUndefined(result) && isNullOrUndefined(categoryresult)) { res.status(404).send({ msg: "user not found" }); } else { res.status(200).send({ msg: "user details found", data: { result, categoryresult } }); } }); app.get("/categorylist", async function (req, res) { var Category = await rpgcategory_data.find({}, { Category: 1 }); if (isNullOrUndefined(Category)) { res.status(404).send({ msg: "No Category Found" }); } else { res.status(200).send({ Category }); } }); app.post('/addrpguser', function (req, res) { var Userid = randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); var Firstname = req.body.Firstname; var Lastname = req.body.Lastname; var Email = req.body.Email; var BirthYear = req.body.BirthYear; var Gender = req.body.Gender; var DeviceId = req.body.DeviceId; var Username = Firstname + ' ' + Lastname; var Userrole = req.body.Userrole; var Password = req.body.Password; var ProfilePic = req.body.ProfilePic; var Language = req.body.Language; var MobileNo = req.body.MobileNo; var TotalPoints = ''; var StepsTaken = ''; rpguser_data.findOne({ Userid: Userid }).then((result) => { if (result) { Userid = randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); } else { rpguser_data.findOne({ Email: Email, MobileNo: MobileNo }).then((result) => { if (result) { res.send({ msg: "user already exists" }); } else { new rpguser_data({ Userid: Userid, Firstname: Firstname, Lastname: Lastname, Email: Email, BirthYear: BirthYear, Gender: Gender, DeviceId: DeviceId, Username: Username, Userrole: Userrole, Password: Password, ProfilePic: ProfilePic, Language: Language, MobileNo: MobileNo, TotalPoints: TotalPoints, StepsTaken: StepsTaken, DateofRegistration: new Date() }).save(); res.send({ msg: "user details added" }); } }); } }); }); app.post('/updaterpguserprofile', function (req, res) { var storage = multer.diskStorage({ destination: function (req, file, cb) { const storagepath = './public/images/profle'; fs.exists(storagepath, exist => { if (!exist) { fs.mkdir(storagepath, { recursive: true }, (err) => { if (err) { throw err; } else { return cb(null, storagepath) } }); } else { return cb(null, storagepath) } }) }, filename: function (req, file, cb) { cb(null, file.originalname); } }); var upload = multer({ storage: storage, fileFilter: (req, file, cb) => { if (file.mimetype == "image/png" || file.mimetype == "image/gif" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") { cb(null, true); } else { cb(null, false); return cb(new Error('Only .png, .gif, .jpg and .jpeg format allowed!')); } }, limits: { fieldSize: 50000000 } }).single('file'); upload(req, res, async function (err) { // check for error thrown by multer- file size etc if (err) { // An unknown error occurred when uploading. //console.log("Unknown error occured",err); res.send({ message: "Unknown error occured", err: err }); } else { // Everything went fine. // var Buffer = req.file; var file = req.body.file; if (isNullOrUndefined(file)) { res.send({ message: "file is not present" }); } else { var format = req.body.format; var filename = `${randomString(5, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')}.${format}`; var path = `public/images/profile/${filename}`; console.log(path); fs.writeFile(path, file, function (err) { if (err) throw err; console.log('Saved!'); }); if (!path) { //console.log('Please choose a file'); res.send({ message: "Please choose a file" }); } else { var Userid = req.body.Userid; var ProfilePic = ''; var newfilename = Userid + '-profilepic'; var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https'; var urlpath = securelink + '://' + req.get('host'); var filename = filename; var filenamepath = "public/images/profile/" + filename; var newfilenamepath = "public/images/UserProfile/" + newfilename + ".jpeg"; var fullnewfilenamepath = urlpath + "/images/UserProfile/" + newfilename + ".jpeg"; ProfilePic = fullnewfilenamepath; console.log(fullnewfilenamepath); fs.rename(filenamepath, newfilenamepath, function (err) { if (err) { console.log('ERROR: ' + err); } else { rpguser_data.findOneAndUpdate({ Userid: Userid }, { $set: { ProfilePic: ProfilePic } }).then((result) => { if (result) { res.send({ msg: "user profilepic updated", data: result }); } else { res.send({ msg: "user profilepic updation failed" }); } }); } }); } } } }); }); app.get('/appVersions',async function(req,res){ var appVersion = { android : "1.0.0", ios : "1.0.0" } res.status(200).send({appVersion}); }); app.listen(port, () => { console.log(`Server Running on port ${port} `) })