rcscript.js 39 KB

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