const GuildM = require('../models/guilds'); const STRIKES = require('../models/strikes'); const roleRulesM = require('../models/autoRoleRule'); const feedsM = require('../models/feeds'); const xmlparser = require('xml-js') const {isValidObjectId} = require('mongoose') exports.getUser = (io)=> { return(req,res)=> { fetch('https://discord.com/api/users/@me', { headers: { authorization: req.headers.authorization, }, }) .then(result=>result.json()) .then(response => { res.json(response); }) } }; exports.guildData = (io,bot)=> { return async (req, res)=> { let userGuilds = await fetch('https://discord.com/api/users/@me/guilds', { headers: { authorization: req.headers.authorization, }, }) .then(result => result.json()) .then(response => { if(response.message) return response.message return response.filter(x=>x.owner==true); }) var promises = []; if(typeof userGuilds == 'string') return res.json({Error:userGuilds}) for(var guild of userGuilds) { promises.push(new Promise((resolve, reject) => { (async (guild)=> { var aux = await getSpecificGuildData(guild.id); var roleRules = aux ? await getRoleRules(guild.id):null; var guildTextChannels = aux ? aux.TextChannels:null; var emojis = aux ? aux.emojis:null; var roles = aux ? aux.roles:null; const dataObject = { id:guild.id, music:aux.guild?aux.guild.guild[0].music:false, strikes:aux.guild?aux.guild.guild[0].strikes:false, allowInvites:aux?.guild?.guild[0]?.allowInvites, name:guild.name, icon:guild.icon?`https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.webp`:'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/discord-512.png', features:guild.features, hasRem:aux.extra?true:false, memberCount:aux.extra?aux.extra.memberCount:null, roleRules, guildTextChannels, emojis, roles }; resolve(dataObject); })(guild) })); } Promise.all(promises).then((values) => { return res.json(values); }); } async function getSpecificGuildData(guildID) { var extra = bot.guilds.cache.get(guildID) var guild = await GuildM.find({gID:guildID}) .then((guild,err)=> { if(err || guild.length==0) return; return {guild}; }); var TextChannels = []; var emojis = []; var roles = []; if(extra) { for(var channel of extra.channels.cache) { if(channel[1].type==0) { TextChannels.push( { 'id':channel[0], 'name':channel[1].name }); } } for(var emoji of extra.emojis.cache) { emojis.push( { 'id':emoji[0], 'name':emoji[1].name }); } for(var role of extra.roles.cache) { roles.push( { 'id':role[0], 'name':role[1].name }); } } return {guild, extra, TextChannels, emojis, roles}; } async function getRoleRules(guildid) { return await roleRulesM.find({gID:guildid}).then((err, rules)=> { if(err || rules.length==0) return return rules }) } } exports.updateGuild = (io)=> { return (req, res)=> { GuildM.findOne({gID:req.body.guildID}) .then( (guild, err)=> { if(err || guild.length) return res.json({Error:'No guild'}); guild[`${req.body.property}`] =! guild[`${req.body.property}`]; GuildM.updateOne({gID:req.body.guildID}, guild).then(()=> { return res.json(guild); }) }) } } exports.getMessage = (bot)=> { return async (req, res)=> { if(!req.headers.guildid && !req.headers.messageid) return res.json({error:'No gid or messageid or both.'}) const TextChannels = bot.guilds.cache.get(req.headers.guildid).channels.cache.filter(x=>x.type==0); TextChannels.forEach(channel => { (async (channel)=> { var message try { message = await channel.messages.fetch(req.headers.messageid); } catch (error) { //message doesn't exist on this channel or at all } if(message) { message = message.content if(message.split('***').length %2 == 1) message = message.replaceAll('***', ''); if(message.split('**').length %2 == 1) message = message.replaceAll('**', ''); if(message.split('*').length %2 == 1) message = message.replaceAll('*', ''); if(message.split('~~').length %2 == 1) message = message.replaceAll('~~', ''); if(message.split('```').length %2 == 1) message = message.replaceAll('```', ''); if(message.split('``').length %2 == 1) message = message.replaceAll('``', ''); if(message.split('`').length %2 == 1) message = message.replaceAll('`', ''); res.json({message}) } })(channel) }); } } exports.getRules = async (req,res)=> { var payload; if(req.headers.guildid) { payload = await roleRulesM.find({gID:req.headers.guildid}) .then(rules =>{return rules}) .catch(()=>{return null}) return res.json(payload); } payload = await roleRulesM.findOne({_id:req.headers.id}) .then(rule=>{return rule}) .catch(()=>{return null}) return res.json(payload); } exports.deleteRule = async (req, res)=> { var deleted = await roleRulesM.findByIdAndDelete(req.headers.ruleid) .then(()=>{return {success:'Done'}}) .catch(()=>{return {error:'Failed to delete'}}); res.json(deleted); } exports.updateRule = (bot)=> { return async (req, res)=> { let args = req.headers; if(args.isnew == 'true') { const validationResult = await confirmArgs(args); if (validationResult.error) return res.json({error:validationResult.error}) var rule = new roleRulesM(); rule.gID = validationResult.gID; rule.mID = validationResult.mID; rule.roleID = validationResult.roleID; rule.roleEmoji = validationResult.roleEmoji; rule.roleName = validationResult.roleName; rule.save(err=> { if(err)res.json(err); res.json({success:true,rule}) }) } else { const validationResult = await confirmArgs(args); if (validationResult.error) return res.json({error:validationResult.error}) roleRulesM.findOne({id:args.id}).then(rule=> { if(!rule) return res.json({error:'DB Error'}); rule.gID = validationResult.gID; rule.mID = validationResult.mID; rule.roleID = validationResult.roleID; rule.roleEmoji = validationResult.roleEmoji; rule.roleName = validationResult.roleName; roleRulesM.updateOne({_id:rule.id}, rule,{upsert:true}).then(updatedG=> { res.json({success:true, rule}) }) }) } } async function confirmArgs(args) { var mID = args.messageid; var roleID = args.roleid; var roleEmoji = args.emojiid; var gID = args.gid; var roleName; if(!mID) return {error:'Message ID'} if(!roleID) return {error:'Role ID'} if(!roleEmoji) return {error:'Emoji ID'} if(!gID) return {error:'Guild ID'} var m = await (async ()=> { for(const [id, channel] of bot.channels.cache) { if(channel.type == 0) { try { const exists = await bot.channels.cache.get(id).messages.fetch(mID); if(exists) return m = true; } catch (error) {} } } })(); const r = bot.guilds.cache.get(gID).roles.cache.get(roleID); const e = bot.guilds.cache.get(gID).emojis.cache.get(roleEmoji); bot.guilds.cache.get(gID).emojis.cache.forEach(emoji=> { if(emoji.name == 'tuturu') console.log(emoji) }) console.log('Emoji', roleEmoji, e) if(!m || !r || !e) return m?(r?(e?false:{error:'Emoji ID'}):{error:'Role ID'}):{error:'Message ID'} roleName = r.name; return {mID, roleID, roleEmoji, roleName, gID} } } exports.getFeeds = async (req, res)=> { var payload = await feedsM.find({gID:req.headers.guildid}).then(res=>{return res}).catch(err=>{return err}); res.json(payload) } exports.getFeed = async (req, res)=> { var payload = await feedsM.find({_id:req.headers.feedid}).then(res=>{return res}).catch(err=>{return err}); res.json(payload) } exports.getChannelName = async (req,res)=> { var payload = await fetch('https://www.youtube.com/feeds/videos.xml?channel_id='+req.headers.channelid, { method: "GET", mode: "cors", }) .then(response=> { if(response.ok) return response.text(); }) .then(data=> { data = xmlparser.xml2json(data, { compact: true, space: 4 }); data = JSON.parse(data); return data.feed.author.name._text }) .catch(error=> { return error; }); res.json(payload); } exports.checkChannel = async (req, res)=> { var url = req.headers.id; var regExp = '^(?:(?:https?:)?\/\/)?(?:www\.|(m\.)?)(youtube\.com|youtu\.be)(\/[^\s]*)?$'; var rE = new RegExp(regExp); if (rE.test(url)) { url = req.headers.id; } else { url = 'https://www.youtube.com/'+req.headers.id } var isValid = await fetch(url, { method: "GET", mode: "cors", }) .then(response=> { if(response.ok) return response.text(); }) .then(data=> { return data ? true :false }) .catch(error=> { return error; }); res.json(isValid) } exports.addFeed = (bot)=> { return async (req, res)=> { var headers= req.headers; var args = [headers.gid, headers.dcchannelid, headers.ytchannelid] const validationResult = await confirmArgs(args, bot); // console.log('Before new or old check', validationResult) if (validationResult.error) return res.json({error:validationResult.error}); if(!headers.feedid) { //new var feed = new feedsM(); feed.gID = headers.gid; feed.ChannelId = validationResult.channelId feed.YTChannelId = validationResult.YTChannelId; feed.CostumMessage = headers.costummessagei!=''?headers.costummessagei:'New video:'; feed.save(err=> { if(err)res.json({error:err}); res.json({success:true, feed}) }) } else { feedsM.findOne({id:args.id}).then(feed=> { if(!feed) return res.json({error:'DB Error'}); feed.gID = headers.gid; feed.ChannelId = validationResult.channelId feed.YTChannelId = validationResult.YTChannelId; feed.CostumMessage = headers.costummessagei!=''?headers.costummessagei:'New video:'; feedsM.updateOne({_id:feed.id}, feed,{upsert:true}).then(updatedG=> { res.json({success:true, feed}) }) }) } } } async function confirmArgs(args, bot) { var channelId = args[1]; var channelURL = args[2] async function getChannelId(url) { if(url.split('@').length<1) return return await fetch(url) .then(handleResponse) .then(handleData) .catch(handleError); function handleResponse(response) { if(response.ok) return response.text(); } function handleError(error) { return {error:'Bad youtube channel link.'}; } function handleData(data) { return data ? data.split('https://www.youtube.com/feeds/videos.xml?channel_id=')[1].split('"')[0] : false; } } const YTChannelId = await getChannelId(channelURL); if(YTChannelId.error) return {error:YTChannelId.error} const discordChannel = await bot.channels.fetch(channelId).then(channel=>{return channel }).catch(()=>{return null}); if(!discordChannel) return {error:'Provided discord channel id does not exist.'} var name = await fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${YTChannelId}`) .then(response => { return response.text() }) .then(data=> { data = xmlparser.xml2json(data, { compact: true, space: 4 }); data = JSON.parse(data); return data.feed.author.name._text }) .catch(error=>{return error;}); return {YTChannelId, channelId, name, channelName:discordChannel.name} } exports.deleteFeed = (req,res) => { feedsM.findOneAndDelete({_id:req.headers.feedid}).then(()=>{res.json({success:true})}).catch(error=>{res.json({error})}) } /** * *! '/strikes/:id/:userid/:strikeid?' */ exports.strikeDashboard = (bot)=> { return async (req, res)=> { // const user = bot.users.cache.get(req.params.userid) const guild = bot.guilds.cache.get(req.params.id); const strikes = await STRIKES.find({guildID:req.params.id}) const moderator = req.params.userid; res.render('strikesDashboard.ejs', {strikes, guild, moderator}) } } exports.getStrikes = (bot)=> { return async (req,res)=> { var strikes = await STRIKES.find({guildID:req.params.id}); const moderator = req.params.userid res.render('strikelist.ejs', {strikes}) } } exports.updateStrikes = (bot)=> { return async (req,res)=> { const strike = await STRIKES.findByIdAndUpdate(req.params.strikeid, {validated:true}); const strikes = await STRIKES.find({guildID:req.params.id}) const moderator = req.params.userid; res.render('strikelist.ejs', {strikes, moderator}) } } exports.deleteStrikes = (bot)=> { return async (req,res)=> { await STRIKES.findByIdAndDelete(req.params.strikeid); const strikes = await STRIKES.find({guildID:req.params.id}) const moderator = req.params.userid; res.render('strikelist.ejs', {strikes, moderator}) } }