rcscript.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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 {Object} settings - The current settings
  60. * @param {Boolean} settings.patreon
  61. * @param {String} [settings.channel]
  62. * @param {String} settings.wiki
  63. * @param {String} settings.lang
  64. * @param {Number} settings.display
  65. * @param {Number} [settings.wikiid]
  66. * @param {Number} [settings.rcid]
  67. * @param {Object[]} guildChannels - The guild channels
  68. * @param {String} guildChannels.id
  69. * @param {String} guildChannels.name
  70. * @param {Number} guildChannels.userPermissions
  71. * @param {Number} guildChannels.botPermissions
  72. * @param {String[]} allWikis - The guild wikis
  73. */
  74. function createForm($, header, settings, guildChannels, allWikis) {
  75. var readonly = ( process.env.READONLY ? true : false );
  76. var curChannel = guildChannels.find( guildChannel => settings.channel === guildChannel.id );
  77. var fields = [];
  78. let channel = $('<div>').append(fieldset.channel);
  79. if ( !settings.channel || ( curChannel && hasPerm(curChannel.botPermissions, 'MANAGE_WEBHOOKS') && hasPerm(curChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) ) {
  80. channel.find('#wb-settings-channel').append(
  81. ...guildChannels.filter( guildChannel => {
  82. return ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') && hasPerm(guildChannel.botPermissions, 'MANAGE_WEBHOOKS') );
  83. } ).map( guildChannel => {
  84. var optionChannel = $(`<option id="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id);
  85. if ( settings.channel === guildChannel.id ) {
  86. optionChannel.attr('selected', '');
  87. }
  88. return optionChannel.text(`${guildChannel.id} – #${guildChannel.name}`);
  89. } )
  90. );
  91. if ( !settings.channel ) {
  92. if ( !channel.find('#wb-settings-channel').children('option').length ) {
  93. createNotice($, 'missingperm', ['Manage Webhooks']);
  94. }
  95. channel.find('#wb-settings-channel').prepend(
  96. $(`<option id="wb-settings-channel-default" selected hidden>`).val('').text('-- Select a Channel --')
  97. );
  98. }
  99. }
  100. else if ( curChannel ) channel.find('#wb-settings-channel').append(
  101. $(`<option id="wb-settings-channel-${curChannel.id}">`).val(curChannel.id).attr('selected', '').text(`${curChannel.id} – #${curChannel.name}`)
  102. );
  103. else channel.find('#wb-settings-channel').append(
  104. $(`<option id="wb-settings-channel-${settings.channel}">`).val(settings.channel).attr('selected', '').text(settings.channel)
  105. );
  106. fields.push(channel);
  107. let wiki = $('<div>').append(fieldset.wiki);
  108. wiki.find('#wb-settings-wiki').val(settings.wiki);
  109. wiki.find('#wb-settings-wiki-list').append(
  110. ...allWikis.map( listWiki => $(`<option>`).val(listWiki) )
  111. );
  112. fields.push(wiki);
  113. let lang = $('<div>').append(fieldset.lang);
  114. lang.find(`#wb-settings-lang-${settings.lang}`).attr('selected', '');
  115. fields.push(lang);
  116. let display = $('<div>').append(fieldset.display);
  117. display.find(`#wb-settings-display-${settings.display}`).attr('checked', '');
  118. if ( !settings.patreon ) display.find('.wb-settings-display').filter( (i, radioDisplay) => {
  119. return ( i > rcgcdwLimit.display && !$(radioDisplay).has('input:checked').length );
  120. } ).remove();
  121. fields.push(display);
  122. let feeds = $('<div id="wb-settings-feeds-hide">').append(fieldset.feeds);
  123. if ( /\.(?:fandom\.com|wikia\.org)$/.test(new URL(settings.wiki).hostname) ) {
  124. if ( settings.wikiid ) {
  125. feeds.find('#wb-settings-feeds').attr('checked', '');
  126. if ( settings.rcid === -1 ) feeds.find('#wb-settings-feeds-only').attr('checked', '');
  127. }
  128. else feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
  129. }
  130. else {
  131. feeds.attr('style', 'display: none;');
  132. feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
  133. }
  134. fields.push(feeds);
  135. fields.push($(fieldset.save).val('Save'));
  136. if ( settings.channel && curChannel && hasPerm(curChannel.userPermissions, 'MANAGE_WEBHOOKS') ) {
  137. fields.push($(fieldset.delete).val('Delete').attr('onclick', `return confirm('Are you sure?');`));
  138. }
  139. var form = $('<fieldset>').append(...fields);
  140. if ( readonly ) {
  141. form.find('input').attr('readonly', '');
  142. form.find('input[type="checkbox"], input[type="radio"]:not(:checked), option').attr('disabled', '');
  143. form.find('input[type="submit"], button.addmore').remove();
  144. }
  145. return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  146. $('<h2>').text(header),
  147. form
  148. );
  149. }
  150. const explanation = `
  151. <h2>Recent Changes Webhook</h2>
  152. <p>Wiki-Bot is able to run a recent changes webhook based on <a href="https://gitlab.com/piotrex43/RcGcDw" target="_blank">RcGcDw</a>. The recent changes can be displayed in compact text messages with inline links or embed messages with edit tags and category changes.</p>
  153. <p>Requirements to add a recent changes webhook:</p>
  154. <ul>
  155. <li>The wiki needs to run on <a href="https://www.mediawiki.org/wiki/MediaWiki_1.30" target="_blank">MediaWiki 1.30</a> or higher.</li>
  156. <li>The system message <code>MediaWiki:Custom-RcGcDw</code> needs to be set to the Discord server id <code id="server-id" class="user-select"></code>.</li>
  157. </ul>
  158. `;
  159. /**
  160. * Let a user change recent changes scripts
  161. * @param {import('http').ServerResponse} res - The server response
  162. * @param {import('cheerio')} $ - The response body
  163. * @param {import('./util.js').Guild} guild - The current guild
  164. * @param {String[]} args - The url parts
  165. */
  166. function dashboard_rcscript(res, $, guild, args) {
  167. db.all( 'SELECT discord.wiki mainwiki, discord.lang mainlang, (SELECT GROUP_CONCAT(DISTINCT wiki) FROM discord WHERE guild = ?) allwikis, webhook, configid, rcgcdw.wiki, rcgcdw.lang, display, wikiid, rcid FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild WHERE discord.guild = ? AND discord.channel IS NULL ORDER BY configid ASC', [guild.id, guild.id], function(dberror, rows) {
  168. if ( dberror ) {
  169. console.log( '- Dashboard: Error while getting the RcGcDw: ' + dberror );
  170. createNotice($, 'error');
  171. $('#text .description').html(explanation);
  172. $('#text code#server-id').text(guild.id);
  173. $('.channel#rcscript').addClass('selected');
  174. let body = $.html();
  175. res.writeHead(200, {'Content-Length': body.length});
  176. res.write( body );
  177. return res.end();
  178. }
  179. if ( rows.length === 0 ) {
  180. createNotice($, 'nosettings', [guild.id]);
  181. $('#text .description').html(explanation);
  182. $('#text code#server-id').text(guild.id);
  183. $('.channel#rcscript').addClass('selected');
  184. let body = $.html();
  185. res.writeHead(200, {'Content-Length': body.length});
  186. res.write( body );
  187. return res.end();
  188. }
  189. var wiki = rows[0].mainwiki;
  190. var lang = rows[0].mainlang;
  191. var allwikis = rows[0].allwikis.split(',').sort();
  192. if ( rows.length === 1 && rows[0].configid === null ) rows.pop();
  193. $('<p>').text(`These are the recent changes webhooks for "${guild.name}":`).appendTo('#text .description');
  194. Promise.all(rows.map( row => {
  195. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( response => {
  196. if ( !response.body?.channel_id ) {
  197. console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the webhook: ' + response.body?.message );
  198. row.channel = 'UNKNOWN';
  199. }
  200. else row.channel = response.body.channel_id;
  201. }, error => {
  202. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  203. row.channel = 'UNKNOWN';
  204. } );
  205. } )).finally( () => {
  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}`);
  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('New webhook')
  219. ).attr('href', `/guild/${guild.id}/rcscript/new`) )
  220. );
  221. if ( args[4] === 'new' && !( process.env.READONLY || rows.length >= rcgcdwLimit[( guild.patreon ? 'patreon' : 'default' )] ) ) {
  222. $('.channel#channel-new').addClass('selected');
  223. createForm($, 'New Recent Changes Webhook', {
  224. wiki, lang: ( lang in allLangs.names ? 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($, `Recent Changes Webhook #${row.configid}`, 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(explanation);
  238. $('#text code#server-id').text(guild.id);
  239. }
  240. let body = $.html();
  241. res.writeHead(200, {'Content-Length': body.length});
  242. res.write( body );
  243. return res.end();
  244. } );
  245. } );
  246. }
  247. /**
  248. * Change recent changes scripts
  249. * @param {Function} res - The server response
  250. * @param {import('./util.js').Settings} userSettings - The settings of the user
  251. * @param {String} guild - The id of the guild
  252. * @param {String|Number} type - The setting to change
  253. * @param {Object} settings - The new settings
  254. * @param {String} settings.channel
  255. * @param {String} settings.wiki
  256. * @param {String} settings.lang
  257. * @param {Number} settings.display
  258. * @param {String} [settings.feeds]
  259. * @param {String} [settings.feeds_only]
  260. * @param {String} [settings.save_settings]
  261. * @param {String} [settings.delete_settings]
  262. */
  263. function update_rcscript(res, userSettings, guild, type, settings) {
  264. if ( type === 'default' ) {
  265. return res(`/guild/${guild}/rcscript`, 'savefail');
  266. }
  267. if ( !settings.save_settings === !settings.delete_settings ) {
  268. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  269. }
  270. if ( settings.save_settings ) {
  271. if ( !settings.wiki || !( settings.lang in allLangs.names ) ) {
  272. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  273. }
  274. if ( !['0', '1', '2', '3'].includes( settings.display ) ) {
  275. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  276. }
  277. settings.display = parseInt(settings.display, 10);
  278. if ( type === 'new' && !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  279. return ( channel.id === settings.channel );
  280. } ) ) return res(`/guild/${guild}/rcscript/new`, 'savefail');
  281. }
  282. if ( settings.delete_settings && type === 'new' ) {
  283. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  284. }
  285. if ( type === 'new' ) return sendMsg( {
  286. type: 'getMember',
  287. member: userSettings.user.id,
  288. guild: guild,
  289. channel: settings.channel
  290. } ).then( response => {
  291. if ( !response ) {
  292. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  293. userSettings.guilds.isMember.delete(guild);
  294. return res(`/guild/${guild}`, 'savefail');
  295. }
  296. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  297. userSettings.guilds.isMember.delete(guild);
  298. return res('/', 'savefail');
  299. }
  300. if ( response.message === 'noChannel' || !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS') || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  301. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  302. }
  303. if ( settings.display > rcgcdwLimit.display && !response.patreon ) {
  304. settings.display = rcgcdwLimit.display;
  305. }
  306. return db.get( 'SELECT discord.lang, GROUP_CONCAT(configid) count FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild WHERE discord.guild = ? AND discord.channel IS NULL', [guild], function(curerror, row) {
  307. if ( curerror ) {
  308. console.log( '- Dashboard: Error while checking for RcGcDw: ' + curerror );
  309. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  310. }
  311. if ( !row ) return res(`/guild/${guild}/rcscript`, 'savefail');
  312. if ( row.count === null ) row.count = [];
  313. else row.count = row.count.split(',').map( configid => parseInt(configid, 10) );
  314. if ( row.count.length >= rcgcdwLimit[( response.patreon ? 'patreon' : 'default' )] ) {
  315. return res(`/guild/${guild}/rcscript`, 'savefail');
  316. }
  317. var wiki = Wiki.fromInput(settings.wiki);
  318. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&titles=Special:RecentChanges&format=json' ).then( fresponse => {
  319. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  320. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  321. if ( api ) {
  322. wiki = new Wiki(api.split('api.php?')[0], wiki);
  323. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&titles=Special:RecentChanges&format=json' );
  324. }
  325. }
  326. return fresponse;
  327. } ).then( fresponse => {
  328. var body = fresponse.body;
  329. if ( fresponse.statusCode !== 200 || !body?.query?.allmessages || !body?.query?.general || !body?.query?.pages?.['-1'] ) {
  330. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  331. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  332. }
  333. wiki.updateWiki(body.query.general);
  334. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  335. return res(`/guild/${guild}/rcscript/new`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  336. }
  337. if ( body.query.allmessages[0]['*'] !== guild ) {
  338. return res(`/guild/${guild}/rcscript/new`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  339. }
  340. return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
  341. if ( blerror ) {
  342. console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
  343. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  344. }
  345. if ( block ) {
  346. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  347. return res(`/guild/${guild}/rcscript/new`, 'wikiblocked', body.query.general.sitename, block.reason);
  348. }
  349. if ( settings.feeds ) {
  350. let wikiid = body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'];
  351. if ( wiki.isFandom(false) && wikiid ) return got.get( 'https://services.fandom.com/discussion/' + wikiid + '/posts?limit=1&format=json&cache=' + Date.now(), {
  352. headers: {
  353. Accept: 'application/hal+json'
  354. }
  355. } ).then( dsresponse => {
  356. var dsbody = dsresponse.body;
  357. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
  358. if ( dsbody?.title !== 'site doesn\'t exists' ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  359. return createWebhook();
  360. }
  361. return createWebhook(parseInt(wikiid, 10));
  362. }, error => {
  363. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  364. return createWebhook();
  365. } );
  366. }
  367. return createWebhook();
  368. /**
  369. * Creates the webhook.
  370. * @param {Number} wikiid - The ID of the wiki.
  371. */
  372. function createWebhook(wikiid = null) {
  373. var lang = new Lang(row.lang);
  374. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  375. sendMsg( {
  376. type: 'createWebhook',
  377. guild: guild,
  378. channel: settings.channel,
  379. name: ( body.query.allmessages[1]['*'] || 'Recent changes' ),
  380. reason: lang.get('rcscript.audit_reason', wiki.href),
  381. text: webhook_lang.get('created', body.query.general.sitename) + ( wikiid && settings.feeds_only ? '' : `\n<${wiki.toLink(body.query.pages['-1'].title)}>` ) + ( wikiid ? `\n<${wiki.href}f>` : '' )
  382. } ).then( webhook => {
  383. if ( !webhook ) return res(`/guild/${guild}/rcscript/new`, 'savefail');
  384. var configid = 1;
  385. for ( let i of row.count ) {
  386. if ( configid === i ) configid++;
  387. else break;
  388. }
  389. db.run( 'INSERT INTO rcgcdw(guild, configid, webhook, wiki, lang, display, wikiid, rcid) VALUES(?, ?, ?, ?, ?, ?, ?, ?)', [guild, configid, webhook, wiki.href, settings.lang, settings.display, wikiid, ( wikiid && settings.feeds_only ? -1 : null )], function (dberror) {
  390. if ( dberror ) {
  391. console.log( '- Dashboard: Error while adding the RcGcDw: ' + dberror );
  392. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  393. }
  394. console.log( `- Dashboard: RcGcDw successfully added: ${guild}#${configid}` );
  395. res(`/guild/${guild}/rcscript/${configid}`, 'save');
  396. var text = lang.get('rcscript.dashboard.added', `<@${userSettings.user.id}>`, configid);
  397. text += `\n${lang.get('rcscript.channel')} <#${settings.channel}>`;
  398. text += `\n${lang.get('rcscript.wiki')} <${wiki.href}>`;
  399. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[settings.lang]}\``;
  400. text += `\n${lang.get('rcscript.display')} \`${display_types[settings.display]}\``;
  401. if ( wikiid && settings.feeds_only ) text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  402. if ( wiki.isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( wikiid ? 'enabled' : 'disabled' ))}\`*`;
  403. text += `\n<${new URL(`/guild/${guild}/rcscript/${configid}`, process.env.dashboard).href}>`;
  404. sendMsg( {
  405. type: 'notifyGuild', guild, text,
  406. file: [`./RcGcDb/locale/widgets/${settings.lang}.png`]
  407. } ).catch( error => {
  408. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  409. } );
  410. } );
  411. }, error => {
  412. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  413. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  414. } );
  415. }
  416. } );
  417. }, error => {
  418. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  419. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  420. } );
  421. } );
  422. }, error => {
  423. console.log( '- Dashboard: Error while getting the member: ' + error );
  424. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  425. } );
  426. type = parseInt(type, 10);
  427. return db.get( 'SELECT discord.lang mainlang, webhook, rcgcdw.wiki, rcgcdw.lang, display, wikiid, rcid FROM discord LEFT JOIN rcgcdw ON discord.guild = rcgcdw.guild AND configid = ? WHERE discord.guild = ? AND discord.channel IS NULL', [type, guild], function(curerror, row) {
  428. if ( curerror ) {
  429. console.log( '- Dashboard: Error while checking for RcGcDw: ' + curerror );
  430. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  431. }
  432. if ( !row?.webhook ) return res(`/guild/${guild}/rcscript`, 'savefail');
  433. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( wresponse => {
  434. if ( !wresponse.body?.channel_id ) {
  435. console.log( '- Dashboard: ' + wresponse.statusCode + ': Error while getting the webhook: ' + wresponse.body?.message );
  436. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  437. }
  438. row.channel = wresponse.body.channel_id;
  439. var newChannel = false;
  440. if ( settings.save_settings && row.channel !== settings.channel ) {
  441. if ( !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  442. return ( channel.id === settings.channel );
  443. } ) ) return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  444. newChannel = true;
  445. }
  446. return sendMsg( {
  447. type: 'getMember',
  448. member: userSettings.user.id,
  449. guild: guild,
  450. channel: row.channel,
  451. newchannel: ( newChannel ? settings.channel : undefined )
  452. } ).then( response => {
  453. if ( !response ) {
  454. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  455. userSettings.guilds.isMember.delete(guild);
  456. return res(`/guild/${guild}`, 'savefail');
  457. }
  458. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  459. userSettings.guilds.isMember.delete(guild);
  460. return res('/', 'savefail');
  461. }
  462. if ( response.message === 'noChannel' ) {
  463. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  464. }
  465. if ( settings.delete_settings ) {
  466. if ( !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  467. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  468. }
  469. return db.run( 'DELETE FROM rcgcdw WHERE webhook = ?', [row.webhook], function (delerror) {
  470. if ( delerror ) {
  471. console.log( '- Dashboard: Error while removing the RcGcDw: ' + delerror );
  472. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  473. }
  474. console.log( `- Dashboard: RcGcDw successfully removed: ${guild}#${type}` );
  475. res(`/guild/${guild}/rcscript`, 'save');
  476. var lang = new Lang(row.mainlang);
  477. var webhook_lang = new Lang(row.lang, 'rcscript.webhook');
  478. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  479. json: {
  480. content: webhook_lang.get('deleted')
  481. }
  482. } ).then( delresponse => {
  483. if ( delresponse.statusCode !== 204 ) {
  484. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  485. }
  486. }, error => {
  487. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  488. } ).finally( () => {
  489. got.delete( 'https://discord.com/api/webhooks/' + row.webhook, {
  490. headers: {
  491. 'X-Audit-Log-Reason': lang.get('rcscript.audit_reason_delete')
  492. }
  493. } ).then( delresponse => {
  494. if ( delresponse.statusCode !== 204 ) {
  495. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while removing the webhook: ' + delresponse.body?.message );
  496. }
  497. else console.log( `- Dashboard: Webhook successfully removed: ${guild}#${row.channel}` );
  498. }, error => {
  499. console.log( '- Dashboard: Error while removing the webhook: ' + error );
  500. } )
  501. } );
  502. var text = lang.get('rcscript.dashboard.deleted', `<@${userSettings.user.id}>`, type);
  503. text += `\n${lang.get('rcscript.channel')} <#${row.channel}>`;
  504. text += `\n${lang.get('rcscript.wiki')} <${row.wiki}>`;
  505. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[row.lang]}\``;
  506. text += `\n${lang.get('rcscript.display')} \`${display_types[row.display]}\``;
  507. if ( row.rcid === -1 ) {
  508. text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  509. }
  510. if ( new Wiki(row.wiki).isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( row.wikiid ? 'enabled' : 'disabled' ))}\`*`;
  511. text += `\n<${new URL(`/guild/${guild}/rcscript`, process.env.dashboard).href}>`;
  512. sendMsg( {
  513. type: 'notifyGuild', guild, text
  514. } ).catch( error => {
  515. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  516. } );
  517. } );
  518. }
  519. if ( newChannel && ( !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS')
  520. || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  521. || !hasPerm(response.userPermissionsNew, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  522. || !hasPerm(response.botPermissionsNew, 'MANAGE_WEBHOOKS') ) ) {
  523. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  524. }
  525. var hasDiff = false;
  526. if ( newChannel ) hasDiff = true;
  527. if ( row.wiki !== settings.wiki ) hasDiff = true;
  528. if ( row.lang !== settings.lang ) hasDiff = true;
  529. if ( row.display !== settings.display ) hasDiff = true;
  530. if ( ( row.rcid !== -1 ) !== !( settings.feeds && settings.feeds_only ) ) hasDiff = true;
  531. if ( !row.wikiid !== !settings.feeds ) hasDiff = true;
  532. if ( !hasDiff ) return res(`/guild/${guild}/rcscript/${type}`, 'save');
  533. var wiki = Wiki.fromInput(settings.wiki);
  534. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&format=json' ).then( fresponse => {
  535. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  536. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  537. if ( api ) {
  538. wiki = new Wiki(api.split('api.php?')[0], wiki);
  539. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&format=json' );
  540. }
  541. }
  542. return fresponse;
  543. } ).then( fresponse => {
  544. var body = fresponse.body;
  545. if ( fresponse.statusCode !== 200 || !body?.query?.allmessages || !body?.query?.general ) {
  546. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  547. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  548. }
  549. wiki.updateWiki(body.query.general);
  550. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  551. return res(`/guild/${guild}/rcscript/${type}`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  552. }
  553. if ( row.wiki !== wiki.href && body.query.allmessages[0]['*'] !== guild ) {
  554. return res(`/guild/${guild}/rcscript/${type}`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  555. }
  556. return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
  557. if ( blerror ) {
  558. console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
  559. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  560. }
  561. if ( block ) {
  562. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  563. return res(`/guild/${guild}/rcscript/${type}`, 'wikiblocked', body.query.general.sitename, block.reason);
  564. }
  565. if ( settings.feeds ) {
  566. let wikiid = body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'];
  567. if ( wiki.isFandom(false) && wikiid ) return got.get( 'https://services.fandom.com/discussion/' + wikiid + '/posts?limit=1&format=json&cache=' + Date.now(), {
  568. headers: {
  569. Accept: 'application/hal+json'
  570. }
  571. } ).then( dsresponse => {
  572. var dsbody = dsresponse.body;
  573. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
  574. if ( dsbody?.title !== 'site doesn\'t exists' ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  575. return updateWebhook();
  576. }
  577. return updateWebhook(parseInt(wikiid, 10));
  578. }, error => {
  579. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  580. return updateWebhook();
  581. } );
  582. }
  583. return updateWebhook();
  584. /**
  585. * Creates the webhook.
  586. * @param {Number} wikiid - The ID of the wiki.
  587. */
  588. function updateWebhook(wikiid = null) {
  589. var sql = 'UPDATE rcgcdw SET wiki = ?, lang = ?, display = ?, wikiid = ? WHERE webhook = ?';
  590. var sqlargs = [wiki.href, settings.lang, settings.display, wikiid];
  591. if ( wikiid && settings.feeds_only ) {
  592. sql = 'UPDATE rcgcdw SET wiki = ?, lang = ?, display = ?, wikiid = ?, rcid = ? WHERE webhook = ?';
  593. sqlargs.push(-1);
  594. }
  595. db.run( sql, [...sqlargs, row.webhook], function (dberror) {
  596. if ( dberror ) {
  597. console.log( '- Dashboard: Error while updating the RcGcDw: ' + dberror );
  598. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  599. }
  600. console.log( `- Dashboard: RcGcDw successfully updated: ${guild}#${type}` );
  601. var lang = new Lang(row.mainlang);
  602. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  603. var diff = [];
  604. var file = [];
  605. var webhook_diff = [];
  606. if ( newChannel ) {
  607. diff.push(lang.get('rcscript.channel') + ` ~~<#${row.channel}>~~ → <#${settings.channel}>`);
  608. webhook_diff.push(webhook_lang.get('dashboard.channel'));
  609. }
  610. if ( row.wiki !== wiki.href ) {
  611. diff.push(lang.get('rcscript.wiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
  612. webhook_diff.push(webhook_lang.get('dashboard.wiki', `[${body.query.general.sitename}](<${wiki.href}>)`));
  613. }
  614. if ( row.lang !== settings.lang ) {
  615. file.push(`./RcGcDb/locale/widgets/${settings.lang}.png`);
  616. diff.push(lang.get('rcscript.lang') + ` ~~\`${allLangs.names[row.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
  617. webhook_diff.push(webhook_lang.get('dashboard.lang', allLangs.names[settings.lang]));
  618. }
  619. if ( row.display !== settings.display ) {
  620. diff.push(lang.get('rcscript.display') + ` ~~\`${display_types[row.display]}\`~~ → \`${display_types[settings.display]}\``);
  621. webhook_diff.push(webhook_lang.get('dashboard.display_' + display_types[settings.display]));
  622. }
  623. if ( ( row.rcid !== -1 ) !== !( wikiid && settings.feeds_only ) ) {
  624. diff.push(lang.get('rcscript.rc') + ` ~~*\`${lang.get('rcscript.' + ( row.rcid === -1 ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( settings.feeds_only ? 'disabled' : 'enabled' ))}\`*`);
  625. webhook_diff.push(webhook_lang.get('dashboard.' + ( settings.feeds_only ? 'disabled_rc' : 'enabled_rc' )));
  626. }
  627. if ( !row.wikiid !== !wikiid ) {
  628. diff.push(lang.get('rcscript.feeds') + ` ~~*\`${lang.get('rcscript.' + ( row.wikiid ? 'enabled' : 'disabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( wikiid ? 'enabled' : 'disabled' ))}\`*`);
  629. webhook_diff.push(webhook_lang.get('dashboard.' + ( wikiid ? 'disabled_feeds' : 'enabled_feeds' )));
  630. }
  631. if ( newChannel ) return sendMsg( {
  632. type: 'moveWebhook',
  633. guild: guild,
  634. webhook: row.webhook,
  635. channel: settings.channel,
  636. reason: lang.get('rcscript.audit_reason_move'),
  637. text: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  638. } ).then( webhook => {
  639. if ( !webhook ) return Promise.reject();
  640. res(`/guild/${guild}/rcscript/${type}`, 'save');
  641. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  642. text += '\n' + diff.join('\n');
  643. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  644. sendMsg( {
  645. type: 'notifyGuild', guild, text, file
  646. } ).catch( error => {
  647. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  648. } );
  649. }, error => {
  650. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  651. return Promise.reject();
  652. } ).catch( () => {
  653. diff.shift();
  654. webhook_diff.shift();
  655. if ( !diff.length ) {
  656. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  657. }
  658. res(`/guild/${guild}/rcscript/${type}`, 'movefail');
  659. diff.shift();
  660. webhook_diff.shift();
  661. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  662. json: {
  663. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  664. }
  665. } ).then( delresponse => {
  666. if ( delresponse.statusCode !== 204 ) {
  667. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  668. }
  669. }, error => {
  670. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  671. } )
  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. } );
  681. res(`/guild/${guild}/rcscript/${type}`, 'save');
  682. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  683. json: {
  684. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  685. }
  686. } ).then( delresponse => {
  687. if ( delresponse.statusCode !== 204 ) {
  688. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  689. }
  690. }, error => {
  691. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  692. } )
  693. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  694. text += '\n' + diff.join('\n');
  695. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  696. sendMsg( {
  697. type: 'notifyGuild', guild, text, file
  698. } ).catch( error => {
  699. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  700. } );
  701. } );
  702. }
  703. } );
  704. }, error => {
  705. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  706. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  707. } );
  708. }, error => {
  709. console.log( '- Dashboard: Error while getting the member: ' + error );
  710. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  711. } );
  712. }, error => {
  713. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  714. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  715. } );
  716. } );
  717. }
  718. module.exports = {
  719. get: dashboard_rcscript,
  720. post: update_rcscript
  721. };