verification.js 32 KB

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