rcscript.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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, 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>',
  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>'
  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>`).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' ) {
  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?save=failed`);
  238. }
  239. if ( !settings.save_settings === !settings.delete_settings ) {
  240. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  241. }
  242. if ( settings.save_settings ) {
  243. if ( !settings.wiki || !( settings.lang in allLangs.names ) ) {
  244. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  245. }
  246. if ( !['0', '1', '2', '3'].includes( settings.display ) ) {
  247. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  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?save=failed`);
  253. }
  254. if ( settings.delete_settings && type === 'new' ) {
  255. return res(`/guild/${guild}/rcscript/new?save=failed`);
  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}?save=failed`);
  267. }
  268. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  269. userSettings.guilds.isMember.delete(guild);
  270. return res('/?save=failed');
  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?save=failed`);
  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?save=failed`);
  282. }
  283. if ( !row ) return res(`/guild/${guild}/rcscript?save=failed`);
  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?save=failed`);
  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?save=failed`);
  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?save=failed`);
  308. }
  309. if ( body.query.allmessages[0]['*'] !== guild ) {
  310. return res(`/guild/${guild}/rcscript/new?save=failed`);
  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?save=failed`);
  316. }
  317. if ( block ) return res(`/guild/${guild}/rcscript/new?save=failed`);
  318. if ( settings.feeds ) {
  319. let wikiid = body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'];
  320. if ( wiki.isFandom(false) && wikiid ) return got.get( 'https://services.fandom.com/discussion/' + wikiid + '/posts?limit=1&format=json&cache=' + Date.now(), {
  321. headers: {
  322. Accept: 'application/hal+json'
  323. }
  324. } ).then( dsresponse => {
  325. var dsbody = dsresponse.body;
  326. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
  327. if ( dsbody?.title !== 'site doesn\'t exists' ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  328. return createWebhook();
  329. }
  330. return createWebhook(parseInt(wikiid, 10));
  331. }, error => {
  332. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  333. return createWebhook();
  334. } );
  335. }
  336. return createWebhook();
  337. /**
  338. * Creates the webhook.
  339. * @param {Number} wikiid - The ID of the wiki.
  340. */
  341. function createWebhook(wikiid = null) {
  342. var lang = new Lang(row.lang);
  343. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  344. sendMsg( {
  345. type: 'createWebhook',
  346. guild: guild,
  347. channel: settings.channel,
  348. name: ( body.query.allmessages[1]['*'] || 'Recent changes' ),
  349. reason: lang.get('rcscript.audit_reason', wiki.href),
  350. 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>` : '' )
  351. } ).then( webhook => {
  352. if ( !webhook ) return res(`/guild/${guild}/rcscript/new?save=failed`);
  353. var configid = 1;
  354. for ( let i of row.count ) {
  355. if ( configid === i ) configid++;
  356. else break;
  357. }
  358. 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) {
  359. if ( dberror ) {
  360. console.log( '- Dashboard: Error while adding the RcGcDw: ' + dberror );
  361. return res(`/guild/${guild}/rcscript/new?save=failed`);
  362. }
  363. console.log( `- Dashboard: RcGcDw successfully added: ${guild}#${configid}` );
  364. res(`/guild/${guild}/rcscript/${configid}?save=success`);
  365. var text = lang.get('rcscript.dashboard.added', `<@${userSettings.user.id}>`, configid);
  366. text += `\n${lang.get('rcscript.channel')} <#${settings.channel}>`;
  367. text += `\n${lang.get('rcscript.wiki')} <${wiki.href}>`;
  368. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[settings.lang]}\``;
  369. text += `\n${lang.get('rcscript.display')} \`${display_types[settings.display]}\``;
  370. if ( wikiid && settings.feeds_only ) text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  371. if ( wiki.isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( wikiid ? 'enabled' : 'disabled' ))}\`*`;
  372. text += `\n<${new URL(`/guild/${guild}/rcscript/${configid}`, process.env.dashboard).href}>`;
  373. sendMsg( {
  374. type: 'notifyGuild', guild, text
  375. } ).catch( error => {
  376. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  377. } );
  378. } );
  379. }, error => {
  380. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  381. return res(`/guild/${guild}/rcscript/new?save=failed`);
  382. } );
  383. }
  384. } );
  385. }, error => {
  386. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  387. return res(`/guild/${guild}/rcscript/new?save=failed`);
  388. } );
  389. } );
  390. }, error => {
  391. console.log( '- Dashboard: Error while getting the member: ' + error );
  392. return res(`/guild/${guild}/rcscript/new?save=failed`);
  393. } );
  394. type = parseInt(type, 10);
  395. 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) {
  396. if ( curerror ) {
  397. console.log( '- Dashboard: Error while checking for RcGcDw: ' + curerror );
  398. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  399. }
  400. if ( !row?.webhook ) return res(`/guild/${guild}/rcscript?save=failed`);
  401. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( wresponse => {
  402. if ( !wresponse.body?.channel_id ) {
  403. console.log( '- Dashboard: ' + wresponse.statusCode + ': Error while getting the webhook: ' + wresponse.body?.message );
  404. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  405. }
  406. row.channel = wresponse.body.channel_id;
  407. var newChannel = false;
  408. if ( settings.save_settings && row.channel !== settings.channel ) {
  409. if ( !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  410. return ( channel.id === settings.channel );
  411. } ) ) return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  412. newChannel = true;
  413. }
  414. return sendMsg( {
  415. type: 'getMember',
  416. member: userSettings.user.id,
  417. guild: guild,
  418. channel: row.channel,
  419. newchannel: ( newChannel ? settings.channel : undefined )
  420. } ).then( response => {
  421. if ( !response ) {
  422. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  423. userSettings.guilds.isMember.delete(guild);
  424. return res(`/guild/${guild}?save=failed`);
  425. }
  426. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  427. userSettings.guilds.isMember.delete(guild);
  428. return res('/?save=failed');
  429. }
  430. if ( response.message === 'noChannel' ) {
  431. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  432. }
  433. if ( settings.delete_settings ) {
  434. if ( !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  435. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  436. }
  437. return db.run( 'DELETE FROM rcgcdw WHERE webhook = ?', [row.webhook], function (delerror) {
  438. if ( delerror ) {
  439. console.log( '- Dashboard: Error while removing the RcGcDw: ' + delerror );
  440. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  441. }
  442. console.log( `- Dashboard: RcGcDw successfully removed: ${guild}#${type}` );
  443. res(`/guild/${guild}/rcscript?save=success`);
  444. var lang = new Lang(row.mainlang);
  445. var webhook_lang = new Lang(row.lang, 'rcscript.webhook');
  446. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  447. json: {
  448. content: webhook_lang.get('deleted')
  449. }
  450. } ).then( delresponse => {
  451. if ( delresponse.statusCode !== 204 ) {
  452. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  453. }
  454. }, error => {
  455. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  456. } ).finally( () => {
  457. got.delete( 'https://discord.com/api/webhooks/' + row.webhook, {
  458. headers: {
  459. 'X-Audit-Log-Reason': lang.get('rcscript.audit_reason_delete')
  460. }
  461. } ).then( delresponse => {
  462. if ( delresponse.statusCode !== 204 ) {
  463. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while removing the webhook: ' + delresponse.body?.message );
  464. }
  465. else console.log( `- Dashboard: Webhook successfully removed: ${guild}#${row.channel}` );
  466. }, error => {
  467. console.log( '- Dashboard: Error while removing the webhook: ' + error );
  468. } )
  469. } );
  470. var text = lang.get('rcscript.dashboard.deleted', `<@${userSettings.user.id}>`, type);
  471. text += `\n${lang.get('rcscript.channel')} <#${row.channel}>`;
  472. text += `\n${lang.get('rcscript.wiki')} <${row.wiki}>`;
  473. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[row.lang]}\``;
  474. text += `\n${lang.get('rcscript.display')} \`${display_types[row.display]}\``;
  475. if ( row.rcid === -1 ) {
  476. text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  477. }
  478. if ( new Wiki(row.wiki).isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( row.wikiid ? 'enabled' : 'disabled' ))}\`*`;
  479. text += `\n<${new URL(`/guild/${guild}/rcscript`, process.env.dashboard).href}>`;
  480. sendMsg( {
  481. type: 'notifyGuild', guild, text
  482. } ).catch( error => {
  483. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  484. } );
  485. } );
  486. }
  487. if ( newChannel && ( !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS')
  488. || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  489. || !hasPerm(response.userPermissionsNew, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  490. || !hasPerm(response.botPermissionsNew, 'MANAGE_WEBHOOKS') ) ) {
  491. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  492. }
  493. var diff = false;
  494. if ( newChannel ) diff = true;
  495. if ( row.wiki !== settings.wiki ) diff = true;
  496. if ( row.lang !== settings.lang ) diff = true;
  497. if ( row.display !== settings.display ) diff = true;
  498. if ( ( row.rcid !== -1 ) !== !( settings.feeds && settings.feeds_only ) ) diff = true;
  499. if ( !row.wikiid !== !settings.feeds ) diff = true;
  500. if ( !diff ) return res(`/guild/${guild}/rcscript/${type}?save=success`);
  501. var wiki = Wiki.fromInput(settings.wiki);
  502. 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 => {
  503. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  504. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  505. if ( api ) {
  506. wiki = new Wiki(api.split('api.php?')[0], wiki);
  507. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general' + ( wiki.isFandom() ? '|variables' : '' ) + '&format=json' );
  508. }
  509. }
  510. return fresponse;
  511. } ).then( fresponse => {
  512. var body = fresponse.body;
  513. if ( fresponse.statusCode !== 200 || !body?.query?.allmessages || !body?.query?.general ) {
  514. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  515. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  516. }
  517. wiki.updateWiki(body.query.general);
  518. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  519. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  520. }
  521. if ( row.wiki !== wiki.href && body.query.allmessages[0]['*'] !== guild ) {
  522. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  523. }
  524. return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
  525. if ( blerror ) {
  526. console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
  527. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  528. }
  529. if ( block ) return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  530. if ( settings.feeds ) {
  531. let wikiid = body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'];
  532. if ( wiki.isFandom(false) && wikiid ) return got.get( 'https://services.fandom.com/discussion/' + wikiid + '/posts?limit=1&format=json&cache=' + Date.now(), {
  533. headers: {
  534. Accept: 'application/hal+json'
  535. }
  536. } ).then( dsresponse => {
  537. var dsbody = dsresponse.body;
  538. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
  539. if ( dsbody?.title !== 'site doesn\'t exists' ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  540. return updateWebhook();
  541. }
  542. return updateWebhook(parseInt(wikiid, 10));
  543. }, error => {
  544. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  545. return updateWebhook();
  546. } );
  547. }
  548. return updateWebhook();
  549. /**
  550. * Creates the webhook.
  551. * @param {Number} wikiid - The ID of the wiki.
  552. */
  553. function updateWebhook(wikiid = null) {
  554. 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) {
  555. if ( dberror ) {
  556. console.log( '- Dashboard: Error while updating the RcGcDw: ' + dberror );
  557. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  558. }
  559. console.log( `- Dashboard: RcGcDw successfully updated: ${guild}#${type}` );
  560. var lang = new Lang(row.mainlang);
  561. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  562. var diff = [];
  563. var webhook_diff = [];
  564. if ( newChannel ) {
  565. diff.push(lang.get('rcscript.channel') + ` ~~<#${row.channel}>~~ → <#${settings.channel}>`);
  566. webhook_diff.push(webhook_lang.get('dashboard.channel'));
  567. }
  568. if ( row.wiki !== wiki.href ) {
  569. diff.push(lang.get('rcscript.wiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
  570. webhook_diff.push(webhook_lang.get('dashboard.wiki', `[${body.query.general.sitename}](<${wiki.href}>)`));
  571. }
  572. if ( row.lang !== settings.lang ) {
  573. diff.push(lang.get('rcscript.lang') + ` ~~\`${allLangs.names[row.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
  574. webhook_diff.push(webhook_lang.get('dashboard.lang', allLangs.names[settings.lang]));
  575. }
  576. if ( row.display !== settings.display ) {
  577. diff.push(lang.get('rcscript.display') + ` ~~\`${display_types[row.display]}\`~~ → \`${display_types[settings.display]}\``);
  578. webhook_diff.push(webhook_lang.get('dashboard.display_' + display_types[settings.display]));
  579. }
  580. if ( ( row.rcid !== -1 ) !== !( wikiid && settings.feeds_only ) ) {
  581. diff.push(lang.get('rcscript.rc') + ` ~~*\`${lang.get('rcscript.' + ( row.rcid === -1 ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( settings.feeds_only ? 'disabled' : 'enabled' ))}\`*`);
  582. webhook_diff.push(webhook_lang.get('dashboard.' + ( settings.feeds_only ? 'disabled_rc' : 'enabled_rc' )));
  583. }
  584. if ( !row.wikiid !== !wikiid ) {
  585. diff.push(lang.get('rcscript.feeds') + ` ~~*\`${lang.get('rcscript.' + ( row.wikiid ? 'enabled' : 'disabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( wikiid ? 'enabled' : 'disabled' ))}\`*`);
  586. webhook_diff.push(webhook_lang.get('dashboard.' + ( wikiid ? 'disabled_feeds' : 'enabled_feeds' )));
  587. }
  588. if ( newChannel ) return sendMsg( {
  589. type: 'moveWebhook',
  590. guild: guild,
  591. webhook: row.webhook,
  592. channel: settings.channel,
  593. reason: lang.get('rcscript.audit_reason_move'),
  594. text: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  595. } ).then( webhook => {
  596. if ( !webhook ) return Promise.reject();
  597. res(`/guild/${guild}/rcscript/${type}?save=success`);
  598. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  599. text += '\n' + diff.join('\n');
  600. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  601. sendMsg( {
  602. type: 'notifyGuild', guild, text
  603. } ).catch( error => {
  604. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  605. } );
  606. }, error => {
  607. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  608. return Promise.reject();
  609. } ).catch( () => {
  610. res(`/guild/${guild}/rcscript/${type}?save=partial`);
  611. diff.shift();
  612. webhook_diff.shift();
  613. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  614. json: {
  615. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  616. }
  617. } ).then( delresponse => {
  618. if ( delresponse.statusCode !== 204 ) {
  619. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  620. }
  621. }, error => {
  622. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  623. } )
  624. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  625. text += '\n' + diff.join('\n');
  626. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  627. sendMsg( {
  628. type: 'notifyGuild', guild, text
  629. } ).catch( error => {
  630. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  631. } );
  632. } );
  633. res(`/guild/${guild}/rcscript/${type}?save=success`);
  634. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  635. json: {
  636. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  637. }
  638. } ).then( delresponse => {
  639. if ( delresponse.statusCode !== 204 ) {
  640. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  641. }
  642. }, error => {
  643. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  644. } )
  645. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  646. text += '\n' + diff.join('\n');
  647. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  648. sendMsg( {
  649. type: 'notifyGuild', guild, text
  650. } ).catch( error => {
  651. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  652. } );
  653. } );
  654. }
  655. } );
  656. }, error => {
  657. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  658. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  659. } );
  660. }, error => {
  661. console.log( '- Dashboard: Error while getting the member: ' + error );
  662. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  663. } );
  664. }, error => {
  665. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  666. return res(`/guild/${guild}/rcscript/${type}?save=failed`);
  667. } );
  668. } );
  669. }
  670. module.exports = {
  671. get: dashboard_rcscript,
  672. post: update_rcscript
  673. };