verification.js 31 KB

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