rcscript.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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().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', {
  330. responseType: 'text'
  331. } ).then( fresponse => {
  332. try {
  333. fresponse.body = JSON.parse(fresponse.body);
  334. }
  335. catch (error) {
  336. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  337. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  338. if ( api ) {
  339. wiki = new Wiki(api.split('api.php?')[0], wiki);
  340. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json' );
  341. }
  342. }
  343. }
  344. return fresponse;
  345. } ).then( fresponse => {
  346. var body = fresponse.body;
  347. if ( fresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general || !body?.query?.pages?.['-1'] ) {
  348. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  349. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  350. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'private');
  351. }
  352. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  353. }
  354. wiki.updateWiki(body.query.general);
  355. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  356. return res(`/guild/${guild}/rcscript/new`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  357. }
  358. if ( body.query.allmessages[0]['*'] !== guild ) {
  359. return res(`/guild/${guild}/rcscript/new`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  360. }
  361. return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
  362. if ( blerror ) {
  363. console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
  364. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  365. }
  366. if ( block ) {
  367. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  368. return res(`/guild/${guild}/rcscript/new`, 'wikiblocked', body.query.general.sitename, block.reason);
  369. }
  370. 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(), {
  371. headers: {
  372. Accept: 'application/hal+json'
  373. }
  374. } ).then( dsresponse => {
  375. var dsbody = dsresponse.body;
  376. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  377. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  378. return createWebhook();
  379. }
  380. return createWebhook(true);
  381. }, error => {
  382. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  383. return createWebhook();
  384. } );
  385. return createWebhook();
  386. /**
  387. * Creates the webhook.
  388. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  389. */
  390. function createWebhook(enableFeeds = false) {
  391. var lang = new Lang(row.lang);
  392. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  393. sendMsg( {
  394. type: 'createWebhook',
  395. guild: guild,
  396. channel: settings.channel,
  397. name: ( body.query.allmessages[1]['*'] || 'Recent changes' ),
  398. reason: lang.get('rcscript.audit_reason', wiki.href),
  399. 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>` : '' )
  400. } ).then( webhook => {
  401. if ( !webhook ) return res(`/guild/${guild}/rcscript/new`, 'savefail');
  402. var configid = 1;
  403. for ( let i of row.count ) {
  404. if ( configid === i ) configid++;
  405. else break;
  406. }
  407. 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) {
  408. if ( dberror ) {
  409. console.log( '- Dashboard: Error while adding the RcGcDw: ' + dberror );
  410. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  411. }
  412. console.log( `- Dashboard: RcGcDw successfully added: ${guild}#${configid}` );
  413. res(`/guild/${guild}/rcscript/${configid}`, 'save');
  414. var text = lang.get('rcscript.dashboard.added', `<@${userSettings.user.id}>`, configid);
  415. text += `\n${lang.get('rcscript.channel')} <#${settings.channel}>`;
  416. text += `\n${lang.get('rcscript.wiki')} <${wiki.href}>`;
  417. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[settings.lang]}\``;
  418. text += `\n${lang.get('rcscript.display')} \`${display_types[settings.display]}\``;
  419. if ( enableFeeds && settings.feeds_only ) text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  420. if ( wiki.isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`;
  421. text += `\n<${new URL(`/guild/${guild}/rcscript/${configid}`, process.env.dashboard).href}>`;
  422. sendMsg( {
  423. type: 'notifyGuild', guild, text,
  424. file: [`./RcGcDb/locale/widgets/${settings.lang}.png`]
  425. } ).catch( error => {
  426. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  427. } );
  428. } );
  429. }, error => {
  430. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  431. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  432. } );
  433. }
  434. } );
  435. }, error => {
  436. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' ) {
  437. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  438. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'http');
  439. }
  440. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  441. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  442. return res(`/guild/${guild}/rcscript/new`, 'savefail', 'timeout');
  443. }
  444. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  445. } );
  446. } );
  447. }, error => {
  448. console.log( '- Dashboard: Error while getting the member: ' + error );
  449. return res(`/guild/${guild}/rcscript/new`, 'savefail');
  450. } );
  451. type = parseInt(type, 10);
  452. 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) {
  453. if ( curerror ) {
  454. console.log( '- Dashboard: Error while checking for RcGcDw: ' + curerror );
  455. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  456. }
  457. if ( !row?.webhook ) return res(`/guild/${guild}/rcscript`, 'savefail');
  458. return got.get( 'https://discord.com/api/webhooks/' + row.webhook ).then( wresponse => {
  459. if ( !wresponse.body?.channel_id ) {
  460. console.log( '- Dashboard: ' + wresponse.statusCode + ': Error while getting the webhook: ' + wresponse.body?.message );
  461. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  462. }
  463. row.channel = wresponse.body.channel_id;
  464. var newChannel = false;
  465. if ( settings.save_settings && row.channel !== settings.channel ) {
  466. if ( !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  467. return ( channel.id === settings.channel && !channel.isCategory );
  468. } ) ) return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  469. newChannel = true;
  470. }
  471. return sendMsg( {
  472. type: 'getMember',
  473. member: userSettings.user.id,
  474. guild: guild,
  475. channel: row.channel,
  476. newchannel: ( newChannel ? settings.channel : undefined )
  477. } ).then( response => {
  478. if ( !response ) {
  479. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  480. userSettings.guilds.isMember.delete(guild);
  481. return res(`/guild/${guild}`, 'savefail');
  482. }
  483. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  484. userSettings.guilds.isMember.delete(guild);
  485. return res('/', 'savefail');
  486. }
  487. if ( response.message === 'noChannel' ) {
  488. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  489. }
  490. if ( settings.delete_settings ) {
  491. if ( !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS') ) {
  492. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  493. }
  494. return db.run( 'DELETE FROM rcgcdw WHERE webhook = ?', [row.webhook], function (delerror) {
  495. if ( delerror ) {
  496. console.log( '- Dashboard: Error while removing the RcGcDw: ' + delerror );
  497. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  498. }
  499. console.log( `- Dashboard: RcGcDw successfully removed: ${guild}#${type}` );
  500. res(`/guild/${guild}/rcscript`, 'save');
  501. var lang = new Lang(row.mainlang);
  502. var webhook_lang = new Lang(row.lang, 'rcscript.webhook');
  503. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  504. json: {
  505. content: webhook_lang.get('deleted')
  506. }
  507. } ).then( delresponse => {
  508. if ( delresponse.statusCode !== 204 ) {
  509. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  510. }
  511. }, error => {
  512. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  513. } ).finally( () => {
  514. got.delete( 'https://discord.com/api/webhooks/' + row.webhook, {
  515. headers: {
  516. 'X-Audit-Log-Reason': lang.get('rcscript.audit_reason_delete')
  517. }
  518. } ).then( delresponse => {
  519. if ( delresponse.statusCode !== 204 ) {
  520. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while removing the webhook: ' + delresponse.body?.message );
  521. }
  522. else console.log( `- Dashboard: Webhook successfully removed: ${guild}#${row.channel}` );
  523. }, error => {
  524. console.log( '- Dashboard: Error while removing the webhook: ' + error );
  525. } )
  526. } );
  527. var text = lang.get('rcscript.dashboard.deleted', `<@${userSettings.user.id}>`, type);
  528. text += `\n${lang.get('rcscript.channel')} <#${row.channel}>`;
  529. text += `\n${lang.get('rcscript.wiki')} <${row.wiki}>`;
  530. text += `\n${lang.get('rcscript.lang')} \`${allLangs.names[row.lang]}\``;
  531. text += `\n${lang.get('rcscript.display')} \`${display_types[row.display]}\``;
  532. if ( row.rcid === -1 ) {
  533. text += `\n${lang.get('rcscript.rc')} *\`${lang.get('rcscript.disabled')}\`*`;
  534. }
  535. if ( new Wiki(row.wiki).isFandom(false) ) text += `\n${lang.get('rcscript.feeds')} *\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*`;
  536. text += `\n<${new URL(`/guild/${guild}/rcscript`, process.env.dashboard).href}>`;
  537. sendMsg( {
  538. type: 'notifyGuild', guild, text
  539. } ).catch( error => {
  540. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  541. } );
  542. } );
  543. }
  544. if ( newChannel && ( !hasPerm(response.botPermissions, 'MANAGE_WEBHOOKS')
  545. || !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  546. || !hasPerm(response.userPermissionsNew, 'VIEW_CHANNEL', 'MANAGE_WEBHOOKS')
  547. || !hasPerm(response.botPermissionsNew, 'MANAGE_WEBHOOKS') ) ) {
  548. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  549. }
  550. var hasDiff = false;
  551. if ( newChannel ) hasDiff = true;
  552. if ( row.wiki !== settings.wiki ) hasDiff = true;
  553. if ( row.lang !== settings.lang ) hasDiff = true;
  554. if ( row.display !== settings.display ) hasDiff = true;
  555. if ( ( row.rcid !== -1 ) !== !( settings.feeds && settings.feeds_only ) ) hasDiff = true;
  556. if ( ( row.postid === '-1' ) !== !settings.feeds ) hasDiff = true;
  557. if ( !hasDiff ) return res(`/guild/${guild}/rcscript/${type}`, 'save');
  558. var wiki = Wiki.fromInput(settings.wiki);
  559. return got.get( wiki + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json', {
  560. responseType: 'text'
  561. } ).then( fresponse => {
  562. try {
  563. fresponse.body = JSON.parse(fresponse.body);
  564. }
  565. catch (error) {
  566. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  567. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  568. if ( api ) {
  569. wiki = new Wiki(api.split('api.php?')[0], wiki);
  570. return got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&format=json' );
  571. }
  572. }
  573. }
  574. return fresponse;
  575. } ).then( fresponse => {
  576. var body = fresponse.body;
  577. if ( fresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general ) {
  578. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  579. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  580. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'private');
  581. }
  582. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  583. }
  584. wiki.updateWiki(body.query.general);
  585. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  586. return res(`/guild/${guild}/rcscript/${type}`, 'mwversion', body.query.general.generator, body.query.general.sitename);
  587. }
  588. if ( row.wiki !== wiki.href && body.query.allmessages[0]['*'] !== guild ) {
  589. return res(`/guild/${guild}/rcscript/${type}`, 'sysmessage', guild, wiki.toLink('MediaWiki:Custom-RcGcDw', 'action=edit'));
  590. }
  591. return db.get( 'SELECT reason FROM blocklist WHERE wiki = ?', [wiki.href], (blerror, block) => {
  592. if ( blerror ) {
  593. console.log( '- Dashboard: Error while getting the blocklist: ' + blerror );
  594. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  595. }
  596. if ( block ) {
  597. console.log( `- Dashboard: ${wiki.href} is blocked: ${block.reason}` );
  598. return res(`/guild/${guild}/rcscript/${type}`, 'wikiblocked', body.query.general.sitename, block.reason);
  599. }
  600. 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(), {
  601. headers: {
  602. Accept: 'application/hal+json'
  603. }
  604. } ).then( dsresponse => {
  605. var dsbody = dsresponse.body;
  606. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  607. if ( dsbody?.status !== 404 ) console.log( '- Dashboard: ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  608. return updateWebhook();
  609. }
  610. return updateWebhook(true);
  611. }, error => {
  612. console.log( '- Dashboard: Error while checking for discussions: ' + error );
  613. return updateWebhook();
  614. } );
  615. return updateWebhook();
  616. /**
  617. * Creates the webhook.
  618. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  619. */
  620. function updateWebhook(enableFeeds = null) {
  621. var sql = 'UPDATE rcgcdw SET wiki = ?, lang = ?, display = ?';
  622. var sqlargs = [wiki.href, settings.lang, settings.display];
  623. if ( row.wiki !== wiki.href ) {
  624. sql += ', rcid = ?, postid = ?';
  625. sqlargs.push(( enableFeeds && settings.feeds_only ? -1 : null ), ( enableFeeds ? null : '-1' ));
  626. }
  627. else {
  628. if ( enableFeeds && settings.feeds_only ) {
  629. sql += ', rcid = ?';
  630. sqlargs.push(-1);
  631. }
  632. else if ( row.rcid === -1 ) {
  633. sql += ', rcid = ?';
  634. sqlargs.push(null);
  635. }
  636. if ( !enableFeeds ) {
  637. sql += ', postid = ?';
  638. sqlargs.push('-1');
  639. }
  640. else if ( row.postid === '-1' ) {
  641. sql += ', postid = ?';
  642. sqlargs.push(null);
  643. }
  644. }
  645. db.run( sql + ' WHERE webhook = ?', [...sqlargs, row.webhook], function (dberror) {
  646. if ( dberror ) {
  647. console.log( '- Dashboard: Error while updating the RcGcDw: ' + dberror );
  648. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  649. }
  650. console.log( `- Dashboard: RcGcDw successfully updated: ${guild}#${type}` );
  651. var lang = new Lang(row.mainlang);
  652. var webhook_lang = new Lang(settings.lang, 'rcscript.webhook');
  653. var diff = [];
  654. var file = [];
  655. var webhook_diff = [];
  656. if ( newChannel ) {
  657. diff.push(lang.get('rcscript.channel') + ` ~~<#${row.channel}>~~ → <#${settings.channel}>`);
  658. webhook_diff.push(webhook_lang.get('dashboard.channel'));
  659. }
  660. if ( row.wiki !== wiki.href ) {
  661. diff.push(lang.get('rcscript.wiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
  662. webhook_diff.push(webhook_lang.get('dashboard.wiki', `[${body.query.general.sitename}](<${wiki.href}>)`));
  663. }
  664. if ( row.lang !== settings.lang ) {
  665. file.push(`./RcGcDb/locale/widgets/${settings.lang}.png`);
  666. diff.push(lang.get('rcscript.lang') + ` ~~\`${allLangs.names[row.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
  667. webhook_diff.push(webhook_lang.get('dashboard.lang', allLangs.names[settings.lang]));
  668. }
  669. if ( row.display !== settings.display ) {
  670. diff.push(lang.get('rcscript.display') + ` ~~\`${display_types[row.display]}\`~~ → \`${display_types[settings.display]}\``);
  671. webhook_diff.push(webhook_lang.get('dashboard.display_' + display_types[settings.display]));
  672. }
  673. if ( ( row.rcid !== -1 ) !== !( enableFeeds && settings.feeds_only ) ) {
  674. diff.push(lang.get('rcscript.rc') + ` ~~*\`${lang.get('rcscript.' + ( row.rcid === -1 ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( settings.feeds_only ? 'disabled' : 'enabled' ))}\`*`);
  675. webhook_diff.push(webhook_lang.get('dashboard.' + ( settings.feeds_only ? 'disabled_rc' : 'enabled_rc' )));
  676. }
  677. if ( ( row.postid === '-1' ) !== !enableFeeds ) {
  678. diff.push(lang.get('rcscript.feeds') + ` ~~*\`${lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' ))}\`*~~ → *\`${lang.get('rcscript.' + ( enableFeeds ? 'enabled' : 'disabled' ))}\`*`);
  679. webhook_diff.push(webhook_lang.get('dashboard.' + ( enableFeeds ? 'enabled_feeds' : 'disabled_feeds' )));
  680. }
  681. if ( newChannel ) return sendMsg( {
  682. type: 'moveWebhook',
  683. guild: guild,
  684. webhook: row.webhook,
  685. channel: settings.channel,
  686. reason: lang.get('rcscript.audit_reason_move'),
  687. text: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  688. } ).then( webhook => {
  689. if ( !webhook ) return Promise.reject();
  690. res(`/guild/${guild}/rcscript/${type}`, 'save');
  691. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  692. text += '\n' + diff.join('\n');
  693. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  694. sendMsg( {
  695. type: 'notifyGuild', guild, text, file
  696. } ).catch( error => {
  697. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  698. } );
  699. }, error => {
  700. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  701. return Promise.reject();
  702. } ).catch( () => {
  703. diff.shift();
  704. webhook_diff.shift();
  705. if ( !diff.length ) {
  706. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  707. }
  708. res(`/guild/${guild}/rcscript/${type}`, 'movefail');
  709. diff.shift();
  710. webhook_diff.shift();
  711. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  712. json: {
  713. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  714. }
  715. } ).then( delresponse => {
  716. if ( delresponse.statusCode !== 204 ) {
  717. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  718. }
  719. }, error => {
  720. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  721. } )
  722. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  723. text += '\n' + diff.join('\n');
  724. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  725. sendMsg( {
  726. type: 'notifyGuild', guild, text, file
  727. } ).catch( error => {
  728. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  729. } );
  730. } );
  731. res(`/guild/${guild}/rcscript/${type}`, 'save');
  732. got.post( 'https://discord.com/api/webhooks/' + row.webhook, {
  733. json: {
  734. content: webhook_lang.get('dashboard.updated') + '\n' + webhook_diff.join('\n')
  735. }
  736. } ).then( delresponse => {
  737. if ( delresponse.statusCode !== 204 ) {
  738. console.log( '- Dashboard: ' + delresponse.statusCode + ': Error while sending to the webhook: ' + delresponse.body?.message );
  739. }
  740. }, error => {
  741. console.log( '- Dashboard: Error while sending to the webhook: ' + error );
  742. } )
  743. var text = lang.get('rcscript.dashboard.updated', `<@${userSettings.user.id}>`, type);
  744. text += '\n' + diff.join('\n');
  745. text += `\n<${new URL(`/guild/${guild}/rcscript/${type}`, process.env.dashboard).href}>`;
  746. sendMsg( {
  747. type: 'notifyGuild', guild, text, file
  748. } ).catch( error => {
  749. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  750. } );
  751. } );
  752. }
  753. } );
  754. }, error => {
  755. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' ) {
  756. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  757. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'http');
  758. }
  759. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  760. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  761. return res(`/guild/${guild}/rcscript/${type}`, 'savefail', 'timeout');
  762. }
  763. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  764. } );
  765. }, error => {
  766. console.log( '- Dashboard: Error while getting the member: ' + error );
  767. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  768. } );
  769. }, error => {
  770. console.log( '- Dashboard: Error while getting the webhook: ' + error );
  771. return res(`/guild/${guild}/rcscript/${type}`, 'savefail');
  772. } );
  773. } );
  774. }
  775. module.exports = {
  776. get: dashboard_rcscript,
  777. post: update_rcscript
  778. };