rcscript.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. const cheerio = require('cheerio');
  2. const {defaultSettings, limit: {rcgcdw: rcgcdwLimit}} = require('../util/default.json');
  3. const Lang = require('../util/i18n.js');
  4. const allLangs = Lang.allLangs(true);
  5. const Wiki = require('../util/wiki.js');
  6. const {got, db, sendMsg, createNotice, hasPerm} = require('./util.js');
  7. const display_types = [
  8. 'compact',
  9. 'embed',
  10. 'image',
  11. 'diff'
  12. ];
  13. const avatar_content_types = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
  14. const fieldset = {
  15. channel: '<label for="wb-settings-channel">Channel:</label>'
  16. + '<select id="wb-settings-channel" name="channel" required></select>',
  17. name: '<label for="wb-settings-name">Webhook name:</label>'
  18. + '<input type="text" id="wb-settings-name" name="name" minlength="2" maxlength="32" autocomplete="on">',
  19. avatar: '<label for="wb-settings-avatar">Webhook avatar:</label>'
  20. + '<input type="url" id="wb-settings-avatar" name="avatar" list="wb-settings-avatar-list" autocomplete="url">'
  21. + '<datalist id="wb-settings-avatar-list"></datalist>'
  22. + '<button type="button" id="wb-settings-avatar-preview">Preview</button>',
  23. wiki: '<label for="wb-settings-wiki">Wiki:</label>'
  24. + '<input type="url" id="wb-settings-wiki" name="wiki" list="wb-settings-wiki-list" required autocomplete="url">'
  25. + '<datalist id="wb-settings-wiki-list"></datalist>'
  26. + '<button type="button" id="wb-settings-wiki-check">Check wiki</button>'
  27. + '<div id="wb-settings-wiki-check-notice"></div>',
  28. //+ '<button type="button" id="wb-settings-wiki-search" class="collapsible">Search wiki</button>'
  29. //+ '<fieldset style="display: none;">'
  30. //+ '<legend>Wiki search</legend>'
  31. //+ '</fieldset>',
  32. lang: '<label for="wb-settings-lang">Language:</label>'
  33. + '<select id="wb-settings-lang" name="lang" required autocomplete="language">'
  34. + Object.keys(allLangs.names).map( lang => {
  35. return `<option id="wb-settings-lang-${lang}" value="${lang}">${allLangs.names[lang]}</option>`
  36. } ).join('')
  37. + '</select>'
  38. + '<img id="wb-settings-lang-widget">',
  39. display: '<span>Display mode:</span>'
  40. + '<div class="wb-settings-display">'
  41. + '<input type="radio" id="wb-settings-display-0" name="display" value="0" required>'
  42. + '<label for="wb-settings-display-0" class="radio-label">Compact text messages with inline links.</label>'
  43. + '</div><div class="wb-settings-display">'
  44. + '<input type="radio" id="wb-settings-display-1" name="display" value="1" required>'
  45. + '<label for="wb-settings-display-1" class="radio-label">Embed messages with edit tags and category changes.</label>'
  46. + '</div><div class="wb-settings-display">'
  47. + '<input type="radio" id="wb-settings-display-2" name="display" value="2" required>'
  48. + '<label for="wb-settings-display-2" class="radio-label">Embed messages with image previews.</label>'
  49. + '</div><div class="wb-settings-display">'
  50. + '<input type="radio" id="wb-settings-display-3" name="display" value="3" required>'
  51. + '<label for="wb-settings-display-3" class="radio-label">Embed messages with image previews and edit differences.</label>'
  52. + '</div>',
  53. feeds: '<label for="wb-settings-feeds">Feeds based changes:</label>'
  54. + '<input type="checkbox" id="wb-settings-feeds" name="feeds">'
  55. + '<div id="wb-settings-feeds-only-hide">'
  56. + '<label for="wb-settings-feeds-only">Only feeds based changes:</label>'
  57. + '<input type="checkbox" id="wb-settings-feeds-only" name="feeds_only">'
  58. + '</div>',
  59. save: '<input type="submit" id="wb-settings-save" name="save_settings">',
  60. delete: '<input type="submit" id="wb-settings-delete" name="delete_settings" formnovalidate>'
  61. };
  62. /**
  63. * Create a settings form
  64. * @param {import('cheerio')} $ - The response body
  65. * @param {String} header - The form header
  66. * @param {import('./i18n.js')} dashboardLang - The user language
  67. * @param {Object} settings - The current settings
  68. * @param {Boolean} settings.patreon
  69. * @param {String} [settings.channel]
  70. * @param {String} [settings.name]
  71. * @param {String} [settings.avatar]
  72. * @param {String} settings.wiki
  73. * @param {String} settings.lang
  74. * @param {Number} settings.display
  75. * @param {Number} [settings.rcid]
  76. * @param {String} [settings.postid]
  77. * @param {import('./util.js').Channel[]} guildChannels - The guild channels
  78. * @param {String[]} allWikis - The guild wikis
  79. */
  80. function createForm($, header, dashboardLang, settings, guildChannels, allWikis) {
  81. var readonly = ( process.env.READONLY ? true : false );
  82. var curChannel = guildChannels.find( guildChannel => settings.channel === guildChannel.id );
  83. var fields = [];
  84. let channel = $('<div>').append(fieldset.channel);
  85. channel.find('label').text(dashboardLang.get('rcscript.form.channel'));
  86. let curCat = null;
  87. if ( !settings.channel || ( curChannel && hasPerm(curChannel.botPermissions, 'MANAGE_WEBHOOKS') && hasPerm(curChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) ) {
  88. channel.find('#wb-settings-channel').append(
  89. ...guildChannels.filter( guildChannel => {
  90. return ( ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') && hasPerm(guildChannel.botPermissions, 'MANAGE_WEBHOOKS') ) || guildChannel.isCategory );
  91. } ).map( guildChannel => {
  92. if ( guildChannel.isCategory ) {
  93. curCat = $('<optgroup>').attr('label', guildChannel.name);
  94. return curCat;
  95. }
  96. var optionChannel = $(`<option id="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – #${guildChannel.name}`);
  97. if ( settings.channel === guildChannel.id ) {
  98. optionChannel.attr('selected', '');
  99. }
  100. if ( !curCat ) return optionChannel;
  101. optionChannel.appendTo(curCat);
  102. } ).filter( catChannel => {
  103. if ( !catChannel ) return false;
  104. if ( catChannel.is('optgroup') && !catChannel.children('option').length ) return false;
  105. return true;
  106. } )
  107. );
  108. if ( !settings.channel ) {
  109. if ( !channel.find('#wb-settings-channel').children().length ) {
  110. createNotice($, 'missingperm', dashboardLang, ['Manage Webhooks']);
  111. }
  112. channel.find('#wb-settings-channel').prepend(
  113. $(`<option id="wb-settings-channel-default" selected hidden>`).val('').text(dashboardLang.get('rcscript.form.select_channel'))
  114. );
  115. }
  116. }
  117. else if ( curChannel ) channel.find('#wb-settings-channel').append(
  118. $(`<option id="wb-settings-channel-${curChannel.id}">`).val(curChannel.id).attr('selected', '').text(`${curChannel.id} – #${curChannel.name}`)
  119. );
  120. else channel.find('#wb-settings-channel').append(
  121. $(`<option id="wb-settings-channel-${settings.channel}">`).val(settings.channel).attr('selected', '').text(settings.channel)
  122. );
  123. fields.push(channel);
  124. let webhook_name = $('<div>').append(fieldset.name);
  125. webhook_name.find('label').text(dashboardLang.get('rcscript.form.name'));
  126. webhook_name.find('#wb-settings-name').val(settings.name);
  127. fields.push(webhook_name);
  128. let avatar = $('<div>').append(fieldset.avatar);
  129. avatar.find('label').text(dashboardLang.get('rcscript.form.avatar'));
  130. avatar.find('#wb-settings-avatar-preview').text(dashboardLang.get('rcscript.form.avatar_preview'));
  131. avatar.find('#wb-settings-avatar').val(( settings.avatar || '' ));
  132. if ( settings.avatar ) avatar.find('#wb-settings-avatar').attr('size', settings.avatar.length + 10);
  133. avatar.find('#wb-settings-avatar-list').append(
  134. $(`<option>`).val(new URL('/src/icon.png', process.env.dashboard).href),
  135. ( settings.avatar ? $(`<option>`).val(settings.avatar) : null )
  136. );
  137. fields.push(avatar);
  138. let wiki = $('<div>').append(fieldset.wiki);
  139. wiki.find('label').text(dashboardLang.get('rcscript.form.wiki'));
  140. wiki.find('#wb-settings-wiki-check').text(dashboardLang.get('rcscript.form.wiki_check'));
  141. wiki.find('#wb-settings-wiki').val(settings.wiki);
  142. wiki.find('#wb-settings-wiki-list').append(
  143. ...allWikis.map( listWiki => $(`<option>`).val(listWiki) )
  144. );
  145. fields.push(wiki);
  146. let lang = $('<div>').append(fieldset.lang);
  147. lang.find('label').text(dashboardLang.get('rcscript.form.lang'));
  148. lang.find(`#wb-settings-lang-${settings.lang}`).attr('selected', '');
  149. fields.push(lang);
  150. let display = $('<div>').append(fieldset.display);
  151. display.find('span').text(dashboardLang.get('rcscript.form.display'));
  152. display.find('label').eq(0).text(dashboardLang.get('rcscript.form.display_compact'));
  153. display.find('label').eq(1).text(dashboardLang.get('rcscript.form.display_embed'));
  154. display.find('label').eq(2).text(dashboardLang.get('rcscript.form.display_image'));
  155. display.find('label').eq(3).text(dashboardLang.get('rcscript.form.display_diff'));
  156. display.find(`#wb-settings-display-${settings.display}`).attr('checked', '');
  157. if ( !settings.patreon ) display.find('.wb-settings-display').filter( (i, radioDisplay) => {
  158. return ( i > rcgcdwLimit.display && !$(radioDisplay).has('input:checked').length );
  159. } ).remove();
  160. fields.push(display);
  161. let feeds = $('<div id="wb-settings-feeds-hide">').append(fieldset.feeds);
  162. feeds.find('label').eq(0).text(dashboardLang.get('rcscript.form.feeds'));
  163. feeds.find('label').eq(1).text(dashboardLang.get('rcscript.form.feeds_only'));
  164. if ( /\.(?:fandom\.com|wikia\.org)$/.test(new URL(settings.wiki).hostname) ) {
  165. if ( settings.postid !== '-1' ) {
  166. feeds.find('#wb-settings-feeds').attr('checked', '');
  167. if ( settings.rcid === -1 ) feeds.find('#wb-settings-feeds-only').attr('checked', '');
  168. }
  169. else feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
  170. }
  171. else {
  172. feeds.attr('style', 'display: none;');
  173. feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
  174. }
  175. fields.push(feeds);
  176. fields.push($(fieldset.save).val(dashboardLang.get('general.save')));
  177. if ( settings.channel && curChannel && hasPerm(curChannel.userPermissions, 'MANAGE_WEBHOOKS') ) {
  178. fields.push($(fieldset.delete).val(dashboardLang.get('general.delete')).attr('onclick', `return confirm('${dashboardLang.get('rcscript.form.confirm').replace( /'/g, '\\$&' )}');`));
  179. }
  180. var form = $('<fieldset>').append(...fields);
  181. if ( readonly ) {
  182. form.find('input').attr('readonly', '');
  183. form.find('input[type="checkbox"], input[type="radio"]:not(:checked), option, optgroup').attr('disabled', '');
  184. form.find('input[type="submit"]').remove();
  185. }
  186. return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  187. $('<h2>').text(header),
  188. form
  189. );
  190. }
  191. /**
  192. * Let a user change recent changes scripts
  193. * @param {import('http').ServerResponse} res - The server response
  194. * @param {import('cheerio')} $ - The response body
  195. * @param {import('./util.js').Guild} guild - The current guild
  196. * @param {String[]} args - The url parts
  197. * @param {import('./i18n.js')} dashboardLang - The user language
  198. */
  199. function dashboard_rcscript(res, $, guild, args, dashboardLang) {
  200. db.query( 'SELECT discord.wiki mainwiki, discord.lang mainlang, (SELECT ARRAY_AGG(DISTINCT wiki ORDER BY wiki ASC) FROM discord WHERE guild = $1) allwikis, webhook, configid, rcgcdw.wiki, rcgcdw.lang, display, rcid, postid FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild WHERE discord.guild = $1 AND discord.channel IS NULL ORDER BY configid ASC', [guild.id] ).then( ({rows}) => {
  201. if ( rows.length === 0 ) {
  202. createNotice($, 'nosettings', dashboardLang, [guild.id]);
  203. $('#text .description').html(dashboardLang.get('rcscript.explanation'));
  204. $('#text code#server-id').text(guild.id);
  205. $('.channel#rcscript').addClass('selected');
  206. let body = $.html();
  207. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  208. res.write( body );
  209. return res.end();
  210. }
  211. var wiki = rows[0].mainwiki;
  212. var lang = rows[0].mainlang;
  213. var allwikis = rows[0].allwikis;
  214. if ( rows.length === 1 && rows[0].configid === null ) rows.pop();
  215. $('<p>').html(dashboardLang.get('rcscript.desc', true, $('<code>').text(guild.name))).appendTo('#text .description');
  216. Promise.all(rows.map( row => {
  217. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( response => {
  218. if ( !response.body?.channel_id ) {
  219. console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the webhook: ' + response.body?.message );
  220. if ( ( response.body?.message === 'Unknown Webhook' && response.body?.code === 10015 )
  221. || ( response.body?.message === 'Invalid Webhook Token' && response.body?.code === 50027 ) ) {
  222. row.DELETED = true;
  223. }
  224. else {
  225. row.channel = 'UNKNOWN';
  226. row.name = 'UNKNOWN';
  227. row.avatar = '';
  228. }
  229. }
  230. else {
  231. row.channel = response.body.channel_id;
  232. row.name = response.body.name;
  233. row.avatar = ( response.body.avatar ? `https://cdn.discordapp.com/avatars/${response.body.id}/${response.body.avatar}` : '' );
  234. }
  235. }, error => {
  236. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  237. row.channel = 'UNKNOWN';
  238. row.name = 'UNKNOWN';
  239. row.avatar = '';
  240. } );
  241. } )).finally( () => {
  242. if ( rows.some( row => row.DELETED ) ) {
  243. let deletedRows = rows.filter( row => row.DELETED ).map( row => row.webhook );
  244. db.query( 'DELETE FROM rcgcdw WHERE webhook IN (' + deletedRows.map( (row, i) => '$' + ( i + 1 ) ).join(', ') + ')', deletedRows ).then( () => {
  245. console.log( '- Dashboard: Deleted RcGcDw successfully removed.' );
  246. }, dberror => {
  247. console.log( '- Dashboard: Error while removing the deleted RcGcDw: ' + dberror );
  248. } );
  249. rows = rows.filter( row => !row.DELETED );
  250. }
  251. let suffix = ( args[0] === 'owner' ? '?owner=true' : '' );
  252. $('#channellist #rcscript').after(
  253. ...rows.map( row => {
  254. let text = `${row.configid} - ${( guild.channels.find( channel => {
  255. return channel.id === row.channel;
  256. } )?.name || row.channel )}`;
  257. return $('<a class="channel">').attr('id', `channel-${row.configid}`).append(
  258. $('<img>').attr('src', '/src/channel.svg'),
  259. $('<div>').text(text)
  260. ).attr('title', text).attr('href', `/guild/${guild.id}/rcscript/${row.configid}${suffix}`);
  261. } ),
  262. ( process.env.READONLY || rows.length >= rcgcdwLimit[( guild.patreon ? 'patreon' : 'default' )] ? '' :
  263. $('<a class="channel" id="channel-new">').append(
  264. $('<img>').attr('src', '/src/channel.svg'),
  265. $('<div>').text(dashboardLang.get('rcscript.new'))
  266. ).attr('href', `/guild/${guild.id}/rcscript/new${suffix}`) )
  267. );
  268. if ( args[4] === 'new' && !( process.env.READONLY || rows.length >= rcgcdwLimit[( guild.patreon ? 'patreon' : 'default' )] ) ) {
  269. $('.channel#channel-new').addClass('selected');
  270. createForm($, dashboardLang.get('rcscript.form.new'), dashboardLang, {
  271. wiki, lang: ( allLangs.names.hasOwnProperty(lang) ? lang : defaultSettings.lang ),
  272. display: 1, patreon: guild.patreon
  273. }, guild.channels, allwikis).attr('action', `/guild/${guild.id}/rcscript/new`).appendTo('#text');
  274. }
  275. else if ( rows.some( row => row.configid.toString() === args[4] ) ) {
  276. let row = rows.find( row => row.configid.toString() === args[4] );
  277. $(`.channel#channel-${row.configid}`).addClass('selected');
  278. createForm($, dashboardLang.get('rcscript.form.entry', false, row.configid), dashboardLang, Object.assign({
  279. patreon: guild.patreon
  280. }, row), guild.channels, allwikis).attr('action', `/guild/${guild.id}/rcscript/${row.configid}`).appendTo('#text');
  281. }
  282. else {
  283. $('.channel#rcscript').addClass('selected');
  284. $('#text .description').html(dashboardLang.get('rcscript.explanation'));
  285. $('#text code#server-id').text(guild.id);
  286. }
  287. let body = $.html();
  288. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  289. res.write( body );
  290. return res.end();
  291. } );
  292. }, dberror => {
  293. console.log( '- Dashboard: Error while getting the RcGcDw: ' + dberror );
  294. createNotice($, 'error', dashboardLang);
  295. $('#text .description').html(dashboardLang.get('rcscript.explanation'));
  296. $('#text code#server-id').text(guild.id);
  297. $('.channel#rcscript').addClass('selected');
  298. let body = $.html();
  299. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  300. res.write( body );
  301. return res.end();
  302. } );
  303. }
  304. /**
  305. * Change recent changes scripts
  306. * @param {Function} res - The server response
  307. * @param {import('./util.js').Settings} userSettings - The settings of the user
  308. * @param {String} guild - The id of the guild
  309. * @param {String|Number} type - The setting to change
  310. * @param {Object} settings - The new settings
  311. * @param {String} settings.channel
  312. * @param {String} [settings.name]
  313. * @param {String} [settings.avatar]
  314. * @param {String} settings.wiki
  315. * @param {String} settings.lang
  316. * @param {Number} settings.display
  317. * @param {String} [settings.feeds]
  318. * @param {String} [settings.feeds_only]
  319. * @param {String} [settings.save_settings]
  320. * @param {String} [settings.delete_settings]
  321. */
  322. function update_rcscript(res, userSettings, guild, type, settings) {
  323. if ( type === 'default' || type === 'notice' ) {
  324. return res(`/guild/${guild}/rcscript`, 'savefail');
  325. }
  326. if ( !settings.save_settings === !settings.delete_settings ) {
  327. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  328. }
  329. if ( settings.save_settings ) {
  330. if ( !settings.wiki || !allLangs.names.hasOwnProperty(settings.lang) ) {
  331. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  332. }
  333. if ( !['0', '1', '2', '3'].includes( settings.display ) ) {
  334. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  335. }
  336. settings.display = parseInt(settings.display, 10);
  337. if ( type === 'new' && !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  338. return ( channel.id === settings.channel && !channel.isCategory );
  339. } ) ) return res(`/guild/${guild}/rcscript/new`, 'savefail');
  340. settings.name = ( settings.name || '' ).trim();
  341. if ( settings.name.length < 2 ) settings.name = '';
  342. if ( !settings.avatar || !/^https?:\/\//.test(settings.avatar) ) settings.avatar = '';
  343. }
  344. if ( settings.delete_settings && type === 'new' ) {
  345. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  346. }
  347. if ( type === 'new' ) return sendMsg( {
  348. type: 'getMember',
  349. member: userSettings.user.id,
  350. guild: guild,
  351. channel: settings.channel
  352. } ).then( response => {
  353. if ( !response ) {
  354. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  355. userSettings.guilds.isMember.delete(guild);
  356. return res(`/guild/${guild}`, 'savefail');
  357. }
  358. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  359. userSettings.guilds.isMember.delete(guild);
  360. return res('/', 'savefail');
  361. }
  362. if ( response.message === 'noChannel' || !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS') || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  363. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  364. }
  365. if ( settings.display > rcgcdwLimit.display && !response.patreon ) {
  366. settings.display = rcgcdwLimit.display;
  367. }
  368. return db.query( 'SELECT discord.lang, ARRAY_REMOVE(ARRAY_AGG(configid ORDER BY configid), NULL) count FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild WHERE discord.guild = $1 AND discord.channel IS NULL GROUP BY discord.lang', [guild] ).then( ({rows:[row]}) => {
  369. if ( !row ) return res(`/guild/${guild}/rcscript`, 'savefail');
  370. if ( row.count.length >= rcgcdwLimit[( response.patreon ? 'patreon' : 'default' )] ) {
  371. return res(`/guild/${guild}/rcscript`, 'savefail');
  372. }
  373. var wiki = Wiki.fromInput(settings.wiki);
  374. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json', {
  375. responseType: 'text'
  376. } ).then( fresponse => {
  377. try {
  378. fresponse.body = JSON.parse(fresponse.body);
  379. }
  380. catch (error) {
  381. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  382. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  383. if ( api ) {
  384. wiki = new Wiki(api.split('api.php?')[0], wiki);
  385. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json' );
  386. }
  387. }
  388. }
  389. return fresponse;
  390. } ).then( fresponse => {
  391. var body = fresponse.body;
  392. if ( fresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general || !body?.query?.pages?.['-1'] ) {
  393. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  394. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  395. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'private');
  396. }
  397. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  398. }
  399. wiki.updateWiki(body.query.general);
  400. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  401. return res(`/guild/${guild}/rcscript/new`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  402. }
  403. if ( body.query.allmessages[0]['*'] !== guild ) {
  404. return res(`/guild/${guild}/rcscript/new`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  405. }
  406. return Promise.all([
  407. db.query( 'SELECT reason FROM blocklist WHERE wiki = $1', [wiki.href] ),
  408. ( settings.avatar ? got.head( settings.avatar ).then( headresponse => {
  409. if ( avatar_content_types.includes( headresponse.headers?.['content-type'] ) ) return;
  410. settings.avatar = '';
  411. }, error => {
  412. console.log( '- Dashboard: Error while checking for the HEAD: ' + error );
  413. settings.avatar = '';
  414. } ) : null )
  415. ]).then( ([{rows:[block]}]) => {
  416. if ( block ) {
  417. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  418. return res(`/guild/${guild}/rcscript/new`, 'wikiblocked', body.query.general.sitename, block.reason);
  419. }
  420. if ( settings.feeds && wiki.isFandom(false) ) return got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=1&format=json&cache=' + Date.now(), {
  421. headers: {
  422. Accept: 'application/hal+json'
  423. }
  424. } ).then( dsresponse => {
  425. var dsbody = dsresponse.body;
  426. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  427. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  428. return createWebhook();
  429. }
  430. return createWebhook(true);
  431. }, error => {
  432. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  433. return createWebhook();
  434. } );
  435. return createWebhook();
  436. /**
  437. * Creates the webhook.
  438. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  439. */
  440. function createWebhook(enableFeeds = false) {
  441. var lang = new Lang(row.lang);
  442. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  443. sendMsg( {
  444. type: 'createWebhook',
  445. guild: guild,
  446. channel: settings.channel,
  447. name: ( settings.name || body.query.allmessages[1]['*'] || 'Recent changes' ),
  448. avatar: settings.avatar,
  449. reason: lang.get('rcscript.audit_reason', wiki.href),
  450. text: webhook_lang.get('created', body.query.general.sitename) + ( enableFeeds && settings.feeds_only ? '' : `\n<${wiki.toLink(body.query.pages['-1'].title)}>` ) + ( enableFeeds ? `\n<${wiki.href}f>` : '' )
  451. } ).then( webhook => {
  452. if ( !webhook ) return res(`/guild/${guild}/rcscript/new`, 'savefail');
  453. var configid = 1;
  454. for ( let i of row.count ) {
  455. if ( configid === i ) configid++;
  456. else break;
  457. }
  458. db.query( 'INSERT INTO rcgcdw(guild, configid, webhook, wiki, lang, display, rcid, postid) VALUES($1, $2, $3, $4, $5, $6, $7, $8)', [guild, configid, webhook, wiki.href, settings.lang, settings.display, ( enableFeeds && settings.feeds_only ? -1 : null ), ( enableFeeds ? null : '-1' )] ).then( () => {
  459. console.log( `- Dashboard: RcGcDw successfully added: ${guild}#${configid}` );
  460. res(`/guild/${guild}/rcscript/${configid}`, 'save');
  461. var text = lang.get('rcscript.dashboard.added', `<@${userSettings.user.id}>`, configid);
  462. text += `\n${lang.get('rcscript.channel')} <#${settings.channel}>`;
  463. text += `\n${lang.get('rcscript.name')} \`${( settings.name || body.query.allmessages[1]['*'] || 'Recent changes' )}\``;
  464. if ( settings.avatar ) text += `\n${lang.get('rcscript.avatar')} <${settings.avatar}>`;
  465. text += `\n${lang.get('rcscript.wiki')} <${wiki.href}>`;
  466. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[settings.lang]}\``;
  467. text += `\n${lang.get('rcscript.display')} \`${display_types[settings.display]}\``;
  468. if ( enableFeeds && settings.feeds_only ) text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  469. if ( wiki.isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`;
  470. text += `\n<${new URL(`/guild/${guild}/rcscript/${configid}`, process.env.dashboard).href}>`;
  471. sendMsg( {
  472. type: 'notifyGuild', guild, text,
  473. file: [`./RcGcDb/locale/widgets/${settings.lang}.png`]
  474. } ).catch( error => {
  475. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  476. } );
  477. }, dberror => {
  478. console.log( '- Dashboard: Error while adding the RcGcDw: ' + dberror );
  479. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  480. } );
  481. }, error => {
  482. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  483. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  484. } );
  485. }
  486. }, dberror => {
  487. console.log( '- Dashboard: Error while getting the blocklist: ' + dberror );
  488. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  489. } );
  490. }, error => {
  491. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' || error.message === 'self signed certificate' ) {
  492. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  493. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'http');
  494. }
  495. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  496. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  497. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'timeout');
  498. }
  499. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  500. } );
  501. }, dberror => {
  502. console.log( '- Dashboard: Error while checking for RcGcDw: ' + dberror );
  503. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  504. } );
  505. }, error => {
  506. console.log( '- Dashboard: Error while getting the member: ' + error );
  507. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  508. } );
  509. type = parseInt(type, 10);
  510. return db.query( 'SELECT discord.lang mainlang, webhook, rcgcdw.wiki, rcgcdw.lang, display, rcid, postid FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild AND configid = $1 WHERE discord.guild = $2 AND discord.channel IS NULL', [type, guild] ).then( ({rows:[row]}) => {
  511. if ( !row?.webhook ) return res(`/guild/${guild}/rcscript`, 'savefail');
  512. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( wresponse => {
  513. if ( !wresponse.body?.channel_id ) {
  514. console.log( '- Dashboard: ' + wresponse.statusCode + ': Error while getting the webhook: ' + wresponse.body?.message );
  515. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  516. }
  517. row.channel = wresponse.body.channel_id;
  518. row.name = wresponse.body.name;
  519. row.avatar = ( wresponse.body.avatar ? `https://cdn.discordapp.com/avatars/${wresponse.body.id}/${wresponse.body.avatar}` : '' );
  520. var newChannel = false;
  521. if ( settings.save_settings && row.channel !== settings.channel ) {
  522. if ( !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  523. return ( channel.id === settings.channel && !channel.isCategory );
  524. } ) ) return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  525. newChannel = true;
  526. }
  527. return sendMsg( {
  528. type: 'getMember',
  529. member: userSettings.user.id,
  530. guild: guild,
  531. channel: row.channel,
  532. newchannel: ( newChannel ? settings.channel : undefined )
  533. } ).then( response => {
  534. if ( !response ) {
  535. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  536. userSettings.guilds.isMember.delete(guild);
  537. return res(`/guild/${guild}`, 'savefail');
  538. }
  539. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  540. userSettings.guilds.isMember.delete(guild);
  541. return res('/', 'savefail');
  542. }
  543. if ( response.message === 'noChannel' ) {
  544. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  545. }
  546. if ( settings.delete_settings ) {
  547. if ( !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  548. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  549. }
  550. return db.query( 'DELETE FROM rcgcdw WHERE webhook = $1', [row.webhook] ).then( () => {
  551. console.log( `- Dashboard: RcGcDw successfully removed: ${guild}#${type}` );
  552. res(`/guild/${guild}/rcscript`, 'save');
  553. var lang = new Lang(row.mainlang);
  554. var webhook_lang = new Lang(row.lang, 'rcscript.webhook');
  555. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  556. json: {
  557. content: webhook_lang.get('deleted')
  558. }
  559. } ).then( delresponse => {
  560. if ( delresponse.statusCode !== 204 ) {
  561. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  562. }
  563. }, error => {
  564. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  565. } ).finally( () => {
  566. got.delete( 'https://discord.com/api/webhooks/' + row.webhook, {
  567. headers: {
  568. 'X-Audit-Log-Reason': lang.get('rcscript.audit_reason_delete')
  569. }
  570. } ).then( delresponse => {
  571. if ( delresponse.statusCode !== 204 ) {
  572. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while removing the webhook: ' + delresponse.body?.message );
  573. }
  574. else console.log( `- Dashboard: Webhook successfully removed: ${guild}#${row.channel}` );
  575. }, error => {
  576. console.log( '- Dashboard: Error while removing the webhook: ' + error );
  577. } )
  578. } );
  579. var text = lang.get('rcscript.dashboard.removed', `<@${userSettings.user.id}>`, type);
  580. text += `\n${lang.get('rcscript.channel')} <#${row.channel}>`;
  581. text += `\n${lang.get('rcscript.name')} \`${row.name}\``;
  582. text += `\n${lang.get('rcscript.wiki')} <${row.wiki}>`;
  583. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[row.lang]}\``;
  584. text += `\n${lang.get('rcscript.display')} \`${display_types[row.display]}\``;
  585. if ( row.rcid === -1 ) {
  586. text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  587. }
  588. if ( new Wiki(row.wiki).isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*`;
  589. text += `\n<${new URL(`/guild/${guild}/rcscript`, process.env.dashboard).href}>`;
  590. sendMsg( {
  591. type: 'notifyGuild', guild, text
  592. } ).catch( error => {
  593. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  594. } );
  595. }, dberror => {
  596. console.log( '- Dashboard: Error while removing the RcGcDw: ' + dberror );
  597. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  598. } );
  599. }
  600. if ( newChannel && ( !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS')
  601. || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  602. || !hasPerm(response.userPermissionsNew, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  603. || !hasPerm(response.botPermissionsNew, 'MANAGE_WEBHOOKS') ) ) {
  604. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  605. }
  606. var hasDiff = false;
  607. if ( newChannel ) hasDiff = true;
  608. if ( settings.name && row.name !== settings.name ) hasDiff = true;
  609. if ( settings.avatar && row.avatar !== settings.avatar ) hasDiff = true;
  610. if ( row.wiki !== settings.wiki ) hasDiff = true;
  611. if ( row.lang !== settings.lang ) hasDiff = true;
  612. if ( row.display !== settings.display ) hasDiff = true;
  613. if ( ( row.rcid !== -1 ) !== !( settings.feeds && settings.feeds_only ) ) hasDiff = true;
  614. if ( ( row.postid === '-1' ) !== !settings.feeds ) hasDiff = true;
  615. if ( !hasDiff ) return res(`/guild/${guild}/rcscript/${type}`, 'save');
  616. var wiki = Wiki.fromInput(settings.wiki);
  617. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json', {
  618. responseType: 'text'
  619. } ).then( fresponse => {
  620. try {
  621. fresponse.body = JSON.parse(fresponse.body);
  622. }
  623. catch (error) {
  624. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  625. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  626. if ( api ) {
  627. wiki = new Wiki(api.split('api.php?')[0], wiki);
  628. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json' );
  629. }
  630. }
  631. }
  632. return fresponse;
  633. } ).then( fresponse => {
  634. var body = fresponse.body;
  635. if ( fresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general ) {
  636. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  637. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  638. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'private');
  639. }
  640. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  641. }
  642. wiki.updateWiki(body.query.general);
  643. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  644. return res(`/guild/${guild}/rcscript/${type}`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  645. }
  646. if ( row.wiki !== wiki.href && body.query.allmessages[0]['*'] !== guild ) {
  647. return res(`/guild/${guild}/rcscript/${type}`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  648. }
  649. return Promise.all([
  650. db.query( 'SELECT reason FROM blocklist WHERE wiki = $1', [wiki.href] ),
  651. ( settings.avatar && row.avatar !== settings.avatar ? got.head( settings.avatar ).then( headresponse => {
  652. if ( avatar_content_types.includes( headresponse.headers?.['content-type'] ) ) return;
  653. settings.avatar = '';
  654. }, error => {
  655. console.log( '- Dashboard: Error while checking for the HEAD: ' + error );
  656. settings.avatar = '';
  657. } ) : null )
  658. ]).then( ([{rows:[block]}]) => {
  659. if ( block ) {
  660. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  661. return res(`/guild/${guild}/rcscript/${type}`, 'wikiblocked', body.query.general.sitename, block.reason);
  662. }
  663. if ( settings.feeds && wiki.isFandom(false) ) return got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=1&format=json&cache=' + Date.now(), {
  664. headers: {
  665. Accept: 'application/hal+json'
  666. }
  667. } ).then( dsresponse => {
  668. var dsbody = dsresponse.body;
  669. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  670. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  671. return updateWebhook();
  672. }
  673. return updateWebhook(true);
  674. }, error => {
  675. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  676. return updateWebhook();
  677. } );
  678. return updateWebhook();
  679. /**
  680. * Creates the webhook.
  681. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  682. */
  683. function updateWebhook(enableFeeds = null) {
  684. var sqlargs = [row.webhook, wiki.href, settings.lang, settings.display];
  685. var sql = 'UPDATE rcgcdw SET wiki = $2, lang = $3, display = $4';
  686. if ( row.wiki !== wiki.href ) {
  687. sqlargs.push(( enableFeeds && settings.feeds_only ? -1 : null ), ( enableFeeds ? null : '-1' ));
  688. sql += ', rcid = $5, postid = $6';
  689. }
  690. else {
  691. if ( enableFeeds && settings.feeds_only ) {
  692. sqlargs.push(-1);
  693. sql += ', rcid = $' + sqlargs.length;
  694. }
  695. else if ( row.rcid === -1 ) {
  696. sqlargs.push(null);
  697. sql += ', rcid = $' + sqlargs.length;
  698. }
  699. if ( !enableFeeds ) {
  700. sqlargs.push('-1');
  701. sql += ', postid = $' + sqlargs.length;
  702. }
  703. else if ( row.postid === '-1' ) {
  704. sqlargs.push(null);
  705. sql += ', postid = $' + sqlargs.length;
  706. }
  707. }
  708. db.query( sql + ' WHERE webhook = $1', sqlargs ).then( () => {
  709. console.log( `- Dashboard: RcGcDw successfully updated: ${guild}#${type}` );
  710. var webhook_changes = {};
  711. var lang = new Lang(row.mainlang);
  712. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  713. var diff = [];
  714. var file = [];
  715. var webhook_diff = [];
  716. if ( newChannel ) {
  717. diff.push(lang.get('rcscript.channel') + ` ~~<#${row.channel}>~~ → <#${settings.channel}>`);
  718. webhook_diff.push(webhook_lang.get('dashboard.channel'));
  719. webhook_changes.channel = settings.channel;
  720. }
  721. if ( settings.name && row.name !== settings.name ) {
  722. diff.push(lang.get('rcscript.name') + ` ~~\`${row.name}\`~~ → \`${settings.name}\``);
  723. webhook_diff.push(webhook_lang.get('dashboard.name', settings.name));
  724. webhook_changes.name = settings.name;
  725. }
  726. if ( settings.avatar && row.avatar !== settings.avatar ) {
  727. diff.push(lang.get('rcscript.avatar') + ` <${settings.avatar}>`);
  728. webhook_diff.push(webhook_lang.get('dashboard.avatar'));
  729. webhook_changes.avatar = settings.avatar;
  730. }
  731. if ( row.wiki !== wiki.href ) {
  732. diff.push(lang.get('rcscript.wiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
  733. webhook_diff.push(webhook_lang.get('dashboard.wiki', `[${body.query.general.sitename}](<${wiki.href}>)`));
  734. }
  735. if ( row.lang !== settings.lang ) {
  736. file.push(`./RcGcDb/locale/widgets/${settings.lang}.png`);
  737. diff.push(lang.get('rcscript.lang') + ` ~~\`${allLangs.names[row.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
  738. webhook_diff.push(webhook_lang.get('dashboard.lang', allLangs.names[settings.lang]));
  739. }
  740. if ( row.display !== settings.display ) {
  741. diff.push(lang.get('rcscript.display') + ` ~~\`${display_types[row.display]}\`~~ → \`${display_types[settings.display]}\``);
  742. webhook_diff.push(webhook_lang.get('dashboard.display_' + display_types[settings.display]));
  743. }
  744. if ( ( row.rcid !== -1 ) !== !( enableFeeds && settings.feeds_only ) ) {
  745. diff.push(lang.get('rcscript.rc') + ` ~~*\`${lang.get('rcscript.' + ( row.rcid === -1 ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( settings.feeds_only ? 'disabled' : 'enabled' ))}\`*`);
  746. webhook_diff.push(webhook_lang.get('dashboard.' + ( settings.feeds_only ? 'disabled_rc' : 'enabled_rc' )));
  747. }
  748. if ( ( row.postid === '-1' ) !== !enableFeeds ) {
  749. diff.push(lang.get('rcscript.feeds') + ` ~~*\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`);
  750. webhook_diff.push(webhook_lang.get('dashboard.' + ( enableFeeds ? 'enabled_feeds' : 'disabled_feeds' )));
  751. }
  752. if ( Object.keys(webhook_changes).length ) return sendMsg( {
  753. type: 'editWebhook',
  754. guild: guild,
  755. webhook: row.webhook,
  756. channel: webhook_changes.channel,
  757. name: webhook_changes.name,
  758. avatar: webhook_changes.avatar,
  759. reason: lang.get('rcscript.audit_reason_edit'),
  760. text: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  761. } ).then( webhook => {
  762. if ( !webhook ) return Promise.reject();
  763. res(`/guild/${guild}/rcscript/${type}`, 'save');
  764. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  765. text += '\n' + diff.join('\n');
  766. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  767. sendMsg( {
  768. type: 'notifyGuild', guild, text, file
  769. } ).catch( error => {
  770. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  771. } );
  772. }, error => {
  773. console.log( '- Dashboard: Error while editing the webhook: ' + error );
  774. return Promise.reject();
  775. } ).catch( () => {
  776. Object.keys(webhook_changes).forEach( () => {
  777. diff.shift();
  778. webhook_diff.shift();
  779. } );
  780. if ( !diff.length ) {
  781. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  782. }
  783. res(`/guild/${guild}/rcscript/${type}`, 'webhookfail');
  784. diff.shift();
  785. webhook_diff.shift();
  786. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  787. json: {
  788. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  789. }
  790. } ).then( delresponse => {
  791. if ( delresponse.statusCode !== 204 ) {
  792. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  793. }
  794. }, error => {
  795. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  796. } )
  797. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  798. text += '\n' + diff.join('\n');
  799. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  800. sendMsg( {
  801. type: 'notifyGuild', guild, text, file
  802. } ).catch( error => {
  803. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  804. } );
  805. } );
  806. res(`/guild/${guild}/rcscript/${type}`, 'save');
  807. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  808. json: {
  809. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  810. }
  811. } ).then( delresponse => {
  812. if ( delresponse.statusCode !== 204 ) {
  813. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  814. }
  815. }, error => {
  816. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  817. } )
  818. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  819. text += '\n' + diff.join('\n');
  820. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  821. sendMsg( {
  822. type: 'notifyGuild', guild, text, file
  823. } ).catch( error => {
  824. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  825. } );
  826. }, dberror => {
  827. console.log( '- Dashboard: Error while updating the RcGcDw: ' + dberror );
  828. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  829. } );
  830. }
  831. }, dberror => {
  832. console.log( '- Dashboard: Error while getting the blocklist: ' + dberror );
  833. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  834. } );
  835. }, error => {
  836. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' || error.message === 'self signed certificate' ) {
  837. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  838. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'http');
  839. }
  840. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  841. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  842. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'timeout');
  843. }
  844. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  845. } );
  846. }, error => {
  847. console.log( '- Dashboard: Error while getting the member: ' + error );
  848. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  849. } );
  850. }, error => {
  851. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  852. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  853. } );
  854. }, dberror => {
  855. console.log( '- Dashboard: Error while checking for RcGcDw: ' + dberror );
  856. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  857. } );
  858. }
  859. module.exports = {
  860. get: dashboard_rcscript,
  861. post: update_rcscript
  862. };