Sequelize Validation with condition object - javascript

const db = require("../models");
const Meet = db.meet;
checkDuplicateTime = (req, res, next) => {
Meet.findAll({
where: {
tanggal: req.body.date,
waktu: req.body.time
}
}).then(time => {
if(time --- (1000 * 60 * 60) || time +++ (2000 * 60 * 60)) {
res.status(400).send({
message: "Failed! Time already use!!"
});
return;
}
next();
});
});
}
How to inspection data from already in database with condition isBetween before and after time??
in Frontend, I succeed to do it like this :
timedi() {
const timede = this.dateCheck.filter((item) => {
return moment(item.dates).isSame(new Date(this.dates), "day")
}).some((item)=> {
const format = 'hh:mm:ss'
const time = moment(this.time, format) // from input user
const beforeTime = moment(item.time, format).add(-1, 'hours') // from already database
const afterTime = moment(item.time, format).add(2, 'hours'); // from already database
if(time.isBetween(beforeTime, afterTime)) {
console.log('Ignore')
} else {
console.log('Allow')
}
})
},
Hope there is an answer. Thanks.

Source code :
const db = require("../models");
const Meet = db.meet;
checkDuplicateDate = (req, res, next) => {
const dates = req.body.dated;
const times = req.body.timed;
const date = moment(dates).tz('Asia/Jakarta').format('YYYY-MM-DD');
const time = moment(times, [moment.ISO_8601, 'HH:mm']).tz('Asia/Jakarta').format('HH:mm:ss');
const startTime = moment(time, [moment.ISO_8601, 'HH:mm']).add(-2, 'hours').tz('Asia/Jakarta').format('HH:mm:ss');
const beforeTime = moment(time, [moment.ISO_8601, 'HH:mm']).add(2, 'hours').tz('Asia/Jakarta').format('HH:mm:ss');
Meet.findOne({
where: {
tanggal: date,
waktu: {
[Op.between]: [startTime, beforeTime]
}
}
}).then(meet => {
if(meet) {
res.status(400).send({
message: "Failed! Time is booked!!"
})
return
}
next();
});
});
};
I hope in future, this case can help anyone. Thanks.

Related

Firebase Cloud Functions Async

I am making a function for firebase cloud functions, I want a function to be called every time a new document is created in "posts". I want this function to perform the tasks that I put inside the "onCeatePost" function.
The problem I have is that I'm not sure if this is the correct way to structure such a function.
In several firebase examples I have seen that it is always called return _; or return null; at the end of a task, but I don't know how to structure the function so that all the tasks are carried out, could someone help me to restructure my function or tell me what is wrong please.
There are several if statements in the function, if the created publication does not comply with them, I would like it to skip them but continue with the other tasks that I put inside the function.
I don't know if it's too much to ask, but I'm new to this language and I haven't been able to find the answer I'm looking for. Thank you!
exports.onPostCreate = functions.firestore.document("/posts/{postId}").onCreate(async (snap) => {
const post = snap.data();
if (post) {
try {
const topic = post.topic;
const contentForFeed = post.contentForFeed;
const uid = post.uid;
const previous = post.prev;
await db.collection("users").doc(uid).update({"stats.posts": admin.firestore.FieldValue.increment(1)});
if (topic) {
await db.collection("topics").doc(topic.id).collection("user-authors").doc(uid).set({"date": snap.createTime});
}
if (contentForFeed == true) {
const userPath = db.collection("users").doc(uid);
await userPath.update({"stats.lastUpdate": snap.createTime});
}
if (previous) {
const previousId = previous.id;
const previousUid = previous.uid;
const refPrev = db.collection("posts").doc(previousId);
await db.runTransaction(async (t) => {
const doc = await t.get(refPrev);
const priority = doc.data().stats.date;
const newDate = new admin.firestore.Timestamp(priority.seconds + 120, priority.nanoseconds);
await db.collection("posts").doc(previousId).update({"newDate": newDate});
});
if (previousUid != uid) {
const path = db.collection("users").doc(uid).collection("user-posts");
const dataToSet = {"timestamp": snap.createTime, "uid": uid, "postId": onReplyToPostId};
await path(dataToSet);
}
}
} catch (err) {
functions.logger.log(err);
}
} else {
return null;
}
});
You'll find below the adapted code (untested) with 4 corrections.
Here are explanations for the two most important ones:
(Correction 2) In a transaction you need to use the transaction's update() method and not the "standard one"
(Correction 4) When all the asynchronous work is complete you need to return a value or a Promise. See this documntation page for more details.
exports.onPostCreate = functions.firestore
.document('/posts/{postId}')
.onCreate(async (snap) => {
const post = snap.data();
if (post) {
try {
const topic = post.topic;
const contentForFeed = post.contentForFeed;
const uid = post.uid;
const previous = post.prev;
await db
.collection('users')
.doc(uid)
.update({
'stats.posts': admin.firestore.FieldValue.increment(1),
});
if (topic) {
await db
.collection('topics')
.doc(topic.id)
.collection('user-authors')
.doc(uid)
.set({ date: snap.createTime });
}
if (contentForFeed == true) {
const userPath = db.collection('users').doc(uid);
await userPath.update({ 'stats.lastUpdate': snap.createTime });
}
let previousUid; // <= Correction 1
if (previous) {
const previousId = previous.id;
previousUid = previous.uid; // <= Correction 1
const refPrev = db.collection('posts').doc(previousId);
await db.runTransaction(async (t) => {
const doc = await t.get(refPrev);
const priority = doc.data().stats.date;
const newDate = new admin.firestore.Timestamp(
priority.seconds + 120,
priority.nanoseconds
);
t.update(refPrev, { newDate: newDate }); // <= Correction 2
});
if (previousUid != uid) {
const path = db
.collection('users')
.doc(uid)
.collection('user-posts');
const dataToSet = {
timestamp: snap.createTime,
uid: uid,
postId: onReplyToPostId,
};
await path.add(dataToSet); // <= Correction 3
}
}
return null; // <= Correction 4
} catch (err) {
functions.logger.log(err);
}
} else {
return null;
}
});

