verification.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. const {limit: {verification: verificationLimit}, usergroups} = require('../util/default.json');
  2. const Lang = require('../util/i18n.js');
  3. const {got, db, sendMsg, createNotice, escapeText, 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(dashboardLang.get('verification.form.select_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. db.all( 'SELECT wiki, discord.role defaultrole, prefix, 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) {
  196. if ( dberror ) {
  197. console.log( '- Dashboard: Error while getting the verifications: ' + dberror );
  198. createNotice($, 'error', dashboardLang);
  199. $('#text .description').html(dashboardLang.get('verification.explanation'));
  200. $('#text code.prefix').prepend(escapeText(process.env.prefix));
  201. $('.channel#verification').addClass('selected');
  202. let body = $.html();
  203. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  204. res.write( body );
  205. return res.end();
  206. }
  207. if ( rows.length === 0 ) {
  208. createNotice($, 'nosettings', dashboardLang, [guild.id]);
  209. $('#text .description').html(dashboardLang.get('verification.explanation'));
  210. $('#text code.prefix').prepend(escapeText(process.env.prefix));
  211. $('.channel#verification').addClass('selected');
  212. let body = $.html();
  213. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  214. res.write( body );
  215. return res.end();
  216. }
  217. if ( !hasPerm(guild.botPermissions, 'MANAGE_ROLES') ) {
  218. createNotice($, 'missingperm', dashboardLang, ['Manage Roles']);
  219. $('#text .description').html(dashboardLang.get('verification.explanation'));
  220. $('#text code.prefix').prepend(escapeText(rows[0].prefix));
  221. $('.channel#verification').addClass('selected');
  222. let body = $.html();
  223. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  224. res.write( body );
  225. return res.end();
  226. }
  227. var wiki = rows[0].wiki;
  228. var defaultrole = rows[0].defaultrole;
  229. var prefix = rows[0].prefix;
  230. if ( rows.length === 1 && rows[0].configid === null ) rows.pop();
  231. $('<p>').html(dashboardLang.get('verification.desc', true, $('<code>').text(guild.name))).appendTo('#text .description');
  232. let suffix = ( args[0] === 'owner' ? '?owner=true' : '' );
  233. $('#channellist #verification').after(
  234. ...rows.map( row => {
  235. return $('<a class="channel">').attr('id', `channel-${row.configid}`).append(
  236. $('<img>').attr('src', '/src/channel.svg'),
  237. $('<div>').text(`${row.configid} - ${( guild.roles.find( role => {
  238. return role.id === row.role.split('|')[0];
  239. } )?.name || guild.channels.find( channel => {
  240. return channel.id === row.channel.split('|')[1];
  241. } )?.name || row.usergroup.split('|')[( row.usergroup.startsWith('AND|') ? 1 : 0 )] )}`)
  242. ).attr('href', `/guild/${guild.id}/verification/${row.configid}${suffix}`);
  243. } ),
  244. ( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ? '' :
  245. $('<a class="channel" id="channel-new">').append(
  246. $('<img>').attr('src', '/src/channel.svg'),
  247. $('<div>').text(dashboardLang.get('verification.new'))
  248. ).attr('href', `/guild/${guild.id}/verification/new${suffix}`) )
  249. );
  250. if ( args[4] === 'new' && !( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ) ) {
  251. $('.channel#channel-new').addClass('selected');
  252. createForm($, dashboardLang.get('verification.form.new'), dashboardLang, {
  253. channel: '', role: '', usergroup: 'user',
  254. editcount: 0, accountage: 0, rename: false, defaultrole
  255. }, guild.channels, guild.roles).attr('action', `/guild/${guild.id}/verification/new`).appendTo('#text');
  256. }
  257. else if ( rows.some( row => row.configid.toString() === args[4] ) ) {
  258. let row = rows.find( row => row.configid.toString() === args[4] );
  259. $(`.channel#channel-${row.configid}`).addClass('selected');
  260. 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');
  261. }
  262. else {
  263. $('.channel#verification').addClass('selected');
  264. $('#text .description').html(dashboardLang.get('verification.explanation'));
  265. $('#text code.prefix').prepend(escapeText(prefix));
  266. }
  267. let body = $.html();
  268. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  269. res.write( body );
  270. return res.end();
  271. } );
  272. }
  273. /**
  274. * Change verifications
  275. * @param {Function} res - The server response
  276. * @param {import('./util.js').Settings} userSettings - The settings of the user
  277. * @param {String} guild - The id of the guild
  278. * @param {String|Number} type - The setting to change
  279. * @param {Object} settings - The new settings
  280. * @param {String[]} settings.channel
  281. * @param {String[]} settings.role
  282. * @param {String[]} [settings.usergroup]
  283. * @param {String} [settings.usergroup_and]
  284. * @param {Number} settings.editcount
  285. * @param {Number} settings.accountage
  286. * @param {String} [settings.rename]
  287. * @param {String} [settings.save_settings]
  288. * @param {String} [settings.delete_settings]
  289. */
  290. function update_verification(res, userSettings, guild, type, settings) {
  291. if ( type === 'default' ) {
  292. return res(`/guild/${guild}/verification`, 'savefail');
  293. }
  294. if ( !settings.save_settings === !settings.delete_settings ) {
  295. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  296. }
  297. if ( settings.save_settings ) {
  298. if ( !/^[\d|]+ [\d|]+$/.test(`${settings.channel} ${settings.role}`) ) {
  299. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  300. }
  301. if ( !/^\d+ \d+$/.test(`${settings.editcount} ${settings.accountage}`) ) {
  302. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  303. }
  304. settings.channel = settings.channel.split('|').filter( (channel, i, self) => {
  305. return ( channel.length && self.indexOf(channel) === i );
  306. } );
  307. if ( !settings.channel.length || settings.channel.length > 10 ) {
  308. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  309. }
  310. settings.role = settings.role.split('|').filter( (role, i, self) => {
  311. return ( role.length && self.indexOf(role) === i );
  312. } );
  313. if ( !settings.role.length || settings.role.length > 10 ) {
  314. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  315. }
  316. if ( !settings.usergroup ) settings.usergroup = 'user';
  317. settings.usergroup = settings.usergroup.replace( /_/g, ' ' ).trim().toLowerCase();
  318. settings.usergroup = settings.usergroup.split(/\s*[,|]\s*/).map( usergroup => {
  319. if ( usergroup === '*' ) return 'user';
  320. return usergroup.replace( / /g, '_' );
  321. } ).filter( (usergroup, i, self) => {
  322. return ( usergroup.length && self.indexOf(usergroup) === i );
  323. } );
  324. if ( !settings.usergroup.length ) settings.usergroup.push('user');
  325. if ( settings.usergroup.length > 10 || settings.usergroup.some( usergroup => {
  326. return ( usergroup.length > 100 );
  327. } ) ) return res(`/guild/${guild}/verification/${type}`, 'invalidusergroup');
  328. settings.editcount = parseInt(settings.editcount, 10);
  329. settings.accountage = parseInt(settings.accountage, 10);
  330. if ( type === 'new' ) {
  331. let curGuild = userSettings.guilds.isMember.get(guild);
  332. if ( settings.channel.some( channel => {
  333. return !curGuild.channels.some( guildChannel => {
  334. return ( guildChannel.id === channel && !guildChannel.isCategory );
  335. } );
  336. } ) || settings.role.some( role => {
  337. return !curGuild.roles.some( guildRole => {
  338. return ( guildRole.id === role && guildRole.lower );
  339. } );
  340. } ) ) return res(`/guild/${guild}/verification/new`, 'savefail');
  341. }
  342. }
  343. if ( settings.delete_settings && type === 'new' ) {
  344. return res(`/guild/${guild}/verification/new`, 'savefail');
  345. }
  346. if ( type !== 'new' ) type = parseInt(type, 10);
  347. sendMsg( {
  348. type: 'getMember',
  349. member: userSettings.user.id,
  350. guild: guild
  351. } ).then( response => {
  352. if ( !response ) {
  353. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  354. userSettings.guilds.isMember.delete(guild);
  355. return res(`/guild/${guild}`, 'savefail');
  356. }
  357. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  358. userSettings.guilds.isMember.delete(guild);
  359. return res('/', 'savefail');
  360. }
  361. 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) {
  362. if ( !dberror && !row?.channel ) return res(`/guild/${guild}/verification`, 'save');
  363. db.run( 'DELETE FROM verification WHERE guild = ? AND configid = ?', [guild, type], function (delerror) {
  364. if ( delerror ) {
  365. console.log( '- Dashboard: Error while removing the verification: ' + delerror );
  366. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  367. }
  368. console.log( `- Dashboard: Verification successfully removed: ${guild}#${type}` );
  369. res(`/guild/${guild}/verification`, 'save');
  370. if ( dberror ) {
  371. console.log( '- Dashboard: Error while notifying the guild: ' + dberror );
  372. return;
  373. }
  374. var lang = new Lang(row.lang);
  375. var text = lang.get('verification.dashboard.removed', `<@${userSettings.user.id}>`, type);
  376. if ( row ) {
  377. text += '\n' + lang.get('verification.channel') + ' <#' + row.channel.split('|').filter( channel => channel.length ).join('>, <#') + '>';
  378. text += '\n' + lang.get('verification.role') + ' <@&' + row.role.split('|').join('>, <@&') + '>';
  379. text += '\n' + lang.get('verification.editcount') + ' `' + row.editcount + '`';
  380. 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') + ' `') ) + '`';
  381. text += '\n' + lang.get('verification.accountage') + ' `' + row.accountage + '` ' + lang.get('verification.indays');
  382. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled')) + '`*';
  383. }
  384. text += `\n<${new URL(`/guild/${guild}/verification`, process.env.dashboard).href}>`;
  385. sendMsg( {
  386. type: 'notifyGuild', guild, text
  387. } ).catch( error => {
  388. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  389. } );
  390. } );
  391. } );
  392. if ( !hasPerm(response.botPermissions, 'MANAGE_ROLES') ) {
  393. return res(`/guild/${guild}/verification`, 'savefail');
  394. }
  395. 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) {
  396. if ( curerror ) {
  397. console.log( '- Dashboard: Error while checking for verifications: ' + curerror );
  398. return res(`/guild/${guild}/verification/new`, 'savefail');
  399. }
  400. if ( !row ) return res(`/guild/${guild}/verification`, 'savefail');
  401. if ( row.count === null ) row.count = [];
  402. else row.count = row.count.split(',').map( configid => parseInt(configid, 10) );
  403. if ( row.count.length >= verificationLimit[( response.patreon ? 'patreon' : 'default' )] ) {
  404. return res(`/guild/${guild}/verification`, 'savefail');
  405. }
  406. return got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  407. var body = gresponse.body;
  408. if ( gresponse.statusCode !== 200 || !body || !body.query || !body.query.allmessages ) {
  409. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  410. return;
  411. }
  412. var groups = body.query.allmessages.filter( group => {
  413. if ( group.name === 'group-all' ) return false;
  414. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  415. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  416. return true;
  417. } ).map( group => {
  418. return {
  419. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  420. content: group['*'].replace( / /g, '_' ).toLowerCase()
  421. };
  422. } );
  423. settings.usergroup = settings.usergroup.map( usergroup => {
  424. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  425. if ( groups.some( group => group.content === usergroup ) ) {
  426. return groups.find( group => group.content === usergroup ).name;
  427. }
  428. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  429. if ( usergroup === '*' ) return 'user';
  430. return usergroup;
  431. } );
  432. }, error => {
  433. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  434. } ).finally( () => {
  435. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  436. var configid = 1;
  437. for ( let i of row.count ) {
  438. if ( configid === i ) configid++;
  439. else break;
  440. }
  441. 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) {
  442. if ( dberror ) {
  443. console.log( '- Dashboard: Error while adding the verification: ' + dberror );
  444. return res(`/guild/${guild}/verification/new`, 'savefail');
  445. }
  446. console.log( `- Dashboard: Verification successfully added: ${guild}#${configid}` );
  447. res(`/guild/${guild}/verification/${configid}`, 'save');
  448. var lang = new Lang(row.lang);
  449. var text = lang.get('verification.dashboard.added', `<@${userSettings.user.id}>`, configid);
  450. text += '\n' + lang.get('verification.channel') + ' <#' + settings.channel.join('>, <#') + '>';
  451. text += '\n' + lang.get('verification.role') + ' <@&' + settings.role.join('>, <@&') + '>';
  452. text += '\n' + lang.get('verification.editcount') + ' `' + settings.editcount + '`';
  453. 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') + ' `') ) + '`';
  454. text += '\n' + lang.get('verification.accountage') + ' `' + settings.accountage + '` ' + lang.get('verification.indays');
  455. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled')) + '`*';
  456. text += `\n<${new URL(`/guild/${guild}/verification/${configid}`, process.env.dashboard).href}>`;
  457. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  458. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  459. }
  460. if ( settings.role.some( role => {
  461. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  462. return ( guildRole.id === role && guildRole.lower );
  463. } );
  464. } ) ) {
  465. text += '\n';
  466. settings.role.forEach( role => {
  467. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  468. return ( guildRole.id === role );
  469. } ) ) {
  470. text += '\n' + lang.get('verification.role_deleted', `<@&${role}>`);
  471. }
  472. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  473. return ( guildRole.id === role && !guildRole.lower );
  474. } ) ) {
  475. text += '\n' + lang.get('verification.role_too_high', `<@&${role}>`, `<@${process.env.bot}>`);
  476. }
  477. } );
  478. }
  479. sendMsg( {
  480. type: 'notifyGuild', guild, text
  481. } ).catch( error => {
  482. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  483. } );
  484. } );
  485. } );
  486. } );
  487. 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) {
  488. if ( curerror ) {
  489. console.log( '- Dashboard: Error while checking for verifications: ' + curerror );
  490. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  491. }
  492. if ( !row?.channel ) return res(`/guild/${guild}/verification`, 'savefail');
  493. row.channel = row.channel.split('|').filter( channel => channel.length );
  494. var newChannel = settings.channel.filter( channel => !row.channel.includes( channel ) );
  495. row.role = row.role.split('|');
  496. var newRole = settings.role.filter( role => !row.role.includes( role ) );
  497. row.usergroup = row.usergroup.split('|');
  498. var newUsergroup = settings.usergroup.filter( group => !row.usergroup.includes( group ) );
  499. if ( newChannel.length || newRole.length ) {
  500. let curGuild = userSettings.guilds.isMember.get(guild);
  501. if ( newChannel.some( channel => {
  502. return !curGuild.channels.some( guildChannel => {
  503. return ( guildChannel.id === channel && !guildChannel.isCategory );
  504. } );
  505. } ) || newRole.some( role => {
  506. return !curGuild.roles.some( guildRole => {
  507. return ( guildRole.id === role && guildRole.lower );
  508. } );
  509. } ) ) return res(`/guild/${guild}/verification/${type}`, 'savefail');
  510. }
  511. ( newUsergroup.length ? got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  512. var body = gresponse.body;
  513. if ( gresponse.statusCode !== 200 || !body || !body.query || !body.query.allmessages ) {
  514. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  515. return;
  516. }
  517. var groups = body.query.allmessages.filter( group => {
  518. if ( group.name === 'group-all' ) return false;
  519. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  520. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  521. return true;
  522. } ).map( group => {
  523. return {
  524. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  525. content: group['*'].replace( / /g, '_' ).toLowerCase()
  526. };
  527. } );
  528. settings.usergroup = settings.usergroup.map( usergroup => {
  529. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  530. if ( groups.some( group => group.content === usergroup ) ) {
  531. return groups.find( group => group.content === usergroup ).name;
  532. }
  533. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  534. if ( usergroup === '*' ) return 'user';
  535. return usergroup;
  536. } );
  537. }, error => {
  538. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  539. } ) : Promise.resolve() ).finally( () => {
  540. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  541. var lang = new Lang(row.lang);
  542. var diff = [];
  543. if ( newChannel.length || row.channel.some( channel => {
  544. return !settings.channel.includes( channel );
  545. } ) ) {
  546. diff.push(lang.get('verification.channel') + ` ~~<#${row.channel.join('>, <#')}>~~ → <#${settings.channel.join('>, <#')}>`);
  547. }
  548. if ( newRole.length || row.role.some( role => {
  549. return !settings.role.includes( role );
  550. } ) ) {
  551. diff.push(lang.get('verification.role') + ` ~~<@&${row.role.join('>, <@&')}>~~ → <@&${settings.role.join('>, <@&')}>`);
  552. }
  553. if ( row.editcount !== settings.editcount ) {
  554. diff.push(lang.get('verification.editcount') + ` ~~\`${row.editcount}\`~~ → \`${settings.editcount}\``);
  555. }
  556. if ( newUsergroup.length || row.usergroup.some( usergroup => {
  557. return !settings.usergroup.includes( usergroup );
  558. } ) ) {
  559. 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') + ' `') ) + '`');
  560. }
  561. if ( row.accountage !== settings.accountage ) {
  562. diff.push(lang.get('verification.accountage') + ` ~~\`${row.accountage}\`~~ → \`${settings.accountage}\``);
  563. }
  564. if ( row.rename !== ( settings.rename ? 1 : 0 ) ) {
  565. diff.push(lang.get('verification.rename') + ` ~~*\`${lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled'))}\`*~~ → *\`${lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled'))}\`*`);
  566. }
  567. if ( !diff.length ) return res(`/guild/${guild}/verification/${type}`, 'save');
  568. 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) {
  569. if ( dberror ) {
  570. console.log( '- Dashboard: Error while updating the verification: ' + dberror );
  571. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  572. }
  573. console.log( `- Dashboard: Verification successfully updated: ${guild}#${type}` );
  574. res(`/guild/${guild}/verification/${type}`, 'save');
  575. var text = lang.get('verification.dashboard.updated', `<@${userSettings.user.id}>`, type);
  576. text += '\n' + diff.join('\n');
  577. text += `\n<${new URL(`/guild/${guild}/verification/${type}`, process.env.dashboard).href}>`;
  578. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  579. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  580. }
  581. if ( settings.role.some( role => {
  582. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  583. return ( guildRole.id === role && guildRole.lower );
  584. } );
  585. } ) ) {
  586. text += '\n';
  587. settings.role.forEach( role => {
  588. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  589. return ( guildRole.id === role );
  590. } ) ) {
  591. text += '\n' + lang.get('verification.role_deleted', `<@&${role}>`);
  592. }
  593. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  594. return ( guildRole.id === role && !guildRole.lower );
  595. } ) ) {
  596. text += '\n' + lang.get('verification.role_too_high', `<@&${role}>`, `<@${process.env.bot}>`);
  597. }
  598. } );
  599. }
  600. sendMsg( {
  601. type: 'notifyGuild', guild, text
  602. } ).catch( error => {
  603. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  604. } );
  605. } );
  606. } );
  607. } );
  608. }, error => {
  609. console.log( '- Dashboard: Error while getting the member: ' + error );
  610. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  611. } );
  612. }
  613. module.exports = {
  614. get: dashboard_verification,
  615. post: update_verification
  616. };