rcscript.js 45 KB

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