1
0

rcscript.js 34 KB

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