Skip to content

Commit

Permalink
Added: Some change for file download
Browse files Browse the repository at this point in the history
  • Loading branch information
shreyvishal committed Apr 8, 2024
1 parent 73f35d8 commit 751d3da
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 8 deletions.
44 changes: 41 additions & 3 deletions controllers/Bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import logger from '../utils/logger.js'
import {db} from '../server.js'
import { v4 as uuidv4 } from 'uuid'
import MapsService from '../services/MapService.js'
import { fileURLToPath } from 'url';
import path from 'path'
const mapService = new MapsService()


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import CronService from '../services/CronService.js'
const actionsService = new ActionsService()

Expand Down Expand Up @@ -395,9 +398,44 @@ async function process_action(action, text, session, sender=null, format='applic
})
}
}


async function webhookControl (req, res) {
try{
console.log("Body",req.body)
const sessions = await db.get_data('')
console.log(JSON.stringify(sessions))
return res.status(200).json({
status:true,
message:'Notification Sent'
})
}catch(error){
return res.status(400).json({
status:false,
message:'Some Error Occured'
})
}
}

async function downloadFile (req, res) {
try{
const url = "https://maps.googleapis.com/maps/api/staticmap?size=300x300&path=enc:yrpqF`|x_SoFxgCwfApWyeBqkCa`Cq\_pHk`@qiLji@iuUo|@qoZaHwiRdFmgS|g@_dQn^eoXzy@ynO}AicKao@swPwjCo}U{vGofLceCwsEwzAuhFmdF{tNqoAg`PoKgoVngEgzLrm@}`FppB_mJgGsqD_zAanK{hDiyDshAqaEqdAwzBrf@izHao@ksAmjEikCeQmzHh_JocFnwEefDjeGswFtuCk|Tz~AavDllBosEfiAefInk@sfOd`FqlDhv@{yGwFivKuMmwM{{A}tEE{jF|m@guNpbTqoEncKibGpyIkqCh~K}hAhiKul@buAa`Bd`BwlBl~BsLz`JiwAlpTmoBnkOcu@h}N{oBb}YsNv}x@o~A`}VecAnrArf@zyImoDfnMacCtsGoyJpw^}nEjsGcwCxpIs^dzM|u@haQi}AjcP{vA|cNuiCdz_@ahGzyMwbCpjPpHh}b@gmCh}Ocn@d_R{aDthRwnCjrHsQl}IeyAlaPo|C|a@i{B`iAouFtJgjGuz@urAfdBwnEtiG{mBxLswEic@swBcFa`BmbA}dAxiAut@trAwcA}r@alB`eAm}@`rBeuD`t@sfI|o@{K{w@_o@`OjC|aBnc@jxB_o@`rAawBfr@{bDnpHamG`dNc{E`zJihJjr@i_Dm^}qCpk@swD`bCcdExjI}fHteM}vC`jIg|D|uDusIbuLefDvsFoqDdwH_y@`mBk_EsX_jFc`GcyAfd@eu@xyCctDhiEg_FrcHseFdxC{uEdeBiiBjqC_tDts@srLroAct@b{AcThpAiiBt]sx@viAkjHznHcjEjfDgpJ|bIs_F~_C}jBl`@|qAb{Ajy@zzI{w@zl@hHxy@az@o@r\le@n_@h|AWxzAeeA~`Eg`Dji@toAv[ay@~Pl^pGmi@vn@q^tFnc@duBqvAeXcIfw@uUbb@ayA}@}hC`~Bg_CdoCk{BjuDafAxcC`~@jaDlm@`eDyNr}Cyr@j{E}_CpoAqfDdxCw`CpcFqiCfhLasE~uJaaEdaD{hBtkDjQlmDjwBdoMb@|{Hv`MlqFfwDnoEdsEh~IeJftD{fDdzEksBpmHxAx}EnVlhIgz@f`DbZfwA|p@kmAfsB_`BpbAmc@~}AzmAoUdtAtjAl[xyAbqC~gA~eAxnBsHzfBuDldBnwAlk@kOfj@v{@pqAxzBrbEzdBhxBdYhmGmhGlhDm}BzaCo_G|[krBp_DuWp~DjgFreC~yBdrAquBpqE`_CxlAlpDd{AhtE_mCpcD~YdkDh_Cbx@~cC~`C&key=AIzaSyD1nA0k1OsFbmIAqD7N1nYrAI6CqkZbHDc"
const download_file_resp = await actionsService.download_file(url,path.join(__dirname,'../public'))
return res.status(200).json({
status:true,
message:download_file_resp.message
})
}catch(error){
return res.status(400).json({
status:false,
message:'Some Error Occured'
})
}
}

