rcscript.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. import cheerio 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').default} $ - 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').default} $ - 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. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json', {
  377. responseType: 'text'
  378. } ).then( fresponse => {
  379. try {
  380. fresponse.body = JSON.parse(fresponse.body);
  381. }
  382. catch (error) {
  383. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  384. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  385. if ( api ) {
  386. wiki = new Wiki(api.split('api.php?')[0], wiki);
  387. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json' );
  388. }
  389. }
  390. }
  391. return fresponse;
  392. } ).then( fresponse => {
  393. var body = fresponse.body;
  394. if ( fresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general || !body?.query?.pages?.['-1'] ) {
  395. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  396. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  397. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'private');
  398. }
  399. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  400. }
  401. wiki.updateWiki(body.query.general);
  402. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  403. return res(`/guild/${guild}/rcscript/new`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  404. }
  405. if ( body.query.allmessages[0]['*'] !== guild ) {
  406. return res(`/guild/${guild}/rcscript/new`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  407. }
  408. return Promise.all([
  409. db.query( 'SELECT reason FROM blocklist WHERE wiki = $1', [wiki.href] ),
  410. ( settings.avatar ? got.head( settings.avatar ).then( headresponse => {
  411. if ( avatar_content_types.includes( headresponse.headers?.['content-type'] ) ) return;
  412. settings.avatar = '';
  413. }, error => {
  414. console.log( '- Dashboard: Error while checking for the HEAD: ' + error );
  415. settings.avatar = '';
  416. } ) : null )
  417. ]).then( ([{rows:[block]}]) => {
  418. if ( block ) {
  419. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  420. return res(`/guild/${guild}/rcscript/new`, 'wikiblocked', body.query.general.sitename, block.reason);
  421. }
  422. 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(), {
  423. headers: {
  424. Accept: 'application/hal+json'
  425. }
  426. } ).then( dsresponse => {
  427. var dsbody = dsresponse.body;
  428. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  429. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  430. return createWebhook();
  431. }
  432. return createWebhook(true);
  433. }, error => {
  434. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  435. return createWebhook();
  436. } );
  437. return createWebhook();
  438. /**
  439. * Creates the webhook.
  440. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  441. */
  442. function createWebhook(enableFeeds = false) {
  443. var lang = new Lang(row.lang);
  444. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  445. sendMsg( {
  446. type: 'createWebhook',
  447. guild: guild,
  448. channel: settings.channel,
  449. name: ( settings.name || body.query.allmessages[1]['*'] || 'Recent changes' ),
  450. avatar: settings.avatar,
  451. reason: lang.get('rcscript.audit_reason', wiki.href),
  452. 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>` : '' )
  453. } ).then( webhook => {
  454. if ( !webhook ) return res(`/guild/${guild}/rcscript/new`, 'savefail');
  455. var configid = 1;
  456. for ( let i of row.count ) {
  457. if ( configid === i ) configid++;
  458. else break;
  459. }
  460. 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( () => {
  461. console.log( `- Dashboard: RcGcDw successfully added: ${guild}#${configid}` );
  462. res(`/guild/${guild}/rcscript/${configid}`, 'save');
  463. var text = lang.get('rcscript.dashboard.added', `<@${userSettings.user.id}>`, configid);
  464. text += `\n${lang.get('rcscript.channel')} <#${settings.channel}>`;
  465. text += `\n${lang.get('rcscript.name')} \`${( settings.name || body.query.allmessages[1]['*'] || 'Recent changes' )}\``;
  466. if ( settings.avatar ) text += `\n${lang.get('rcscript.avatar')} <${settings.avatar}>`;
  467. text += `\n${lang.get('rcscript.wiki')} <${wiki.href}>`;
  468. text += `\n${lang.get('rcscript.lang')} \`${allLangs[settings.lang]}\``;
  469. text += `\n${lang.get('rcscript.display')} \`${display_types[settings.display]}\``;
  470. if ( enableFeeds && settings.feeds_only ) text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  471. if ( wiki.isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`;
  472. text += `\n<${new URL(`/guild/${guild}/rcscript/${configid}`, process.env.dashboard).href}>`;
  473. sendMsg( {
  474. type: 'notifyGuild', guild, text,
  475. file: [`./RcGcDb/locale/widgets/${settings.lang}.png`]
  476. } ).catch( error => {
  477. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  478. } );
  479. }, dberror => {
  480. console.log( '- Dashboard: Error while adding the RcGcDw: ' + dberror );
  481. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  482. } );
  483. }, error => {
  484. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  485. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  486. } );
  487. }
  488. }, dberror => {
  489. console.log( '- Dashboard: Error while getting the blocklist: ' + dberror );
  490. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  491. } );
  492. }, error => {
  493. 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' ) {
  494. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  495. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'http');
  496. }
  497. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  498. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  499. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'timeout');
  500. }
  501. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  502. } );
  503. }, dberror => {
  504. console.log( '- Dashboard: Error while checking for RcGcDw: ' + dberror );
  505. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  506. } );
  507. }, error => {
  508. console.log( '- Dashboard: Error while getting the member: ' + error );
  509. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  510. } );
  511. type = parseInt(type, 10);
  512. 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]}) => {
  513. if ( !row?.webhook ) return res(`/guild/${guild}/rcscript`, 'savefail');
  514. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( wresponse => {
  515. if ( !wresponse.body?.channel_id ) {
  516. console.log( '- Dashboard: ' + wresponse.statusCode + ': Error while getting the webhook: ' + wresponse.body?.message );
  517. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  518. }
  519. row.channel = wresponse.body.channel_id;
  520. row.name = wresponse.body.name;
  521. row.avatar = ( wresponse.body.avatar ? `https://cdn.discordapp.com/avatars/${wresponse.body.id}/${wresponse.body.avatar}` : '' );
  522. var newChannel = false;
  523. if ( settings.save_settings && row.channel !== settings.channel ) {
  524. if ( !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  525. return ( channel.id === settings.channel && !channel.isCategory );
  526. } ) ) return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  527. newChannel = true;
  528. }
  529. return sendMsg( {
  530. type: 'getMember',
  531. member: userSettings.user.id,
  532. guild: guild,
  533. channel: row.channel,
  534. newchannel: ( newChannel ? settings.channel : undefined )
  535. } ).then( response => {
  536. if ( !response ) {
  537. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  538. userSettings.guilds.isMember.delete(guild);
  539. return res(`/guild/${guild}`, 'savefail');
  540. }
  541. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  542. userSettings.guilds.isMember.delete(guild);
  543. return res('/', 'savefail');
  544. }
  545. if ( response.message === 'noChannel' ) {
  546. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  547. }
  548. if ( settings.delete_settings ) {
  549. if ( !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  550. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  551. }
  552. return db.query( 'DELETE FROM rcgcdw WHERE webhook = $1', [row.webhook] ).then( () => {
  553. console.log( `- Dashboard: RcGcDw successfully removed: ${guild}#${type}` );
  554. res(`/guild/${guild}/rcscript`, 'save');
  555. var lang = new Lang(row.mainlang);
  556. var webhook_lang = new Lang(row.lang, 'rcscript.webhook');
  557. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  558. json: {
  559. content: webhook_lang.get('deleted')
  560. }
  561. } ).then( delresponse => {
  562. if ( delresponse.statusCode !== 204 ) {
  563. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  564. }
  565. }, error => {
  566. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  567. } ).finally( () => {
  568. got.delete( 'https://discord.com/api/webhooks/' + row.webhook, {
  569. headers: {
  570. 'X-Audit-Log-Reason': lang.get('rcscript.audit_reason_delete')
  571. }
  572. } ).then( delresponse => {
  573. if ( delresponse.statusCode !== 204 ) {
  574. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while removing the webhook: ' + delresponse.body?.message );
  575. }
  576. else console.log( `- Dashboard: Webhook successfully removed: ${guild}#${row.channel}` );
  577. }, error => {
  578. console.log( '- Dashboard: Error while removing the webhook: ' + error );
  579. } )
  580. } );
  581. var text = lang.get('rcscript.dashboard.removed', `<@${userSettings.user.id}>`, type);
  582. text += `\n${lang.get('rcscript.channel')} <#${row.channel}>`;
  583. text += `\n${lang.get('rcscript.name')} \`${row.name}\``;
  584. text += `\n${lang.get('rcscript.wiki')} <${row.wiki}>`;
  585. text += `\n${lang.get('rcscript.lang')} \`${allLangs[row.lang]}\``;
  586. text += `\n${lang.get('rcscript.display')} \`${display_types[row.display]}\``;
  587. if ( row.rcid === -1 ) {
  588. text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  589. }
  590. if ( new Wiki(row.wiki).isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*`;
  591. text += `\n<${new URL(`/guild/${guild}/rcscript`, process.env.dashboard).href}>`;
  592. sendMsg( {
  593. type: 'notifyGuild', guild, text
  594. } ).catch( error => {
  595. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  596. } );
  597. }, dberror => {
  598. console.log( '- Dashboard: Error while removing the RcGcDw: ' + dberror );
  599. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  600. } );
  601. }
  602. if ( newChannel && ( !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS')
  603. || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  604. || !hasPerm(response.userPermissionsNew, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  605. || !hasPerm(response.botPermissionsNew, 'MANAGE_WEBHOOKS') ) ) {
  606. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  607. }
  608. var hasDiff = false;
  609. if ( newChannel ) hasDiff = true;
  610. if ( settings.name && row.name !== settings.name ) hasDiff = true;
  611. if ( settings.avatar && row.avatar !== settings.avatar ) hasDiff = true;
  612. if ( row.wiki !== settings.wiki ) hasDiff = true;
  613. if ( row.lang !== settings.lang ) hasDiff = true;
  614. if ( row.display !== settings.display ) hasDiff = true;
  615. if ( ( row.rcid !== -1 ) !== !( settings.feeds && settings.feeds_only ) ) hasDiff = true;
  616. if ( ( row.postid === '-1' ) !== !settings.feeds ) hasDiff = true;
  617. if ( !hasDiff ) return res(`/guild/${guild}/rcscript/${type}`, 'save');
  618. var wiki = Wiki.fromInput(settings.wiki);
  619. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json', {
  620. responseType: 'text'
  621. } ).then( fresponse => {
  622. try {
  623. fresponse.body = JSON.parse(fresponse.body);
  624. }
  625. catch (error) {
  626. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  627. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  628. if ( api ) {
  629. wiki = new Wiki(api.split('api.php?')[0], wiki);
  630. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json' );
  631. }
  632. }
  633. }
  634. return fresponse;
  635. } ).then( fresponse => {
  636. var body = fresponse.body;
  637. if ( fresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general ) {
  638. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  639. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  640. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'private');
  641. }
  642. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  643. }
  644. wiki.updateWiki(body.query.general);
  645. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  646. return res(`/guild/${guild}/rcscript/${type}`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  647. }
  648. if ( row.wiki !== wiki.href && body.query.allmessages[0]['*'] !== guild ) {
  649. return res(`/guild/${guild}/rcscript/${type}`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  650. }
  651. return Promise.all([
  652. db.query( 'SELECT reason FROM blocklist WHERE wiki = $1', [wiki.href] ),
  653. ( settings.avatar && row.avatar !== settings.avatar ? got.head( settings.avatar ).then( headresponse => {
  654. if ( avatar_content_types.includes( headresponse.headers?.['content-type'] ) ) return;
  655. settings.avatar = '';
  656. }, error => {
  657. console.log( '- Dashboard: Error while checking for the HEAD: ' + error );
  658. settings.avatar = '';
  659. } ) : null )
  660. ]).then( ([{rows:[block]}]) => {
  661. if ( block ) {
  662. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  663. return res(`/guild/${guild}/rcscript/${type}`, 'wikiblocked', body.query.general.sitename, block.reason);
  664. }
  665. 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(), {
  666. headers: {
  667. Accept: 'application/hal+json'
  668. }
  669. } ).then( dsresponse => {
  670. var dsbody = dsresponse.body;
  671. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  672. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  673. return updateWebhook();
  674. }
  675. return updateWebhook(true);
  676. }, error => {
  677. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  678. return updateWebhook();
  679. } );
  680. return updateWebhook();
  681. /**
  682. * Creates the webhook.
  683. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  684. */
  685. function updateWebhook(enableFeeds = null) {
  686. var sqlargs = [row.webhook, wiki.href, settings.lang, settings.display];
  687. var sql = 'UPDATE rcgcdw SET wiki = $2, lang = $3, display = $4';
  688. if ( row.wiki !== wiki.href ) {
  689. sqlargs.push(( enableFeeds && settings.feeds_only ? -1 : null ), ( enableFeeds ? null : '-1' ));
  690. sql += ', rcid = $5, postid = $6';
  691. }
  692. else {
  693. if ( enableFeeds && settings.feeds_only ) {
  694. sqlargs.push(-1);
  695. sql += ', rcid = $' + sqlargs.length;
  696. }
  697. else if ( row.rcid === -1 ) {
  698. sqlargs.push(null);
  699. sql += ', rcid = $' + sqlargs.length;
  700. }
  701. if ( !enableFeeds ) {
  702. sqlargs.push('-1');
  703. sql += ', postid = $' + sqlargs.length;
  704. }
  705. else if ( row.postid === '-1' ) {
  706. sqlargs.push(null);
  707. sql += ', postid = $' + sqlargs.length;
  708. }
  709. }
  710. db.query( sql + ' WHERE webhook = $1', sqlargs ).then( () => {
  711. console.log( `- Dashboard: RcGcDw successfully updated: ${guild}#${type}` );
  712. var webhook_changes = {};
  713. var lang = new Lang(row.mainlang);
  714. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  715. var diff = [];
  716. var file = [];
  717. var webhook_diff = [];
  718. if ( newChannel ) {
  719. diff.push(lang.get('rcscript.channel') + ` ~~<#${row.channel}>~~ → <#${settings.channel}>`);
  720. webhook_diff.push(webhook_lang.get('dashboard.channel'));
  721. webhook_changes.channel = settings.channel;
  722. }
  723. if ( settings.name && row.name !== settings.name ) {
  724. diff.push(lang.get('rcscript.name') + ` ~~\`${row.name}\`~~ → \`${settings.name}\``);
  725. webhook_diff.push(webhook_lang.get('dashboard.name', settings.name));
  726. webhook_changes.name = settings.name;
  727. }
  728. if ( settings.avatar && row.avatar !== settings.avatar ) {
  729. diff.push(lang.get('rcscript.avatar') + ` <${settings.avatar}>`);
  730. webhook_diff.push(webhook_lang.get('dashboard.avatar'));
  731. webhook_changes.avatar = settings.avatar;
  732. }
  733. if ( row.wiki !== wiki.href ) {
  734. diff.push(lang.get('rcscript.wiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
  735. webhook_diff.push(webhook_lang.get('dashboard.wiki', `[${body.query.general.sitename}](<${wiki.href}>)`));
  736. }
  737. if ( row.lang !== settings.lang ) {
  738. file.push(`./RcGcDb/locale/widgets/${settings.lang}.png`);
  739. diff.push(lang.get('rcscript.lang') + ` ~~\`${allLangs[row.lang]}\`~~ → \`${allLangs[settings.lang]}\``);
  740. webhook_diff.push(webhook_lang.get('dashboard.lang', allLangs[settings.lang]));
  741. }
  742. if ( row.display !== settings.display ) {
  743. diff.push(lang.get('rcscript.display') + ` ~~\`${display_types[row.display]}\`~~ → \`${display_types[settings.display]}\``);
  744. webhook_diff.push(webhook_lang.get('dashboard.display_' + display_types[settings.display]));
  745. }
  746. if ( ( row.rcid !== -1 ) !== !( enableFeeds && settings.feeds_only ) ) {
  747. diff.push(lang.get('rcscript.rc') + ` ~~*\`${lang.get('rcscript.' + ( row.rcid === -1 ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( settings.feeds_only ? 'disabled' : 'enabled' ))}\`*`);
  748. webhook_diff.push(webhook_lang.get('dashboard.' + ( settings.feeds_only ? 'disabled_rc' : 'enabled_rc' )));
  749. }
  750. if ( ( row.postid === '-1' ) !== !enableFeeds ) {
  751. diff.push(lang.get('rcscript.feeds') + ` ~~*\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`);
  752. webhook_diff.push(webhook_lang.get('dashboard.' + ( enableFeeds ? 'enabled_feeds' : 'disabled_feeds' )));
  753. }
  754. if ( Object.keys(webhook_changes).length ) return sendMsg( {
  755. type: 'editWebhook',
  756. guild: guild,
  757. webhook: row.webhook,
  758. channel: webhook_changes.channel,
  759. name: webhook_changes.name,
  760. avatar: webhook_changes.avatar,
  761. reason: lang.get('rcscript.audit_reason_edit'),
  762. text: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  763. } ).then( webhook => {
  764. if ( !webhook ) return Promise.reject();
  765. res(`/guild/${guild}/rcscript/${type}`, 'save');
  766. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  767. text += '\n' + diff.join('\n');
  768. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  769. sendMsg( {
  770. type: 'notifyGuild', guild, text, file
  771. } ).catch( error => {
  772. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  773. } );
  774. }, error => {
  775. console.log( '- Dashboard: Error while editing the webhook: ' + error );
  776. return Promise.reject();
  777. } ).catch( () => {
  778. Object.keys(webhook_changes).forEach( () => {
  779. diff.shift();
  780. webhook_diff.shift();
  781. } );
  782. if ( !diff.length ) {
  783. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  784. }
  785. res(`/guild/${guild}/rcscript/${type}`, 'webhookfail');
  786. diff.shift();
  787. webhook_diff.shift();
  788. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  789. json: {
  790. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  791. }
  792. } ).then( delresponse => {
  793. if ( delresponse.statusCode !== 204 ) {
  794. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  795. }
  796. }, error => {
  797. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  798. } )
  799. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  800. text += '\n' + diff.join('\n');
  801. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  802. sendMsg( {
  803. type: 'notifyGuild', guild, text, file
  804. } ).catch( error => {
  805. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  806. } );
  807. } );
  808. res(`/guild/${guild}/rcscript/${type}`, 'save');
  809. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  810. json: {
  811. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  812. }
  813. } ).then( delresponse => {
  814. if ( delresponse.statusCode !== 204 ) {
  815. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  816. }
  817. }, error => {
  818. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  819. } )
  820. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  821. text += '\n' + diff.join('\n');
  822. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  823. sendMsg( {
  824. type: 'notifyGuild', guild, text, file
  825. } ).catch( error => {
  826. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  827. } );
  828. }, dberror => {
  829. console.log( '- Dashboard: Error while updating the RcGcDw: ' + dberror );
  830. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  831. } );
  832. }
  833. }, dberror => {
  834. console.log( '- Dashboard: Error while getting the blocklist: ' + dberror );
  835. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  836. } );
  837. }, error => {
  838. 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' ) {
  839. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  840. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'http');
  841. }
  842. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  843. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  844. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'timeout');
  845. }
  846. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  847. } );
  848. }, error => {
  849. console.log( '- Dashboard: Error while getting the member: ' + error );
  850. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  851. } );
  852. }, error => {
  853. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  854. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  855. } );
  856. }, dberror => {
  857. console.log( '- Dashboard: Error while checking for RcGcDw: ' + dberror );
  858. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  859. } );
  860. }
  861. export {
  862. dashboard_rcscript as get,
  863. update_rcscript as post
  864. };