1
0

rcscript.js 44 KB

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