export default {
process_wa_webhook,
process_text,
notifyStatusUpdate
notifyStatusUpdate,
webhookControl,
downloadFile
}
14 changes: 11 additions & 3 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import dotenv from 'dotenv'
import cors from 'cors'
import path from 'path'
import { fileURLToPath } from 'url';
dotenv.config()
import express from 'express'
import bodyParser from 'body-parser'
Expand All @@ -11,30 +13,36 @@ import {
cancelBooking,
updateCatalog,
notify,
triggerExceptionOnLocation,
updateStatus,
unpublishItem
unpublishItem,
} from './controllers/ControlCenter.js'
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express()
app.use(cors())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use('/static', express.static(path.join(__dirname, 'public')));
// Define endpoints here
// app.post('/act', actions.act)
app.post('/webhook', messageController.process_text)
app.post('/notify', notify)
app.post('/cancel-booking', cancelBooking)
app.post('/update-catalog', updateCatalog)
app.post('/trigger-exception', triggerExceptionOnLocation)
app.post('/update-status', updateStatus)
app.get('/notify-status', messageController.notifyStatusUpdate)
app.post('/unpublish-item', unpublishItem)
app.post('/webhook-ps', messageController.webhookControl)
app.get('/download', messageController.downloadFile);
// Reset all sessions
export const db = new DBService()

await db.clear_all_sessions()
// await db.clear_all_sessions()
await db.set_data('orderDetails', ORDER_DETAILS)

// Start the Express server
Expand Down
26 changes: 25 additions & 1 deletion services/Actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import twilio from 'twilio'
import logger from '../utils/logger.js'
import axios from 'axios'
import AI from './AI.js'

import path from 'path'
import { writeFileSync,createWriteStream } from 'fs';
const accountSid = process.env.TWILIO_ACCOUNT_SID
const authToken = process.env.TWILIO_AUTH_TOKEN
const twilioNumber = process.env.TWILIO_NUMBER
Expand Down Expand Up @@ -123,6 +124,29 @@ class Actions {
return false;
}
}

async download_file(url, destination_path) {
try {
const response = await axios.get(url, 'GET',{responseType:'arraybuffer'});

const filePath = path.join(destination_path, 'downloaded-image.png');
// const writer = createWriteStream(filePath);
console.log(Buffer.from(response.data));
writeFileSync(filePath, response.data);
// response.data.pipe(writer);
// return new Promise((resolve, reject) => {
// writer.on('finish', resolve);
// writer.on('error', reject);
// });
return {
message:'File downloaded successfully and saved at ' + filePath
}
} catch (error) {
logger.error(`Error sending message: ${error.message}`)
return false;
}
}

}

export default Actions
2 changes: 1 addition & 1 deletion tests/unit/controllers/bot.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ describe('Test cases for Google maps', () => {
expect(source_gps).to.have.property('lng');
})

it('It should take a trip plannign input and generate static route image and directions link.', async () => {
it.only('It should take a trip plannign input and generate static route image and directions link.', async () => {
const ask = "Can you plean a trip from Denver to Yellowstone national park?";

// identify source and destination
Expand Down

0 comments on commit 751d3da

Please sign in to comment.