rcscript.js 44 KB

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