123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681 |
- const cheerio = require('cheerio');
- const {defaultSettings, limit: {rcgcdw: rcgcdwLimit}} = require('../util/default.json');
- const Lang = require('../util/i18n.js');
- const allLangs = Lang.allLangs(true);
- const Wiki = require('../util/wiki.js');
- const {got, db, sendMsg, hasPerm} = require('./util.js');
- const display_types = [
- 'compact',
- 'embed',
- 'image',
- 'diff'
- ];
- const fieldset = {
- channel: '<label for="wb-settings-channel">Channel:</label>'
- + '<select id="wb-settings-channel" name="channel" required></select>',
- wiki: '<label for="wb-settings-wiki">Wiki:</label>'
- + '<input type="url" id="wb-settings-wiki" name="wiki" required>',
- //+ '<button type="button" id="wb-settings-wiki-search" class="collapsible">Search wiki</button>'
- //+ '<fieldset style="display: none;">'
- //+ '<legend>Wiki search</legend>'
- //+ '</fieldset>',
- lang: '<label for="wb-settings-lang">Language:</label>'
- + '<select id="wb-settings-lang" name="lang" required>'
- + Object.keys(allLangs.names).map( lang => {
- return `<option id="wb-settings-lang-${lang}" value="${lang}">${allLangs.names[lang]}</option>`
- } ).join('\n')
- + '</select>',
- display: '<span>Display mode:</span>'
- + '<div class="wb-settings-display">'
- + '<input type="radio" id="wb-settings-display-0" name="display" value="0" required>'
- + '<label for="wb-settings-display-0">Compact text messages with inline links.</label>'
- + '</div><div class="wb-settings-display">'
- + '<input type="radio" id="wb-settings-display-1" name="display" value="1" required>'
- + '<label for="wb-settings-display-1">Embed messages with edit tags and category changes.</label>'
- + '</div><div class="wb-settings-display">'
- + '<input type="radio" id="wb-settings-display-2" name="display" value="2" required>'
- + '<label for="wb-settings-display-2">Embed messages with image previews.</label>'
- + '</div><div class="wb-settings-display">'
- + '<input type="radio" id="wb-settings-display-3" name="display" value="3" required>'
- + '<label for="wb-settings-display-3">Embed messages with image previews and edit differences.</label>'
- + '</div>',
- feeds: '<label for="wb-settings-feeds">Feeds based changes:</label>'
- + '<input type="checkbox" id="wb-settings-feeds" name="feeds">'
- + '<div id="wb-settings-feeds-only-hide">'
- + '<label for="wb-settings-feeds-only">Only feeds based changes:</label>'
- + '<input type="checkbox" id="wb-settings-feeds-only" name="feeds_only">'
- + '</div>',
- save: '<input type="submit" id="wb-settings-save" name="save_settings">',
- delete: '<input type="submit" id="wb-settings-delete" name="delete_settings">'
- };
- /**
- * Create a settings form
- * @param {import('cheerio')} $ - The response body
- * @param {String} header - The form header
- * @param {Object} settings - The current settings
- * @param {Boolean} settings.patreon
- * @param {String} [settings.channel]
- * @param {String} settings.wiki
- * @param {String} settings.lang
- * @param {Number} settings.display
- * @param {Number} [settings.wikiid]
- * @param {Number} [settings.rcid]
- * @param {Object[]} guildChannels - The guild channels
- * @param {String} guildChannels.id
- * @param {String} guildChannels.name
- * @param {Number} guildChannels.userPermissions
- * @param {Number} guildChannels.botPermissions
- */
- function createForm($, header, settings, guildChannels) {
- var readonly = ( process.env.READONLY ? true : false );
- var curChannel = guildChannels.find( guildChannel => settings.channel === guildChannel.id );
- var fields = [];
- let channel = $('<div>').append(fieldset.channel);
- if ( !settings.channel || ( curChannel && hasPerm(curChannel.botPermissions, 'MANAGE_WEBHOOKS') && hasPerm(curChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) ) {
- channel.find('#wb-settings-channel').append(
- ...guildChannels.filter( guildChannel => {
- return ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') && hasPerm(guildChannel.botPermissions, 'MANAGE_WEBHOOKS') );
- } ).map( guildChannel => {
- var optionChannel = $(`<option id="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id);
- if ( settings.channel === guildChannel.id ) {
- optionChannel.attr('selected', '');
- }
- return optionChannel.text(`${guildChannel.id} – #${guildChannel.name}`);
- } )
- );
- if ( !settings.channel ) channel.find('#wb-settings-channel').prepend(
- $(`<option id="wb-settings-channel-default" selected>`).val('').text('-- Select a Channel --')
- );
- }
- else if ( curChannel ) channel.find('#wb-settings-channel').append(
- $(`<option id="wb-settings-channel-${curChannel.id}">`).val(curChannel.id).attr('selected', '').text(`${curChannel.id} – #${curChannel.name}`)
- );
- else channel.find('#wb-settings-channel').append(
- $(`<option id="wb-settings-channel-${settings.channel}">`).val(settings.channel).attr('selected', '').text(settings.channel)
- );
- fields.push(channel);
- let wiki = $('<div>').append(fieldset.wiki);
- wiki.find('#wb-settings-wiki').val(settings.wiki);
- fields.push(wiki);
- let lang = $('<div>').append(fieldset.lang);
- lang.find(`#wb-settings-lang-${settings.lang}`).attr('selected', '');
- fields.push(lang);
- let display = $('<div>').append(fieldset.display);
- display.find(`#wb-settings-display-${settings.display}`).attr('checked', '');
- if ( !settings.patreon ) display.find('.wb-settings-display').filter( (i, radioDisplay) => {
- return ( i > rcgcdwLimit.display && !$(radioDisplay).has('input:checked').length );
- } ).remove();
- fields.push(display);
- let feeds = $('<div id="wb-settings-feeds-hide">').append(fieldset.feeds);
- if ( /\.(?:fandom\.com|wikia\.org)$/.test(new URL(settings.wiki).hostname) ) {
- if ( settings.wikiid ) {
- feeds.find('#wb-settings-feeds').attr('checked', '');
- if ( settings.rcid === -1 ) feeds.find('#wb-settings-feeds-only').attr('checked', '');
- }
- else feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
- }
- else {
- feeds.attr('style', 'display: none;');
- feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
- }
- fields.push(feeds);
- fields.push($(fieldset.save).val('Save'));
- if ( settings.channel && curChannel && hasPerm(curChannel.userPermissions, 'MANAGE_WEBHOOKS') ) {
- fields.push($(fieldset.delete).val('Delete').attr('onclick', `return confirm('Are you sure?');`));
- }
- var form = $('<fieldset>').append(...fields);
- if ( readonly ) {
- form.find('input').attr('readonly', '');
- form.find('input[type="checkbox"], input[type="radio"]:not(:checked), option').attr('disabled', '');
- form.find('input[type="submit"], button.addmore').remove();
- }
- return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
- $('<h2>').text(header),
- form
- );
- }
- /**
- * Let a user change recent changes scripts
- * @param {import('http').ServerResponse} res - The server response
- * @param {import('cheerio')} $ - The response body
- * @param {import('./util.js').Guild} guild - The current guild
- * @param {String[]} args - The url parts
- */
- function dashboard_rcscript(res, $, guild, args) {
- db.all( 'SELECT discord.wiki mainwiki, discord.lang mainlang, webhook, configid, rcgcdw.wiki, rcgcdw.lang, display, wikiid, rcid FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild WHERE discord.guild = ? AND discord.channel IS NULL ORDER BY configid ASC', [guild.id], function(dberror, rows) {
- if ( dberror ) {
- console.log( '- Dashboard: Error while getting the RcGcDw: ' + dberror );
- $('#text .description').text('Failed to load the recent changes webhooks!');
- $('.channel#rcscript').addClass('selected');
- let body = $.html();
- res.writeHead(200, {'Content-Length': body.length});
- res.write( body );
- return res.end();
- }
- if ( rows.length === 0 ) {
- $('#text .description').text(`You need to set up the server first: /guild/${guild.id}/settings`);
- $('.channel#rcscript').addClass('selected');
- let body = $.html();
- res.writeHead(200, {'Content-Length': body.length});
- res.write( body );
- return res.end();
- }
- var wiki = rows[0].mainwiki;
- var lang = rows[0].mainlang;
- if ( rows.length === 1 && rows[0].configid === null ) rows.pop();
- $('#text .description').text(`These are the recent changes webhooks for "${guild.name}":`);
- Promise.all(rows.map( row => {
- return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( response => {
- if ( !response.body?.channel_id ) {
- console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the webhook: ' + response.body?.message );
- row.channel = 'UNKNOWN';
- }
- else row.channel = response.body.channel_id;
- }, error => {
- console.log( '- Dashboard: Error while getting the webhook: ' + error );
- row.channel = 'UNKNOWN';
- } );
- } )).finally( () => {
- $('#channellist #rcscript').after(
- ...rows.map( row => {
- return $('<a class="channel">').attr('id', `channel-${row.configid}`).append(
- $('<img>').attr('src', '/src/channel.svg'),
- $('<div>').text(`${row.configid} - ${( guild.channels.find( channel => {
- return channel.id === row.channel;
- } )?.name || row.channel )}`)
- ).attr('href', `/guild/${guild.id}/rcscript/${row.configid}`);
- } ),
- ( process.env.READONLY || rows.length >= rcgcdwLimit[( guild.patreon ? 'patreon' : 'default' )] ? '' :
- $('<a class="channel" id="channel-new">').append(
- $('<img>').attr('src', '/src/channel.svg'),
- $('<div>').text('New webhook')
- ).attr('href', `/guild/${guild.id}/rcscript/new`) )
- );
- if ( args[4] === 'new' ) {
- $('.channel#channel-new').addClass('selected');
- createForm($, 'New Recent Changes Webhook', {
- wiki, lang: ( lang in allLangs.names ? lang : defaultSettings.lang ),
- display: 1, patreon: guild.patreon
- }, guild.channels).attr('action', `/guild/${guild.id}/rcscript/new`).appendTo('#text');
- }
- else if ( rows.some( row => row.configid.toString() === args[4] ) ) {
- let row = rows.find( row => row.configid.toString() === args[4] );
- $(`.channel#channel-${row.configid}`).addClass('selected');
- createForm($, `Recent Changes Webhook #${row.configid}`, Object.assign({
- patreon: guild.patreon
- }, row), guild.channels).attr('action', `/guild/${guild.id}/rcscript/${row.configid}`).appendTo('#text');
- }
- else {
- $('.channel#rcscript').addClass('selected');
- $('#text .description').text(`*Insert explanation about recent changes webhooks here*`);
- }
- let body = $.html();
- res.writeHead(200, {'Content-Length': body.length});
- res.write( body );
- return res.end();
- } );
- } );
- }
- /**
- * Change recent changes scripts
- * @param {Function} res - The server response
- * @param {import('./util.js').Settings} userSettings - The settings of the user
- * @param {String} guild - The id of the guild
- * @param {String|Number} type - The setting to change
- * @param {Object} settings - The new settings
- * @param {String} settings.channel
- * @param {String} settings.wiki
- * @param {String} settings.lang
- * @param {Number} settings.display
- * @param {String} [settings.feeds]
- * @param {String} [settings.feeds_only]
- * @param {String} [settings.save_settings]
- * @param {String} [settings.delete_settings]
- */
- function update_rcscript(res, userSettings, guild, type, settings) {
- if ( type === 'default' ) {
- return res(`/guild/${guild}/rcscript?save=failed`);
- }
- if ( !settings.save_settings === !settings.delete_settings ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- if ( settings.save_settings ) {
- if ( !settings.wiki || !( settings.lang in allLangs.names ) ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- if ( !['0', '1', '2', '3'].includes( settings.display ) ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- settings.display = parseInt(settings.display, 10);
- if ( type === 'new' && !userSettings.guilds.isMember.get(guild).channels.some( channel => {
- return ( channel.id === settings.channel );
- } ) ) return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- if ( settings.delete_settings && type === 'new' ) {
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- if ( type === 'new' ) return sendMsg( {
- type: 'getMember',
- member: userSettings.user.id,
- guild: guild,
- channel: settings.channel
- } ).then( response => {
- if ( !response ) {
- userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
- userSettings.guilds.isMember.delete(guild);
- return res(`/guild/${guild}?save=failed`);
- }
- if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
- userSettings.guilds.isMember.delete(guild);
- return res('/?save=failed');
- }
- if ( response.message === 'noChannel' || !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS') || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- if ( settings.display > rcgcdwLimit.display && !response.patreon ) {
- settings.display = rcgcdwLimit.display;
- }
- return db.get( 'SELECT discord.lang, GROUP_CONCAT(configid) count FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild WHERE discord.guild = ? AND discord.channel IS NULL', [guild], function(curerror, row) {
- if ( curerror ) {
- console.log( '- Dashboard: Error while checking for RcGcDw: ' + curerror );
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- if ( !row ) return res(`/guild/${guild}/rcscript?save=failed`);
- if ( row.count === null ) row.count = [];
- else row.count = row.count.split(',').map( configid => parseInt(configid, 10) );
- if ( row.count.length >= rcgcdwLimit[( response.patreon ? 'patreon' : 'default' )] ) {
- return res(`/guild/${guild}/rcscript?save=failed`);
- }
- var wiki = Wiki.fromInput(settings.wiki);
- return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&titles=Special:RecentChanges&format=json' ).then( fresponse => {
- if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
- let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
- if ( api ) {
- wiki = new Wiki(api.split('api.php?')[0], wiki);
- return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&titles=Special:RecentChanges&format=json' );
- }
- }
- return fresponse;
- } ).then( fresponse => {
- var body = fresponse.body;
- if ( fresponse.statusCode !== 200 || !body?.query?.allmessages || !body?.query?.general || !body?.query?.pages?.['-1'] ) {
- console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- wiki.updateWiki(body.query.general);
- if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- if ( body.query.allmessages[0]['*'] !== guild ) {
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
- if ( blerror ) {
- console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- if ( block ) return res(`/guild/${guild}/rcscript/new?save=failed`);
- if ( settings.feeds ) {
- let wikiid = body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'];
- if ( wiki.isFandom(false) && wikiid ) return got.get( 'https://services.fandom.com/discussion/' + wikiid + '/posts?limit=1&format=json&cache=' + Date.now(), {
- headers: {
- Accept: 'application/hal+json'
- }
- } ).then( dsresponse => {
- var dsbody = dsresponse.body;
- if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
- if ( dsbody?.title !== 'site doesn\'t exists' ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
- return createWebhook();
- }
- return createWebhook(parseInt(wikiid, 10));
- }, error => {
- console.log( '- Dashboard: Error while checking for discussions: ' + error );
- return createWebhook();
- } );
- }
- return createWebhook();
- /**
- * Creates the webhook.
- * @param {Number} wikiid - The ID of the wiki.
- */
- function createWebhook(wikiid = null) {
- var lang = new Lang(row.lang);
- var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
- sendMsg( {
- type: 'createWebhook',
- guild: guild,
- channel: settings.channel,
- name: ( body.query.allmessages[1]['*'] || 'Recent changes' ),
- reason: lang.get('rcscript.audit_reason', wiki.href),
- text: webhook_lang.get('created', body.query.general.sitename) + ( wikiid && settings.feeds_only ? '' : `\n<${wiki.toLink(body.query.pages['-1'].title)}>` ) + ( wikiid ? `\n<${wiki.href}f>` : '' )
- } ).then( webhook => {
- if ( !webhook ) return res(`/guild/${guild}/rcscript/new?save=failed`);
- var configid = 1;
- for ( let i of row.count ) {
- if ( configid === i ) configid++;
- else break;
- }
- db.run( 'INSERT INTO rcgcdw(guild, configid, webhook, wiki, lang, display, wikiid, rcid) VALUES(?, ?, ?, ?, ?, ?, ?, ?)', [guild, configid, webhook, wiki.href, settings.lang, settings.display, wikiid, ( wikiid && settings.feeds_only ? -1 : null )], function (dberror) {
- if ( dberror ) {
- console.log( '- Dashboard: Error while adding the RcGcDw: ' + dberror );
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- }
- console.log( `- Dashboard: RcGcDw successfully added: ${guild}#${configid}` );
- res(`/guild/${guild}/rcscript/${configid}?save=success`);
- var text = lang.get('rcscript.dashboard.added', `<@${userSettings.user.id}>`, configid);
- text += `\n${lang.get('rcscript.channel')} <#${settings.channel}>`;
- text += `\n${lang.get('rcscript.wiki')} <${wiki.href}>`;
- text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[settings.lang]}\``;
- text += `\n${lang.get('rcscript.display')} \`${display_types[settings.display]}\``;
- if ( wikiid && settings.feeds_only ) text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
- if ( wiki.isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( wikiid ? 'enabled' : 'disabled' ))}\`*`;
- text += `\n<${new URL(`/guild/${guild}/rcscript/${configid}`, process.env.dashboard).href}>`;
- sendMsg( {
- type: 'notifyGuild', guild, text
- } ).catch( error => {
- console.log( '- Dashboard: Error while notifying the guild: ' + error );
- } );
- } );
- }, error => {
- console.log( '- Dashboard: Error while creating the webhook: ' + error );
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- } );
- }
- } );
- }, error => {
- console.log( '- Dashboard: Error while testing the wiki: ' + error );
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- } );
- } );
- }, error => {
- console.log( '- Dashboard: Error while getting the member: ' + error );
- return res(`/guild/${guild}/rcscript/new?save=failed`);
- } );
- type = parseInt(type, 10);
- return db.get( 'SELECT discord.lang mainlang, webhook, rcgcdw.wiki, rcgcdw.lang, display, wikiid, rcid FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild AND configid = ? WHERE discord.guild = ? AND discord.channel IS NULL', [type, guild], function(curerror, row) {
- if ( curerror ) {
- console.log( '- Dashboard: Error while checking for RcGcDw: ' + curerror );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- if ( !row?.webhook ) return res(`/guild/${guild}/rcscript?save=failed`);
- return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( wresponse => {
- if ( !wresponse.body?.channel_id ) {
- console.log( '- Dashboard: ' + wresponse.statusCode + ': Error while getting the webhook: ' + wresponse.body?.message );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- row.channel = wresponse.body.channel_id;
- var newChannel = false;
- if ( settings.save_settings && row.channel !== settings.channel ) {
- if ( !userSettings.guilds.isMember.get(guild).channels.some( channel => {
- return ( channel.id === settings.channel );
- } ) ) return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- newChannel = true;
- }
- return sendMsg( {
- type: 'getMember',
- member: userSettings.user.id,
- guild: guild,
- channel: row.channel,
- newchannel: ( newChannel ? settings.channel : undefined )
- } ).then( response => {
- if ( !response ) {
- userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
- userSettings.guilds.isMember.delete(guild);
- return res(`/guild/${guild}?save=failed`);
- }
- if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
- userSettings.guilds.isMember.delete(guild);
- return res('/?save=failed');
- }
- if ( response.message === 'noChannel' ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- if ( settings.delete_settings ) {
- if ( !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- return db.run( 'DELETE FROM rcgcdw WHERE webhook = ?', [row.webhook], function (delerror) {
- if ( delerror ) {
- console.log( '- Dashboard: Error while removing the RcGcDw: ' + delerror );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- console.log( `- Dashboard: RcGcDw successfully removed: ${guild}#${type}` );
- res(`/guild/${guild}/rcscript?save=success`);
- var lang = new Lang(row.mainlang);
- var webhook_lang = new Lang(row.lang, 'rcscript.webhook');
- got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
- json: {
- content: webhook_lang.get('deleted')
- }
- } ).then( delresponse => {
- if ( delresponse.statusCode !== 204 ) {
- console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
- }
- }, error => {
- console.log( '- Dashboard: Error while sending to the webhook: ' + error );
- } ).finally( () => {
- got.delete( 'https://discord.com/api/webhooks/' + row.webhook, {
- headers: {
- 'X-Audit-Log-Reason': lang.get('rcscript.audit_reason_delete')
- }
- } ).then( delresponse => {
- if ( delresponse.statusCode !== 204 ) {
- console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while removing the webhook: ' + delresponse.body?.message );
- }
- else console.log( `- Dashboard: Webhook successfully removed: ${guild}#${row.channel}` );
- }, error => {
- console.log( '- Dashboard: Error while removing the webhook: ' + error );
- } )
- } );
- var text = lang.get('rcscript.dashboard.deleted', `<@${userSettings.user.id}>`, type);
- text += `\n${lang.get('rcscript.channel')} <#${row.channel}>`;
- text += `\n${lang.get('rcscript.wiki')} <${row.wiki}>`;
- text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[row.lang]}\``;
- text += `\n${lang.get('rcscript.display')} \`${display_types[row.display]}\``;
- if ( row.rcid === -1 ) {
- text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
- }
- if ( new Wiki(row.wiki).isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( row.wikiid ? 'enabled' : 'disabled' ))}\`*`;
- text += `\n<${new URL(`/guild/${guild}/rcscript`, process.env.dashboard).href}>`;
- sendMsg( {
- type: 'notifyGuild', guild, text
- } ).catch( error => {
- console.log( '- Dashboard: Error while notifying the guild: ' + error );
- } );
- } );
- }
- if ( newChannel && ( !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS')
- || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
- || !hasPerm(response.userPermissionsNew, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
- || !hasPerm(response.botPermissionsNew, 'MANAGE_WEBHOOKS') ) ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- var diff = false;
- if ( newChannel ) diff = true;
- if ( row.wiki !== settings.wiki ) diff = true;
- if ( row.lang !== settings.lang ) diff = true;
- if ( row.display !== settings.display ) diff = true;
- if ( ( row.rcid !== -1 ) !== !( settings.feeds && settings.feeds_only ) ) diff = true;
- if ( !row.wikiid !== !settings.feeds ) diff = true;
- if ( !diff ) return res(`/guild/${guild}/rcscript/${type}?save=success`);
- var wiki = Wiki.fromInput(settings.wiki);
- return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&format=json' ).then( fresponse => {
- if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
- let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
- if ( api ) {
- wiki = new Wiki(api.split('api.php?')[0], wiki);
- return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&format=json' );
- }
- }
- return fresponse;
- } ).then( fresponse => {
- var body = fresponse.body;
- if ( fresponse.statusCode !== 200 || !body?.query?.allmessages || !body?.query?.general ) {
- console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- wiki.updateWiki(body.query.general);
- if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- if ( row.wiki !== wiki.href && body.query.allmessages[0]['*'] !== guild ) {
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
- if ( blerror ) {
- console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- if ( block ) return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- if ( settings.feeds ) {
- let wikiid = body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'];
- if ( wiki.isFandom(false) && wikiid ) return got.get( 'https://services.fandom.com/discussion/' + wikiid + '/posts?limit=1&format=json&cache=' + Date.now(), {
- headers: {
- Accept: 'application/hal+json'
- }
- } ).then( dsresponse => {
- var dsbody = dsresponse.body;
- if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
- if ( dsbody?.title !== 'site doesn\'t exists' ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
- return updateWebhook();
- }
- return updateWebhook(parseInt(wikiid, 10));
- }, error => {
- console.log( '- Dashboard: Error while checking for discussions: ' + error );
- return updateWebhook();
- } );
- }
- return updateWebhook();
- /**
- * Creates the webhook.
- * @param {Number} wikiid - The ID of the wiki.
- */
- function updateWebhook(wikiid = null) {
- db.run( 'UPDATE rcgcdw SET wiki = ?, lang = ?, display = ?, wikiid = ?, rcid = ? WHERE webhook = ?', [wiki.href, settings.lang, settings.display, wikiid, ( wikiid && settings.feeds_only ? -1 : null ), row.webhook], function (dberror) {
- if ( dberror ) {
- console.log( '- Dashboard: Error while updating the RcGcDw: ' + dberror );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- }
- console.log( `- Dashboard: RcGcDw successfully updated: ${guild}#${type}` );
- var lang = new Lang(row.mainlang);
- var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
- var diff = [];
- var webhook_diff = [];
- if ( newChannel ) {
- diff.push(lang.get('rcscript.channel') + ` ~~<#${row.channel}>~~ → <#${settings.channel}>`);
- webhook_diff.push(webhook_lang.get('dashboard.channel'));
- }
- if ( row.wiki !== wiki.href ) {
- diff.push(lang.get('rcscript.wiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
- webhook_diff.push(webhook_lang.get('dashboard.wiki', `[${body.query.general.sitename}](<${wiki.href}>)`));
- }
- if ( row.lang !== settings.lang ) {
- diff.push(lang.get('rcscript.lang') + ` ~~\`${allLangs.names[row.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
- webhook_diff.push(webhook_lang.get('dashboard.lang', allLangs.names[settings.lang]));
- }
- if ( row.display !== settings.display ) {
- diff.push(lang.get('rcscript.display') + ` ~~\`${display_types[row.display]}\`~~ → \`${display_types[settings.display]}\``);
- webhook_diff.push(webhook_lang.get('dashboard.display_' + display_types[settings.display]));
- }
- if ( ( row.rcid !== -1 ) !== !( wikiid && settings.feeds_only ) ) {
- diff.push(lang.get('rcscript.rc') + ` ~~*\`${lang.get('rcscript.' + ( row.rcid === -1 ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( settings.feeds_only ? 'disabled' : 'enabled' ))}\`*`);
- webhook_diff.push(webhook_lang.get('dashboard.' + ( settings.feeds_only ? 'disabled_rc' : 'enabled_rc' )));
- }
- if ( !row.wikiid !== !wikiid ) {
- diff.push(lang.get('rcscript.feeds') + ` ~~*\`${lang.get('rcscript.' + ( row.wikiid ? 'enabled' : 'disabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( wikiid ? 'enabled' : 'disabled' ))}\`*`);
- webhook_diff.push(webhook_lang.get('dashboard.' + ( wikiid ? 'disabled_feeds' : 'enabled_feeds' )));
- }
- if ( newChannel ) return sendMsg( {
- type: 'moveWebhook',
- guild: guild,
- webhook: row.webhook,
- channel: settings.channel,
- reason: lang.get('rcscript.audit_reason_move'),
- text: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
- } ).then( webhook => {
- if ( !webhook ) return Promise.reject();
- res(`/guild/${guild}/rcscript/${type}?save=success`);
- var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
- text += '\n' + diff.join('\n');
- text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
- sendMsg( {
- type: 'notifyGuild', guild, text
- } ).catch( error => {
- console.log( '- Dashboard: Error while notifying the guild: ' + error );
- } );
- }, error => {
- console.log( '- Dashboard: Error while moving the webhook: ' + error );
- return Promise.reject();
- } ).catch( () => {
- res(`/guild/${guild}/rcscript/${type}?save=partial`);
- diff.shift();
- webhook_diff.shift();
- got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
- json: {
- content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
- }
- } ).then( delresponse => {
- if ( delresponse.statusCode !== 204 ) {
- console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
- }
- }, error => {
- console.log( '- Dashboard: Error while sending to the webhook: ' + error );
- } )
- var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
- text += '\n' + diff.join('\n');
- text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
- sendMsg( {
- type: 'notifyGuild', guild, text
- } ).catch( error => {
- console.log( '- Dashboard: Error while notifying the guild: ' + error );
- } );
- } );
- res(`/guild/${guild}/rcscript/${type}?save=success`);
- got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
- json: {
- content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
- }
- } ).then( delresponse => {
- if ( delresponse.statusCode !== 204 ) {
- console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
- }
- }, error => {
- console.log( '- Dashboard: Error while sending to the webhook: ' + error );
- } )
- var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
- text += '\n' + diff.join('\n');
- text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
- sendMsg( {
- type: 'notifyGuild', guild, text
- } ).catch( error => {
- console.log( '- Dashboard: Error while notifying the guild: ' + error );
- } );
- } );
- }
- } );
- }, error => {
- console.log( '- Dashboard: Error while testing the wiki: ' + error );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- } );
- }, error => {
- console.log( '- Dashboard: Error while getting the member: ' + error );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- } );
- }, error => {
- console.log( '- Dashboard: Error while getting the webhook: ' + error );
- return res(`/guild/${guild}/rcscript/${type}?save=failed`);
- } );
- } );
- }
- module.exports = {
- get: dashboard_rcscript,
- post: update_rcscript
- };
|