var express = require('express') var router = express.Router() var puppeteer = require('puppeteer') 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'); const imageSize = require('image-size'); var appleSignin = require('apple-signin-auth'); var fs = require('fs'); const { uploadFileToS3, deleteFileToS3 } = require('../config/s3-config'); const Banner = require('../models/bannermodel'); const GuidedWalkBooking = require('../models/guidedwalkmodel'); const { createRazorpayOrder, processRazorpayRefund, getOrderDetails } = require('../config/razorpay-service'); const newRpguserlistEntry = require('../models/rpguserlist'); const UserFeedback = require('../models/userratingmodel'); const GuestToggle = require('../models/guesttogglemodel'); 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; }; const storage = multer.memoryStorage({ destination: function (req, file, callback) { callback(null, ''); } }); // Initialize multer with S3 storage engine const upload = multer({ storage: storage, fileFilter: function (req, file, cb) { if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) { return cb(new Error('Only image files are allowed!'), false); } cb(null, true); } }); // Middleware to validate image dimensions for all image files except contenturl const validateImageDimensions = async (req, res, next) => { try { // Check if there's a single file upload if (req.file && req.file.fieldname !== 'contenturl') { const dimensions = imageSize(req.file.buffer); if (dimensions.width !== 512 || dimensions.height !== 512) { throw new Error(`Image dimensions for file ${req.file.originalname} should be 512x512 pixels!`); } } // Check if there are multiple files const files = req.files || {}; const imageFields = Object.keys(files).filter(fieldName => fieldName !== 'contenturl'); for (let fieldName of imageFields) { const fileArray = files[fieldName]; for (let file of fileArray) { const dimensions = imageSize(file.buffer); if (dimensions.width !== 512 || dimensions.height !== 512) { throw new Error(`Image dimensions for file ${file.originalname} should be 512x512 pixels!`); } } } next(); // Proceed to the next middleware if validation passes } catch (error) { // Send error response if validation fails res.status(400).send({ code: 400, msg: error.message }); } }; router.get('/', function (req, res) { res.render('layout', { layout: 'api' }); }); router.get('/appVersions', function(req, res) { var appVersions = { androidVersion: '1.0.0', iosVersion: '1.0.0' }; res.status(200).json({ data: appVersions, message: "Versions got successfully." }); }); 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 = 'com.amble.rpgfios'; var code = req.body.code; 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 client_secret = await appleSignin.getClientSecret({ clientID: "com.amble.rpgfios", // Apple Client ID teamID: "6574RD4TUC", // Apple Developer Team ID. privateKey: fs.readFileSync('./public/AuthKey_3BHBGB5T8A.p8', 'utf8'), // private key associated with your client ID. -- Or provide a `privateKeyPath` property instead. keyIdentifier: "3BHBGB5T8A", // identifier of the private key. expAfter: 1200, }); const options = { clientID: 'com.amble.rpgfios', // Apple Client ID clientSecret: client_secret }; const tokenResponse = await appleSignin.getAuthorizationToken(code, options); console.log(tokenResponse); if (tokenResponse.error) { res.status(404).send({ code: 404, msg: tokenResponse.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: tokenResponse.refresh_token, access_token: tokenResponse.access_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.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 sns = new AWS.SNS({ apiVersion: '2010-03-31' }); var publishTextPromise = sns.publish(params).promise(); publishTextPromise.then((data) => { console.log("MessageID is " + data.MessageId); res.status(200).send({ code: 200, msg: "Success", otp: MobileOTP }); }).catch((err) => { console.error(err, err.stack); 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) { const clientSecret = appleSignin.getClientSecret({ clientID: result1.client_id, // Apple Client ID teamID: "6574RD4TUC", // Apple Developer Team ID. privateKey: fs.readFileSync('./public/AuthKey_3BHBGB5T8A.p8', 'utf8'), // private key associated with your client ID. -- Or provide a `privateKeyPath` property instead. keyIdentifier: "3BHBGB5T8A", // identifier of the private key. expAfter: 1200, }); const optionsrefresh = { clientID: result1.client_id, // Apple Client ID clientSecret }; var access_token_response = await appleSignin.refreshAuthorizationToken(result1.refresh_token, optionsrefresh); if (access_token_response.error) { res.status(404).send({ code: 404, msg: access_token_response.error }); } else { await rpguser_data.findOneAndUpdate({ Email: Email }, { $set: { access_token: access_token_response.access_token, client_secret: clientSecret } }, { new: true }).then(async (data) => { if (data) { const options = { clientID: data.client_id, // Apple Client ID clientSecret, tokenTypeHint: 'access_token' }; var revokeresponse = await appleSignin.revokeAuthorizationToken(data.access_token, options); if (revokeresponse.error) { res.send({ code: 404, msg: revokeresponse.error }); } else { 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: "Success", 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; var LoginType = req.body.LoginType; var code = req.body.code; if (LoginType == "Apple") { const data = await rpguser_data.findOne({ Email: Email }); if (data) { var client_secret = await appleSignin.getClientSecret({ clientID: "com.amble.rpgfios", // Apple Client ID teamID: "6574RD4TUC", // Apple Developer Team ID. privateKey: fs.readFileSync('./public/AuthKey_3BHBGB5T8A.p8', 'utf8'), // private key associated with your client ID. -- Or provide a `privateKeyPath` property instead. keyIdentifier: "3BHBGB5T8A", // identifier of the private key. expAfter: 1200, }); const options = { clientID: 'com.amble.rpgfios', // Apple Client ID clientSecret: client_secret }; const tokenResponse = await appleSignin.getAuthorizationToken(code, options); if (tokenResponse.error) { res.status(404).send({ code: 404, msg: tokenResponse.error }); } else { await rpguser_data.findOneAndUpdate({ Email: Email }, { $set: { client_secret: client_secret, refresh_token: tokenResponse.refresh_token, access_token: tokenResponse.access_token } }, { new: true }).then(async (result) => { if (result) { res.status(200).send({ code: 200, msg: "User updated", 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" }); } }); } console.log(tokenResponse); } else { res.status(404).send({ code: 404, msg: "user not found", Email }); } } else { 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', upload.single('file'), async function (req, res) { const file = req.file; const filename = Date.now() + '.' + file.originalname.split('.').pop(); const fullnewfilenamepath = `Database/images/UserProfile/${filename}`; // Assuming uploadFileToS3 is a function to upload to AWS S3 const ProfilePic = await uploadFileToS3(file.buffer, fullnewfilenamepath, file.mimetype); var Userid = req.body.Userid; await rpguser_data.findOneAndUpdate({ Userid: Userid }, { 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', upload.single('mapthumbnail'), validateImageDimensions, async (req, res) => { var Map_ID = req.query.mapid; 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) } // Everything went fine. var file = req.file; //var Map_ID = randomString(10,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); if (file && file.fieldname == 'mapthumbnail') { var Map_ID = req.body.mapid; var Map_Version = 0; var Sort_Number = req.body.sortno var Walk_Type = req.body.walktype let Amount_Per_Person = null let Maximum_Persons_Allowed = null let Walk_Duration = req.body.durationwalk let Dates = [] let properArray = [] console.log(Walk_Type == 'Guided Walk', Walk_Type) if (Walk_Type == 'Guided Walk') { Walk_Duration = req.body.durationwalk Amount_Per_Person = req.body.amountsingelperson Maximum_Persons_Allowed = req.body.maximumperson Dates = req.body.dates const trimmedValue = Dates.replace(/^["`']+|["`']+$/g, ''); // Parse the JSON string into a JavaScript array properArray = await sortDatesAndTimeSlots(JSON.parse(trimmedValue)); } 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 = Date.now() + '.' + file.originalname.split('.').pop(); var fullnewfilenamepath = `/Database/MapPoiContent/${Map_ID}/Image/${filename}`; 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 = await uploadFileToS3(file.buffer, 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) }) } }) 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, Sort_Number: Sort_Number, Walk_Type: Walk_Type, Amount_Per_Person: Amount_Per_Person, Maximum_Persons_Allowed: Maximum_Persons_Allowed, Walk_Duration, Map_Startlongitude: Map_Startlongitude, Map_Startlatitude: Map_Startlatitude, Map_Zip_Url: Map_Zip_Url, Total_Trivia: Total_Trivia, Dates: properArray } }, { 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 { 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, Sort_Number: Sort_Number, Walk_Type: Walk_Type, Amount_Per_Person: Amount_Per_Person, Maximum_Persons_Allowed: Maximum_Persons_Allowed, Walk_Duration, Dates: properArray, 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) { if (err) { res.status(404).send({ msg: err.message }); } var initfilename = `/Database/MapPoiContent/${Map_ID}/MapDetails/0.txt`; var initfilepath = './public' + initfilename; if (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 Sort_Number = req.body.sortno var Walk_Type = req.body.walktype let Amount_Per_Person = null let Maximum_Persons_Allowed = null let Dates = [] let properArray = [] let Walk_Duration if (Walk_Type == 'Guided Walk') { Walk_Duration = req.body.durationwalk Amount_Per_Person = req.body.amountsingelperson Maximum_Persons_Allowed = req.body.maximumperson Dates = req.body.dates const trimmedValue = Dates.replace(/^["`']+|["`']+$/g, ''); // Parse the JSON string into a JavaScript array properArray = await sortDatesAndTimeSlots(JSON.parse(trimmedValue)); } 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; 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, Sort_Number: Sort_Number, Walk_Type: Walk_Type, Amount_Per_Person: Amount_Per_Person, Maximum_Persons_Allowed: Maximum_Persons_Allowed, Dates: properArray, Walk_Duration, 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" }) } }); } else { res.status(404).send({ msg: "map detail not found ." }) } }); } }); // Function to sort dates and time slots const sortDatesAndTimeSlots = (dates) => { // Function to convert time to minutes for comparison const convertToMinutes = (time) => { const [hours, minutes, meridian] = time.split(/[:\s]+/); let hour = parseInt(hours, 10); if (meridian.toLowerCase() === 'pm' && hour !== 12) { hour += 12; } else if (meridian.toLowerCase() === 'am' && hour === 12) { hour = 0; } return hour * 60 + parseInt(minutes, 10); }; // Sort dates by date dates.sort((a, b) => { const dateA = new Date(a.Date.split("-").reverse().join("-")); const dateB = new Date(b.Date.split("-").reverse().join("-")); return dateA - dateB; }); // Sort time slots within each date dates.forEach(date => { date.Time_Slots.sort((a, b) => { const timeA = convertToMinutes(a); const timeB = convertToMinutes(b); return timeA - timeB; }); }); return dates; }; 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: "Success", 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; console.log(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" }); } }); }); const storage1 = multer.memoryStorage(); const upload1 = multer({ storage: storage1, fileFilter: (req, file, cb) => { const contenturlFiles = req.files ? req.files['contenturl'] : undefined; if (!req.body.contenturl && !contenturlFiles) { return res.status(404).send({ message: "Audio file is required" }); } // Define allowed mimetypes and extensions const allowedMimeTypes = ['audio/mpeg', 'audio/mp3', 'image/png', 'image/gif', 'image/jpeg']; const allowedExtensions = ['mp3', 'png', 'gif', 'jpg', 'jpeg']; // Check if the mimetype and extension of the file are allowed if (allowedMimeTypes.includes(file.mimetype) && allowedExtensions.includes(file.originalname.split('.').pop())) { cb(null, true); } else { cb(null, false); cb(new Error('Only .mp3, .png, .gif, .jpg, and .jpeg formats allowed!')); } }, limits: { fieldSize: 50000000 } }); router.post('/rpgaddupdatewalkpoidetails', upload1.fields([ { name: 'contenturl', maxCount: 1 }, { name: 'poithumbnail' } ]), validateImageDimensions, async (req, res) => { // Everything went fine. var files = req.files; // if (req.files.contenturl === undefined) { // return res.status(404).send({ message: "Audio file is required" }); // } // if (Object.keys(files).length === 0) { // console.log('Please choose a file'); // return res.status(404).send({ message: "please upload proper file" }); // } // 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_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 POI_Thumbnail_URL = []; var securelink = req.hostname == 'localhost' || req.hostname == '127.0.0.1' ? 'http' : 'https'; var filename1 = Date.now() + '.' + files.contenturl[0].originalname.split('.').pop(); var newfilenamepath1 = `/Database/MapPoiContent/POIAudio/` + filename1 POI_Content_URL = await uploadFileToS3(files.contenturl[0].buffer, newfilenamepath1); // var filename0 = files.poithumbnail[0].filename; for (let i = 0; i < files.poithumbnail.length; i++) { var filename0 = Date.now() + '.' + files.poithumbnail[i].originalname.split('.').pop() var newfilenamepath0 = `Database/MapPoiContent/POIImage/` + filename0 var fullnewfilenamepath0 = await uploadFileToS3(files.poithumbnail[i].buffer, newfilenamepath0) POI_Thumbnail_URL.push(fullnewfilenamepath0); if (files.poithumbnail !== undefined && files.poithumbnail.length > 0) { if (i == files.poithumbnail.length - 1) { rpgwalk_data.findOne({ Map_ID: Map_ID }).then(async (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; } }; const ifExist = await rpgwalk_data.findOne({ Map_ID: Map_ID }); if (ifExist && ifExist.POI_List) { for (let j = 0; j < ifExist.POI_List.length; j++) { if (ifExist.POI_List[j].POI_ID === POI_ID) { const audioPath = path.join(process.cwd(), 'public', ifExist.POI_List[j].POI_Content_URL.replace(`${req.protocol}://${req.get('host')}`, '')); for (let k = 0; k < ifExist.POI_List[j].POI_Thumbnail_URL.length; k++) { const imagePath = path.join(process.cwd(), 'public', ifExist.POI_List[j].POI_Thumbnail_URL[k].replace(`${req.protocol}://${req.get('host')}`, '')); if (fs.existsSync(imagePath)) { fs.unlinkSync(imagePath); } } if (fs.existsSync(audioPath)) { fs.unlinkSync(audioPath); } } } } 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(async (result) => { if (result) { const poi = (await rpgwalk_data.findOne({ Map_ID: req.body.mapid2 })).POI_List.length await rpgwalk_data.findOneAndUpdate({ Map_ID: req.body.mapid2 }, { Total_POI: poi }, { new: true }) 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 { res.status(400).send({ msg: "No thumbnails provided" }); } } } 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 filename1 = Date.now() + '.' + files.contenturl[0].originalname.split('.').pop(); var newfilenamepath1 = path.join(process.cwd(), `public/Database/MapPoiContent/POIAudio/` + filename1) var fullnewfilenamepath1 = `Database/MapPoiContent/POIAudio/` + filename1 POI_Content_URL = await uploadFileToS3(files.contenturl[0].buffer, fullnewfilenamepath1); 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_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(async (result) => { if (result) { const poi = await rpgwalk_data.findOne({ Map_ID: req.body.mapid2 }); const poiListLength = poi.POI_List.length console.log(poiListLength) await rpgwalk_data.findOneAndUpdate({ Map_ID: req.body.mapid2 }, { Total_POI: poiListLength }, { new: true }) 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_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 POI_Thumbnail_URL = []; rpgwalk_data.findOne({ Map_ID: Map_ID }).then(async (result) => { if (result) { if (files.poithumbnail) { if (result && result.POI_List) { for (let j = 0; j < result.POI_List.length; j++) { if (result.POI_List[j].POI_ID === POI_ID) { const audioPath = path.join(process.cwd(), 'public', result.POI_List[j].POI_Content_URL.replace(`${req.protocol}://${req.get('host')}`, '')); if (result.POI_List[j].POI_Thumbnail_URL.length > 0) { for (let k = 0; k < result.POI_List[j].POI_Thumbnail_URL.length; k++) { // const imagePath = path.join(process.cwd(), 'public', result.POI_List[j].POI_Thumbnail_URL[k].replace(`${req.protocol}://${req.get('host')}`, '')); // if (fs.existsSync(imagePath)) { // fs.unlinkSync(imagePath); // } POI_Thumbnail_URL.push(result.POI_List[j].POI_Thumbnail_URL[k]); } } if (fs.existsSync(audioPath)) { fs.unlinkSync(audioPath); } } } } for (let i = 0; i < files.poithumbnail.length; i++) { var filename0 = Date.now() + '.' + files.poithumbnail[i].originalname.split('.').pop() var newfilenamepath0 = `Database/MapPoiContent/POIImage/` + filename0 var fullnewfilenamepath0 = await uploadFileToS3(files.poithumbnail[i].buffer, newfilenamepath0) POI_Thumbnail_URL.push(fullnewfilenamepath0); } } 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; POI_Thumbnail_URL.length == 0 ? POI_Thumbnail_URL = poidata[i].POI_Thumbnail_URL : null; } }; 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(async (result) => { if (result) { const poi = await rpgwalk_data.findOne({ Map_ID: req.body.mapid2 }); const poiListLength = poi.POI_List.length console.log(poiListLength) await rpgwalk_data.findOneAndUpdate({ Map_ID: req.body.mapid2 }, { Total_POI: poiListLength }, { new: true }); 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.delete('/rpgdeletepoiaudio', async (req, res) => { try { const { mapid, poiid } = req.query; const result = await rpgwalk_data.findOne({ Map_ID: mapid }); if (!result) { return res.status(404).send({ msg: "Map not found" }); } const poi = result.POI_List.find(p => p.POI_ID === poiid); if (!poi) { return res.status(404).send({ msg: "POI not found" }); } // Delete associated audio file if (poi.POI_Content_URL) { const audioPath = path.join(process.cwd(), 'public', poi.POI_Content_URL.replace(`${req.protocol}://${req.get('host')}`, '')); fs.unlinkSync(audioPath); // Update the database to remove the audio file reference const updatedResult = await rpgwalk_data.findOneAndUpdate( { Map_ID: mapid, 'POI_List.POI_ID': poiid }, { $set: { 'POI_List.$.POI_Content_URL': '' } }, { new: true } ); return res.status(200).send({ msg: "Audio file deleted for the POI", data: updatedResult }); } else { return res.status(404).send({ msg: "Audio file not found for the POI" }); } } catch (error) { console.error(error); res.status(500).send({ msg: "Internal Server Error" }); } }) router.delete('/rpgdeletepoithumbnail', async (req, res) => { try { const { mapid, poiid, thumbnail } = req.query; const result = await rpgwalk_data.findOne({ Map_ID: mapid }); if (!result) { return res.status(404).send({ msg: "Map not found" }); } const poi = result.POI_List.find(p => p.POI_ID === poiid); if (!poi) { return res.status(404).send({ msg: "POI not found" }); } // Check if the thumbnail exists in the array if (poi.POI_Thumbnail_URL.includes(thumbnail)) { await deleteFileToS3(thumbnail) // Update the database to remove the image file reference const updatedResult = await rpgwalk_data.findOneAndUpdate( { Map_ID: mapid, 'POI_List.POI_ID': poiid }, { $pull: { 'POI_List.$.POI_Thumbnail_URL': thumbnail } }, { new: true } ); return res.status(200).send({ msg: "Image deleted for the POI", data: updatedResult }); } else { return res.status(404).send({ msg: "Image file not found for the POI" }); } } catch (error) { console.error(error); res.status(500).send({ msg: "Internal Server Error" }); } }); //update poi number router.patch('/update-poinumber', async (req, res) => { const { mapid, poiid } = req.body; try { const walklist = await rpgwalk_data.findOne({ Map_ID: mapid }); if (!walklist) { return res.status(400).send({ msg: `Walklist not found for Map_ID: ${mapid}` }); } for (let i = 0; i < poiid.length; i++) { const indexToUpdate = walklist.POI_List.findIndex((elem) => elem.POI_ID === poiid[i]); if (indexToUpdate !== -1) { walklist.POI_List[indexToUpdate].POI_Number = i; } else { return res.status(400).send({ msg: `POI_ID ${id} not found in the document.` }); } } walklist.POI_List.sort((a, b) => a.POI_Number - b.POI_Number) .forEach((poi, i) => poi.POI_ID = `poi${poi.POI_Number}`); await walklist.save(); return res.status(200).send({ msg: `Successfully updated POI_Number for Map_ID: ${mapid}` }); } catch (error) { console.error(error); return res.status(500).send({ msg: "Internal Server Error" }); } }); //Delete API router.delete('/rpgdeletepoidetails', async (req, res) => { try { const { mapid, poiid } = req.query; // Validate mapid and poiid const result = await rpgwalk_data.findOne({ Map_ID: mapid }); if (!result) { return res.status(404).send({ msg: "Map not found" }); } const poi = result.POI_List.find(p => p.POI_ID === poiid); if (!poi) { return res.status(404).send({ msg: "POI not found" }); } // Delete associated image file if (poi.POI_Thumbnail_URL) { poi.POI_Thumbnail_URL.forEach((url) => { const imagePath = path.join(process.cwd(), 'public', url.replace(`${req.protocol}://${req.get('host')}`, '')); try { fs.unlinkSync(imagePath); } catch (err) { console.error(`Error deleting ${imagePath}:`, err); } }); } // Delete associated audio file if (poi.POI_Content_URL) { const audioPath = path.join(process.cwd(), 'public', poi.POI_Content_URL.replace(`${req.protocol}://${req.get('host')}`, '')); try { fs.unlinkSync(audioPath); } catch (err) { console.error(`Error deleting ${audioPath}:`, err); } } // Update the database to remove the POI const updatedResult = await rpgwalk_data.findOneAndUpdate( { Map_ID: mapid }, { $pull: { POI_List: { POI_ID: poiid } } }, { new: true } ); for (let i = 0; i < updatedResult.POI_List.length; i++) { if (updatedResult.POI_List[i].POI_Number !== i) { updatedResult.POI_List[i].POI_Number = i updatedResult.POI_List[i].POI_ID = `poi${i}` await updatedResult.save() } // await rpgwalk_data.findOne({POI_Number:poiList[i].POI_Number}) } // await rpgwalk_data.findOne({ // POI_Number:updatedResult}) const poiLen = (await rpgwalk_data.findOne({ Map_ID: mapid })).POI_List.length await rpgwalk_data.findOneAndUpdate({ Map_ID: mapid }, { Total_POI: poiLen }, { new: true }) res.status(200).send({ msg: "POI details deleted", data: updatedResult }); } catch (error) { console.error(error); res.status(500).send({ msg: "Internal Server Error" }); } }); // 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, Sort_Number: result.Sort_Number, Walk_Type: result.Walk_Type, Amount_Per_Person: result.Amount_Per_Person, Maximum_Persons_Allowed: result.Maximum_Persons_Allowed, Walk_Duration: result.Walk_Duration, Dates: result.Dates }; 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", Walk_Type: "Self-Paced Walk" }).then((result) => { if (result && result.length > 0) { // Mapping and sorting simultaneously var datas = result.map(item => ({ Map_ID: item.Map_ID, Map_Name: item.Map_Name, Map_Description: item.Map_Description, Map_Thumbnail_URL: item.Map_Thumbnail_URL, Map_Status: item.Map_Status, Map_Type: item.Map_Type, Map_Category: item.Map_Category[0], Total_POI: item.Total_POI, Map_Startlongitude: item.Map_Startlongitude, Map_Startlatitude: item.Map_Startlatitude, Map_Version: item.Map_Version, Map_Ratting: item.Map_Ratting, Sort_Number: item.Sort_Number, Walk_Type: item.Walk_Type, Walk_Duration: item.Walk_Duration, })).sort((a, b) => { if (a.Sort_Number !== undefined && b.Sort_Number !== undefined) { return a.Sort_Number - b.Sort_Number; } else if (a.Sort_Number !== undefined) { return -1; } else if (b.Sort_Number !== undefined) { return 1; } else { return 0; } }); 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" }); } }).catch(error => { console.error("Error occurred:", error); res.status(500).send({ code: 500, msg: "Internal Server Error" }); }); }); router.get('/getallrpgpublishedwalkinfodata1', function (req, res) { rpgwalk_data.find().then((result) => { if (result && result.length > 0) { // Mapping the data var datas = result.map(item => ({ _id: item._id, Map_ID: item.Map_ID, Map_Name: item.Map_Name, Map_Description: item.Map_Description, Map_Thumbnail_URL: item.Map_Thumbnail_URL, Map_Status: item.Map_Status, Map_Type: item.Map_Type, Map_Category: item.Map_Category[0], Total_POI: item.Total_POI, Map_Startlongitude: item.Map_Startlongitude, Map_Startlatitude: item.Map_Startlatitude, Map_Version: item.Map_Version, Map_Ratting: item.Map_Ratting, Sort_Number: item.Sort_Number, Walk_Type: item.Walk_Type, })); // Sorting the mapped data datas.sort((a, b) => { if (a.Sort_Number !== undefined && b.Sort_Number !== undefined) { return a.Sort_Number - b.Sort_Number; } else if (a.Sort_Number !== undefined) { return -1; } else if (b.Sort_Number !== undefined) { return 1; } else { return 0; } }); 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" }); } }).catch(error => { console.error("Error occurred:", error); res.status(500).send({ code: 500, msg: "Internal Server Error" }); }); }); router.get('/getallrpgguidedwalks', function (req, res) { rpgwalk_data.find({ Walk_Type: 'Guided Walk', Map_Status: "Published" }).then((result) => { if (result && result.length > 0) { // Mapping the data var datas = result.map(item => ({ _id: item._id, Map_ID: item.Map_ID, Map_Name: item.Map_Name, Map_Description: item.Map_Description, Map_Thumbnail_URL: item.Map_Thumbnail_URL, Map_Status: item.Map_Status, Map_Type: item.Map_Type, Map_Category: item.Map_Category[0], Total_POI: item.Total_POI, Map_Startlongitude: item.Map_Startlongitude, Map_Startlatitude: item.Map_Startlatitude, Map_Version: item.Map_Version, Map_Ratting: item.Map_Ratting, Sort_Number: item.Sort_Number, Walk_Type: item.Walk_Type, Walk_Duration: item.Walk_Duration, Amount_Per_Person: item.Amount_Per_Person, Maximum_Persons_Allowed: item.Maximum_Persons_Allowed, Dates: item.Dates })); // Sorting the mapped data datas.sort((a, b) => { if (a.Sort_Number !== undefined && b.Sort_Number !== undefined) { return a.Sort_Number - b.Sort_Number; } else if (a.Sort_Number !== undefined) { return -1; } else if (b.Sort_Number !== undefined) { return 1; } else { return 0; } }); 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" }); } }).catch(error => { console.error("Error occurred:", error); res.status(500).send({ code: 500, msg: "Internal Server Error" }); }); }); 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) { result.POI_List.sort((a, b) => a.POI_Number - b.POI_Number); 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" }); } }); }); router.post('/delete-poi-thumbnails', async function (req, res) { try { // Find all walks const walks = await rpgwalk_data.find(); // Loop through each walk for (let walk of walks) { // Loop through each POI in the POI_List of the walk for (let poi of walk.POI_List) { // Set POI_Thumbnail_URL to an empty array poi.POI_Thumbnail_URL = []; } // Save the modified walk object await walk.save(); } // Respond with success message return res.status(200).send({ code: 200, msg: "walks updated", data: {} }); } catch (error) { console.error('Error deleting POI Thumbnails:', error); // Respond with error message res.status(404).send({ code: 404, msg: "failed" }); } }); router.get('/update-walk-type', async function (req, res) { try { // Update all walks to have Walk_type = "Self-Paced Walk" await rpgwalk_data.updateMany({}, { Walk_Type: "Self-Paced Walk" }); // Respond with success message return res.status(200).send({ code: 200, msg: "walks updated", data: {} }); } catch (error) { console.error('Error updating Walk_type:', error); // Respond with error message res.status(500).send({ code: 500, msg: "failed" }); } }); router.post('/create-banner', upload.single('image'), validateImageDimensions, async function (req, res) { try { const file = req.file; const filename = Date.now() + '.' + file.originalname.split('.').pop(); const fullnewfilenamepath = `Database/banner/${filename}`; // Assuming uploadFileToS3 is a function to upload to AWS S3 const image = await uploadFileToS3(file.buffer, fullnewfilenamepath, file.mimetype); //const image = 'https://amble.theheritageproject.in/Walks/Thumbnails/map2-mapthumbnail.jpeg'; // Assuming Banner is your Mongoose model const banner = await Banner.create({ location_name: req.body.location_name, image }); // Respond with success message return res.status(200).send({ code: 200, msg: "banner created", data: banner }); } catch (error) { console.error('Error creating banner:', error); // Respond with error message res.status(500).send({ code: 500, msg: "failed", data: { error: error.message } }); } }); router.get('/list-banners', async function (req, res) { try { // Retrieve all banners from the database const banners = await Banner.find().sort('created_at'); // Respond with success message and the list of banners return res.status(200).send({ code: 200, msg: "List of banners", data: banners }); } catch (error) { // If there's an error, log it and respond with an error message console.error('Error listing banners:', error); res.status(500).send({ code: 500, msg: "Failed to list banners" }); } }); router.get('/get-banner/:id', async function (req, res) { try { // Find the banner by its ID const banner = await Banner.findById(req.params.id); // If the banner is found, respond with success message and the banner data if (banner) { return res.status(200).send({ code: 200, msg: "Banner details", data: banner }); } else { // If the banner is not found, respond with an appropriate message return res.status(404).send({ code: 404, msg: "Banner not found" }); } } catch (error) { // If there's an error, log it and respond with an error message console.error('Error fetching banner details:', error); res.status(500).send({ code: 500, msg: "Failed to fetch banner details" }); } }); router.patch('/update-banner/:id', upload.single('image'), validateImageDimensions, async function (req, res) { try { const { id } = req.params; const { location_name } = req.body; const file = req.file; if (!id) { return res.status(400).json({ code: 400, msg: "Banner ID is required" }); } const params = { location_name }; if (file) { const filename = Date.now() + '.' + file.originalname.split('.').pop(); const fullNewFilenamePath = `Database/banner/${filename}`; params.image = await uploadFileToS3(file.buffer, fullNewFilenamePath, file.mimetype); } // Find the banner by its ID and update the image field const updatedBanner = await Banner.findByIdAndUpdate(id, params, { new: true }); if (!updatedBanner) { return res.status(404).json({ code: 404, msg: "Banner not found" }); } return res.status(200).json({ code: 200, msg: "Banner updated successfully", data: updatedBanner }); } catch (error) { console.error('Error updating banner:', error); return res.status(500).json({ code: 500, msg: "Failed to update banner" }); } }); router.delete('/delete-banner/:id', async function (req, res) { try { // Assuming Banner is your Mongoose model const deletedBanner = await Banner.findByIdAndDelete(req.params.id); if (!deletedBanner) { return res.status(404).send({ code: 404, msg: "Banner not found" }); } // Respond with success message return res.status(200).send({ code: 200, msg: "Banner deleted successfully", data: {} }); } catch (error) { console.error('Error deleting banner:', error); // Respond with error message res.status(500).send({ code: 500, msg: "Failed to delete banner" }); } }); router.get('/list-banners', async function (req, res) { try { // Retrieve all banners from the database const banners = await Banner.find(); // Respond with success message and the list of banners return res.status(200).send({ code: 200, msg: "List of banners", data: banners }); } catch (error) { // If there's an error, log it and respond with an error message console.error('Error listing banners:', error); res.status(500).send({ code: 500, msg: "Failed to list banners" }); } }); router.get('/list-time-slots/:walkId', async function (req, res) { try { const walkId = req.params.walkId; const date = req.query.date; // Get date from request parameters // Find the booking by ID const booking = await rpgwalk_data.findById(walkId); if (!booking) { res.status(400).send({ code: 400, msg: "Walk details not found" }); } let slots = []; // Initialize slots array outside the loop for (const slotDate of booking.Dates) { if (slotDate.Date === date) { slots = slotDate.Time_Slots; // Update slots only if date matches break; // Exit loop since we found the matching date } } // Return response return res.status(200).json({ code: 200, msg: "Time slots listed successfully", data: slots }); } catch (error) { console.error('Error listing time slots:', error); return res.status(500).json({ code: 500, msg: "Failed to list time slots" }); } }); router.post('/book-guided-walk', async function (req, res) { try { const { start, date, walk_id, members_count, user_id, pickup_location, walk_address } = req.body; // Assuming client sends start time and date of the slot to be booked const walkDetails = await rpgwalk_data.findById(walk_id); if (!walkDetails) { return res.status(400).json({ code: 400, msg: "Not a valid walk" }); } if (walkDetails.Walk_Type !== 'Guided Walk') { return res.status(400).json({ code: 400, msg: "Not a Guided walk" }); } if (walkDetails.Maximum_Persons_Allowed < members_count) { return res.status(400).json({ code: 400, msg: "Exceeding members allowed" }); } const duration = walkDetails.Walk_Duration // Parse the start time and date into JavaScript Date object const startTime = parseTimeString(start, date); // Add duration to start time to get end time const endTime = new Date(startTime.getTime() + duration * 60000); // Multiply by 60000 to convert minutes to milliseconds // Format the end time in the same format as start time (e.g., "11:30 am") const endTimeFormatted = formatTime(endTime); // Convert start time to UTC for comparison const startTimeUTC = startTime.toISOString(); // // Check if the slot is available for booking // const existingBooking = await GuidedWalkBooking.findOne({ time_slot: startTimeUTC }); // if (existingBooking) { // return res.status(400).json({ code: 400, msg: "Slot already booked" }); // } // Calculate the amount based on the number of members const amount = members_count * walkDetails.Amount_Per_Person; // Create a new booking entry const newBooking = new GuidedWalkBooking({ duration, time_slot: startTimeUTC, start, end: endTimeFormatted, date, walk_id, members_count, user_id, walk_address, pickup_location, amount: amount, }); // Save the new booking await newBooking.save(); return res.status(200).json({ code: 200, msg: "Slot booked successfully", data: newBooking }); } catch (error) { console.error('Error booking slot:', error); return res.status(500).json({ code: 500, msg: "Failed to book slot" }); } }); // Function to format time (e.g., "11:30 am") function formatTime(date) { const hours = date.getHours(); const minutes = date.getMinutes(); const ampm = hours >= 12 ? 'pm' : 'am'; const formattedHours = hours % 12 === 0 ? 12 : hours % 12; const formattedMinutes = minutes < 10 ? '0' + minutes : minutes; return `${formattedHours}:${formattedMinutes} ${ampm}`; } function parseTimeString(timeString, dateString) { const [hourMinute, meridiem] = timeString.split(' '); let [hour, minute] = hourMinute.split(':').map(Number); if (meridiem.toLowerCase() === 'pm' && hour < 12) { hour += 12; } else if (meridiem.toLowerCase() === 'am' && hour === 12) { hour = 0; } const [day, month, year] = dateString.split('-').map(Number); return new Date(year, month - 1, day, hour, minute, 0); } // PATCH /api/update-booking-details/:bookingId router.patch('/update-booking-details/:bookingId', async (req, res) => { try { const bookingId = req.params.bookingId; // Find the booking by ID const booking = await GuidedWalkBooking.findById(bookingId); if (!booking) { return res.status(404).json({ code: 404, msg: 'Booking not found' }); } const order = await createRazorpayOrder(booking.amount, booking.id) // const order = 'orderid' req.body.order_id = order.id // Update booking details with values from request body Object.assign(booking, req.body); // Save the updated booking await booking.save(); booking._doc.razor_key_id = process.env.RAZORPAY_KEY_ID booking._doc.razpr_merchant_id = process.env.RAZORPAY_MERCHEND_ID booking._doc.razpr_merchant_name = process.env.RAZORPAY_MERCHEND_NAME res.status(200).json({ code: 200, msg: 'Booking details updated successfully', data: booking }); } catch (error) { console.error('Error updating booking details:', error); res.status(500).json({ code: 500, msg: 'Failed to update booking details' }); } }); // PATCH /api/update-booking-details/:bookingId router.patch('/conform-booking/:bookingId', async (req, res) => { try { const bookingId = req.params.bookingId; // Find the booking by ID const booking = await GuidedWalkBooking.findById(bookingId).populate('walk_id user_id'); if (!booking) { return res.status(404).json({ code: 404, msg: 'Booking not found' }); } const ticketPdf = await generateTickets(booking) // Update booking details with values from request body Object.assign(booking, { is_paid: true, ticket_pdf: ticketPdf, payment_id: req.body.payment_id }); // Save the updated booking await booking.save(); res.status(200).json({ code: 200, msg: 'Booking confirmed successfully', data: booking }); } catch (error) { console.error('Error confirming booking details:', error); res.status(500).json({ code: 500, msg: 'Failed to update booking details' }); } }); // PATCH /api/update-booking-details/:bookingId router.patch('/cancel-booking/:bookingId', async (req, res) => { try { const bookingId = req.params.bookingId; // Find the booking by ID const booking = await GuidedWalkBooking.findById(bookingId); if (!booking) { return res.status(404).json({ code: 404, msg: 'Booking not found' }); } // Update booking details with values from request body Object.assign(booking, { is_paid: false }); // Save the updated booking await booking.save(); await processRazorpayRefund(booking.payment_id) res.status(200).json({ code: 200, msg: 'Booking canceled successfully', data: booking }); } catch (error) { console.error('Error canceling booking details:', error); res.status(500).json({ code: 500, msg: 'Failed to update booking details' }); } }); // PATCH /api/update-booking-details/:bookingId router.get('/list-bookings/:userId', async (req, res) => { try { const userId = req.params.userId; // Find the booking by ID const booking = await GuidedWalkBooking.find({ user_id: userId, is_paid: true }).sort('-created_at').populate('walk_id'); res.status(200).json({ code: 200, msg: 'Booking details listed successfully', data: booking }); } catch (error) { console.error('Error listing bookings:', error); res.status(500).json({ code: 500, msg: 'Failed to list bookings' }); } }); router.get('/ticket-details/:bookingId', async (req, res) => { try { const bookingId = req.params.bookingId; // Find the booking by ID const booking = await GuidedWalkBooking.findById(bookingId).populate('walk_id user_id'); if (!booking) { return res.status(404).json({ code: 404, msg: 'Booking not found' }); } res.status(200).json({ code: 200, msg: 'Ticket details retrived successfully', data: booking }); } catch (error) { console.error('Error listing bookings:', error); res.status(500).json({ code: 500, msg: 'Failed to list bookings' }); } }); router.post('/upload-image', upload.single('image'), async function (req, res) { try { const file = req.file; const filename = Date.now() + '.' + file.originalname.split('.').pop(); const fullnewfilenamepath = `Database/images/${filename}`; // Assuming uploadFileToS3 is a function to upload to AWS S3 const image = await uploadFileToS3(file.buffer, fullnewfilenamepath, file.mimetype); //const image = 'https://amble.theheritageproject.in/Walks/Thumbnails/map2-mapthumbnail.jpeg'; // Respond with success message return res.status(200).send({ code: 200, msg: "Image uploaded", data: image }); } catch (error) { console.error('Error uploading image:', error); // Respond with error message res.status(500).send({ code: 500, msg: "failed to upload image" }); } }); const generateTickets = async (data) => { const htmlContent = await generateInvoiceHTML(data); const pdfBuffer = await convertToPdfBuffer(htmlContent); const filename = Date.now() + '.' + 'pdf'; const fullNewFilenamePath = `Database/tickets/${filename}`; const ticket = await uploadFileToS3(pdfBuffer, fullNewFilenamePath, 'application/pdf'); return ticket; }; const convertToPdfBuffer = async (htmlContent) => { const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] }); const page = await browser.newPage(); await page.setContent(htmlContent); const pdfBuffer = await page.pdf({ format: 'A4', printBackground: true }); await browser.close(); return pdfBuffer; } const generateInvoiceHTML = async (data) => { const timeStr = timeToString(data.time_slot); const dateStr = dateToString(data.time_slot); const content = ` Background Image Page
Image Below Header

