Files
amble_api/api.js
2025-07-15 15:54:43 +05:30

3295 lines
110 KiB
JavaScript

var express = require('express')
var router = express.Router()
var rpguser_data = require('../models/rpguserlist');
var rpgwalk_data = require('../models/rpgwalklist');
var rpgcategory_data = require("../models/rpgcategorylist");
var rpgcategoryuser_data = require("../models/rpgcategoryuserlist");
var rpgwalkcategory_data = require('../models/rpgwalkcategory');
var rpgusermaprating_data = require('../models/rpgusermaprating');
var rpguserapprating_data = require("../models/rpguserapprating");
var rpgratingquestion = require('../models/rpgratingquestion');
var rpgtoggle_data = require('../models/licensingmodel');
var base64 = require('file-base64');
var zipper = require("zip-local");
var rimraf = require("rimraf");
var ReadableData = require('stream').Readable
var fetch = require("node-fetch");
var path = require('path');
var keys = require('../keysfile');
var multer = require('multer');
var AWS = require('aws-sdk');
var FormData = require('form-data');
var fs = require('fs');
var client = require('twilio')(keys.twilio.accountSid, keys.twilio.authToken, { lazyLoading: true });
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;
};
router.get('/', function (req, res) {
res.render('layout', { layout: 'api' });
});
router.post('/addrpguser', async 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 Categories = ""
var Platform = req.body.Platform;
var LoginType = req.body.LoginType;
var client_id = req.body.client_id;
var client_secret = req.body.client_secret;
var Username = Firstname + ' ' + Lastname;
var Userrole = req.body.Userrole;
var Password = req.body.Password;
if (isNullOrUndefined(req.body.ProfilePic)) {
var ProfilePic = "https://amble.theheritageproject.in/images/UserProfile/avatardefault.png";
} else {
var ProfilePic = req.body.ProfilePic;
}
var Language = req.body.Language;
var MobileNo = req.body.MobileNo;
var TotalPoints = '';
var StepsTaken = '';
await rpguser_data.findOne({ Userid: Userid }).then(async (result) => {
if (result) {
Userid = randomString(10, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
}
else {
await rpguser_data.findOne({ Email: Email, MobileNo: MobileNo, DeviceID: DeviceID }).then(async (result) => {
if (result) {
res.status(404).send({ code: 404, msg: "user already exists" });
} else {
if (LoginType == "Apple") {
var formData = new FormData();
formData.append('client_id', client_id);
formData.append('client_secret', client_secret);
formData.append('grant_type', 'refresh_token');
await fetch('https://appleid.apple.com/auth/token', {
method: 'POST',
body: formData
}).then((resp) => {
return resp.json();
}).then((response) => {
console.log(response)
if (response.error) {
res.status(404).send({ code: 404, msg: response.error });
} else {
new rpguser_data({
Userid: Userid,
Firstname: Firstname,
Lastname: Lastname,
Categories: Categories,
Email: Email,
BirthYear: BirthYear,
Gender: Gender,
DeviceID: DeviceID,
Platform: Platform,
Username: Username,
Userrole: Userrole,
Password: Password,
ProfilePic: ProfilePic,
client_id: client_id,
client_secret: client_secret,
refresh_token: response.refresh_token,
Language: Language,
MobileNo: MobileNo,
TotalPoints: TotalPoints,
StepsTaken: StepsTaken,
DateofRegistration: new Date()
}).save(
function (err, result) {
if (err) {
res.status(404).send({ code: 404, msg: "user details not added" });
} else {
res.status(200).send({ code: 200, msg: "user details added", result });
}
});
}
})
} else {
await new rpguser_data({
Userid: Userid,
Firstname: Firstname,
Lastname: Lastname,
Categories: Categories,
Email: Email,
BirthYear: BirthYear,
Gender: Gender,
DeviceID: DeviceID,
Platform: Platform,
Username: Username,
Userrole: Userrole,
Password: Password,
ProfilePic: ProfilePic,
Language: Language,
MobileNo: MobileNo,
TotalPoints: TotalPoints,
StepsTaken: StepsTaken,
DateofRegistration: new Date()
}).save(
function (err, result) {
if (err) {
res.status(404).send({ code: 404, msg: "user details not added" });
} else {
res.status(200).send({ code: 200, msg: "user details added", result });
}
});
}
}
});
}
});
});
router.post('/rpguserlogin', function (req, res) {
var Email = req.body.Email;
var Password = req.body.Password;
rpguser_data.findOne({ Email: Email, Password: Password }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "user details found", data: result });
} else {
res.status(404).send({ code: 404, msg: "user not found" });
}
});
});
router.post('/sendsms', function (req, res) {
AWS.config.update({
region: process.env.REGION, accessKeyId: process.env.ASSESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY
});
var MobileNo = req.query.number;
var MobileOTP = randomString(6, '0123456789');
var OTPValidity = 2;
var params = {
Message: MobileOTP + ` is your One Time Password to login to Amble.
This OTP will be valid for ${OTPValidity} minutes.`,
PhoneNumber: '+' + MobileNo,
MessageAttributes: {
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': req.query.subject
},
'AWS.SNS.SMS.SMSType': {
'DataType': 'String',
'StringValue': 'Transactional'
},
'AWS.SNS.SMS.MaxPrice': {
'DataType': 'Number',
'StringValue': '0.1'
}
}
};
var publishTextPromise = new AWS.SNS({ apiVersion: '2010-03-31' }).publish(params).promise();
publishTextPromise.then(
function (data) {
res.end(JSON.stringify({ MessageID: data }));
}).catch(
function (err) {
res.end(JSON.stringify({ Error: err }));
});
})
router.get('/appVersions', function(req, res){
var appVersions = {
andriodVersion: '1.0.0',
iosVersion:'1.0.0'
res.status(200).json({data: appVersions, message: "Versions got successfully."})
}})
router.post('/rpgusergenerateopt', function (req, res) {
var MobileNo = req.body.MobileNo;
var MobileOTP = Math.floor(100000 + Math.random() * 900000) + ""
var OTPValidity = 2;
rpguser_data.findOne({ MobileNo: MobileNo }).then((result) => {
if (result) {
console.log("user otp generated");
var resnum1 = result.MobileNo;
var phonenumber;
var resnum = resnum1.substring(0, 3);
if (resnum !== '+91' && resnum1.length == 10) {
phonenumber = '+91'.concat(resnum1);
}
else if (resnum === '+91' && resnum1.length == 13) {
phonenumber = result.MobileNo;
}
AWS.config.update({
region: process.env.REGION, accessKeyId: process.env.ASSESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY
});
var params = {
Message: MobileOTP + ` is your One Time Password to login to Amble.
This OTP will be valid for ${OTPValidity} minutes.`,
PhoneNumber: phonenumber,
MessageAttributes: {
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': "Amble"
},
'AWS.SNS.SMS.SMSType': {
'DataType': 'String',
'StringValue': 'Transactional'
},
'AWS.SNS.SMS.MaxPrice': {
'DataType': 'Number',
'StringValue': '0.1'
}
}
};
var publishTextPromise = new AWS.SNS({ apiVersion: '2010-03-31' }).publish(params).promise();
publishTextPromise.then((message) => {
if (message) {
console.log(message);
}
else {
res.status(404).send({ code: 404, msg: "Failed" });
}
});
// var data = {};
// client.messages.create({
// body: 'Amble RPG Walk: '+ MobileOTP +' is your otp. This otp will be valid only for '+OTPValidity+' seconds.',
// from: '+13605487039',
// to: phonenumber,
// }).then((message) => {
// if(message){
// data = {
// message : message.body,
// from : message.from,
// to : message.to ,
// otp : MobileOTP
// };
// console.log(data);
// }
// else{
// res.status(404).send({code:404,msg:"OTP sending failed"});
// }
// }).done();
setTimeout(function () {
rpguser_data.findOneAndUpdate({ MobileNo: MobileNo }, { $set: { MobileOTP: null } }, { new: true }).then((result) => {
if (result) {
console.log({ code: 200, msg: "Success", data: result });
} else {
console.log({ code: 404, msg: "Failed" });
}
});
}, OTPValidity * 60 * 1000);
rpguser_data.findOneAndUpdate({ MobileNo: MobileNo }, { $set: { MobileOTP: MobileOTP } }, { new: true }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
});
} else {
var resnum1 = MobileNo;
var phonenumber;
var resnum = resnum1.substring(0, 3);
if (resnum !== '+91' && resnum1.length == 10) {
phonenumber = '+91'.concat(resnum1);
}
else if (resnum === '+91' && resnum1.length == 13) {
phonenumber = result.MobileNo;
}
AWS.config.update({
region: process.env.REGION, accessKeyId: process.env.ASSESS_KEY_ID,
secretAccessKey: process.env.SECRET_ACCESS_KEY
});
var params = {
Message: MobileOTP + ` is your One Time Password to login to Amble.
This OTP will be valid for ${OTPValidity} minutes.`,
PhoneNumber: phonenumber,
MessageAttributes: {
'AWS.SNS.SMS.SenderID': {
'DataType': 'String',
'StringValue': "Amble"
},
'AWS.SNS.SMS.SMSType': {
'DataType': 'String',
'StringValue': 'Transactional'
},
'AWS.SNS.SMS.MaxPrice': {
'DataType': 'Number',
'StringValue': '0.1'
}
}
};
var publishTextPromise = new AWS.SNS({ apiVersion: '2010-03-31' }).publish(params).promise();
publishTextPromise.then((message) => {
if (message) {
res.status(200).send({ code: 200, msg: "Success", otp: MobileOTP });
}
else {
res.status(404).send({ code: 404, msg: "Failed" });
}
});
}
});
});
router.post('/rpguserremoveopt', function (req, res) {
var MobileNo = req.body.MobileNo;
rpguser_data.findOneAndUpdate({ MobileNo: MobileNo }, { $set: { MobileOTP: null } }, { new: true }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
});
});
router.post('/rpguserotplogin', function (req, res) {
var MobileNo = req.body.MobileNo;
var MobileOTP = req.body.MobileOTP;
rpguser_data.findOne({ MobileNo: MobileNo, MobileOTP: MobileOTP }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
});
});
router.post('/deleterpguser', async function (req, res) {
var Email = req.body.Email;
var LoginType = req.body.LoginType;
if (LoginType == "Apple") {
await rpguser_data.findOne({ Email: Email }).then(async (result1) => {
if (result1) {
var formData = new FormData();
formData.append("client_id", result1.client_id);
formData.append("client_secret", result1.client_secret);
formData.append("grant_type", "client_credentials");
formData.append("token", result1.refresh_token);
await fetch("https://appleid.apple.com/auth/revoke", {
method: "POST",
body: formData
}).then(async (resp) => {
resp.json()
}).then(async (response) => {
if (response.status == 200) {
console.log("Apple ID Deleted");
await rpguser_data.findOneAndDelete({ Email: Email }).then(async (result) => {
console.log(result);
if (result) {
await rpgcategoryuser_data.findOneAndDelete({ Userid: result.Userid }).then((data) => {
if (data) {
console.log("success");
} else {
console.log("failed");
}
})
await rpgusermaprating_data.findOneAndDelete({ Userid: result.Userid }).then((data) => {
if (data) {
console.log("success");
} else {
console.log("failed");
}
})
await rpguserapprating_data.findOneAndDelete({ Userid: result.Userid }).then((data) => {
if (data) {
console.log("success");
} else {
console.log("failed");
}
})
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
} else {
await rpguser_data.findOneAndDelete({ Email: Email }).then(async (result) => {
console.log(result);
if (result) {
await rpgcategoryuser_data.findOneAndDelete({ Userid: result.Userid }).then((data) => {
if (data) {
console.log("success");
} else {
console.log("failed");
}
})
await rpgusermaprating_data.findOneAndDelete({ Userid: result.Userid }).then((data) => {
if (data) {
console.log("success");
} else {
console.log("failed");
}
})
await rpguserapprating_data.findOneAndDelete({ Userid: result.Userid }).then((data) => {
if (data) {
console.log("success");
} else {
console.log("failed");
}
})
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
}
})
router.post("/addrpgcategoryuser", async function (req, res) {
var UserID = req.body.UserID;
var Categories = req.body.Categories;
var separatedArray = new Array();
separatedArray = Categories.split(',')
Categories = [...new Set(separatedArray)]
if (isNullOrUndefined(UserID) && isNullOrUndefined(Categories)) {
res.status(404).send({ code: 404, msg: "Empty Category found" });
} else {
var result1 = await rpguser_data.findOne({ Userid: UserID });
if (isNullOrUndefined(result1) || result1.length == 0) {
res.status(404).send({ code: 404, msg: "No User Found" })
} else {
var result = await rpguser_data.findOneAndUpdate({ Userid: UserID }, { $set: { Categories: Categories } }, { new: true })
if (isNullOrUndefined(result) || result.length == 0) {
res.status(404).send({ code: 404, msg: "Failed" })
} else {
res.status(200).send({ code: 200, msg: "Sucess", result })
}
}
}
})
router.post("/addrpgcategory", async function (req, res) {
var Category = req.body.Category;
if (isNullOrUndefined(Category)) {
res.status(404).send({ code: 404, msg: "Empty Category Found" });
} else {
await new rpgcategory_data({ Category: Category }).save();
res.status(200).send({ code: 200, msg: "Category added successfully" });
}
});
router.post("/addfeedbackquestion", async function (req, res) {
var AppQuestions = req.body.AppQuestions;
var MapQuestions = req.body.MapQuestions;
await rpgratingquestion.findOneAndUpdate({ id: "1" }, { $set: { MapQuestions: MapQuestions, AppQuestions: AppQuestions } }, { new: true }).then(async (data) => {
if (!isNullOrUndefined(data)) {
res.status(200).send({ code: 200, msg: "Success" });
} else {
await new rpgratingquestion({
id: "1",
MapQuestions: MapQuestions,
AppQuestions: AppQuestions
}).save(function (err, data) {
if (err) {
res.status(404).send({ code: 404, msg: "Failed" });
} else {
res.status(200).send({ code: 200, msg: "Success" });
}
})
}
});
})
router.get("/getfeedbackquestion", async function (req, res) {
var result = await rpgratingquestion.find({});
if (isNullOrUndefined(result)) {
res.status(404).send({ code: 404, msg: "No Question Found" })
} else {
result = result[0];
res.status(200).send({ code: 200, result });
}
})
router.post("/addPostMyWalks", 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 Map_Thumbnail = req.body.Map_Thumbnail;
if (isNullOrUndefined(Map_Thumbnail)) {
const result = await rpgwalk_data.findOne({ Map_ID: MapId })
if (isNullOrUndefined(result)) {
Map_Thumbnail = Map_Thumbnail
} else {
Map_Thumbnail = result.Map_Thumbnail_URL
}
} else {
Map_Thumbnail = Map_Thumbnail
}
if (isNullOrUndefined(NoofPOIVisited)) {
NoofPOIVisited = "0"
} else {
NoofPOIVisited = NoofPOIVisited
}
if (isNullOrUndefined(Rating)) {
Rating = "0"
} else {
Rating = Rating
}
var TotalNoOfPOI = req.body.TotalNoOfPOI;
var Language = req.body.Language;
var POI_TimeTaken = req.body.POI_TimeTaken;
var result = await rpgcategoryuser_data.findOne({ Userid: Userid, MapId: MapId });
if (!result) {
await new rpgcategoryuser_data({ Categories: Categories, MapId: MapId, Userid: Userid, MapName: MapName, Rating: Rating, NoofPOIVisited: NoofPOIVisited, Map_Thumbnail: Map_Thumbnail, TotalNoOfPOI: TotalNoOfPOI, Language: Language, POI_TimeTaken: POI_TimeTaken }).save(function (err, result) {
res.status(200).send({ code: 200, msg: "Data added successfully", result });
});
}
else {
const result = await rpgcategoryuser_data.findOneAndUpdate({ Userid: Userid, MapId: MapId }, {
$set: {
Categories: Categories,
MapName: MapName,
Rating: Rating,
Map_Thumbnail: Map_Thumbnail,
NoofPOIVisited: NoofPOIVisited,
TotalNoOfPOI: TotalNoOfPOI,
Language: Language,
POI_TimeTaken: POI_TimeTaken
}
}, { new: true });
res.status(200).send({ code: 200, msg: "Data Updated successfully", result });
}
});
router.post("/getMyWalks", async function (req, res) {
var Userid = req.body.Userid;
var result = await rpgcategoryuser_data.find({ Userid: Userid });
if (result.length == 0 || isNullOrUndefined(result)) {
res.status(404).send({ code: 404, msg: "No Walk detail found" });
} else {
res.status(200).send({ code: 200, result });
}
})
router.post("/rpgusermapfeedback", async function (req, res) {
var UserID = req.body.UserID;
var Map_ID = req.body.Map_ID;
var MapQuestion_ID = req.body.MapQuestion_ID;
var Question = req.body.Question;
var Rating = req.body.Rating;
var Feedback_Map = req.body.Feedback_Map;
await rpgusermaprating_data.findOne({ UserID: UserID, Map_ID: Map_ID }).then((data) => {
if (!isNullOrUndefined(data)) {
var m = 0;
for (let i = 0; i < data.MapQuestions.length; i++) {
if (data.MapQuestions[i].MapQuestion_ID == MapQuestion_ID) {
m = i;
}
}
rpgusermaprating_data.findOneAndUpdate({ UserID: UserID, Map_ID: Map_ID, 'MapQuestions.MapQuestion_ID': MapQuestion_ID }, {
$set: {
['MapQuestions.' + m + '.Question']: Question,
['MapQuestions.' + m + '.Rating']: Rating,
['MapQuestions.' + m + '.Feedback_Map']: Feedback_Map
}
}, { new: true }).then((result) => {
if (!isNullOrUndefined(result)) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
rpgusermaprating_data.findOneAndUpdate({ UserID: UserID, Map_ID: Map_ID }, {
$push: {
MapQuestions: {
MapQuestion_ID: MapQuestion_ID,
Question: Question,
Rating: Rating,
Feedback_Map: Feedback_Map
}
}
}, { new: true }).then((result) => {
if (!isNullOrUndefined(result)) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
}
})
} else {
new rpgusermaprating_data({
UserID: UserID,
Map_ID: Map_ID,
MapQuestions: [{
MapQuestion_ID: MapQuestion_ID,
Question: Question,
Rating: Rating,
Feedback_Map: Feedback_Map
}]
}).save(function (err, result) {
if (!isNullOrUndefined(result)) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
}
})
});
router.post("/rpguserappfeedback", async function (req, res) {
var UserID = req.body.UserID;
var AppQuestion_ID = req.body.AppQuestion_ID;
var Question = req.body.Question;
var Rating = req.body.Rating;
var Feedback_App = req.body.Feedback_App;
await rpguserapprating_data.findOne({ UserID: UserID }).then((data) => {
if (!isNullOrUndefined(data)) {
var m = 0;
for (let i = 0; i < data.AppQuestions.length; i++) {
if (data.AppQuestions[i].AppQuestion_ID == AppQuestion_ID) {
m = i;
}
}
rpguserapprating_data.findOneAndUpdate({ UserID: UserID, 'AppQuestions.AppQuestion_ID': AppQuestion_ID }, {
$set: {
['AppQuestions.' + m + '.Question']: Question,
['AppQuestions.' + m + '.Rating']: Rating,
['AppQuestions.' + m + '.Feedback_App']: Feedback_App
}
}, { new: true }).then((result) => {
if (!isNullOrUndefined(result)) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
rpguserapprating_data.findOneAndUpdate({ UserID: UserID }, {
$push: {
AppQuestions: {
AppQuestion_ID: AppQuestion_ID,
Question: Question,
Rating: Rating,
Feedback_App: Feedback_App
}
}
}, { new: true }).then((result) => {
if (!isNullOrUndefined(result)) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
}
})
} else {
new rpguserapprating_data({
UserID: UserID,
AppQuestions: [{
AppQuestion_ID: AppQuestion_ID,
Question: Question,
Rating: Rating,
Feedback_App: Feedback_App
}]
}).save(function (err, result) {
if (!isNullOrUndefined(result)) {
res.status(200).send({ code: 200, msg: "Success", result });
} else {
res.status(404).send({ code: 404, msg: "Failed" });
}
})
}
})
});
router.post("/getrpguserfeedback", async function (req, res) {
var UserID = req.body.UserID;
var Map_ID = req.body.Map_ID;
var Feedback_Question = await rpgratingquestion.find({});
var map_result = await rpgusermaprating_data.find({ UserID: UserID, Map_ID: Map_ID })
var App_result = await rpguserapprating_data.find({ UserID: UserID });
if (isNullOrUndefined(map_result) || isNullOrUndefined(App_result) || isNullOrUndefined(Feedback_Question)) {
res.status(404).send({ code: 404, msg: "No Feedback Detail found" });
} else {
Feedback_Question = Feedback_Question[0]
map_result = map_result[0];
App_result = App_result[0];
res.status(200).send({ code: 200, Feedback_Question, map_result, App_result });
}
})
router.post("/addiosperiscopearscene", async function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = './public/AssetBundle/';
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,
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.status(404).send({ message: "Unknown error occured", err: err });
}
else {
// Everything went fine.
var file = req.file
if (!file) {
//console.log('Please choose a file');
res.status(404).send({ message: "Please choose a file" });
} else {
var Map_ID = req.body.MapId;
var PeriscopeARScene_IOS_URL = "";
var newfilename = Map_ID + 'PeriscopeARScene_IOS';
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var filename = file.filename;
var filenamepath = "public/AssetBundle/" + filename;
var newfilenamepath = "public/AssetBundle/" + newfilename;
var fullnewfilenamepath = urlpath + "/AssetBundle/" + newfilename;
PeriscopeARScene_IOS_URL = fullnewfilenamepath;
console.log(fullnewfilenamepath);
fs.rename(filenamepath, newfilenamepath, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
const query = { Map_ID: Map_ID };
const updateDocument = {
$set: { PeriscopeARScene_IOS_URL: PeriscopeARScene_IOS_URL }
};
rpgwalk_data.findOneAndUpdate(query, updateDocument, { new: true }).then(async (result) => {
if (result) {
res.status(200).send({ msg: "PeriscopeARSceneIOS updated", data: result });
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
}
})
})
router.post("/addperiscopearscene", async function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = './public/AssetBundle/';
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,
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.status(404).send({ message: "Unknown error occured", err: err });
}
else {
// Everything went fine.
var file = req.file
if (!file) {
//console.log('Please choose a file');
res.status(404).send({ message: "Please choose a file" });
} else {
var Map_ID = req.body.MapId;
var PeriscopeARScene_URL = "";
var PeriscopeARScene_Name = req.body.PeriscopeARScene_Name;
var newfilename = Map_ID + 'PeriscopeARScene';
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var filename = file.filename;
var filenamepath = "public/AssetBundle/" + filename;
var newfilenamepath = "public/AssetBundle/" + newfilename;
var fullnewfilenamepath = urlpath + "/AssetBundle/" + newfilename;
PeriscopeARScene_URL = fullnewfilenamepath;
console.log(fullnewfilenamepath);
fs.rename(filenamepath, newfilenamepath, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
const query = { Map_ID: Map_ID };
const updateDocument = {
$set: { PeriscopeARScene_URL: PeriscopeARScene_URL, PeriscopeARScene_Name: PeriscopeARScene_Name }
};
rpgwalk_data.findOneAndUpdate(query, updateDocument, { new: true }).then(async (result) => {
if (result) {
res.status(200).send({ msg: "PeriscopeARScene updated", data: result });
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
}
})
})
router.post("/addmapzipurl", async function (req, res) {
var Map_ID = req.body.Map_ID;
var Map_Zip_Url = req.body.Map_Zip_Url
await rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, { $set: { Map_Zip_Url: Map_Zip_Url } }, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "Map Detail updated", result })
} else {
res.status(404).send({ msg: "No Map detail found" })
}
})
})
router.post("/addassetbundle", async function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = './public/AssetBundle/';
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,
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.status(404).send({ message: "Unknown error occured", err: err });
}
else {
// Everything went fine.
var file = req.file
if (!file) {
//console.log('Please choose a file');
res.status(404).send({ message: "Please choose a file" });
} else {
var Map_ID = req.body.MapId;
var Arscene = "";
var ArPoi = req.body.ArPoi;
var AssetBundle_Name = req.body.AssetBundle_Name;
var newfilename = Map_ID + 'Arscene';
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var filename = file.filename;
var filenamepath = "public/AssetBundle/" + filename;
var newfilenamepath = "public/AssetBundle/" + newfilename;
var fullnewfilenamepath = urlpath + "/AssetBundle/" + newfilename;
Arscene = fullnewfilenamepath;
console.log(fullnewfilenamepath);
fs.rename(filenamepath, newfilenamepath, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
const query = { Map_ID: Map_ID };
const updateDocument = {
$set: { ArScene_AB_Url: Arscene, ArPoi: ArPoi, AssetBundle_Name: AssetBundle_Name }
};
rpgwalk_data.findOneAndUpdate(query, updateDocument, { new: true }).then(async (result) => {
if (result) {
res.status(200).send({ msg: "Arscene updated", data: result });
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
}
})
})
router.post("/addiosassetbundle", async function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = './public/AssetBundle/';
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,
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.status(404).send({ message: "Unknown error occured", err: err });
}
else {
// Everything went fine.
var file = req.file
if (!file) {
//console.log('Please choose a file');
res.status(404).send({ message: "Please choose a file" });
} else {
var Map_ID = req.body.MapId;
var ArScene_AB_IOS_Url = "";
var newfilename = Map_ID + 'ArScene_AB_IOS';
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var filename = file.filename;
var filenamepath = "public/AssetBundle/" + filename;
var newfilenamepath = "public/AssetBundle/" + newfilename;
var fullnewfilenamepath = urlpath + "/AssetBundle/" + newfilename;
ArScene_AB_IOS_Url = fullnewfilenamepath;
console.log(fullnewfilenamepath);
fs.rename(filenamepath, newfilenamepath, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
const query = { Map_ID: Map_ID };
const updateDocument = {
$set: { ArScene_AB_IOS_Url: ArScene_AB_IOS_Url }
};
rpgwalk_data.findOneAndUpdate(query, updateDocument, { new: true }).then(async (result) => {
if (result) {
res.status(200).send({ msg: "Arscene updated", data: result });
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
}
})
})
router.post('/getuserlocation', function (req, res) {
var latitude = req.body.latitude;
var longitude = req.body.longitude;
var ACCESS_TOKEN = "pk.eyJ1IjoiZW5zby1pbW1lcnNpdmUiLCJhIjoiY2toMW01ODE4MTk0NzJxbnZyYzhsMHB1cyJ9.02d-FQX0o80XjwRPNQXzoA"
var url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'
+ longitude + ', ' + latitude
+ '.json?access_token=' + ACCESS_TOKEN;
async function ResponseData() {
const resp = await fetch(url);
const response = await resp.json();
return response
}
ResponseData().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(postcode)) {
postcode = "000000";
} else {
postcode = postcode;
}
}
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).json({ err: err.toString() });
})
})
router.post('/getrpguser', async function (req, res) {
var Email = req.body.Email;
const result = await rpguser_data.findOne({ Email: Email });
if (result) {
var result1 = result.Userid
}
else {
var result1 = ""
}
// const Categories = await rpgcategoryuser_data.findOne({Userid:result1});
if (result) {
res.status(200).send({ code: 200, msg: "user details found", result, HyperLink: "Just completed a Heritage Walk in Mumbai, give it a try!", PlayStoreLink: "https://www.maharashtratourism.gov.in/" });
}
else {
res.status(404).send({ code: 404, msg: "user not found", Email });
}
});
router.get("/categorylist", async function (req, res) {
var Category = await rpgcategory_data.find();
if (isNullOrUndefined(Category)) {
res.status(404).send({ code: 404, msg: "No Category Found" });
} else {
var code = `code: ${200}`
res.status(200).send(Category[0]);
}
});
router.post('/updaterpguser', function (req, res) {
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 Username = Firstname + ' ' + Lastname;
var Userrole = req.body.Userrole;
var Password = req.body.Password;
var Language = req.body.Language;
var MobileNo = req.body.MobileNo;
if (Email == "dev.g@immative.com") {
rpguser_data.findOneAndUpdate({ Email: Email }, {
$set: {
Firstname: Firstname,
Lastname: Lastname,
BirthYear: BirthYear,
Gender: Gender,
Username: Username,
Userrole: "Admin",
Password: "admin12345",
Language: Language,
MobileNo: MobileNo
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "user details updated", result: result });
} else {
res.status(404).send({ code: 404, msg: "user not found" });
}
});
} else {
rpguser_data.findOneAndUpdate({ Email: Email }, {
$set: {
Firstname: Firstname,
Lastname: Lastname,
BirthYear: BirthYear,
Gender: Gender,
Username: Username,
Userrole: Userrole,
Password: Password,
Language: Language,
MobileNo: MobileNo
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "user details updated", result: result });
} else {
res.status(404).send({ code: 404, msg: "user not found" });
}
});
}
});
router.post('/updatelicensingtoggledata', function (req, res) {
var toggleid = req.body.toggleid;
var togglename = req.body.togglename;
var togglestatus = req.body.togglestatus;
rpgtoggle_data.findOneAndUpdate({ toggleid: toggleid, togglename: togglename }, { $set: { togglestatus: togglestatus } }).then((result) => {
if (result) {
res.status(200).send({ message: "toggle status updated" });
}
else {
new rpgtoggle_data({
toggleid: toggleid,
togglename: togglename,
togglestatus: togglestatus
}).save();
res.status(200).send({ message: "toggle status update failed but new added" });
}
});
});
router.post('/getlicensingtoggledata', function (req, res) {
var toggleid = req.body.toggleid;
var togglename = req.body.togglename;
rpgtoggle_data.findOne({ toggleid: toggleid, togglename: togglename }).then((result) => {
if (result) {
console.log(result.togglestatus);
res.status(200).send("" + result.togglestatus);
}
else {
res.status(404).send({ code: 404, message: "toggle status not found" });
}
});
});
router.post('/btffileupload', function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = './public/anchor/';
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, limits: { fieldSize: 50000000000 } }).array('filey', 50);
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 mapname = req.body.mapname;
if (isNullOrUndefined(req.body.worldmap)) {
res.send({ message: "file is not present" });
} else {
// Buffer.from(json, 'base64').toString('ascii')
const data = new Uint8Array(Buffer.from(req.body.worldmap));
fs.writeFile(`./public/anchor/${mapname}`, data, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
// const destination = `./public/anchor/BTF.zip`;
// zlib.gzip(data, (err, response) => {
// if (err) {
// console.log(err);
// }
// fs.writeFile(destination, response, (err, data) => {
// if (err) {
// console.log(err);
// }
// })
// })
// var format1 = "worldmap"
// var filename1 = `${'Latest17_my_session'}.${format1}`;
// fs.writeFile(`./public/anchor/${filename1}`, worldmap, function(err) {
// if(err) {
// return console.log(err);
// }
// console.log("The file was saved!");
// });
if (!mapname) {
//console.log('Please choose a file');
res.send({ message: "Please choose a file" });
} else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
// var filename2 = file[1].filename;
var fullnewfilenamepath1 = urlpath + `/anchor/${mapname}`;
// var fullnewfilenamepath2 = urlpath + "/anchor/"+filename1;
// filename2:fullnewfilenamepath2
res.send({ msg: "uploded", filename1: fullnewfilenamepath1 });
}
}
}
})
})
router.post('/updaterpguserprofile', async function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = './public/images/UserProfile/';
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, limits: {fieldSize: 50000000}}).single('myFiles');
var upload = multer({ storage: storage, limits: { fieldSize: 50000000 } }).array('filey', 50);
upload(req, res, async function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
//console.log("Something went wrong");
res.status(404).send({ code: 404, message: "Something went wrong" });
}
else if (err) {
// An unknown error occurred when uploading.
//console.log("Unknown error occured",err);
res.status(404).send({ code: 404, message: "Unknown error occured", err: err });
}
else {
var file = req.body.file;
if (isNullOrUndefined(file)) {
res.status(404).send({ code: 404, message: "file is not present" });
} else {
var format = "png"
var filename = `${randomString(5, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')}.${format}`;
const imageBufferData = Buffer.from(file, 'base64')
var streamObj = new ReadableData()
streamObj.push(imageBufferData)
streamObj.push(null)
streamObj.pipe(fs.createWriteStream(filename));
if (!filename) {
//console.log('Please choose a file');
res.status(404).send({ code: 404, 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' : 'http';
var urlpath = securelink + '://' + req.get('host');
var filename = filename;
var filenamepath = filename;
var newfilenamepath = "public/images/UserProfile/" + newfilename + ".png";
var fullnewfilenamepath = urlpath + "/images/UserProfile/" + newfilename + ".png";
ProfilePic = fullnewfilenamepath;
console.log(fullnewfilenamepath);
await fs.rename(filenamepath, newfilenamepath, async function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
await rpguser_data.findOneAndUpdate({ Userid: Userid }, {
$set: {
ProfilePic: ProfilePic
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "user profilepic updated", result: result });
}
else {
res.status(404).send({ code: 404, msg: "user profilepic updation failed" });
}
});
}
})
}
}
}
})
});
router.post('/updaterpguserprofilepic', function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = './public/Walks/';
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('rpguserprofilepic');
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 file = req.file;
if (!file) {
//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 = file.filename;
var filenamepath = "public/Walks/" + filename;
var newfilenamepath = "public/Walks/ProfilePictures/" + newfilename + ".jpeg";
var fullnewfilenamepath = urlpath + "/Walks/ProfilePictures/" + newfilename + ".jpeg";
ProfilePic = fullnewfilenamepath;
console.log(fullnewfilenamepath);
fs.rename(filenamepath, newfilenamepath, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
rpgwalk_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" });
}
});
}
});
}
}
});
});
router.post('/rpgappratingandfeedback', function (req, res) {
var Email = req.body.Email;
var AppFeedback = req.body.AppFeedback;
var AppRating = req.body.AppRating;
rpguser_data.findOneAndUpdate({ Email: Email }, {
$set: {
AppFeedback: AppFeedback,
AppRating: AppRating
}
}).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "app rated by user", data: result });
} else {
res.status(404).send({ code: 404, msg: "app rating failed" });
}
});
});
router.post('/updaterpguserdeviceid', function (req, res) {
var Email = req.body.Email;
var DeviceID = req.body.DeviceID;
var Platform = req.body.Platform
rpguser_data.findOneAndUpdate({ Email: Email }, {
$set: {
DeviceID: DeviceID, Platform: Platform
}
}).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "deviceid and Platform for user updated", data: result });
} else {
res.status(404).send({ code: 404, msg: "deviceid and Platform updation failed" });
}
});
});
router.post('/getuseremail', function (req, res) {
var DeviceID = req.body.DeviceID;
rpguser_data.findOne({ DeviceID: DeviceID }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "User found", Email: result.Email })
} else {
res.status(404).send({ code: 404, msg: "No User found" })
}
});
});
router.post('/findrpguserdeviceid', function (req, res) {
var Email = req.body.Email;
var DeviceID = req.body.DeviceID;
rpguser_data.findOne({ Email: Email }).then((result) => {
if (result) {
rpguser_data.findOne({ Email: Email, DeviceID: DeviceID }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "deviceid for user exists" });
}
else {
res.status(404).send({ code: 404, msg: "no deviceid for user found" });
}
});
}
else {
res.status(404).send({ code: 404, msg: "user not found" });
}
});
});
router.post('/updaterpguserpoints', function (req, res) {
var Email = req.body.Email;
var TotalPoints = req.body.TotalPoints;
rpguser_data.findOneAndUpdate({ Email: Email }, {
$set: {
TotalPoints: TotalPoints
}
}).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "points for user added/updated", data: result });
} else {
res.status(404).send({ code: 404, msg: "points addition/updation failed" });
}
});
});
router.post('/updaterpgusersteps', function (req, res) {
var Email = req.body.Email;
var StepsTaken = req.body.StepsTaken;
rpguser_data.findOneAndUpdate({ Email: Email }, {
$set: {
StepsTaken: StepsTaken
}
}).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "steps for user added/updated", data: result });
} else {
res.status(404).send({ code: 404, msg: "steps addition/updation failed" });
} r
});
});
router.post('/rpgaddupdateuserwalkdetails', function (req, res) {
var Userid = req.body.Userid;
var Map_ID = req.body.Map_ID;
var Map_Feedback = req.body.Map_Feedback;
var Map_StartTime = req.body.Map_StartTime;
var Map_Endtime = req.body.Map_Endtime;
var Map_Status = req.body.Map_Status;
var Map_Rating = req.body.Map_Rating;
rpguser_data.findOneAndUpdate({ Userid: Userid, "WalkDetails.Map_ID": Map_ID }, {
$set: {
Map_Feedback: Map_Feedback,
Map_StartTime: Map_StartTime,
Map_Endtime: Map_Endtime,
Map_Status: Map_Status,
Map_Rating: Map_Rating
}
}).then((result) => {
if (result) {
res.status(200).send({ msg: "walk details for user updated", data: result });
} else {
var WalkDetails = {
Map_ID: Map_ID,
Map_Feedback: Map_Feedback,
Map_StartTime: Map_StartTime,
Map_Endtime: Map_Endtime,
Map_Status: Map_Status,
Map_Rating: Map_Rating,
POI_Data: []
}
rpguser_data.findOneAndUpdate({ Userid: Userid }, { $push: { WalkDetails: WalkDetails } }).then((result) => {
if (result) {
res.status(200).send({ msg: "walk details for user updated", data: result });
} else {
res.status(200).send({ msg: "walk details for user updated", data: result });
}
});
}
});
});
router.get('/rpggetwalkrating', async function (req, res) {
const result = await rpgusermaprating_data.find({});
if (result.length == 0 || isNullOrUndefined(result)) {
res.status(404).send({ code: 404, avg: "5" })
} else {
var avg;
var sum1 = 0;
for (let i = 0; i < result.length; i++) {
var sum = 0;
for (let j = 0; j < result[i].MapQuestions.length; j++) {
sum += Number(result[i].MapQuestions[j].Rating)
}
if (sum < 9) {
sum = 13
} else {
sum = sum
}
sum1 += Number(sum / result[i].MapQuestions.length)
}
avg = Number(sum1 / result.length)
res.status(200).send({ code: 200, avg: avg.toFixed(1) })
}
})
router.get('/rpggetmaprating', async function (req, res) {
var result = await rpgusermaprating_data.find({});
if (result.length == 0 || isNullOrUndefined(result)) {
res.status(404).send({ code: 404, avg: "Not Updating" })
} else {
var Map_ID;
for (let z = 0; z < result.length; z++) {
Map_ID = result[z].Map_ID
var data = await rpgusermaprating_data.find({ Map_ID: Map_ID });
var avg;
var sum1 = 0;
for (i = 0; i < data.length; i++) {
var sum = 0
for (let j = 0; j < data[i].MapQuestions.length; j++) {
sum += Number(data[i].MapQuestions[j].Rating)
}
if (sum <= 9) {
sum = 13
} else {
sum = sum
}
sum1 += Number(sum / data[i].MapQuestions.length)
}
avg = Number(sum1 / data.length)
await rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, { $set: { Map_Ratting: avg.toFixed(1) } }, { new: true }).then((result) => {
if (result) {
var initfilename = `/Database/MapPoiContent/${Map_ID}/MapDetails/0.txt`;
var initfilepath = './public' + initfilename;
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
console.log("map info file updation failed");
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
var ZipFileurl = urlpath + "/Database.zip"
zipper.sync.zip(`./public/Database/MapPoiContent/${Map_ID}`).compress().save(`./public/Database/MapPoiContent/${Map_ID}.zip`);
console.log("map details updated");
}
});
} else {
console.log("Map detail not found")
}
})
}
res.status(200).send({ code: 200, msg: "Rating Updated" })
}
})
router.get('/rpggetapprating', async function (req, res) {
const result = await rpguserapprating_data.find({});
if (isNullOrUndefined(result) || result.length == 0) {
res.send({ avg: "5" })
} else {
var avg;
var sum1 = 0;
for (let i = 0; i < result.length; i++) {
var sum = 0
for (let j = 0; j < result[i].AppQuestions.length; j++) {
sum += Number(result[i].AppQuestions[j].Rating)
}
if (sum < 9) {
sum = 13
} else {
sum = sum
}
sum1 += Number(sum / result[i].AppQuestions.length)
}
avg = Number(sum1 / result.length)
res.status(200).send({ avg: avg.toFixed(1) })
}
})
router.post('/rpggetwalkratingdetails', function (req, res) {
var Map_ID = req.body.Map_ID;
rpguser_data.find({ Map_ID: Map_ID }).then((results) => {
if (results) {
var sum;
for (var i = 0, len = results.length; i < len; i++) {
sum += parseInt(results[i].Map_Rating, 10); //don't forget to add the base
}
var avg = sum / results.length;
rpgwalk_data.findOneAndUpdate({ Userid: Userid }, { $push: { Map_Rating: avg } }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "walk ratings updated", data: result });
} else {
res.status(404).send({ code: 404, msg: "walk ratings updation failed" });
}
});
}
else {
res.status(404).send({ code: 404, msg: "no user details found" });
}
});
});
router.post('/rpgaddupdateuserpoidetails', function (req, res) {
var Userid = req.body.Userid;
var Map_ID = req.body.Map_ID;
var POI_ID = req.body.POI_ID;
var AmbleFeedback = req.body.AmbleFeedback;
var AmbleStartTime = req.body.AmbleStartTime;
var AmbleEndtime = req.body.AmbleEndtime;
var AmbleStatus = req.body.AmbleStatus;
var AmbleRating = req.body.AmbleRating;
rpguser_data.findOneAndUpdate({ Userid: Userid, "WalkDetails.Map_ID": Map_ID, "WalkDetails.POI_Data.POI_ID": POI_ID }, {
$set: {
AmbleFeedback: AmbleFeedback,
AmbleStartTime: AmbleStartTime,
AmbleEndtime: AmbleEndtime,
AmbleStatus: AmbleStatus,
AmbleRating: AmbleRating
}
}).then((result) => {
if (result) {
res.status(200).send({ msg: "walk details for user updated", data: result });
} else {
var POI_Data = {
Map_ID: Map_ID,
Map_Feedback: Map_Feedback,
Map_StartTime: Map_StartTime,
Map_Endtime: Map_Endtime,
Map_Status: Map_Status,
Map_Rating: Map_Rating,
POI_Data: []
}
rpguser_data.findOneAndUpdate({ Userid: Userid }, { $push: { POI_Data: POI_Data } }).then((result) => {
if (result) {
res.status(200).send({ msg: "walk details for user updated", data: result });
} else {
res.status(200).send({ msg: "walk details for user updated", data: result });
}
});
}
});
});
router.post('/rpgaddMapversion', async function (req, res) {
var Map_ID = req.body.Map_ID;
var Map_Version = req.body.Map_Version;
await rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, { $set: { Map_Version: Map_Version } }, { new: true }).then((result) => {
if (result) {
res.status(200).send({ result })
} else {
res.status(404).send({ msg: "no Detail updated" })
}
})
})
router.post('/rpgaddupdatewalkdetails', (req, res) => {
var Map_ID = req.query.mapid;
console.log(Map_ID)
var folder = `./public/Database/MapPoiContent/${Map_ID}`;
var subfolder1 = `./public/Database/MapPoiContent/${Map_ID}/Image`;
var subfolder = `./public/Database/MapPoiContent/${Map_ID}/MapDetails`;
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
if (!fs.existsSync(subfolder)) {
fs.mkdirSync(subfolder)
}
if (!fs.existsSync(subfolder1)) {
fs.mkdirSync(subfolder1)
}
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = `./public/Database/MapPoiContent/${Map_ID}/Image/`
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 }
}).fields(
[
{
name: 'mapthumbnail',
maxCount: 1
}
]
);
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.status(404).send({ message: "Unknown error occured", err: err });
}
else {
// Everything went fine.
var files = req.files;
console.log(files)
if (!files) {
//console.log('Please choose a file');
res.status(404).send({ message: "Please choose a file" });
} else {
//var Map_ID = randomString(10,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
if (files.mapthumbnail !== undefined) {
var Map_ID = req.body.mapid;
var Map_Version = 0;
var Map_Name = req.body.mapname;
var Map_Description = req.body.mapdescription;
var Map_Thumbnail_URL = '';
var Map_Category = req.body.mapcategory;
var Total_POI = req.body.totalpoi;
var Map_Startlongitude = req.body.startlongitude;
var Map_Startlatitude = req.body.startlatitude;
var newfilename = "0";
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'http';
var urlpath = securelink + '://' + req.get('host');
var filename = files.mapthumbnail[0].filename;
var filenamepath = `public/Database/MapPoiContent/${Map_ID}/Image/` + filename;
var newfilenamepath = `public/Database/MapPoiContent/${Map_ID}/Image/` + newfilename + ".png";
var fullnewfilenamepath = urlpath + `/Database/MapPoiContent/${Map_ID}/Image/` + newfilename + ".png";
var Map_Zip_Url = urlpath + `/Database/MapPoiContent/${Map_ID}.zip`;
var Total_Trivia = req.body.Total_Trivia;
// var image = await sharp(req.file.buffer).resize({ width: 400, height:400 })// Resize if you want
// .jpeg({
// quality: 40,
// }).toFile("public/Walks/" + newfilename + "_Pavan.jpeg")
// .catch( err => { console.log('error: ', err) })
Map_Thumbnail_URL = fullnewfilenamepath;
console.log(fullnewfilenamepath);
await rpgwalk_data.find({}).then((result) => {
if (isNullOrUndefined(result) || result.length == 0) {
Map_Version = Map_Version
} else {
Map_Version = Number(result[0].Map_Version) + 1
rpgwalk_data.updateMany({}, { $set: { Map_Version: Map_Version } }).then((resu) => {
console.log(resu)
})
}
})
fs.rename(filenamepath, newfilenamepath, async function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, {
$set: {
Map_Name: Map_Name,
Map_Description: Map_Description,
Map_Thumbnail_URL: Map_Thumbnail_URL,
Map_Category: Map_Category,
Total_POI: Total_POI,
Map_Startlongitude: Map_Startlongitude,
Map_Startlatitude: Map_Startlatitude,
Map_Zip_Url: Map_Zip_Url,
Total_Trivia: Total_Trivia
}
}, { new: true }).then(async (result) => {
if (result) {
var initfilename = `/Database/MapPoiContent/${Map_ID}/MapDetails/0.txt`;
var initfilepath = './public' + initfilename;
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ msg: "map info file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
var ZipFileurl = urlpath + "/Database.zip"
zipper.sync.zip(`./public/Database/MapPoiContent/${Map_ID}`).compress().save(`./public/Database/MapPoiContent/${Map_ID}.zip`);
res.status(200).send({ msg: "map details updated", data: result });
}
});
}
else {
console.log(Map_Version)
new rpgwalk_data({
Map_ID: Map_ID,
Map_Name: Map_Name,
Trivia_List: [],
Map_Description: Map_Description,
Map_Thumbnail_URL: Map_Thumbnail_URL,
Map_Status: 'UnPublished',
Map_Type: 'test',
Map_Category: Map_Category,
Total_POI: Total_POI,
Map_Version: Map_Version,
Map_Startlongitude: Map_Startlongitude,
Map_Startlatitude: Map_Startlatitude,
Map_Polycoords: [],
POI_Data: [],
Map_Zip_Url: Map_Zip_Url,
Total_Trivia: Total_Trivia,
Map_Ratting: 0.0,
DateofRegistration: new Date()
}).save(function (err, result) {
var initfilename = `/Database/MapPoiContent/${Map_ID}/MapDetails/0.txt`;
var initfilepath = './public' + initfilename;
if (result) {
console.log(result)
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ msg: "map info file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
var ZipFileurl = urlpath + "/Database.zip"
zipper.sync.zip(`./public/Database/MapPoiContent/${Map_ID}`).compress().save(`./public/Database/MapPoiContent/${Map_ID}.zip`);
res.status(200).send({ msg: "new map details added" });
}
});
} else {
res.status(404).send({ msg: "all map info not found" });
}
})
}
});
}
});
} else {
console.log("else ")
var Map_ID = req.body.mapid;
var Map_Name = req.body.mapname;
var Map_Description = req.body.mapdescription;
var Map_Thumbnail_URL = '';
var Map_Category = req.body.mapcategory;
var Total_POI = req.body.totalpoi;
var Map_Startlongitude = req.body.startlongitude;
var Map_Startlatitude = req.body.startlatitude;
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var Map_Zip_Url = urlpath + `/Database/MapPoiContent/${Map_ID}.zip`;
var Total_Trivia = req.body.Total_Trivia;
console.log(Total_Trivia)
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
Map_Thumbnail_URL = result.Map_Thumbnail_URL
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, {
$set: {
Map_Name: Map_Name,
Map_Description: Map_Description,
Map_Thumbnail_URL: Map_Thumbnail_URL,
Map_Category: Map_Category,
Total_POI: Total_POI,
Map_Startlongitude: Map_Startlongitude,
Map_Startlatitude: Map_Startlatitude,
Map_Zip_Url: Map_Zip_Url,
Total_Trivia: Total_Trivia
}
}, { new: true }).then((result) => {
if (result) {
var initfilename = `/Database/MapPoiContent/${Map_ID}/MapDetails/0.txt`;
var initfilepath = './public' + initfilename;
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ msg: "map info file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
var ZipFileurl = urlpath + "/Database.zip"
zipper.sync.zip(`./public/Database/MapPoiContent/${Map_ID}`).compress().save(`./public/Database/MapPoiContent/${Map_ID}.zip`);
res.status(200).send({ msg: "map details updated", data: result });
}
});
} else {
res.status(404).send({ msg: "map detail not found" })
}
});
}
});
}
}
}
});
});
router.post("/rpgaddtotalwalkdistance", async function (req, res) {
var Map_ID = req.body.Map_ID;
var TotalWalkDistance = req.body.TotalWalkDistance;
await rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, { $set: { TotalWalkDistance: TotalWalkDistance } }, { new: true }).then((result) => {
if (result) {
var initfilename = `/Database/MapPoiContent/${Map_ID}/MapDetails/0.txt`;
var initfilepath = './public' + initfilename;
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ msg: "map info file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
var ZipFileurl = urlpath + "/Database.zip"
zipper.sync.zip(`./public/Database/MapPoiContent/${Map_ID}`).compress().save(`./public/Database/MapPoiContent/${Map_ID}.zip`);
res.status(200).send({ msg: "Sucess", result })
}
});
} else {
res.status(404).send({ msg: "No walk detail found" })
}
})
})
router.post('/rpgaddupdatewalkpolydetails', (req, res) => {
var Map_ID = req.body.Map_ID;
var Map_Polycoords = req.body.Map_Polycoords;
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, { $set: { Map_Polycoords: Map_Polycoords } }).then((result) => {
if (result) {
var initfilename = `/Database/MapPoiContent/${Map_ID}/MapDetails/0.txt`;
var initfilepath = './public' + initfilename;
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ msg: "map info file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
zipper.sync.zip(`./public/Database/MapPoiContent/${Map_ID}`).compress().save(`./public/Database/MapPoiContent/${Map_ID}.zip`);
res.status(200).send({ msg: "map polgon details updated", data: result });
}
});
} else {
res.status(404).send({ msg: "map polygon details updation failed" });
}
});
});
router.post('/rpgaddupdatewalkpoidetails', (req, res) => {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
const storagepath = `./public/Database/MapPoiContent/`;
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 == "audio/mpeg" || file.mimetype == "audio/mp3" || 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 }
}).fields(
[
{
name: 'poithumbnail',
maxCount: 1
},
{
name: 'contenturl',
maxCount: 1
}
]
);
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.status(404).send({ message: "Unknown error occured", err: err });
}
else {
// Everything went fine.
var files = req.files;
if (!files) {
//console.log('Please choose a file');
res.status(404).send({ message: "Please choose files correctly" });
} else {
if (files.poithumbnail !== undefined && files.contenturl !== undefined) {
var Map_ID = req.body.mapid2;
var POI_ID = req.body.poiid;
var POI_Name = req.body.poiname;
var POI_Description = req.body.poidesc;
var POI_Type = req.body.poitype;
var POI_Thumbnail_URL = '';
var POI_Status = req.body.poistatus;
var POI_Content_Type = req.body.contenttype;
var POI_Content_URL = '';
var POI_Trigger_Area = req.body.triggerarea;
var Latitude = req.body.latitude;
var Longitude = req.body.longitude;
var newfilename0 = req.body.mapaudio;
var newfilename1 = req.body.mapaudio;
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var filename0 = files.poithumbnail[0].filename;
var filename1 = files.contenturl[0].filename;
var filenamepath0 = `public/Database/MapPoiContent/` + filename0;
var filenamepath1 = `public/Database/MapPoiContent/` + filename1;
var newfilenamepath0 = `public/Database/MapPoiContent/POIImage/` + filename0
var newfilenamepath1 = `public/Database/MapPoiContent/POIAudio/` + filename1
var fullnewfilenamepath0 = req.protocol + '://' + req.get('host') + `/Database/MapPoiContent/POIImage/` + filename0
var fullnewfilenamepath1 = req.protocol + '://' + req.get('host') + `/Database/MapPoiContent/POIAudio/` + filename1
POI_Thumbnail_URL = fullnewfilenamepath0;
POI_Content_URL = fullnewfilenamepath1;
fs.rename(filenamepath0, newfilenamepath0, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
fs.rename(filenamepath1, newfilenamepath1, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
console.log('File Renamed');
}
});
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
var NewPOI_number;
for (var i = 0; i < poidata.length; i++) {
if (POI_ID == poidata[i].POI_ID) {
NewPOI_number = poidata[i].POI_Number;
}
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID, 'POI_List.POI_ID': POI_ID }, {
$set: {
["POI_List." + NewPOI_number + ".POI_Name"]: POI_Name,
["POI_List." + NewPOI_number + ".POI_Description"]: POI_Description,
["POI_List." + NewPOI_number + ".POI_Type"]: POI_Type,
["POI_List." + NewPOI_number + ".POI_Thumbnail_URL"]: POI_Thumbnail_URL,
["POI_List." + NewPOI_number + ".POI_Status"]: POI_Status,
["POI_List." + NewPOI_number + ".POI_Content_Type"]: POI_Content_Type,
["POI_List." + NewPOI_number + ".POI_Content_URL"]: POI_Content_URL,
["POI_List." + NewPOI_number + ".POI_Trigger_Area"]: POI_Trigger_Area,
["POI_List." + NewPOI_number + ".Latitude"]: Latitude,
["POI_List." + NewPOI_number + ".Longitude"]: Longitude,
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details updated", data: result });
}
else {
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
var POI_Number;
if (poidata.length == 0) {
POI_Number = 0;
}
else {
for (var i = 0; i < poidata.length; i++) {
// if(poidata[i].POI_Number.indexOf(i)){
// }
if (i !== poidata[i].POI_Number) {
POI_Number = i;
break;
}
else {
POI_Number = poidata.length;
}
}
}
var POI_List = {
POI_ID: POI_ID,
POI_Name: POI_Name,
POI_Description: POI_Description,
POI_Type: POI_Type,
POI_Thumbnail_URL: POI_Thumbnail_URL,
POI_Number: POI_Number,
POI_Status: POI_Status,
POI_Content_Type: POI_Content_Type,
POI_Content_URL: POI_Content_URL,
POI_Trigger_Area: POI_Trigger_Area,
Latitude: Latitude,
Longitude: Longitude
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, {
$push: {
POI_List: POI_List
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details added", data: result });
}
else {
res.status(404).send({ msg: "poi details addition failed" });
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
} else if (files.poithumbnail !== undefined && files.contenturl === undefined) {
var Map_ID = req.body.mapid2;
var POI_ID = req.body.poiid;
var POI_Name = req.body.poiname;
var POI_Description = req.body.poidesc;
var POI_Type = req.body.poitype;
var POI_Thumbnail_URL = '';
var POI_Status = req.body.poistatus;
var POI_Content_Type = req.body.contenttype;
var POI_Content_URL = '';
var POI_Trigger_Area = req.body.triggerarea;
var Latitude = req.body.latitude;
var Longitude = req.body.longitude;
var newfilename0 = req.body.mapaudio;
var newfilename1 = req.body.mapaudio;
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var filename0 = files.poithumbnail[0].filename;
var filenamepath0 = `public/Database/MapPoiContent/` + filename0;
var newfilenamepath0 = `public/Database/MapPoiContent/POIImage/` + filename0
var fullnewfilenamepath0 = req.protocol + '://' + req.get('host') + `/Database/MapPoiContent/POIImage/` + filename0;
// var image = await sharp(req.file.buffer).resize({ width: 400, height:400 })// Resize if you want
// .jpeg({
// quality: 40,
// }).toFile("public/Walks/" + newfilename + "_Pavan.jpeg")
// .catch( err => { console.log('error: ', err) })
POI_Thumbnail_URL = fullnewfilenamepath0;
fs.rename(filenamepath0, newfilenamepath0, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
var NewPOI_number;
for (var i = 0; i < poidata.length; i++) {
if (POI_ID == poidata[i].POI_ID) {
console.log(POI_ID, poidata[i].POI_ID);
NewPOI_number = poidata[i].POI_Number;
POI_Content_URL = poidata[i].POI_Content_URL;
}
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID, 'POI_List.POI_ID': POI_ID }, {
$set: {
["POI_List." + NewPOI_number + ".POI_Name"]: POI_Name,
["POI_List." + NewPOI_number + ".POI_Description"]: POI_Description,
["POI_List." + NewPOI_number + ".POI_Type"]: POI_Type,
["POI_List." + NewPOI_number + ".POI_Thumbnail_URL"]: POI_Thumbnail_URL,
["POI_List." + NewPOI_number + ".POI_Status"]: POI_Status,
["POI_List." + NewPOI_number + ".POI_Content_Type"]: POI_Content_Type,
["POI_List." + NewPOI_number + ".POI_Content_URL"]: POI_Content_URL,
["POI_List." + NewPOI_number + ".POI_Trigger_Area"]: POI_Trigger_Area,
["POI_List." + NewPOI_number + ".Latitude"]: Latitude,
["POI_List." + NewPOI_number + ".Longitude"]: Longitude,
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details updated", data: result });
}
else {
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
console.log(poidata);
var POI_Number;
if (poidata.length == 0) {
POI_Number = 0;
}
else {
for (var i = 0; i < poidata.length; i++) {
// if(poidata[i].POI_Number.indexOf(i)){
// }
if (i !== poidata[i].POI_Number) {
POI_Number = i;
break;
}
else {
POI_Number = poidata.length;
}
}
}
var POI_List = {
POI_ID: POI_ID,
POI_Name: POI_Name,
POI_Description: POI_Description,
POI_Type: POI_Type,
POI_Thumbnail_URL: POI_Thumbnail_URL,
POI_Number: POI_Number,
POI_Status: POI_Status,
POI_Content_Type: POI_Content_Type,
POI_Content_URL: POI_Content_URL,
POI_Trigger_Area: POI_Trigger_Area,
Latitude: Latitude,
Longitude: Longitude
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, {
$push: {
POI_List: POI_List
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details added", data: result });
}
else {
res.status(404).send({ msg: "poi details addition failed" });
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
} else if (files.poithumbnail === undefined && files.contenturl !== undefined) {
var Map_ID = req.body.mapid2;
var POI_ID = req.body.poiid;
var POI_Name = req.body.poiname;
var POI_Description = req.body.poidesc;
var POI_Type = req.body.poitype;
var POI_Thumbnail_URL = '';
var POI_Status = req.body.poistatus;
var POI_Content_Type = req.body.contenttype;
var POI_Content_URL = '';
var POI_Trigger_Area = req.body.triggerarea;
var Latitude = req.body.latitude;
var Longitude = req.body.longitude;
var newfilename0 = req.body.mapaudio;
var newfilename1 = req.body.mapaudio;
var filename1 = files.contenturl[0].filename;
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var filenamepath1 = `public/Database/MapPoiContent/` + filename1;
var newfilenamepath1 = `public/Database/MapPoiContent/POIAudio/` + filename1
var fullnewfilenamepath1 = req.protocol + '://' + req.get('host') + `/Database/MapPoiContent/POIAudio/` + filename1
POI_Content_URL = fullnewfilenamepath1;
fs.rename(filenamepath1, newfilenamepath1, function (err) {
if (err) {
console.log('ERROR: ' + err);
}
else {
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
var NewPOI_number;
for (var i = 0; i < poidata.length; i++) {
if (POI_ID == poidata[i].POI_ID) {
NewPOI_number = poidata[i].POI_Number;
POI_Thumbnail_URL = poidata[i].POI_Thumbnail_URL;
}
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID, 'POI_List.POI_ID': POI_ID }, {
$set: {
["POI_List." + NewPOI_number + ".POI_Name"]: POI_Name,
["POI_List." + NewPOI_number + ".POI_Description"]: POI_Description,
["POI_List." + NewPOI_number + ".POI_Type"]: POI_Type,
["POI_List." + NewPOI_number + ".POI_Thumbnail_URL"]: POI_Thumbnail_URL,
["POI_List." + NewPOI_number + ".POI_Status"]: POI_Status,
["POI_List." + NewPOI_number + ".POI_Content_Type"]: POI_Content_Type,
["POI_List." + NewPOI_number + ".POI_Content_URL"]: POI_Content_URL,
["POI_List." + NewPOI_number + ".POI_Trigger_Area"]: POI_Trigger_Area,
["POI_List." + NewPOI_number + ".Latitude"]: Latitude,
["POI_List." + NewPOI_number + ".Longitude"]: Longitude,
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details updated", data: result });
}
else {
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
var POI_Number;
if (poidata.length == 0) {
POI_Number = 0;
}
else {
for (var i = 0; i < poidata.length; i++) {
// if(poidata[i].POI_Number.indexOf(i)){
// }
if (i !== poidata[i].POI_Number) {
POI_Number = i;
break;
}
else {
POI_Number = poidata.length;
}
}
}
var POI_List = {
POI_ID: POI_ID,
POI_Name: POI_Name,
POI_Description: POI_Description,
POI_Type: POI_Type,
POI_Thumbnail_URL: POI_Thumbnail_URL,
POI_Number: POI_Number,
POI_Status: POI_Status,
POI_Content_Type: POI_Content_Type,
POI_Content_URL: POI_Content_URL,
POI_Trigger_Area: POI_Trigger_Area,
Latitude: Latitude,
Longitude: Longitude
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, {
$push: {
POI_List: POI_List
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details added", data: result });
}
else {
res.status(404).send({ msg: "poi details addition failed" });
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
else {
var Map_ID = req.body.mapid2;
var POI_ID = req.body.poiid;
var POI_Name = req.body.poiname;
var POI_Description = req.body.poidesc;
var POI_Type = req.body.poitype;
var POI_Thumbnail_URL = '';
var POI_Status = req.body.poistatus;
var POI_Content_Type = req.body.contenttype;
var POI_Content_URL = '';
var POI_Trigger_Area = req.body.triggerarea;
var Latitude = req.body.latitude;
var Longitude = req.body.longitude;
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
var NewPOI_number;
for (var i = 0; i < poidata.length; i++) {
if (POI_ID == poidata[i].POI_ID) {
NewPOI_number = poidata[i].POI_Number;
POI_Content_URL = poidata[i].POI_Content_URL;
POI_Thumbnail_URL = poidata[i].POI_Thumbnail_URL;
}
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID, 'POI_List.POI_ID': POI_ID }, {
$set: {
["POI_List." + NewPOI_number + ".POI_Name"]: POI_Name,
["POI_List." + NewPOI_number + ".POI_Description"]: POI_Description,
["POI_List." + NewPOI_number + ".POI_Type"]: POI_Type,
["POI_List." + NewPOI_number + ".POI_Thumbnail_URL"]: POI_Thumbnail_URL,
["POI_List." + NewPOI_number + ".POI_Status"]: POI_Status,
["POI_List." + NewPOI_number + ".POI_Content_Type"]: POI_Content_Type,
["POI_List." + NewPOI_number + ".POI_Content_URL"]: POI_Content_URL,
["POI_List." + NewPOI_number + ".POI_Trigger_Area"]: POI_Trigger_Area,
["POI_List." + NewPOI_number + ".Latitude"]: Latitude,
["POI_List." + NewPOI_number + ".Longitude"]: Longitude,
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details updated", data: result });
}
else {
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var poidata = result.POI_List;
console.log(poidata);
var POI_Number;
if (poidata.length == 0) {
POI_Number = 0;
}
else {
for (var i = 0; i < poidata.length; i++) {
// if(poidata[i].POI_Number.indexOf(i)){
// }
if (i !== poidata[i].POI_Number) {
POI_Number = i;
break;
}
else {
POI_Number = poidata.length;
}
}
}
var POI_List = {
POI_ID: POI_ID,
POI_Name: POI_Name,
POI_Description: POI_Description,
POI_Type: POI_Type,
POI_Thumbnail_URL: POI_Thumbnail_URL,
POI_Number: POI_Number,
POI_Status: POI_Status,
POI_Content_Type: POI_Content_Type,
POI_Content_URL: POI_Content_URL,
POI_Trigger_Area: POI_Trigger_Area,
Latitude: Latitude,
Longitude: Longitude
};
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, {
$push: {
POI_List: POI_List
}
}, { new: true }).then((result) => {
if (result) {
res.status(200).send({ msg: "poi details added", data: result });
}
else {
res.status(404).send({ msg: "poi details addition failed" });
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
});
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
}
}
}
});
});
router.post('/rpggetpoidetail', async function (req, res) {
var Map_ID = req.body.mapid;
var POI_ID = req.body.poiid;
await rpgwalk_data.findOne({ Map_ID: Map_ID, "POI_List.POI_ID": POI_ID }).then((result) => {
if (result) {
for (let i = 0; i < result.POI_List.length; i++) {
if (result.POI_List[i].POI_ID == POI_ID) {
var POI_Name = result.POI_List[i].POI_Name;
var POI_Description = result.POI_List[i].POI_Description;
var POI_Type = result.POI_List[i].POI_Type;
var POI_Thumbnail_URL = result.POI_List[i].POI_Thumbnail_URL;
var POI_Status = result.POI_List[i].POI_Status
var POI_Content_Type = result.POI_List[i].POI_Content_Type
var POI_Content_URL = result.POI_List[i].POI_Content_URL
var POI_Trigger_Area = result.POI_List[i].POI_Trigger_Area
var Latitude = result.POI_List[i].Latitude
var Longitude = result.POI_List[i].Longitude
res.status(200).send({ code: 200, msg: "Poi details", POI_Name, POI_Description, POI_Type, POI_Thumbnail_URL, POI_Status, POI_Content_Type, POI_Content_URL, POI_Trigger_Area, Latitude, Longitude })
}
}
} else {
res.status(404).send({ code: 404, msg: "No poi details found" })
}
})
})
router.post('/rpgremovewalktriviadetails', async function (req, res) {
var Map_ID = req.body.mapid;
var Trivia_ID = req.body.triviaid;
rpgwalk_data.findOneAndRemove({ Map_ID: Map_ID, "Trivia_List.Trivia_ID": Trivia_ID }).then((result) => {
if (result) {
res.status(200).send({ msg: "map removed successfully" });
} else {
res.status(404).send({ msg: "map info not found" });
}
});
})
router.post('/rpgaddupdatewalktriviadetails', async function (req, res) {
var Map_ID = req.body.mapid;
var Trivia = req.body.trivia;
console.log(Trivia)
const query = { Map_ID: Map_ID };
const updateDocument = {
$set: { Trivia_List: Trivia }
};
await rpgwalk_data.findOneAndUpdate(query, updateDocument, { new: true }).then(async (result) => {
if (result) {
res.status(200).send({ msg: "Trivia updated", data: result.Trivia_List });
}
else {
res.status(404).send({ msg: "map details not found" });
}
});
});
router.post('/getrpgpublishedwalkinfo', function (req, res) {
var Map_ID = req.body.Map_ID;
rpgwalk_data.findOne({ Map_ID: Map_ID, Map_Status: "Published" }).then((result) => {
if (result) {
var data = {
Map_Name: result.Map_Name,
Map_Description: result.Map_Description,
Map_Thumbnail_URL: result.Map_Thumbnail_URL,
Map_Status: result.Map_Status,
Map_Type: result.Map_Type,
Map_Category: result.Map_Category[0],
Total_POI: result.Total_POI,
Map_Startlongitude: result.Map_Startlongitude,
Map_Startlatitude: result.Map_Startlatitude,
TotalWalkDistance: result.TotalWalkDistance,
Total_Trivia: result.Total_Trivia,
Trivia_List: result.Trivia_List
};
res.status(200).send({ code: 200, msg: "map info found", data: data });
} else {
res.status(404).send({ code: 404, msg: "map info not found" });
}
});
});
router.post('/getrpgpublishedwalkinfo1', function (req, res) {
var Map_ID = req.body.Map_ID;
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
var data = {
Map_Name: result.Map_Name,
Map_Description: result.Map_Description,
Map_Thumbnail_URL: result.Map_Thumbnail_URL,
Map_Status: result.Map_Status,
Map_Type: result.Map_Type,
Map_Category: result.Map_Category[0],
Total_POI: result.Total_POI,
Map_Startlongitude: result.Map_Startlongitude,
Map_Startlatitude: result.Map_Startlatitude,
TotalWalkDistance: result.TotalWalkDistance,
Total_Trivia: result.Total_Trivia,
Trivia_List: result.Trivia_List
};
res.status(200).send({ code: 200, msg: "map info found", data: data });
} else {
res.status(404).send({ code: 404, msg: "map info not found" });
}
});
});
router.post('/removerpgpublishedwalk', function (req, res) {
var Map_ID = req.body.Map_ID;
rimraf(`./public/Database/MapPoiContent/${Map_ID}`, function () { console.log("done"); })
rpgwalk_data.findOneAndRemove({ Map_ID: Map_ID }).then((result) => {
if (result) {
res.status(200).send({ msg: "map removed successfully" });
} else {
res.status(404).send({ msg: "map info not found" });
}
});
});
router.post('/setrpgpublishedwalkstatus', function (req, res) {
var Map_ID = req.body.Map_ID;
var Map_Status = req.body.Map_Status;
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, { $set: { Map_Status: Map_Status } }).then((result) => {
if (result) {
var data = {
Map_Name: result.Map_Name,
Map_Description: result.Map_Description,
Map_Thumbnail_URL: result.Map_Thumbnail_URL,
Map_Status: result.Map_Status,
Map_Type: result.Map_Type,
Map_Category: result.Map_Category[0],
Total_POI: result.Total_POI,
Map_Startlongitude: result.Map_Startlongitude,
Map_Startlatitude: result.Map_Startlatitude
};
res.status(200).send({ msg: "map status updated", data: data });
} else {
res.status(404).send({ msg: "map status updation failed" });
}
});
});
router.post('/setrpgpublishedwalktype', function (req, res) {
var Map_ID = req.body.Map_ID;
var Map_Type = req.body.Map_Type;
var Map_Status = req.body.Map_Status;
rpgwalk_data.findOneAndUpdate({ Map_ID: Map_ID }, { $set: { Map_Type: Map_Type, Map_Status: Map_Status } }).then((result) => {
if (result) {
var data = {
Map_Name: result.Map_Name,
Map_Description: result.Map_Description,
Map_Thumbnail_URL: result.Map_Thumbnail_URL,
Map_Status: result.Map_Status,
Map_Type: result.Map_Type,
Map_Category: result.Map_Category[0],
Total_POI: result.Total_POI,
Map_Startlongitude: result.Map_Startlongitude,
Map_Startlatitude: result.Map_Startlatitude
};
res.status(200).send({ msg: "map type updated", data: data });
} else {
res.status(404).send({ msg: "map type updation failed" });
}
});
});
router.get('/getallrpgpublishedwalkinfodata', function (req, res) {
rpgwalk_data.find({ Map_Status: "Published" }).then((result) => {
if (result) {
var datas = [];
for (var i = 0; i < result.length; i++) {
var data = {
Map_ID: result[i].Map_ID,
Map_Name: result[i].Map_Name,
Map_Description: result[i].Map_Description,
Map_Thumbnail_URL: result[i].Map_Thumbnail_URL,
Map_Status: result[i].Map_Status,
Map_Type: result[i].Map_Type,
Map_Category: result[i].Map_Category[0],
Total_POI: result[i].Total_POI,
Map_Startlongitude: result[i].Map_Startlongitude,
Map_Startlatitude: result[i].Map_Startlatitude,
Map_Version: result[i].Map_Version,
Map_Ratting: result[i].Map_Ratting
};
datas.push(data);
};
res.status(200).send({ code: 200, msg: "all map info found", data: datas });
} else {
res.status(404).send({ code: 404, msg: "all map info not found" });
}
});
});
router.get('/getallrpgpublishedwalkinfodata1', function (req, res) {
rpgwalk_data.find().then((result) => {
if (result) {
var datas = [];
for (var i = 0; i < result.length; i++) {
var data = {
Map_ID: result[i].Map_ID,
Map_Name: result[i].Map_Name,
Map_Description: result[i].Map_Description,
Map_Thumbnail_URL: result[i].Map_Thumbnail_URL,
Map_Status: result[i].Map_Status,
Map_Type: result[i].Map_Type,
Map_Category: result[i].Map_Category[0],
Total_POI: result[i].Total_POI,
Map_Startlongitude: result[i].Map_Startlongitude,
Map_Startlatitude: result[i].Map_Startlatitude,
Map_Version: result[i].Map_Version,
Map_Ratting: result[i].Map_Ratting
};
datas.push(data);
};
res.status(200).send({ code: 200, msg: "all map info found", data: datas });
} else {
res.status(404).send({ code: 404, msg: "all map info not found" });
}
});
});
router.get('/getallrpgpublishedwalkinfo', function (req, res) {
var initfilename = '/Database/MapDetails.txt';
var initfilepath = './public' + initfilename;
rpgwalk_data.find().then((result) => {
if (result) {
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ code: 404, msg: "map info file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
var ZipFileurl = urlpath + "/Database.zip"
zipper.sync.zip("./public/Database/").compress().save("./public/Database.zip");
res.status(200).send({ code: 200, msg: "map info file updated", zipurl: ZipFileurl, mapurl: fileurl });
}
});
} else {
res.status(404).send({ code: 200, msg: "all map info not found" });
}
});
});
router.post('/getrpgpublishedwalkdetail', function (req, res) {
var Map_ID = req.body.Map_ID;
rpgwalk_data.findOne({ Map_ID: Map_ID, Map_Status: "Published" }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "map detail found", data: result });
} else {
res.status(404).send({ code: 404, msg: "map detail not found" });
}
});
});
router.post('/getrpgpublishedwalkdetail1', function (req, res) {
var Map_ID = req.body.Map_ID;
rpgwalk_data.findOne({ Map_ID: Map_ID }).then((result) => {
if (result) {
res.status(200).send({ code: 200, msg: "map detail found", data: result });
} else {
res.status(404).send({ code: 404, msg: "map detail not found" });
}
});
});
router.post('/getrpgpublishedwalkdetails', function (req, res) {
var Map_ID = req.body.Map_ID;
var initfilename = '/Walks/WalkInfoFiles/' + Map_ID + '_WalkDetails.txt';
var initfilepath = './public' + initfilename;
rpgwalk_data.findOne({ Map_ID: Map_ID, Map_Status: "Published" }).then((result) => {
if (result) {
var strresult = JSON.stringify(result);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ code: 404, msg: "map details file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
res.status(200).send({ code: 200, msg: "map details file updated", data: fileurl });
}
});
} else {
res.status(404).send({ code: 404, msg: "map details not found" });
}
});
});
router.get('/getallrpgpublishedwalkdetails', function (req, res) {
var initfilename = '/Walks/WalkInfoFiles/All_WalkDetails.txt';
var initfilepath = './public' + initfilename;
rpgwalk_data.find({ Map_Status: "Published" }).then((results) => {
if (results) {
var strresult = JSON.stringify(results);
fs.writeFile(initfilepath, strresult, function (err) {
if (err) {
res.status(404).send({ code: 404, msg: "map details file updation failed" });
}
else {
var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https';
var urlpath = securelink + '://' + req.get('host');
var fileurl = urlpath + initfilename;
res.status(200).send({ code: 200, msg: "map details file updated", data: fileurl });
}
});
} else {
res.status(404).send({ code: 404, msg: "map details not found" });
}
});
});
module.exports = router;