rcscript.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. const cheerio = require('cheerio');
  2. const {defaultSettings, limit: {rcgcdw: rcgcdwLimit}} = require('../util/default.json');
  3. const Lang = require('../util/i18n.js');
  4. const allLangs = Lang.allLangs(true);
  5. const Wiki = require('../util/wiki.js');
  6. const {got, db, sendMsg, createNotice, hasPerm} = require('./util.js');
  7. const display_types = [
  8. 'compact',
  9. 'embed',
  10. 'image',
  11. 'diff'
  12. ];
  13. const fieldset = {
  14. channel: '<label for="wb-settings-channel">Channel:</label>'
  15. + '<select id="wb-settings-channel" name="channel" required></select>',
  16. wiki: '<label for="wb-settings-wiki">Wiki:</label>'
  17. + '<input type="url" id="wb-settings-wiki" name="wiki" list="wb-settings-wiki-list" required autocomplete="url">'
  18. + '<datalist id="wb-settings-wiki-list"></datalist>'
  19. + '<button type="button" id="wb-settings-wiki-check">Check wiki</button>'
  20. + '<div id="wb-settings-wiki-check-notice"></div>',
  21. //+ '<button type="button" id="wb-settings-wiki-search" class="collapsible">Search wiki</button>'
  22. //+ '<fieldset style="display: none;">'
  23. //+ '<legend>Wiki search</legend>'
  24. //+ '</fieldset>',
  25. lang: '<label for="wb-settings-lang">Language:</label>'
  26. + '<select id="wb-settings-lang" name="lang" required autocomplete="language">'
  27. + Object.keys(allLangs.names).map( lang => {
  28. return `<option id="wb-settings-lang-${lang}" value="${lang}">${allLangs.names[lang]}</option>`
  29. } ).join('')
  30. + '</select>'
  31. + '<img id="wb-settings-lang-widget">',
  32. display: '<span>Display mode:</span>'
  33. + '<div class="wb-settings-display">'
  34. + '<input type="radio" id="wb-settings-display-0" name="display" value="0" required>'
  35. + '<label for="wb-settings-display-0">Compact text messages with inline links.</label>'
  36. + '</div><div class="wb-settings-display">'
  37. + '<input type="radio" id="wb-settings-display-1" name="display" value="1" required>'
  38. + '<label for="wb-settings-display-1">Embed messages with edit tags and category changes.</label>'
  39. + '</div><div class="wb-settings-display">'
  40. + '<input type="radio" id="wb-settings-display-2" name="display" value="2" required>'
  41. + '<label for="wb-settings-display-2">Embed messages with image previews.</label>'
  42. + '</div><div class="wb-settings-display">'
  43. + '<input type="radio" id="wb-settings-display-3" name="display" value="3" required>'
  44. + '<label for="wb-settings-display-3">Embed messages with image previews and edit differences.</label>'
  45. + '</div>',
  46. feeds: '<label for="wb-settings-feeds">Feeds based changes:</label>'
  47. + '<input type="checkbox" id="wb-settings-feeds" name="feeds">'
  48. + '<div id="wb-settings-feeds-only-hide">'
  49. + '<label for="wb-settings-feeds-only">Only feeds based changes:</label>'
  50. + '<input type="checkbox" id="wb-settings-feeds-only" name="feeds_only">'
  51. + '</div>',
  52. save: '<input type="submit" id="wb-settings-save" name="save_settings">',
  53. delete: '<input type="submit" id="wb-settings-delete" name="delete_settings" formnovalidate>'
  54. };
  55. /**
  56. * Create a settings form
  57. * @param {import('cheerio')} $ - The response body
  58. * @param {String} header - The form header
  59. * @param {import('./i18n.js')} dashboardLang - The user language
  60. * @param {Object} settings - The current settings
  61. * @param {Boolean} settings.patreon
  62. * @param {String} [settings.channel]
  63. * @param {String} settings.wiki
  64. * @param {String} settings.lang
  65. * @param {Number} settings.display
  66. * @param {Number} [settings.rcid]
  67. * @param {String} [settings.postid]
  68. * @param {import('./util.js').Channel[]} guildChannels - The guild channels
  69. * @param {String[]} allWikis - The guild wikis
  70. */
  71. function createForm($, header, dashboardLang, settings, guildChannels, allWikis) {
  72. var readonly = ( process.env.READONLY ? true : false );
  73. var curChannel = guildChannels.find( guildChannel => settings.channel === guildChannel.id );
  74. var fields = [];
  75. let channel = $('<div>').append(fieldset.channel);
  76. channel.find('label').text(dashboardLang.get('rcscript.form.channel'));
  77. let curCat = null;
  78. if ( !settings.channel || ( curChannel && hasPerm(curChannel.botPermissions, 'MANAGE_WEBHOOKS') && hasPerm(curChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) ) {
  79. channel.find('#wb-settings-channel').append(
  80. ...guildChannels.filter( guildChannel => {
  81. return ( ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') && hasPerm(guildChannel.botPermissions, 'MANAGE_WEBHOOKS') ) || guildChannel.isCategory );
  82. } ).map( guildChannel => {
  83. if ( guildChannel.isCategory ) {
  84. curCat = $('<optgroup>').attr('label', guildChannel.name);
  85. return curCat;
  86. }
  87. var optionChannel = $(`<option id="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – #${guildChannel.name}`);
  88. if ( settings.channel === guildChannel.id ) {
  89. optionChannel.attr('selected', '');
  90. }
  91. if ( !curCat ) return optionChannel;
  92. optionChannel.appendTo(curCat);
  93. } ).filter( catChannel => {
  94. if ( !catChannel ) return false;
  95. if ( catChannel.is('optgroup') && !catChannel.children('option').length ) return false;
  96. return true;
  97. } )
  98. );
  99. if ( !settings.channel ) {
  100. if ( !channel.find('#wb-settings-channel').children('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.postid !== '-1' ) {
  143. feeds.find('#wb-settings-feeds').attr('checked', '');
  144. if ( settings.rcid === -1 ) feeds.find('#wb-settings-feeds-only').attr('checked', '');
  145. }
  146. else feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
  147. }
  148. else {
  149. feeds.attr('style', 'display: none;');
  150. feeds.find('#wb-settings-feeds-only-hide').attr('style', 'visibility: hidden;');
  151. }
  152. fields.push(feeds);
  153. fields.push($(fieldset.save).val(dashboardLang.get('general.save')));
  154. if ( settings.channel && curChannel && hasPerm(curChannel.userPermissions, 'MANAGE_WEBHOOKS') ) {
  155. fields.push($(fieldset.delete).val(dashboardLang.get('general.delete')).attr('onclick', `return confirm('${dashboardLang.get('rcscript.form.confirm').replace( /'/g, '\\$&' )}');`));
  156. }
  157. var form = $('<fieldset>').append(...fields);
  158. if ( readonly ) {
  159. form.find('input').attr('readonly', '');
  160. form.find('input[type="checkbox"], input[type="radio"]:not(:checked), option, optgroup').attr('disabled', '');
  161. form.find('input[type="submit"], button.addmore').remove();
  162. }
  163. return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  164. $('<h2>').text(header),
  165. form
  166. );
  167. }
  168. /**
  169. * Let a user change recent changes scripts
  170. * @param {import('http').ServerResponse} res - The server response
  171. * @param {import('cheerio')} $ - The response body
  172. * @param {import('./util.js').Guild} guild - The current guild
  173. * @param {String[]} args - The url parts
  174. * @param {import('./i18n.js')} dashboardLang - The user language
  175. */
  176. function dashboard_rcscript(res, $, guild, args, dashboardLang) {
  177. db.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, rcid, postid 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': Buffer.byteLength(body)});
  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': Buffer.byteLength(body)});
  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: ( allLangs.names.hasOwnProperty(lang) ? 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': Buffer.byteLength(body)});
  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 || !allLangs.names.hasOwnProperty(settings.lang) ) {
  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&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&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 && wiki.isFandom(false) ) return got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=1&format=json&cache=' + Date.now(), {
  361. headers: {
  362. Accept: 'application/hal+json'
  363. }
  364. } ).then( dsresponse => {
  365. var dsbody = dsresponse.body;
  366. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  367. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  368. return createWebhook();
  369. }
  370. return createWebhook(true);
  371. }, error => {
  372. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  373. return createWebhook();
  374. } );
  375. return createWebhook();
  376. /**
  377. * Creates the webhook.
  378. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  379. */
  380. function createWebhook(enableFeeds = false) {
  381. var lang = new Lang(row.lang);
  382. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  383. sendMsg( {
  384. type: 'createWebhook',
  385. guild: guild,
  386. channel: settings.channel,
  387. name: ( body.query.allmessages[1]['*'] || 'Recent changes' ),
  388. reason: lang.get('rcscript.audit_reason', wiki.href),
  389. text: webhook_lang.get('created', body.query.general.sitename) + ( enableFeeds && settings.feeds_only ? '' : `\n<${wiki.toLink(body.query.pages['-1'].title)}>` ) + ( enableFeeds ? `\n<${wiki.href}f>` : '' )
  390. } ).then( webhook => {
  391. if ( !webhook ) return res(`/guild/${guild}/rcscript/new`, 'savefail');
  392. var configid = 1;
  393. for ( let i of row.count ) {
  394. if ( configid === i ) configid++;
  395. else break;
  396. }
  397. db.run( 'INSERT INTO rcgcdw(guild, configid, webhook, wiki, lang, display, rcid, postid) VALUES(?, ?, ?, ?, ?, ?, ?, ?)', [guild, configid, webhook, wiki.href, settings.lang, settings.display, ( enableFeeds && settings.feeds_only ? -1 : null ), ( enableFeeds ? null : '-1' )], function (dberror) {
  398. if ( dberror ) {
  399. console.log( '- Dashboard: Error while adding the RcGcDw: ' + dberror );
  400. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  401. }
  402. console.log( `- Dashboard: RcGcDw successfully added: ${guild}#${configid}` );
  403. res(`/guild/${guild}/rcscript/${configid}`, 'save');
  404. var text = lang.get('rcscript.dashboard.added', `<@${userSettings.user.id}>`, configid);
  405. text += `\n${lang.get('rcscript.channel')} <#${settings.channel}>`;
  406. text += `\n${lang.get('rcscript.wiki')} <${wiki.href}>`;
  407. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[settings.lang]}\``;
  408. text += `\n${lang.get('rcscript.display')} \`${display_types[settings.display]}\``;
  409. if ( enableFeeds && settings.feeds_only ) text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  410. if ( wiki.isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`;
  411. text += `\n<${new URL(`/guild/${guild}/rcscript/${configid}`, process.env.dashboard).href}>`;
  412. sendMsg( {
  413. type: 'notifyGuild', guild, text,
  414. file: [`./RcGcDb/locale/widgets/${settings.lang}.png`]
  415. } ).catch( error => {
  416. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  417. } );
  418. } );
  419. }, error => {
  420. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  421. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  422. } );
  423. }
  424. } );
  425. }, error => {
  426. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  427. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  428. } );
  429. } );
  430. }, error => {
  431. console.log( '- Dashboard: Error while getting the member: ' + error );
  432. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  433. } );
  434. type = parseInt(type, 10);
  435. return db.get( 'SELECT discord.lang mainlang, webhook, rcgcdw.wiki, rcgcdw.lang, display, rcid, postid 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) {
  436. if ( curerror ) {
  437. console.log( '- Dashboard: Error while checking for RcGcDw: ' + curerror );
  438. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  439. }
  440. if ( !row?.webhook ) return res(`/guild/${guild}/rcscript`, 'savefail');
  441. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( wresponse => {
  442. if ( !wresponse.body?.channel_id ) {
  443. console.log( '- Dashboard: ' + wresponse.statusCode + ': Error while getting the webhook: ' + wresponse.body?.message );
  444. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  445. }
  446. row.channel = wresponse.body.channel_id;
  447. var newChannel = false;
  448. if ( settings.save_settings && row.channel !== settings.channel ) {
  449. if ( !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  450. return ( channel.id === settings.channel && !channel.isCategory );
  451. } ) ) return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  452. newChannel = true;
  453. }
  454. return sendMsg( {
  455. type: 'getMember',
  456. member: userSettings.user.id,
  457. guild: guild,
  458. channel: row.channel,
  459. newchannel: ( newChannel ? settings.channel : undefined )
  460. } ).then( response => {
  461. if ( !response ) {
  462. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  463. userSettings.guilds.isMember.delete(guild);
  464. return res(`/guild/${guild}`, 'savefail');
  465. }
  466. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  467. userSettings.guilds.isMember.delete(guild);
  468. return res('/', 'savefail');
  469. }
  470. if ( response.message === 'noChannel' ) {
  471. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  472. }
  473. if ( settings.delete_settings ) {
  474. if ( !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  475. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  476. }
  477. return db.run( 'DELETE FROM rcgcdw WHERE webhook = ?', [row.webhook], function (delerror) {
  478. if ( delerror ) {
  479. console.log( '- Dashboard: Error while removing the RcGcDw: ' + delerror );
  480. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  481. }
  482. console.log( `- Dashboard: RcGcDw successfully removed: ${guild}#${type}` );
  483. res(`/guild/${guild}/rcscript`, 'save');
  484. var lang = new Lang(row.mainlang);
  485. var webhook_lang = new Lang(row.lang, 'rcscript.webhook');
  486. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  487. json: {
  488. content: webhook_lang.get('deleted')
  489. }
  490. } ).then( delresponse => {
  491. if ( delresponse.statusCode !== 204 ) {
  492. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  493. }
  494. }, error => {
  495. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  496. } ).finally( () => {
  497. got.delete( 'https://discord.com/api/webhooks/' + row.webhook, {
  498. headers: {
  499. 'X-Audit-Log-Reason': lang.get('rcscript.audit_reason_delete')
  500. }
  501. } ).then( delresponse => {
  502. if ( delresponse.statusCode !== 204 ) {
  503. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while removing the webhook: ' + delresponse.body?.message );
  504. }
  505. else console.log( `- Dashboard: Webhook successfully removed: ${guild}#${row.channel}` );
  506. }, error => {
  507. console.log( '- Dashboard: Error while removing the webhook: ' + error );
  508. } )
  509. } );
  510. var text = lang.get('rcscript.dashboard.deleted', `<@${userSettings.user.id}>`, type);
  511. text += `\n${lang.get('rcscript.channel')} <#${row.channel}>`;
  512. text += `\n${lang.get('rcscript.wiki')} <${row.wiki}>`;
  513. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[row.lang]}\``;
  514. text += `\n${lang.get('rcscript.display')} \`${display_types[row.display]}\``;
  515. if ( row.rcid === -1 ) {
  516. text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  517. }
  518. if ( new Wiki(row.wiki).isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*`;
  519. text += `\n<${new URL(`/guild/${guild}/rcscript`, process.env.dashboard).href}>`;
  520. sendMsg( {
  521. type: 'notifyGuild', guild, text
  522. } ).catch( error => {
  523. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  524. } );
  525. } );
  526. }
  527. if ( newChannel && ( !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS')
  528. || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  529. || !hasPerm(response.userPermissionsNew, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  530. || !hasPerm(response.botPermissionsNew, 'MANAGE_WEBHOOKS') ) ) {
  531. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  532. }
  533. var hasDiff = false;
  534. if ( newChannel ) hasDiff = true;
  535. if ( row.wiki !== settings.wiki ) hasDiff = true;
  536. if ( row.lang !== settings.lang ) hasDiff = true;
  537. if ( row.display !== settings.display ) hasDiff = true;
  538. if ( ( row.rcid !== -1 ) !== !( settings.feeds && settings.feeds_only ) ) hasDiff = true;
  539. if ( ( row.postid === '-1' ) !== !settings.feeds ) hasDiff = true;
  540. if ( !hasDiff ) return res(`/guild/${guild}/rcscript/${type}`, 'save');
  541. var wiki = Wiki.fromInput(settings.wiki);
  542. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json' ).then( fresponse => {
  543. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  544. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  545. if ( api ) {
  546. wiki = new Wiki(api.split('api.php?')[0], wiki);
  547. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json' );
  548. }
  549. }
  550. return fresponse;
  551. } ).then( fresponse => {
  552. var body = fresponse.body;
  553. if ( fresponse.statusCode !== 200 || !body?.query?.allmessages || !body?.query?.general ) {
  554. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  555. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  556. }
  557. wiki.updateWiki(body.query.general);
  558. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  559. return res(`/guild/${guild}/rcscript/${type}`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  560. }
  561. if ( row.wiki !== wiki.href && body.query.allmessages[0]['*'] !== guild ) {
  562. return res(`/guild/${guild}/rcscript/${type}`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  563. }
  564. return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
  565. if ( blerror ) {
  566. console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
  567. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  568. }
  569. if ( block ) {
  570. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  571. return res(`/guild/${guild}/rcscript/${type}`, 'wikiblocked', body.query.general.sitename, block.reason);
  572. }
  573. if ( settings.feeds && wiki.isFandom(false) ) return got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=1&format=json&cache=' + Date.now(), {
  574. headers: {
  575. Accept: 'application/hal+json'
  576. }
  577. } ).then( dsresponse => {
  578. var dsbody = dsresponse.body;
  579. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  580. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  581. return updateWebhook();
  582. }
  583. return updateWebhook(true);
  584. }, error => {
  585. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  586. return updateWebhook();
  587. } );
  588. return updateWebhook();
  589. /**
  590. * Creates the webhook.
  591. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  592. */
  593. function updateWebhook(enableFeeds = null) {
  594. var sql = 'UPDATE rcgcdw SET wiki = ?, lang = ?, display = ?';
  595. var sqlargs = [wiki.href, settings.lang, settings.display];
  596. if ( row.wiki !== wiki.href ) {
  597. sql += ', rcid = ?, postid = ?';
  598. sqlargs.push(( enableFeeds && settings.feeds_only ? -1 : null ), ( enableFeeds ? null : '-1' ));
  599. }
  600. else {
  601. if ( enableFeeds && settings.feeds_only ) {
  602. sql += ', rcid = ?';
  603. sqlargs.push(-1);
  604. }
  605. else if ( row.rcid === -1 ) {
  606. sql += ', rcid = ?';
  607. sqlargs.push(null);
  608. }
  609. if ( !enableFeeds ) {
  610. sql += ', postid = ?';
  611. sqlargs.push('-1');
  612. }
  613. else if ( row.postid === '-1' ) {
  614. sql += ', postid = ?';
  615. sqlargs.push(null);
  616. }
  617. }
  618. db.run( sql + ' WHERE webhook = ?', [...sqlargs, row.webhook], function (dberror) {
  619. if ( dberror ) {
  620. console.log( '- Dashboard: Error while updating the RcGcDw: ' + dberror );
  621. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  622. }
  623. console.log( `- Dashboard: RcGcDw successfully updated: ${guild}#${type}` );
  624. var lang = new Lang(row.mainlang);
  625. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  626. var diff = [];
  627. var file = [];
  628. var webhook_diff = [];
  629. if ( newChannel ) {
  630. diff.push(lang.get('rcscript.channel') + ` ~~<#${row.channel}>~~ → <#${settings.channel}>`);
  631. webhook_diff.push(webhook_lang.get('dashboard.channel'));
  632. }
  633. if ( row.wiki !== wiki.href ) {
  634. diff.push(lang.get('rcscript.wiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
  635. webhook_diff.push(webhook_lang.get('dashboard.wiki', `[${body.query.general.sitename}](<${wiki.href}>)`));
  636. }
  637. if ( row.lang !== settings.lang ) {
  638. file.push(`./RcGcDb/locale/widgets/${settings.lang}.png`);
  639. diff.push(lang.get('rcscript.lang') + ` ~~\`${allLangs.names[row.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
  640. webhook_diff.push(webhook_lang.get('dashboard.lang', allLangs.names[settings.lang]));
  641. }
  642. if ( row.display !== settings.display ) {
  643. diff.push(lang.get('rcscript.display') + ` ~~\`${display_types[row.display]}\`~~ → \`${display_types[settings.display]}\``);
  644. webhook_diff.push(webhook_lang.get('dashboard.display_' + display_types[settings.display]));
  645. }
  646. if ( ( row.rcid !== -1 ) !== !( enableFeeds && settings.feeds_only ) ) {
  647. diff.push(lang.get('rcscript.rc') + ` ~~*\`${lang.get('rcscript.' + ( row.rcid === -1 ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( settings.feeds_only ? 'disabled' : 'enabled' ))}\`*`);
  648. webhook_diff.push(webhook_lang.get('dashboard.' + ( settings.feeds_only ? 'disabled_rc' : 'enabled_rc' )));
  649. }
  650. if ( ( row.postid === '-1' ) !== !enableFeeds ) {
  651. diff.push(lang.get('rcscript.feeds') + ` ~~*\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`);
  652. webhook_diff.push(webhook_lang.get('dashboard.' + ( enableFeeds ? 'enabled_feeds' : 'disabled_feeds' )));
  653. }
  654. if ( newChannel ) return sendMsg( {
  655. type: 'moveWebhook',
  656. guild: guild,
  657. webhook: row.webhook,
  658. channel: settings.channel,
  659. reason: lang.get('rcscript.audit_reason_move'),
  660. text: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  661. } ).then( webhook => {
  662. if ( !webhook ) return Promise.reject();
  663. res(`/guild/${guild}/rcscript/${type}`, 'save');
  664. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  665. text += '\n' + diff.join('\n');
  666. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  667. sendMsg( {
  668. type: 'notifyGuild', guild, text, file
  669. } ).catch( error => {
  670. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  671. } );
  672. }, error => {
  673. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  674. return Promise.reject();
  675. } ).catch( () => {
  676. diff.shift();
  677. webhook_diff.shift();
  678. if ( !diff.length ) {
  679. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  680. }
  681. res(`/guild/${guild}/rcscript/${type}`, 'movefail');
  682. diff.shift();
  683. webhook_diff.shift();
  684. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  685. json: {
  686. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  687. }
  688. } ).then( delresponse => {
  689. if ( delresponse.statusCode !== 204 ) {
  690. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  691. }
  692. }, error => {
  693. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  694. } )
  695. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  696. text += '\n' + diff.join('\n');
  697. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  698. sendMsg( {
  699. type: 'notifyGuild', guild, text, file
  700. } ).catch( error => {
  701. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  702. } );
  703. } );
  704. res(`/guild/${guild}/rcscript/${type}`, 'save');
  705. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  706. json: {
  707. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  708. }
  709. } ).then( delresponse => {
  710. if ( delresponse.statusCode !== 204 ) {
  711. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  712. }
  713. }, error => {
  714. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  715. } )
  716. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  717. text += '\n' + diff.join('\n');
  718. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  719. sendMsg( {
  720. type: 'notifyGuild', guild, text, file
  721. } ).catch( error => {
  722. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  723. } );
  724. } );
  725. }
  726. } );
  727. }, error => {
  728. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  729. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  730. } );
  731. }, error => {
  732. console.log( '- Dashboard: Error while getting the member: ' + error );
  733. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  734. } );
  735. }, error => {
  736. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  737. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  738. } );
  739. } );
  740. }
  741. module.exports = {
  742. get: dashboard_rcscript,
  743. post: update_rcscript
  744. };