Ticket ID
${data._id}

Date
${dateStr}

Time
${timeStr}

Name
${data.user_id.Firstname} ${data.user_id.Lastname}

Number Of People
${data.members_count}

Walk Name
${data.walk_id.Map_Name}





Meeting Location
${data.walk_address}

Total Price
${data.amount}

` return content } function timeToString(date) { let hours = date.getHours(); let minutes = date.getMinutes(); const meridiem = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; // Handle midnight (0 hours) minutes = minutes < 10 ? '0' + minutes : minutes; return `${hours}:${minutes} ${meridiem}`; } function dateToString(date) { const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); // Month is zero-indexed const day = date.getDate().toString().padStart(2, '0'); return `${year}-${month}-${day}`; } router.get('/list-users', async (req, res) => { try { // Find the booking by ID const users = await newRpguserlistEntry.find(); res.status(200).json({ code: 200, msg: 'User list retrived successfully', data: users }); } catch (error) { console.error('Error listing users:', error); res.status(500).json({ code: 500, msg: 'Failed to list users' }); } }); router.post('/user-feedback', async function (req, res) { try { const banner = await UserFeedback.create({ User_Id: req.body.user_id, Description: req.body.description, Rating: req.body.rating, }); // Respond with success message return res.status(200).send({ code: 200, msg: "Feedback created", data: banner }); } catch (error) { console.error('Error creating feedback:', error); // Respond with error message return res.status(500).send({ code: 500, msg: "failed", data: { error: error.message } }); } }); router.get('/user-feedbacks', async function (req, res) { try { const banner = await UserFeedback.find().populate('User_Id'); // Respond with success message return res.status(200).send({ code: 200, msg: "Feedbacks listed", data: banner }); } catch (error) { console.error('Error listing feedback:', error); // Respond with error message return res.status(500).send({ code: 500, msg: "failed", data: { error: error.message } }); } }); router.patch('/guest-status-update', async function (req, res) { try { const result = await GuestToggle.findOneAndUpdate({}, { status: req.body.status }, { new: true }).select('-_id -created_at'); if (!result) { return res.status(404).json({ code: 404, msg: 'Guest toggle not found' }); } // Respond with success message return res.status(200).send({ code: 200, msg: "Guest toggle status changed", data: result }); } catch (error) { console.error('Error in changing toggle status:', error); // Respond with error message return res.status(500).send({ code: 500, msg: "failed", data: { error: error.message } }); } }); router.get('/check-guest-status', async function (req, res) { try { const result = await GuestToggle.findOne().select('-_id -created_at'); if (!result) { return res.status(404).json({ code: 404, msg: 'Guest toggle not found' }); } // Respond with success message return res.status(200).send({ code: 200, msg: "Guest toggle status fetched", data: result }); } catch (error) { console.error('Error in fetching toggle status:', error); // Respond with error message return res.status(500).send({ code: 500, msg: "failed", data: { error: error.message } }); } }); router.post('/guest-login', async function (req, res) { var MobileNo = req.body.MobileNo; const guest = await GuestToggle.findOne(); if (guest.status === true) { rpguser_data.findOne({ MobileNo: MobileNo }).then((result) => { if (result) { res.status(200).send({ code: 200, msg: "Success", result }); } else { res.status(404).send({ code: 404, msg: "No user found" }); } }); } else { res.status(400).send({ code: 400, msg: "Not in guest mode" }); } }); module.exports = router;