rcscript.js 37 KB

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