verification.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. const {limit: {verification: verificationLimit}} = require('../util/default.json');
  2. const Lang = require('../util/i18n.js');
  3. const {got, db, sendMsg, createNotice, hasPerm} = require('./util.js');
  4. const fieldset = {
  5. channel: '<label for="wb-settings-channel">Channel:</label>'
  6. + '<select id="wb-settings-channel" name="channel" required></select>'
  7. + '<button type="button" id="wb-settings-channel-more" class="addmore">Add more</button>',
  8. role: '<label for="wb-settings-role">Role:</label>'
  9. + '<select id="wb-settings-role" name="role" required></select>'
  10. + '<button type="button" id="wb-settings-role-more" class="addmore">Add more</button>',
  11. usergroup: '<label for="wb-settings-usergroup">Wiki user group:</label>'
  12. + '<input type="text" id="wb-settings-usergroup" name="usergroup" autocomplete="on">'
  13. + '<div id="wb-settings-usergroup-multiple">'
  14. + '<label for="wb-settings-usergroup-and">Require all user groups:</label>'
  15. + '<input type="checkbox" id="wb-settings-usergroup-and" name="usergroup_and">'
  16. + '</div>',
  17. editcount: '<label for="wb-settings-editcount">Minimal edit count:</label>'
  18. + '<input type="number" id="wb-settings-editcount" name="editcount" min="0" required>',
  19. accountage: '<label for="wb-settings-accountage">Account age (in days):</label>'
  20. + '<input type="number" id="wb-settings-accountage" name="accountage" min="0" required>',
  21. rename: '<label for="wb-settings-rename">Rename users:</label>'
  22. + '<input type="checkbox" id="wb-settings-rename" name="rename">',
  23. save: '<input type="submit" id="wb-settings-save" name="save_settings">',
  24. delete: '<input type="submit" id="wb-settings-delete" name="delete_settings">'
  25. };
  26. /**
  27. * Create a settings form
  28. * @param {import('cheerio')} $ - The response body
  29. * @param {String} header - The form header
  30. * @param {Object} settings - The current settings
  31. * @param {String} settings.channel
  32. * @param {String} settings.role
  33. * @param {String} settings.usergroup
  34. * @param {Number} settings.editcount
  35. * @param {Number} settings.accountage
  36. * @param {Boolean} settings.rename
  37. * @param {String} [settings.defaultrole]
  38. * @param {Object[]} guildChannels - The guild channels
  39. * @param {String} guildChannels.id
  40. * @param {String} guildChannels.name
  41. * @param {Number} guildChannels.userPermissions
  42. * @param {Object[]} guildRoles - The guild roles
  43. * @param {String} guildRoles.id
  44. * @param {String} guildRoles.name
  45. * @param {Boolean} guildRoles.lower
  46. */
  47. function createForm($, header, settings, guildChannels, guildRoles) {
  48. var readonly = ( process.env.READONLY ? true : false );
  49. var fields = [];
  50. let channel = $('<div>').append(fieldset.channel);
  51. channel.find('#wb-settings-channel').append(
  52. $('<option class="wb-settings-channel-default defaultSelect" hidden>').val('').text('-- Select a Channel --'),
  53. ...guildChannels.filter( guildChannel => {
  54. return ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL') || settings.channel.includes( '|' + guildChannel.id + '|' ) );
  55. } ).map( guildChannel => {
  56. var optionChannel = $(`<option class="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id);
  57. if ( !hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL') ) {
  58. optionChannel.addClass('wb-settings-error');
  59. }
  60. return optionChannel.text(`${guildChannel.id} – #${guildChannel.name}`);
  61. } )
  62. );
  63. if ( settings.channel ) {
  64. let settingsChannels = settings.channel.split('|').filter( guildChannel => guildChannel.length );
  65. channel.find('#wb-settings-channel').append(
  66. ...settingsChannels.filter( guildChannel => {
  67. return !channel.find(`.wb-settings-channel-${guildChannel}`).length;
  68. } ).map( guildChannel => {
  69. return $(`<option class="wb-settings-channel-${guildChannel}">`).val(guildChannel).text(`${guildChannel} – #UNKNOWN`).addClass('wb-settings-error');
  70. } )
  71. );
  72. if ( settingsChannels.length > 1 ) channel.find('#wb-settings-channel').after(
  73. ...settingsChannels.slice(1).map( guildChannel => {
  74. var additionalChannel = channel.find('#wb-settings-channel').clone();
  75. additionalChannel.addClass('wb-settings-additional-select');
  76. additionalChannel.find(`.wb-settings-channel-default`).removeAttr('hidden');
  77. additionalChannel.find(`.wb-settings-channel-${guildChannel}`).attr('selected', '');
  78. return additionalChannel.removeAttr('id').removeAttr('required');
  79. } )
  80. );
  81. channel.find(`#wb-settings-channel .wb-settings-channel-${settingsChannels[0]}`).attr('selected', '');
  82. }
  83. else {
  84. channel.find('.wb-settings-channel-default').attr('selected', '');
  85. channel.find('button.addmore').attr('hidden', '');
  86. }
  87. fields.push(channel);
  88. let role = $('<div>').append(fieldset.role);
  89. role.find('#wb-settings-role').append(
  90. $('<option class="wb-settings-role-default defaultSelect" hidden>').val('').text('-- Select a Role --'),
  91. ...guildRoles.filter( guildRole => {
  92. return guildRole.lower || settings.role.split('|').includes( guildRole.id );
  93. } ).map( guildRole => {
  94. var optionRole = $(`<option class="wb-settings-role-${guildRole.id}">`).val(guildRole.id);
  95. if ( !guildRole.lower ) optionRole.addClass('wb-settings-error');
  96. return optionRole.text(`${guildRole.id} – @${guildRole.name}`);
  97. } )
  98. );
  99. if ( settings.role ) {
  100. let settingsRoles = settings.role.split('|');
  101. role.find('#wb-settings-role').append(
  102. ...settingsRoles.filter( guildRole => {
  103. return !role.find(`.wb-settings-role-${guildRole}`).length;
  104. } ).map( guildRole => {
  105. return $(`<option class="wb-settings-role-${guildRole}">`).val(guildRole).text(`${guildRole} – @UNKNOWN`).addClass('wb-settings-error');
  106. } )
  107. );
  108. if ( settingsRoles.length > 1 ) role.find('#wb-settings-role').after(
  109. ...settingsRoles.slice(1).map( guildRole => {
  110. var additionalRole = role.find('#wb-settings-role').clone();
  111. additionalRole.addClass('wb-settings-additional-select');
  112. additionalRole.find(`.wb-settings-role-default`).removeAttr('hidden');
  113. additionalRole.find(`.wb-settings-role-${guildRole}`).attr('selected', '');
  114. return additionalRole.removeAttr('id').removeAttr('required');
  115. } )
  116. );
  117. role.find(`#wb-settings-role .wb-settings-role-${settingsRoles[0]}`).attr('selected', '');
  118. }
  119. else {
  120. if ( role.find(`.wb-settings-role-${settings.defaultrole}`).length ) {
  121. role.find(`.wb-settings-role-${settings.defaultrole}`).attr('selected', '');
  122. }
  123. else role.find('.wb-settings-role-default').attr('selected', '');
  124. role.find('button.addmore').attr('hidden', '');
  125. }
  126. fields.push(role);
  127. let usergroup = $('<div>').append(fieldset.usergroup);
  128. if ( settings.usergroup.startsWith( 'AND|' ) ) {
  129. settings.usergroup = settings.usergroup.substring(4);
  130. usergroup.find('#wb-settings-usergroup-and').attr('checked', '');
  131. }
  132. usergroup.find('#wb-settings-usergroup').val(settings.usergroup.split('|').join(', '));
  133. if ( !settings.usergroup.includes( '|' ) ) {
  134. usergroup.find('#wb-settings-usergroup-multiple').attr('style', 'display: none;');
  135. }
  136. fields.push(usergroup);
  137. let editcount = $('<div>').append(fieldset.editcount);
  138. editcount.find('#wb-settings-editcount').val(settings.editcount);
  139. fields.push(editcount);
  140. let accountage = $('<div>').append(fieldset.accountage);
  141. accountage.find('#wb-settings-accountage').val(settings.accountage);
  142. fields.push(accountage);
  143. let rename = $('<div>').append(fieldset.rename);
  144. if ( settings.rename ) rename.find('#wb-settings-rename').attr('checked', '');
  145. fields.push(rename);
  146. fields.push($(fieldset.save).val('Save'));
  147. if ( settings.channel ) {
  148. fields.push($(fieldset.delete).val('Delete').attr('onclick', `return confirm('Are you sure?');`));
  149. }
  150. var form = $('<fieldset>').append(...fields);
  151. if ( readonly ) {
  152. form.find('input').attr('readonly', '');
  153. form.find('input[type="checkbox"], option').attr('disabled', '');
  154. form.find('input[type="submit"], button.addmore').remove();
  155. }
  156. return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  157. $('<h2>').text(header),
  158. form
  159. );
  160. }
  161. /**
  162. * Let a user change verifications
  163. * @param {import('http').ServerResponse} res - The server response
  164. * @param {import('cheerio')} $ - The response body
  165. * @param {import('./util.js').Guild} guild - The current guild
  166. * @param {String[]} args - The url parts
  167. */
  168. function dashboard_verification(res, $, guild, args) {
  169. if ( !hasPerm(guild.botPermissions, 'MANAGE_ROLES') ) {
  170. $('#text .description').text('Wiki-Bot is missing the "MANAGE_ROLES" permission!\n\n*Insert explanation about verification here*');
  171. $('.channel#verification').addClass('selected');
  172. let body = $.html();
  173. res.writeHead(200, {'Content-Length': body.length});
  174. res.write( body );
  175. return res.end();
  176. }
  177. db.all( 'SELECT wiki, discord.role defaultrole, configid, verification.channel, verification.role, editcount, usergroup, accountage, rename FROM discord LEFT JOIN verification ON discord.guild = verification.guild WHERE discord.guild = ? AND discord.channel IS NULL ORDER BY configid ASC', [guild.id], function(dberror, rows) {
  178. if ( dberror ) {
  179. console.log( '- Dashboard: Error while getting the verifications: ' + dberror );
  180. $('#text .description').text('Failed to load the verifications!');
  181. $('.channel#verification').addClass('selected');
  182. let body = $.html();
  183. res.writeHead(200, {'Content-Length': body.length});
  184. res.write( body );
  185. return res.end();
  186. }
  187. if ( rows.length === 0 ) {
  188. $('#text .description').text(`You need to set up the server first: /guild/${guild.id}/settings`);
  189. $('.channel#verification').addClass('selected');
  190. let body = $.html();
  191. res.writeHead(200, {'Content-Length': body.length});
  192. res.write( body );
  193. return res.end();
  194. }
  195. var wiki = rows[0].wiki;
  196. var defaultrole = rows[0].defaultrole;
  197. if ( rows.length === 1 && rows[0].configid === null ) rows.pop();
  198. $('#text .description').text(`These are the verifications for "${guild.name}":`);
  199. $('#channellist #verification').after(
  200. ...rows.map( row => {
  201. return $('<a class="channel">').attr('id', `channel-${row.configid}`).append(
  202. $('<img>').attr('src', '/src/channel.svg'),
  203. $('<div>').text(`${row.configid} - ${( guild.roles.find( role => {
  204. return role.id === row.role.split('|')[0];
  205. } )?.name || guild.channels.find( channel => {
  206. return channel.id === row.channel.split('|')[1];
  207. } )?.name || row.usergroup.split('|')[0] )}`)
  208. ).attr('href', `/guild/${guild.id}/verification/${row.configid}`);
  209. } ),
  210. ( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ? '' :
  211. $('<a class="channel" id="channel-new">').append(
  212. $('<img>').attr('src', '/src/channel.svg'),
  213. $('<div>').text('New verification')
  214. ).attr('href', `/guild/${guild.id}/verification/new`) )
  215. );
  216. if ( args[4] === 'new' && !( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ) ) {
  217. $('.channel#channel-new').addClass('selected');
  218. createForm($, 'New Verification', {
  219. channel: '', role: '', usergroup: 'user',
  220. editcount: 0, accountage: 0, rename: false, defaultrole
  221. }, guild.channels, guild.roles).attr('action', `/guild/${guild.id}/verification/new`).appendTo('#text');
  222. }
  223. else if ( rows.some( row => row.configid.toString() === args[4] ) ) {
  224. let row = rows.find( row => row.configid.toString() === args[4] );
  225. $(`.channel#channel-${row.configid}`).addClass('selected');
  226. createForm($, `Verification #${row.configid}`, row, guild.channels, guild.roles).attr('action', `/guild/${guild.id}/verification/${row.configid}`).appendTo('#text');
  227. }
  228. else {
  229. $('.channel#verification').addClass('selected');
  230. $('#text .description').text('*Insert explanation about verification here*');
  231. }
  232. let body = $.html();
  233. res.writeHead(200, {'Content-Length': body.length});
  234. res.write( body );
  235. return res.end();
  236. } );
  237. }
  238. /**
  239. * Change verifications
  240. * @param {Function} res - The server response
  241. * @param {import('./util.js').Settings} userSettings - The settings of the user
  242. * @param {String} guild - The id of the guild
  243. * @param {String|Number} type - The setting to change
  244. * @param {Object} settings - The new settings
  245. * @param {String[]} settings.channel
  246. * @param {String[]} settings.role
  247. * @param {String[]} [settings.usergroup]
  248. * @param {String} [settings.usergroup_and]
  249. * @param {Number} settings.editcount
  250. * @param {Number} settings.accountage
  251. * @param {String} [settings.rename]
  252. * @param {String} [settings.save_settings]
  253. * @param {String} [settings.delete_settings]
  254. */
  255. function update_verification(res, userSettings, guild, type, settings) {
  256. if ( type === 'default' ) {
  257. return res(`/guild/${guild}/verification`, 'savefail');
  258. }
  259. if ( !settings.save_settings === !settings.delete_settings ) {
  260. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  261. }
  262. if ( settings.save_settings ) {
  263. if ( !/^[\d|]+ [\d|]+$/.test(`${settings.channel} ${settings.role}`) ) {
  264. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  265. }
  266. if ( !/^\d+ \d+$/.test(`${settings.editcount} ${settings.accountage}`) ) {
  267. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  268. }
  269. settings.channel = settings.channel.split('|').filter( (channel, i, self) => {
  270. return ( channel.length && self.indexOf(channel) === i );
  271. } );
  272. if ( !settings.channel.length || settings.channel.length > 10 ) {
  273. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  274. }
  275. settings.role = settings.role.split('|').filter( (role, i, self) => {
  276. return ( role.length && self.indexOf(role) === i );
  277. } );
  278. if ( !settings.role.length || settings.role.length > 10 ) {
  279. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  280. }
  281. if ( !settings.usergroup ) settings.usergroup = 'user';
  282. settings.usergroup = settings.usergroup.replace( /_/g, ' ' ).trim().toLowerCase();
  283. settings.usergroup = settings.usergroup.split(/\s*[,|]\s*/).map( usergroup => {
  284. if ( usergroup === '*' ) return 'user';
  285. return usergroup.replace( / /g, '_' );
  286. } ).filter( (usergroup, i, self) => {
  287. return ( usergroup.length && self.indexOf(usergroup) === i );
  288. } );
  289. if ( !settings.usergroup.length ) settings.usergroup.push('user');
  290. if ( settings.usergroup.length > 10 || settings.usergroup.some( usergroup => {
  291. return ( usergroup.length > 100 );
  292. } ) ) return res(`/guild/${guild}/verification/${type}`, 'invalidusergroup');
  293. settings.editcount = parseInt(settings.editcount, 10);
  294. settings.accountage = parseInt(settings.accountage, 10);
  295. if ( type === 'new' ) {
  296. let curGuild = userSettings.guilds.isMember.get(guild);
  297. if ( settings.channel.some( channel => {
  298. return !curGuild.channels.some( guildChannel => guildChannel.id === channel );
  299. } ) || settings.role.some( role => {
  300. return !curGuild.roles.some( guildRole => guildRole.id === role && guildRole.lower );
  301. } ) ) return res(`/guild/${guild}/verification/new`, 'savefail');
  302. }
  303. }
  304. if ( settings.delete_settings && type === 'new' ) {
  305. return res(`/guild/${guild}/verification/new`, 'savefail');
  306. }
  307. if ( type !== 'new' ) type = parseInt(type, 10);
  308. sendMsg( {
  309. type: 'getMember',
  310. member: userSettings.user.id,
  311. guild: guild
  312. } ).then( response => {
  313. if ( !response ) {
  314. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  315. userSettings.guilds.isMember.delete(guild);
  316. return res(`/guild/${guild}`, 'savefail');
  317. }
  318. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  319. userSettings.guilds.isMember.delete(guild);
  320. return res('/', 'savefail');
  321. }
  322. if ( settings.delete_settings ) return db.get( 'SELECT lang, verification.channel, verification.role, editcount, usergroup, accountage, rename FROM discord LEFT JOIN verification ON discord.guild = verification.guild AND configid = ? WHERE discord.guild = ? AND discord.channel IS NULL', [type, guild], function(dberror, row) {
  323. if ( !dberror && !row?.channel ) return res(`/guild/${guild}/verification`, 'save');
  324. db.run( 'DELETE FROM verification WHERE guild = ? AND configid = ?', [guild, type], function (delerror) {
  325. if ( delerror ) {
  326. console.log( '- Dashboard: Error while removing the verification: ' + delerror );
  327. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  328. }
  329. console.log( `- Dashboard: Verification successfully removed: ${guild}#${type}` );
  330. res(`/guild/${guild}/verification`, 'save');
  331. if ( dberror ) {
  332. console.log( '- Dashboard: Error while notifying the guild: ' + dberror );
  333. return;
  334. }
  335. var lang = new Lang(row.lang);
  336. var text = lang.get('verification.dashboard.removed', `<@${userSettings.user.id}>`, type);
  337. if ( row ) {
  338. text += '\n' + lang.get('verification.channel') + ' <#' + row.channel.split('|').filter( channel => channel.length ).join('>, <#') + '>';
  339. text += '\n' + lang.get('verification.role') + ' <@&' + row.role.split('|').join('>, <@&') + '>';
  340. text += '\n' + lang.get('verification.editcount') + ' `' + row.editcount + '`';
  341. text += '\n' + lang.get('verification.usergroup') + ' `' + ( row.usergroup.startsWith( 'AND|' ) ? row.usergroup.split('|').slice(1).join('` ' + lang.get('verification.and') + ' `') : row.usergroup.split('|').join('` ' + lang.get('verification.or') + ' `') ) + '`';
  342. text += '\n' + lang.get('verification.accountage') + ' `' + row.accountage + '` ' + lang.get('verification.indays');
  343. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled')) + '`*';
  344. }
  345. text += `\n<${new URL(`/guild/${guild}/verification`, process.env.dashboard).href}>`;
  346. sendMsg( {
  347. type: 'notifyGuild', guild, text
  348. } ).catch( error => {
  349. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  350. } );
  351. } );
  352. } );
  353. if ( !hasPerm(response.botPermissions, 'MANAGE_ROLES') ) {
  354. return res(`/guild/${guild}/verification`, 'savefail');
  355. }
  356. if ( type === 'new' ) return db.get( 'SELECT wiki, lang, GROUP_CONCAT(configid) count FROM discord LEFT JOIN verification ON discord.guild = verification.guild WHERE discord.guild = ? AND discord.channel IS NULL', [guild], function(curerror, row) {
  357. if ( curerror ) {
  358. console.log( '- Dashboard: Error while checking for verifications: ' + curerror );
  359. return res(`/guild/${guild}/verification/new`, 'savefail');
  360. }
  361. if ( !row ) return res(`/guild/${guild}/verification`, 'savefail');
  362. if ( row.count === null ) row.count = [];
  363. else row.count = row.count.split(',').map( configid => parseInt(configid, 10) );
  364. if ( row.count.length >= verificationLimit[( response.patreon ? 'patreon' : 'default' )] ) {
  365. return res(`/guild/${guild}/verification`, 'savefail');
  366. }
  367. return got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  368. var body = gresponse.body;
  369. if ( gresponse.statusCode !== 200 || !body || !body.query || !body.query.allmessages ) {
  370. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  371. return;
  372. }
  373. var groups = body.query.allmessages.filter( group => {
  374. if ( group.name === 'group-all' ) return false;
  375. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  376. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  377. return true;
  378. } ).map( group => {
  379. return {
  380. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  381. content: group['*'].replace( / /g, '_' ).toLowerCase()
  382. };
  383. } );
  384. settings.usergroup = settings.usergroup.map( usergroup => {
  385. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  386. if ( groups.some( group => group.content === usergroup ) ) {
  387. return groups.find( group => group.content === usergroup ).name;
  388. }
  389. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  390. if ( usergroup === '*' ) return 'user';
  391. return usergroup;
  392. } );
  393. }, error => {
  394. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  395. } ).finally( () => {
  396. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  397. var configid = 1;
  398. for ( let i of row.count ) {
  399. if ( configid === i ) configid++;
  400. else break;
  401. }
  402. db.run( 'INSERT INTO verification(guild, configid, channel, role, editcount, usergroup, accountage, rename) VALUES(?, ?, ?, ?, ?, ?, ?, ?)', [guild, configid, '|' + settings.channel.join('|') + '|', settings.role.join('|'), settings.editcount, settings.usergroup.join('|'), settings.accountage, ( settings.rename ? 1 : 0 )], function (dberror) {
  403. if ( dberror ) {
  404. console.log( '- Dashboard: Error while adding the verification: ' + dberror );
  405. return res(`/guild/${guild}/verification/new`, 'savefail');
  406. }
  407. console.log( `- Dashboard: Verification successfully added: ${guild}#${configid}` );
  408. res(`/guild/${guild}/verification/${configid}`, 'save');
  409. var lang = new Lang(row.lang);
  410. var text = lang.get('verification.dashboard.added', `<@${userSettings.user.id}>`, configid);
  411. text += '\n' + lang.get('verification.channel') + ' <#' + settings.channel.join('>, <#') + '>';
  412. text += '\n' + lang.get('verification.role') + ' <@&' + settings.role.join('>, <@&') + '>';
  413. text += '\n' + lang.get('verification.editcount') + ' `' + settings.editcount + '`';
  414. text += '\n' + lang.get('verification.usergroup') + ' `' + ( settings.usergroup_and ? settings.usergroup.slice(1).join('` ' + lang.get('verification.and') + ' `') : settings.usergroup.join('` ' + lang.get('verification.or') + ' `') ) + '`';
  415. text += '\n' + lang.get('verification.accountage') + ' `' + settings.accountage + '` ' + lang.get('verification.indays');
  416. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled')) + '`*';
  417. text += `\n<${new URL(`/guild/${guild}/verification/${configid}`, process.env.dashboard).href}>`;
  418. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  419. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  420. }
  421. if ( settings.role.some( role => {
  422. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  423. return ( guildRole.id === role && guildRole.lower );
  424. } );
  425. } ) ) {
  426. text += '\n';
  427. settings.role.forEach( role => {
  428. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  429. return ( guildRole.id === role );
  430. } ) ) {
  431. text += '\n' + lang.get('verification.role_deleted', `<@&${role}>`);
  432. }
  433. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  434. return ( guildRole.id === role && !guildRole.lower );
  435. } ) ) {
  436. text += '\n' + lang.get('verification.role_too_high', `<@&${role}>`, `<@${process.env.bot}>`);
  437. }
  438. } );
  439. }
  440. sendMsg( {
  441. type: 'notifyGuild', guild, text
  442. } ).catch( error => {
  443. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  444. } );
  445. } );
  446. } );
  447. } );
  448. return db.get( 'SELECT wiki, lang, verification.channel, verification.role, editcount, usergroup, accountage, rename FROM discord LEFT JOIN verification ON discord.guild = verification.guild AND verification.configid = ? WHERE discord.guild = ? AND discord.channel IS NULL', [type, guild], function(curerror, row) {
  449. if ( curerror ) {
  450. console.log( '- Dashboard: Error while checking for verifications: ' + curerror );
  451. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  452. }
  453. if ( !row?.channel ) return res(`/guild/${guild}/verification`, 'savefail');
  454. row.channel = row.channel.split('|').filter( channel => channel.length );
  455. var newChannel = settings.channel.filter( channel => !row.channel.includes( channel ) );
  456. row.role = row.role.split('|');
  457. var newRole = settings.role.filter( role => !row.role.includes( role ) );
  458. row.usergroup = row.usergroup.split('|');
  459. var newUsergroup = settings.usergroup.filter( group => !row.usergroup.includes( group ) );
  460. if ( newChannel.length || newRole.length ) {
  461. let curGuild = userSettings.guilds.isMember.get(guild);
  462. if ( newChannel.some( channel => {
  463. return !curGuild.channels.some( guildChannel => guildChannel.id === channel );
  464. } ) || newRole.some( role => {
  465. return !curGuild.roles.some( guildRole => guildRole.id === role && guildRole.lower );
  466. } ) ) return res(`/guild/${guild}/verification/${type}`, 'savefail');
  467. }
  468. ( newUsergroup.length ? got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  469. var body = gresponse.body;
  470. if ( gresponse.statusCode !== 200 || !body || !body.query || !body.query.allmessages ) {
  471. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  472. return;
  473. }
  474. var groups = body.query.allmessages.filter( group => {
  475. if ( group.name === 'group-all' ) return false;
  476. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  477. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  478. return true;
  479. } ).map( group => {
  480. return {
  481. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  482. content: group['*'].replace( / /g, '_' ).toLowerCase()
  483. };
  484. } );
  485. settings.usergroup = settings.usergroup.map( usergroup => {
  486. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  487. if ( groups.some( group => group.content === usergroup ) ) {
  488. return groups.find( group => group.content === usergroup ).name;
  489. }
  490. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  491. if ( usergroup === '*' ) return 'user';
  492. return usergroup;
  493. } );
  494. }, error => {
  495. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  496. } ) : Promise.resolve() ).finally( () => {
  497. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  498. var lang = new Lang(row.lang);
  499. var diff = [];
  500. if ( newChannel.length || row.channel.some( channel => {
  501. return !settings.channel.includes( channel );
  502. } ) ) {
  503. diff.push(lang.get('verification.channel') + ` ~~<#${row.channel.join('>, <#')}>~~ → <#${settings.channel.join('>, <#')}>`);
  504. }
  505. if ( newRole.length || row.role.some( role => {
  506. return !settings.role.includes( role );
  507. } ) ) {
  508. diff.push(lang.get('verification.role') + ` ~~<@&${row.role.join('>, <@&')}>~~ → <@&${settings.role.join('>, <@&')}>`);
  509. }
  510. if ( row.editcount !== settings.editcount ) {
  511. diff.push(lang.get('verification.editcount') + ` ~~\`${row.editcount}\`~~ → \`${settings.editcount}\``);
  512. }
  513. if ( newUsergroup.length || row.usergroup.some( usergroup => {
  514. return !settings.usergroup.includes( usergroup );
  515. } ) ) {
  516. diff.push(lang.get('verification.usergroup') + ' ~~`' + ( row.usergroup[0] === 'AND' ? row.usergroup.slice(1).join('` ' + lang.get('verification.and') + ' `') : row.usergroup.join('` ' + lang.get('verification.or') + ' `') ) + '`~~ → `' + ( settings.usergroup_and ? settings.usergroup.slice(1).join('` ' + lang.get('verification.and') + ' `') : settings.usergroup.join('` ' + lang.get('verification.or') + ' `') ) + '`');
  517. }
  518. if ( row.accountage !== settings.accountage ) {
  519. diff.push(lang.get('verification.accountage') + ` ~~\`${row.accountage}\`~~ → \`${settings.accountage}\``);
  520. }
  521. if ( row.rename !== ( settings.rename ? 1 : 0 ) ) {
  522. diff.push(lang.get('verification.rename') + ` ~~*\`${lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled'))}\`*~~ → *\`${lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled'))}\`*`);
  523. }
  524. if ( !diff.length ) return res(`/guild/${guild}/verification/${type}`, 'save');
  525. db.run( 'UPDATE verification SET channel = ?, role = ?, editcount = ?, usergroup = ?, accountage = ?, rename = ? WHERE guild = ? AND configid = ?', ['|' + settings.channel.join('|') + '|', settings.role.join('|'), settings.editcount, settings.usergroup.join('|'), settings.accountage, ( settings.rename ? 1 : 0 ), guild, type], function (dberror) {
  526. if ( dberror ) {
  527. console.log( '- Dashboard: Error while updating the verification: ' + dberror );
  528. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  529. }
  530. console.log( `- Dashboard: Verification successfully updated: ${guild}#${type}` );
  531. res(`/guild/${guild}/verification/${type}`, 'save');
  532. var text = lang.get('verification.dashboard.updated', `<@${userSettings.user.id}>`, type);
  533. text += '\n' + diff.join('\n');
  534. text += `\n<${new URL(`/guild/${guild}/verification/${type}`, process.env.dashboard).href}>`;
  535. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  536. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  537. }
  538. if ( settings.role.some( role => {
  539. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  540. return ( guildRole.id === role && guildRole.lower );
  541. } );
  542. } ) ) {
  543. text += '\n';
  544. settings.role.forEach( role => {
  545. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  546. return ( guildRole.id === role );
  547. } ) ) {
  548. text += '\n' + lang.get('verification.role_deleted', `<@&${role}>`);
  549. }
  550. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  551. return ( guildRole.id === role && !guildRole.lower );
  552. } ) ) {
  553. text += '\n' + lang.get('verification.role_too_high', `<@&${role}>`, `<@${process.env.bot}>`);
  554. }
  555. } );
  556. }
  557. sendMsg( {
  558. type: 'notifyGuild', guild, text
  559. } ).catch( error => {
  560. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  561. } );
  562. } );
  563. } );
  564. } );
  565. }, error => {
  566. console.log( '- Dashboard: Error while getting the member: ' + error );
  567. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  568. } );
  569. }
  570. module.exports = {
  571. get: dashboard_verification,
  572. post: update_verification
  573. };