I need to apply a 24hour cooldown after use, and add to the token balance on a correct answer (discord.js v13)

Here is the challenge bot slash command:
const {
SlashCommandBuilder
} = require('#discordjs/builders');
const {
MessageEmbed,
MessageAttachment,
Role
} = require('discord.js');
const {
$where
} = require('../../schemas/balance');
const Challenge = require('../../schemas/challenge');
const challenges = require('./challenges.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('challenge')
.setDescription('Get your DAILY Fortune! Challenge and progress through the server!'),
async execute(interaction, message) {
const item = challenges[Math.floor(Math.random() * challenges.length)];
const filter = response => {
return response.author.id === interaction.user.id;
};
interaction.reply({
content: `${item.question}`,
ephemeral: true
})
.then(() => {
interaction.channel.awaitMessages({
filter,
max: 1,
time: 30000,
errors: ['time']
})
.then(collected => {
const response = collected.first().content;
collected.first().delete();
if (item.answers.includes(response.toLowerCase())) {
interaction.followUp({
content: `${collected.first().author} got the correct answer!`,
ephemeral: true
});
console.log("Challenge Answered Correct");
var guild = message.guilds.cache.get('948892863926771722');
var role = guild.roles.cache.find(role => role.name === 'Fortune Hunters');
var member = guild.members.cache.get(collected.first().author.id);
member.roles.add(role);
} else {
collected.first().delete();
interaction.followUp({
content: `Looks like you missed the answer this time, come back tomorrow for another chance to find your Fortune! with our daily challenges!`,
ephemeral: true
});
console.log("Challenge Answered Incorrectly");
}
})
.catch(collected => {
interaction.followUp({
content: 'You ran out of time!',
ephemeral: true
});
console.log("Timed Out");
});
});
},
};
And then I have the database setup but I'm not sure how to link it up how I did for the balance command. I think I set it up right, I made clones of the balance stuff and renamed it challenge which brought me up to the implementation into the actual command.
SCHEMA:
const mongoose = require('mongoose');
const challengeSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
guildId: String,
memberId: String,
amount: {type: Number, default: 0 },
correctAnswers: {type: Number, default: 0 },
wrongAnswers: {type: Number, default: 0 },
dateLastAnswered: { type: Date, default: Date.now },
});
module.exports = mongoose.model('Challenge', challengeSchema, 'challenges');
And then there's the createChallenge function:
const Balance = require('../schemas/challenge');
const mongoose = require("mongoose");
module.exports = (client) => {
client.createChallenge = async (member) => {
let challengeProfile = await Challenge.findOne({ memberId: member.id, guildId: member.guild.id });
if (challengeProfile) {
return challengeProfile;
} else {
challengeProfile = await new Challenge({
_id: mongoose.Types.ObjectId(),
guildId: member.guild.id,
memberId: member.id,
});
await challengeProfile.save().catch(err => console.log(err));
return challengeProfile;
console.log('The Challenge Database is live!');
}
};
};
I know the database is setup, because for the /balance command in mongo I can see the balances being updated with the user IDs and all that information. Here is what I have for the balance slash command:
const { SlashCommandBuilder } = require('#discordjs/builders');
const Balance = require('../../schemas/balance');
module.exports = {
data: new SlashCommandBuilder()
.setName('balance')
.setDescription('Returns info based on a user\'s balance.')
.addSubcommand(subcommand =>
subcommand
.setName("user")
.setDescription("Gets information of a user mentioned")
.addUserOption(option => option.setName("target").setDescription("The user mentioned"))),
async execute(interaction, client) {
let user = (interaction.options.getUser("target") ? interaction.options.getUser("target") : interaction.user);
const balanceProfile = await client.createBalance(interaction.member);
await interaction.reply({ content: `${interaction.user.tag} has ${balanceProfile.amount}$FP.`});
},
};
The balance schema:
const mongoose = require('mongoose');
const balanceSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
guildId: String,
memberId: String,
amount: {type: Number, default: 0 }
});
module.exports = mongoose.model('Balance', balanceSchema, 'balances');
Create balance function:
const Balance = require('../schemas/balance');
const mongoose = require("mongoose");
module.exports = (client) => {
client.createBalance = async (member) => {
let balanceProfile = await Balance.findOne({ memberId: member.id, guildId: member.guild.id });
if (balanceProfile) {
return balanceProfile;
} else {
balanceProfile = await new Balance({
_id: mongoose.Types.ObjectId(),
guildId: member.guild.id,
memberId: member.id,
});
await balanceProfile.save().catch(err => console.log(err));
return balanceProfile;
}
};
};
I hope all this information is helpful enough for someone to help... I've been struggling with this for about 9 hours now and it's killing me. I can't figure it out and we need to have this bot live this weekend. Any assistance you can give, I would greatly greatly appreciate! Like I mentioned what I'm trying to do is use the mongoDB database to store when someone does the /challenge command so that I can limit the command to being once per day, and assign an $FP balance reward with the reward role being given after 3 correct answers instead of just the first one.
Hey If your looking to schedule tasks please try this npm package
https://www.npmjs.com/package/cron
It will help.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0");
const day = today.getDay();
cron.schedule(`30 30 23 ${dd} ${mm} ${day}`, async () => {
await IssuesModel.markIssuesAsOverdue();
});
There is an example how I used it to mark issues in my app as overdue at the middle of the night.
I have since been able to solve this issue. Here is the finished code, now I just have to create the event handler that will assign a new addition to the balance when someone gets a correct answer:
const {
SlashCommandBuilder
} = require('#discordjs/builders');
const {
MessageEmbed,
MessageAttachment,
Role
} = require('discord.js');
const {
$where
} = require('../../schemas/balance');
const Challenge = require('../../schemas/challenge');
const challenges = require('./challenges.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('challenge')
.setDescription('Get your DAILY Fortune! Challenge and progress through the server!'),
async execute(interaction, message) {
const item = challenges[Math.floor(Math.random() * challenges.length)];
const filter = response => {
return response.author.id === interaction.user.id;
};
let user;
try {
//check if user has a challenge
user = await Challenge.findOne({
guildId: interaction.guild.id,
memberId: interaction.user.id
});
if (user) {
if (user.dateLastAnswered >= Date.now() - 86400000) {
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} seconds`;
}
interaction.reply({
content: `You have already claimed and answered your challenge for the day!\n\nBe sure to come back in ${timeString} to receive your next Fortune! Challenge!`,
ephemeral: true
});
return;
}
} else {
if (!user) {
//if user doesn't exist, create new challenge
const newChallenge = new Challenge({
guildId: String(interaction.guild.id),
memberId: String(interaction.user.id),
amount: 0,
correctAnswers: 0,
wrongAnswers: 0,
dateLastAnswered: Date.now()
});
await newChallenge.save();
user = await Challenge.findOne({
guildId: interaction.guild.id,
memberId: interaction.user.id
});
}
}
} catch (err) {
console.log(err);
}
interaction.reply({
content: `${item.question}`,
ephemeral: true
})
.then(() => {
interaction.channel.awaitMessages({
filter,
max: 1,
time: 1800000,
errors: ['time']
})
.then(async collected => {
const response = collected.first().content;
await collected.first().delete();
if (item.answers.includes(response.toLowerCase())) {
await interaction.followUp({
content: `${collected.first().author} has completed the challenge!`,
ephemeral: true
});
console.log("Challenge Answered Correct");
let guild = message.guilds.cache.get('948892863926771722');
var role = guild.roles.cache.find(role => role.name === 'Fortune Hunters');
var member = guild.members.cache.get(collected.first().author.id);
//if user exists, update their challenge
if (user) {
user.amount = user.amount + 1;
user.correctAnswers = user.correctAnswers + 1;
user.dateLastAnswered = Date.now();
await user.save();
if (user.correctAnswers >= 4) {
await interaction.followUp({
content: `Congratulations ${collected.first().author}, you have answered ${user.correctAnswers} challenges correct!\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345274883457084/correct.png`,
ephemeral: true
});
return;
}
if (user.correctAnswers === 3) {
await member.roles.add(role);
await interaction.followUp({
content: `Congratulations ${collected.first().author}, you have answered ${user.correctAnswers} out of THREE required challenges, and have earned the Fortune Hunters role!\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345274883457084/correct.png`,
ephemeral: true
});
} else {
//show time remaining until they can do next challenge
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} Hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} Minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} Seconds`;
}
await interaction.followUp({
content: `${collected.first().author} has completed ${user.correctAnswers} out of THREE challenges towards opening full server access! Come back tomorrow for more challenges, and continue your journey!\n\nTime Remaining Until Next Challenge: ${timeString}`,
ephemeral: true
});
}
}
} else {
//if user exists, update their challenge
if (user) {
user.amount = user.amount + 1;
user.wrongAnswers = user.wrongAnswers + 1;
user.dateLastAnswered = Date.now();
await user.save();
}
//show time remaining until they can do next challenge
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} Hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} Minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} Seconds`;
}
await interaction.followUp({
content: `Looks like you didn't get it right this time Fortune Hunter, but be sure to come back tomorrow for another chance to find your Fortune! with our daily challenges!\n\nTime Remaining Until Next Challenge: ${timeString}\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345275193831424/incorrect.png`,
ephemeral: true
});
console.log("Challenge Answered Incorrectly");
}
})
.catch(async collected => {
//show time remaining until they can do next challenge
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} Hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} Minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} Seconds`;
}
await interaction.followUp({
content: `You ran out of time! Please come back and try again tomorrow with another challenge.\n\nTime Remaining Until Next Challenge: ${timeString}\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345274635980900/timed_out.png`,
ephemeral: true
});
console.log("Timed Out");
});
});
},
};

Why does my ffmpeg audio sound slower and deeper - sample rate mismatch

ok so this is a discord bot to record voice chat
https://hatebin.com/hgjlazacri
Now the bot works perfectly fine but the issue is that the audio sounds a bit deeper and slower than normal.. Why does it happen? how can I make the audio sound 1:1..
const Discord = require('discord.js');
const client = new Discord.Client();
const ffmpegInstaller = require('#ffmpeg-installer/ffmpeg');
const ffmpeg = require('fluent-ffmpeg');
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
const fs = require('fs-extra')
const mergeStream = require('merge-stream');
const config = require('./config.json');
const { getAudioDurationInSeconds } = require('get-audio-duration');
const cp = require('child_process');
const path1 = require('path');
const Enmap = require('enmap');
const UserRecords = require("./models/userrecords.js")
const ServerRecords = require("./models/serverrecords.js")
let prefix = `$`
class Readable extends require('stream').Readable { _read() {} }
let recording = false;
let currently_recording = {};
let mp3Paths = [];
const silence_buffer = new Uint8Array(3840);
const express = require('express')
const app = express()
const port = 3000
const publicIP = require('public-ip')
const { program } = require('commander');
const { path } = require('#ffmpeg-installer/ffmpeg');
const version = '0.0.1'
program.version(version);
let debug = false
let runProd = false
let fqdn = "";
const mongoose = require("mongoose");
const MongoClient = require('mongodb').MongoClient;
mongoose.connect('SECRRET',{
useNewUrlParser: true
}, function(err){
if(err){
console.log(err);
}else{
console.log("Database connection initiated");
}
});
require("dotenv").config()
function bufferToStream(buffer) {
let stream = new Readable();
stream.push(buffer);
return stream;
}
client.commands = new Enmap();
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}`);
let host = "localhost"
let ip = await publicIP.v4();
let protocol = "http";
if (!runProd) {
host = "localhost"
} else {
host = `35.226.244.186`;
}
fqdn = `${protocol}://${host}:${port}`
app.listen(port, `0.0.0.0`, () => {
console.log(`Listening on port ${port} for ${host} at fqdn ${fqdn}`)
})
});
let randomArr = []
let finalArrWithIds = []
let variable = 0
client.on('message', async message => {
console.log(`fuck`);
if(message.content === `$record`){
mp3Paths = []
finalArrWithIds = []
let membersToScrape = Array.from(message.member.voice.channel.members.values());
membersToScrape.forEach((member) => {
if(member.id === `749250882830598235`) {
console.log(`botid`);
}
else {
finalArrWithIds.push(member.id)
}
})
const randomNumber = Math.floor(Math.random() * 100)
randomArr = []
randomArr.push(randomNumber)
}
const generateSilentData = async (silentStream, memberID) => {
console.log(`recordingnow`)
while(recording) {
if (!currently_recording[memberID]) {
silentStream.push(silence_buffer);
}
await new Promise(r => setTimeout(r, 20));
}
return "done";
}
console.log(generateSilentData, `status`)
function generateOutputFile(channelID, memberID) {
const dir = `./recordings/${channelID}/${memberID}`;
fs.ensureDirSync(dir);
const fileName = `${dir}/${randomArr[0]}.aac`;
console.log(`${fileName} ---------------------------`);
return fs.createWriteStream(fileName);
}
if (!fs.existsSync("public")) {
fs.mkdirSync("public");
}
app.use("/public", express.static("./public"));
if (!message.guild) return;
if (message.content === config.prefix + config.record_command) {
if (recording) {
message.reply("bot is already recording");
return
}
if (message.member.voice.channel) {
recording = true;
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('./audio.mp3');
connection.on('speaking', (user, speaking) => {
if (speaking.has('SPEAKING')) {
currently_recording[user.id] = true;
} else {
currently_recording[user.id] = false;
}
})
let members = Array.from(message.member.voice.channel.members.values());
members.forEach((member) => {
if (member.id != client.user.id) {
let memberStream = connection.receiver.createStream(member, {mode : 'pcm', end : 'manual'})
let outputFile = generateOutputFile(message.member.voice.channel.id, member.id);
console.log(outputFile, `outputfile here`);
mp3Paths.push(outputFile.path);
silence_stream = bufferToStream(new Uint8Array(0));
generateSilentData(silence_stream, member.id).then(data => console.log(data));
let combinedStream = mergeStream(silence_stream, memberStream);
ffmpeg(combinedStream)
.inputFormat('s32le')
.audioFrequency(44100)
.audioChannels(2)
.on('error', (error) => {console.log(error)})
.audioCodec('aac')
.format('adts')
.pipe(outputFile)
}
})
} else {
message.reply('You need to join a voice channel first!');
}
}
if (message.content === config.prefix + config.stop_command) {
let date = new Date();
let dd = String(date.getDate()).padStart(2, '0');
let mm = String(date.getMonth() + 1).padStart(2, '0');
let yyyy = date.getFullYear();
date = mm + '/' + dd + '/' + yyyy;
let currentVoiceChannel = message.member.voice.channel;
if (currentVoiceChannel) {
recording = false;
await currentVoiceChannel.leave();
let mergedOutputFolder = './recordings/' + message.member.voice.channel.id + `/${randomArr[0]}/`;
fs.ensureDirSync(mergedOutputFolder);
let file_name = `${randomArr[0]}` + '.aac';
let mergedOutputFile = mergedOutputFolder + file_name;
let download_path = message.member.voice.channel.id + `/${randomArr[0]}/` + file_name;
let mixedOutput = new ffmpeg();
console.log(mp3Paths, `mp3pathshere`);
mp3Paths.forEach((mp3Path) => {
mixedOutput.addInput(mp3Path);
})
console.log(mp3Paths);
//mixedOutput.complexFilter('amix=inputs=2:duration=longest');
mixedOutput.complexFilter('amix=inputs=' + mp3Paths.length + ':duration=longest');
let processEmbed = new Discord.MessageEmbed().setTitle(`Audio Processing.`)
processEmbed.addField(`Audio processing starting now..`, `Processing Audio`)
processEmbed.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/748610998985818202/speaker.png`)
processEmbed.setColor(` #00FFFF`)
const processEmbedMsg = await message.channel.send(processEmbed)
async function saveMp3(mixedData, outputMixed) {
console.log(`${mixedData} MIXED `)
return new Promise((resolve, reject) => {
mixedData.on('error', reject).on('progress',
async (progress) => {
let processEmbedEdit = new Discord.MessageEmbed().setTitle(`Audio Processing.`)
processEmbedEdit.addField(`Processing: ${progress.targetSize} KB converted`, `Processing Audio`)
processEmbedEdit.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/748610998985818202/speaker.png`)
processEmbedEdit.setColor(` #00FFFF`)
processEmbedMsg.edit(processEmbedEdit)
console.log('Processing: ' + progress.targetSize + ' KB converted');
}).on('end', () => {
console.log('Processing finished !');
resolve()
}).saveToFile(outputMixed);
console.log(`${outputMixed} IT IS HERE`);
})
}
// mixedOutput.saveToFile(mergedOutputFile);
await saveMp3(mixedOutput, mergedOutputFile);
console.log(`${mixedOutput} IN HEREEEEEEE`);
// We saved the recording, now copy the recording
if (!fs.existsSync(`./public`)) {
fs.mkdirSync(`./public`);
}
let sourceFile = `${__dirname}/recordings/${download_path}`
console.log(`DOWNLOAD PATH HERE ${download_path}`)
const guildName = message.guild.id;
const serveExist = `/public/${guildName}`
if (!fs.existsSync(`.${serveExist}`)) {
fs.mkdirSync(`.${serveExist}`)
}
let destionationFile = `${__dirname}${serveExist}/${file_name}`
let errorThrown = false
try {
fs.copySync(sourceFile, destionationFile);
} catch (err) {
errorThrown = true
await message.channel.send(`Error: ${err.message}`)
}
const usersWithTag = finalArrWithIds.map(user => `\n <#${user}>`);
let timeSpent = await getAudioDurationInSeconds(`public/${guildName}/${file_name}`)
let timesSpentRound = Math.floor(timeSpent)
let finalTimeSpent = timesSpentRound / 60
let finalTimeForReal = Math.floor(finalTimeSpent)
if(!errorThrown){
//--------------------- server recording save START
class GeneralRecords {
constructor(generalLink, date, voice, time) {
this.generalLink = generalLink;
this.date = date;
this.note = `no note`;
this.voice = voice;
this.time = time
}
}
let newGeneralRecordClassObject = new GeneralRecords(`${fqdn}/public/${guildName}/${file_name}`, date, usersWithTag, finalTimeForReal)
let checkingServerRecord = await ServerRecords.exists({userid: `server`})
if(checkingServerRecord === true){
existingServerRecord = await ServerRecords.findOne({userid: `server`})
existingServerRecord.content.push(newGeneralRecordClassObject)
await existingServerRecord.save()
}
if(checkingServerRecord === false){
let serverRecord = new ServerRecords()
serverRecord.userid = `server`
serverRecord.content.push(newGeneralRecordClassObject)
await serverRecord.save()
}
//--------------------- server recording save STOP
}
//--------------------- personal recording section START
for( member of finalArrWithIds) {
let personal_download_path = message.member.voice.channel.id + `/${member}/` + file_name;
let sourceFilePersonal = `${__dirname}/recordings/${personal_download_path}`
let destionationFilePersonal = `${__dirname}${serveExist}/${member}/${file_name}`
await fs.copySync(sourceFilePersonal, destionationFilePersonal);
const user = client.users.cache.get(member);
console.log(user, `user here`);
try {
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
ffmpeg(`public/${guildName}/${member}/${file_name}`)
.audioFilters('silenceremove=stop_periods=-1:stop_duration=1:stop_threshold=-90dB')
.output(`public/${guildName}/${member}/personal-${file_name}`)
.on(`end`, function () {
console.log(`DONE`);
})
.on(`error`, function (error) {
console.log(`An error occured` + error.message)
})
.run();
}
catch (error) {
console.log(error)
}
// ----------------- SAVING PERSONAL RECORDING TO DATABASE START
class PersonalRecords {
constructor(generalLink, personalLink, date, time) {
this.generalLink = generalLink;
this.personalLink = personalLink;
this.date = date;
this.note = `no note`;
this.time = time;
}
}
let timeSpentPersonal = await getAudioDurationInSeconds(`public/${guildName}/${file_name}`)
let timesSpentRoundPersonal = Math.floor(timeSpentPersonal)
let finalTimeSpentPersonal = timesSpentRoundPersonal / 60
let finalTimeForRealPersonal = Math.floor(finalTimeSpentPersonal)
let newPersonalRecordClassObject = new PersonalRecords(`${fqdn}/public/${guildName}/${file_name}`, `${fqdn}/public/${guildName}/${member}/personal-${file_name}`, date, finalTimeForRealPersonal)
let checkingUserRecord = await UserRecords.exists({userid: member})
if(checkingUserRecord === true){
existingUserRecord = await UserRecords.findOne({userid: member})
existingUserRecord.content.push(newPersonalRecordClassObject)
await existingUserRecord.save()
}
if(checkingUserRecord === false){
let newRecord = new UserRecords()
newRecord.userid = member
newRecord.content.push(newPersonalRecordClassObject)
await newRecord.save()
}
// ----------------- SAVING PERSONAL RECORDING TO DATABASE END
const endPersonalEmbed = new Discord.MessageEmbed().setTitle(`Your performance was amazing ! Review it here :D`)
endPersonalEmbed.setColor('#9400D3')
endPersonalEmbed.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/745381641324724294/vinyl.png`)
endPersonalEmbed.addField(`📅 Date`, `${date}`)
endPersonalEmbed.addField(`⏰ Time spent by you`, `${finalTimeForRealPersonal} minute(s)`)
endPersonalEmbed.addField(`🔻 Download`, `${fqdn}/public/${guildName}/${member}/personal-${file_name}`)
endPersonalEmbed.setFooter(`Use \`$myrecordings\` to get a list of all your recordings !`)
user.send(endPersonalEmbed)
}
// ----------------- personal recording section OVER
const endEmbed = new Discord.MessageEmbed().setTitle(`I will be honest, that recording session was sick !`)
endEmbed.setColor('#9400D3')
endEmbed.addField(`🎙️ Voices`, usersWithTag)
endEmbed.addField(`⏰ Time spent`, `${finalTimeForReal} minute(s)`)
endEmbed.addField(`🔻 Download`, `${fqdn}/public/${guildName}/${file_name}`)
endEmbed.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/745370416352067704/microphone.png`)
endEmbed.setFooter(`Check your DMs for a recording of your personal voice during this session.`)
message.channel.send(endEmbed)
} else {
message.reply('You need to join a voice channel first!');
}
}
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const cmd = client.commands.get(command);
if (!cmd) return;
cmd.run(client, message, args);
});
fs.readdir('./commands/', async (err, files) => {
if (err) return console.error;
files.forEach(file => {
if (!file.endsWith('.js')) return;
let props = require(`./commands/${file}`);
let cmdName = file.split('.')[0];
console.log(`Loaded command '${cmdName}'`);
// Register extra Listeners
client.commands.set(cmdName, props);
});
});
async function main() {
program.option('-debug')
program.option('-prod')
program.parse(process.argv)
console.log(program.opts())
if (program.Debug != undefined) {
debug = !debug
}
if (program.Prod != undefined) {
runProd = !runProd
}
if (runProd) {
client.login(process.env.DISCORD_TOKEN_PROD).catch(e => {
console.log("ERROR")
console.log(e)
})
} else {
client.login(process.env.DISCORD_TOKEN_TEST).catch(e => {
console.log("ERROR")
console.log(e)
})
}
}
main()
Now the bot works perfectly fine but the issue is that the audio sounds a bit deeper and slower than normal.. Why does it happen? how can I make the audio sound 1:1..
How do i fix the sample rate mismatch
Note; I have already tried to set Audio freq as 48000 but it has made no difference.

How to return REST API response after utility execution is finished in expressJs

I have written one POST endpoint in expressJS with node.when I a make call to API It runs a utility with setInterval() and I want to send the API response after utility executes clearInterval().
How I can I wait and send response after utility execution is finished?
Please see the code below
REST API code:
const router= express.Router();
const multer= require('multer');
const {readCSVFile}= require('../util/index');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads');
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now()+'.xlsx');
}
});
var upload = multer({storage: storage});
router.post('/fileUpload', upload.single('filename'), async (req, res) => {
readCSVFile();
res.status(201).json({id:1});
});
router.get('/',(req,res)=>{
res.sendFile(__dirname+'/index.html');
});
module.exports=router;
Utilty Code
const config = require('config')
const excelToJson = require('convert-excel-to-json')
const HttpsProxyAgent = require('https-proxy-agent')
const AWS = require('aws-sdk')
const json2xls = require('json2xls')
const fs = require('fs')
const awsConfig = {
httpOptions: {
agent: new HttpsProxyAgent(
config.get('aws.proxy')
),
}
}
AWS.config.credentials = new AWS.SharedIniFileCredentials({
profile: config.get('aws.profile'),
})
AWS.config.update(awsConfig)
let uuidv4 = require('uuid/v4')
let csv = [];
const lexRunTime = new AWS.LexRuntime({
region: config.get('aws.region'),
})
let refreshId
const readCSVFile = () => {
const csvSheet = excelToJson({
sourceFile: './Test.xlsx',
})
csvSheet.Sheet1.forEach(element => {
csv.push((element.A.slice(0, element.A.length)))
})
runTask()
refreshId = setInterval(runTask, 1000)
}
let botParams = {
botAlias: config.get('bot.alias'),
botName: config.get('bot.name'),
sessionAttributes: {},
}
const missedUtterancesArray = []
const matchedUtterancesArray = []
let start = 0
let end = 50
let count = 50
const runTask = () => {
let itemsProcessed = 0
console.log('executing...')
const arrayChunks = csv.slice(start, end)
arrayChunks.forEach((element) => {
botParams.inputText = element
botParams.userId = `${uuidv4()}`
lexRunTime.postText(botParams, function (err, data) {
itemsProcessed++
if (err) console.log(err, err.stack)
else {
if (data.intentName === null) {
missedUtterancesArray.push({
Utterance: element,
})
}
else{
matchedUtterancesArray.push({
Utterance: element,
})
}
}
if (itemsProcessed === arrayChunks.length) {
start = csv.indexOf(csv[end])
end = start + count
}
if (start === -1) {
let xls = json2xls(missedUtterancesArray)
fs.writeFileSync('./MissedUtterances.xlsx', xls, 'binary')
let matchedXls = json2xls(matchedUtterancesArray)
fs.writeFileSync('./MatchedUtterances.xlsx', matchedXls, 'binary')
console.log('File saved successfully!! ')
console.log('Total Matched utterances count: ',csv.length-missedUtterancesArray.length)
console.log('Total Missed utterances count: ',missedUtterancesArray.length)
console.log('Total Utterances count: ',csv.length)
clearInterval(refreshId)
}
})
})
}
I would have needed few more information to answer this but pardon my try if this does not work -
the setInterval method in the readCSVFile the reason. Being an asynchronous function, this will not stop the code progression.
lexRunTime.postText also looks like asynchronous. I think you'd be better off with using promises while responding to the client.

Redis how node return True in function async/await

forgive me the question.
I'm not used to node and sync / await
I have the following function which queries a mongodb returning a json, I'm saving that return on redis.
So far so good.
findLightnings: async (request, h) => {
const q = request.query.q.split(':');
const index = q[0];
const value = q[1].split(',');
const dateInit = new Date(request.query.dateInit);
const dateEnd = new Date(request.query.dateEnd);
const page = request.query.page;
const distance = request.query.distance;
const redis = require('redis');
const client = redis.createClient();
let limit = 300;
let filter = {
$and: [{
data: {
$gte: dateInit.toISOString(),
$lte: dateEnd.toISOString()
}
}]
}
if (index === 'latlng') {
filter['$and'][0]['geo.coordinates'] = {
$near: {
$geometry: {
type: 'Point',
coordinates: value.map(Number),
$minDistance: 0,
$maxDistance: distance
}
}
}
limit = 100;
} else {
filter['$and'][0][`cidade.${index}`] = {
$in: value
}
}
return client.get('elektro', async (err, reply) => {
let resp = null;
if (reply) {
console.log(reply); //<<<<<<<< Return Json OK
resp = reply // <<<<<<<<<< Return TRUE in json's place
} else {
console.log('db')
const query = await Lightning.find(filter).sort('data').skip(page*limit).limit(limit).exec();
client.set('elektro', JSON.stringify(query));
client.expire('elektro', 3600);
resp = query
}
return JSON.stringify(resp);
})
}
The problem is time to recover this data from the redis.
In the console log json appears normal, how much tento returns that value for the main function it comes 'TRUE' and not the json saved in redis.
Someone can give me a helping hand on this.
I really need this function.
const redis = require('redis');
const client = redis.createClient(6379);
const bluebird = require("bluebird");
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
const redisdata = await client.getAsync("user:photos");
if (redisdata) {
console.log(`cache EXISTS`)
return res.json({ source: 'cache', data: JSON.parse(redisdata) })
}
I was able to solve the problem with the redis client.getAsync().
which already has a native async function:
source: Node-redis
The final code is as follows:
findLightnings: async (request, h) => {
const q = request.query.q.split(':');
const index = q[0];
const value = q[1].split(',');
const dateInit = new Date(request.query.dateInit);
const dateEnd = new Date(request.query.dateEnd);
const page = request.query.page;
const distance = request.query.distance;
let limit = 300;
let filter = {
$and: [{
data: {
$gte: dateInit.toISOString(),
$lte: dateEnd.toISOString()
}
}]
}
if (index === 'latlng') {
filter['$and'][0]['geo.coordinates'] = {
$near: {
$geometry: {
type: 'Point',
coordinates: value.map(Number),
$minDistance: 0,
$maxDistance: distance
}
}
}
limit = 100;
} else {
filter['$and'][0][`cidade.${index}`] = {
$in: value
}
}
return getAsync('findLightnings'+ '/' + request.query.q + '/' + request.query.dateInit + '/' + request.query.dateEnd).then(async (res) => {
if(res){
console.log('Fonte Dados => redis')
return res
}else{
console.log('Fonte Dados => db')
try {
const query = await Lightning.find(filter).sort('data').exec();//.skip(page*limit).limit(limit).exec();
client.set('findLightnings'+ '/' + request.query.q + '/' + request.query.dateInit + '/' + request.query.dateEnd, JSON.stringify(query));
return query;
} catch (err) {
return Boom.badData(err);
}
}
client.close();
});
},

Categories

Resources