verification.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. import Lang from '../util/i18n.js';
  2. import { got, db, slashCommands, sendMsg, createNotice, escapeText, hasPerm } from './util.js';
  3. import { createRequire } from 'module';
  4. const require = createRequire(import.meta.url);
  5. const {limit: {verification: verificationLimit}, usergroups} = require('../util/default.json');
  6. const slashCommand = slashCommands.find( slashCommand => slashCommand.name === 'verify' );
  7. const fieldset = {
  8. channel: '<div>'
  9. + '<label for="wb-settings-channel">Channel:</label>'
  10. + '<select id="wb-settings-channel" name="channel-0" required></select>'
  11. + '</div>'
  12. + '<button type="button" id="wb-settings-channel-more" class="addmore">Add more</button>',
  13. role: '<div>'
  14. + '<label for="wb-settings-role">Role:</label>'
  15. + '<select id="wb-settings-role" name="role-0" required></select>'
  16. + '<input type="radio" id="wb-settings-role-0-add" name="role-0-change" value="+">'
  17. + '<label for="wb-settings-role-0-add" class="radio-label">Add</label>'
  18. + '<input type="radio" id="wb-settings-role-0-remove" name="role-0-change" value="-">'
  19. + '<label for="wb-settings-role-0-remove" class="radio-label">Remove</label>'
  20. + '</div>'
  21. + '<button type="button" id="wb-settings-role-more" class="addmore">Add more</button>',
  22. usergroup: '<label for="wb-settings-usergroup">Wiki user group:</label>'
  23. + '<input type="text" id="wb-settings-usergroup" name="usergroup" list="wb-settings-usergroup-list" autocomplete="on">'
  24. + '<datalist id="wb-settings-usergroup-list">'
  25. + usergroups.sorted.filter( group => group !== '__CUSTOM__' ).map( group => {
  26. return `<option value="${group}"></option>`
  27. } ).join('')
  28. + usergroups.global.filter( group => group !== '__CUSTOM__' ).map( group => {
  29. return `<option value="${group}"></option>`
  30. } ).join('')
  31. + '</datalist>'
  32. + '<div id="wb-settings-usergroup-multiple">'
  33. + '<label for="wb-settings-usergroup-and">Require all user groups:</label>'
  34. + '<input type="checkbox" id="wb-settings-usergroup-and" name="usergroup_and">'
  35. + '</div>',
  36. editcount: '<label for="wb-settings-editcount">Minimal edit count:</label>'
  37. + '<input type="number" id="wb-settings-editcount" name="editcount" min="0" max="1000000" required>',
  38. postcount: '<div id="wb-settings-postcount-input">'
  39. + '<label for="wb-settings-postcount">Minimal post count:</label>'
  40. + '<input type="number" id="wb-settings-postcount" name="postcount" min="0" max="1000000" required>'
  41. + '</div><div class="wb-settings-postcount">'
  42. + '<span>Only Fandom wikis:</span>'
  43. + '<input type="radio" id="wb-settings-postcount-and" name="posteditcount" value="and" required>'
  44. + '<label for="wb-settings-postcount-and" class="radio-label">Require both edit and post count.</label>'
  45. + '</div><div class="wb-settings-postcount">'
  46. + '<input type="radio" id="wb-settings-postcount-or" name="posteditcount" value="or" required>'
  47. + '<label for="wb-settings-postcount-or" class="radio-label">Require either edit or post count.</label>'
  48. + '</div><div class="wb-settings-postcount">'
  49. + '<input type="radio" id="wb-settings-postcount-both" name="posteditcount" value="both" required>'
  50. + '<label for="wb-settings-postcount-both" class="radio-label">Require combined edit and post count.</label>'
  51. + '</div>',
  52. accountage: '<label for="wb-settings-accountage">Account age (in days):</label>'
  53. + '<input type="number" id="wb-settings-accountage" name="accountage" min="0" max="1000000" required>',
  54. rename: '<label for="wb-settings-rename">Rename users:</label>'
  55. + '<input type="checkbox" id="wb-settings-rename" name="rename">',
  56. save: '<input type="submit" id="wb-settings-save" name="save_settings">',
  57. delete: '<input type="submit" id="wb-settings-delete" name="delete_settings" formnovalidate>'
  58. };
  59. /**
  60. * Create a settings form
  61. * @param {import('cheerio').default} $ - The response body
  62. * @param {String} header - The form header
  63. * @param {import('./i18n.js').default} dashboardLang - The user language
  64. * @param {Object} settings - The current settings
  65. * @param {String} settings.channel
  66. * @param {String} settings.role
  67. * @param {String} settings.usergroup
  68. * @param {Number} settings.editcount
  69. * @param {Number} settings.postcount
  70. * @param {Number} settings.accountage
  71. * @param {Boolean} settings.rename
  72. * @param {String} [settings.defaultrole]
  73. * @param {import('./util.js').Channel[]} guildChannels - The guild channels
  74. * @param {import('./util.js').Role[]} guildRoles - The guild roles
  75. * @param {String} wiki - The guild wiki
  76. */
  77. function createForm($, header, dashboardLang, settings, guildChannels, guildRoles, wiki) {
  78. var readonly = ( process.env.READONLY ? true : false );
  79. var fields = [];
  80. let channel = $('<div>').append(fieldset.channel);
  81. channel.find('label').text(dashboardLang.get('verification.form.channel'));
  82. let curCat = null;
  83. channel.find('#wb-settings-channel').append(
  84. $('<option class="wb-settings-channel-default defaultSelect" hidden>').val('').text(dashboardLang.get('verification.form.select_channel')),
  85. ...guildChannels.filter( guildChannel => {
  86. return ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL') || guildChannel.isCategory || settings.channel.includes( '|' + guildChannel.id + '|' ) );
  87. } ).map( guildChannel => {
  88. if ( guildChannel.isCategory ) {
  89. curCat = $('<optgroup>').attr('label', guildChannel.name);
  90. return curCat;
  91. }
  92. var optionChannel = $(`<option class="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – #${guildChannel.name}`);
  93. if ( !hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL') ) {
  94. optionChannel.addClass('wb-settings-error');
  95. }
  96. if ( !curCat ) return optionChannel;
  97. optionChannel.appendTo(curCat);
  98. } ).filter( catChannel => {
  99. if ( !catChannel ) return false;
  100. if ( catChannel.is('optgroup') && !catChannel.children('option').length ) return false;
  101. return true;
  102. } )
  103. );
  104. if ( settings.channel ) {
  105. let settingsChannels = settings.channel.split('|').filter( guildChannel => guildChannel.length );
  106. channel.find('#wb-settings-channel').append(
  107. ...settingsChannels.filter( guildChannel => {
  108. return !channel.find(`.wb-settings-channel-${guildChannel}`).length;
  109. } ).map( guildChannel => {
  110. return $(`<option class="wb-settings-channel-${guildChannel}">`).val(guildChannel).text(`${guildChannel} – #UNKNOWN`).addClass('wb-settings-error');
  111. } )
  112. );
  113. if ( settingsChannels.length > 1 ) channel.find('div').after(
  114. ...settingsChannels.slice(1).map( (guildChannel, i) => {
  115. var additionalChannel = channel.find('#wb-settings-channel').clone();
  116. additionalChannel.find(`.wb-settings-channel-default`).removeAttr('hidden');
  117. additionalChannel.find(`.wb-settings-channel-${guildChannel}`).attr('selected', '');
  118. additionalChannel.removeAttr('id').removeAttr('required');
  119. additionalChannel.attr('name', 'channel-' + (i + 1));
  120. return $('<div>').addClass('wb-settings-additional-select').append(additionalChannel);
  121. } )
  122. );
  123. channel.find(`#wb-settings-channel .wb-settings-channel-${settingsChannels[0]}`).attr('selected', '');
  124. }
  125. else {
  126. channel.find('.wb-settings-channel-default').attr('selected', '');
  127. channel.find('button.addmore').attr('hidden', '');
  128. }
  129. fields.push(channel);
  130. let role = $('<div>').append(fieldset.role);
  131. role.find('label').eq(0).text(dashboardLang.get('verification.form.role'));
  132. role.find('label').eq(1).text(dashboardLang.get('verification.form.role_add'));
  133. role.find('label').eq(2).text(dashboardLang.get('verification.form.role_remove'));
  134. role.find('#wb-settings-role').append(
  135. $('<option class="wb-settings-role-default defaultSelect" hidden>').val('').text(dashboardLang.get('verification.form.select_role')),
  136. ...guildRoles.filter( guildRole => {
  137. return guildRole.lower || settings.role.replace( /-/g, '' ).split('|').includes( guildRole.id );
  138. } ).map( guildRole => {
  139. var optionRole = $(`<option class="wb-settings-role-${guildRole.id}">`).val(guildRole.id);
  140. if ( !guildRole.lower ) optionRole.addClass('wb-settings-error');
  141. return optionRole.text(`${guildRole.id} – @${guildRole.name}`);
  142. } )
  143. );
  144. if ( settings.role ) {
  145. let settingsRoles = settings.role.split('|').map( guildRole => {
  146. if ( !guildRole.startsWith( '-' ) ) return {id: guildRole, suffix: 'add'};
  147. return {id: guildRole.replace( '-', '' ), suffix: 'remove'};
  148. } );
  149. role.find('#wb-settings-role').append(
  150. ...settingsRoles.filter( guildRole => {
  151. return !role.find(`.wb-settings-role-${guildRole.id}`).length;
  152. } ).map( guildRole => {
  153. return $(`<option class="wb-settings-role-${guildRole.id}">`).val(guildRole.id).text(`${guildRole.id} – @UNKNOWN`).addClass('wb-settings-error');
  154. } )
  155. );
  156. if ( settingsRoles.length > 1 ) role.find('div').after(
  157. ...settingsRoles.slice(1).map( (guildRole, i) => {
  158. var id = i + 1;
  159. var additionalDiv = role.find('div').clone();
  160. additionalDiv.find('label').eq(0).remove();
  161. var additionalRole = additionalDiv.find('#wb-settings-role');
  162. additionalRole.find(`.wb-settings-role-default`).removeAttr('hidden');
  163. additionalRole.find(`.wb-settings-role-${guildRole.id}`).attr('selected', '');
  164. additionalRole.removeAttr('id').removeAttr('required').attr('name', 'role-' + id);
  165. additionalDiv.find('input').attr('name', 'role-' + id + '-change');
  166. additionalDiv.find('input').eq(0).attr('id', 'wb-settings-role-' + id + '-add');
  167. additionalDiv.find('label').eq(0).attr('for', 'wb-settings-role-' + id + '-add');
  168. additionalDiv.find('input').eq(1).attr('id', 'wb-settings-role-' + id + '-remove');
  169. additionalDiv.find('label').eq(1).attr('for', 'wb-settings-role-' + id + '-remove');
  170. additionalDiv.find(`#wb-settings-role-${id}-${guildRole.suffix}`).attr('checked', '');
  171. return additionalDiv.addClass('wb-settings-additional-select');
  172. } )
  173. );
  174. role.find(`#wb-settings-role .wb-settings-role-${settingsRoles[0].id}`).attr('selected', '');
  175. role.find(`#wb-settings-role-0-${settingsRoles[0].suffix}`).attr('checked', '');
  176. }
  177. else {
  178. if ( role.find(`.wb-settings-role-${settings.defaultrole}`).length ) {
  179. role.find(`.wb-settings-role-${settings.defaultrole}`).attr('selected', '');
  180. }
  181. else role.find('.wb-settings-role-default').attr('selected', '');
  182. role.find('#wb-settings-role-0-add').attr('checked', '');
  183. role.find('button.addmore').attr('hidden', '');
  184. }
  185. fields.push(role);
  186. let usergroup = $('<div>').append(fieldset.usergroup);
  187. usergroup.find('label').eq(0).text(dashboardLang.get('verification.form.usergroup'));
  188. usergroup.find('label').eq(1).text(dashboardLang.get('verification.form.usergroup_and'));
  189. if ( settings.usergroup.startsWith( 'AND|' ) ) {
  190. settings.usergroup = settings.usergroup.substring(4);
  191. usergroup.find('#wb-settings-usergroup-and').attr('checked', '');
  192. }
  193. usergroup.find('#wb-settings-usergroup').val(settings.usergroup.split('|').join(', '));
  194. if ( !settings.usergroup.includes( '|' ) ) {
  195. usergroup.find('#wb-settings-usergroup-multiple').attr('style', 'display: none;');
  196. }
  197. fields.push(usergroup);
  198. $('<script>').attr('src', wiki + 'api.php?action=query&meta=allmessages|siteinfo&amprefix=group-&amincludelocal=true&amenableparser=true&amlang=' + dashboardLang.lang + '&siprop=usergroups&format=json&callback=fillUsergroupList').attr('defer', '').insertAfter('script#indexjs');
  199. let editcount = $('<div>').append(fieldset.editcount);
  200. editcount.find('label').text(dashboardLang.get('verification.form.editcount'));
  201. editcount.find('#wb-settings-editcount').val(settings.editcount);
  202. fields.push(editcount);
  203. let postcount = $('<div>').append(fieldset.postcount);
  204. postcount.find('label').eq(0).text(dashboardLang.get('verification.form.postcount'));
  205. postcount.find('span').text(dashboardLang.get('verification.form.postcount_fandom'));
  206. postcount.find('label').eq(1).text(dashboardLang.get('verification.form.postcount_and'));
  207. postcount.find('label').eq(2).text(dashboardLang.get('verification.form.postcount_or'));
  208. postcount.find('label').eq(3).text(dashboardLang.get('verification.form.postcount_both'));
  209. postcount.find('#wb-settings-postcount').val(Math.abs(settings.postcount));
  210. if ( settings.postcount === null ) {
  211. postcount.find('#wb-settings-postcount-both').attr('checked', '');
  212. postcount.find('#wb-settings-postcount-input').attr('style', 'display: none;');
  213. }
  214. else if ( settings.postcount < 0 ) postcount.find('#wb-settings-postcount-or').attr('checked', '');
  215. else postcount.find('#wb-settings-postcount-and').attr('checked', '');
  216. fields.push(postcount);
  217. let accountage = $('<div>').append(fieldset.accountage);
  218. accountage.find('label').text(dashboardLang.get('verification.form.accountage'));
  219. accountage.find('#wb-settings-accountage').val(settings.accountage);
  220. fields.push(accountage);
  221. if ( settings.rename || guildChannels.some( guildChannel => {
  222. return hasPerm(guildChannel.botPermissions, 'MANAGE_NICKNAMES');
  223. } ) ) {
  224. let rename = $('<div>').append(fieldset.rename);
  225. rename.find('label').text(dashboardLang.get('verification.form.rename'));
  226. if ( settings.rename ) rename.find('#wb-settings-rename').attr('checked', '');
  227. fields.push(rename);
  228. }
  229. fields.push($(fieldset.save).val(dashboardLang.get('general.save')));
  230. if ( settings.channel ) {
  231. fields.push($(fieldset.delete).val(dashboardLang.get('general.delete')).attr('onclick', `return confirm('${dashboardLang.get('verification.form.confirm').replace( /'/g, '\\$&' )}');`));
  232. }
  233. var form = $('<fieldset>').append(...fields);
  234. if ( readonly ) {
  235. form.find('input').attr('readonly', '');
  236. form.find('input[type="checkbox"], input[type="radio"]:not(:checked), option, optgroup').attr('disabled', '');
  237. form.find('input[type="submit"], button.addmore').remove();
  238. }
  239. form.find('button.addmore').text(dashboardLang.get('verification.form.more'));
  240. return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  241. $('<h2>').text(header),
  242. form
  243. );
  244. }
  245. /**
  246. * Let a user change verifications
  247. * @param {import('http').ServerResponse} res - The server response
  248. * @param {import('cheerio').default} $ - The response body
  249. * @param {import('./util.js').Guild} guild - The current guild
  250. * @param {String[]} args - The url parts
  251. * @param {import('./i18n.js').default} dashboardLang - The user language
  252. */
  253. function dashboard_verification(res, $, guild, args, dashboardLang) {
  254. db.query( 'SELECT wiki, discord.role defaultrole, prefix, configid, verification.channel, verification.role, editcount, postcount, usergroup, accountage, rename FROM discord LEFT JOIN verification ON discord.guild = verification.guild WHERE discord.guild = $1 AND discord.channel IS NULL ORDER BY configid ASC', [guild.id] ).then( ({rows}) => {
  255. if ( rows.length === 0 ) {
  256. createNotice($, 'nosettings', dashboardLang, [guild.id]);
  257. $('#text .description').html(dashboardLang.get('verification.explanation'));
  258. $('#text code.prefix').prepend(escapeText(process.env.prefix));
  259. $('.channel#verification').addClass('selected');
  260. let body = $.html();
  261. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  262. res.write( body );
  263. return res.end();
  264. }
  265. if ( !hasPerm(guild.botPermissions, 'MANAGE_ROLES') ) {
  266. createNotice($, 'missingperm', dashboardLang, ['Manage Roles']);
  267. $('#text .description').html(dashboardLang.get('verification.explanation'));
  268. $('#text code.prefix').prepend(escapeText(rows[0].prefix));
  269. $('.channel#verification').addClass('selected');
  270. let body = $.html();
  271. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  272. res.write( body );
  273. return res.end();
  274. }
  275. var wiki = rows[0].wiki;
  276. var defaultrole = rows[0].defaultrole;
  277. var prefix = rows[0].prefix;
  278. if ( rows.length === 1 && rows[0].configid === null ) rows.pop();
  279. $('<p>').html(dashboardLang.get('verification.desc', true, $('<code>').text(guild.name))).appendTo('#text .description');
  280. let suffix = ( args[0] === 'owner' ? '?owner=true' : '' );
  281. $('#channellist #verification').after(
  282. ...rows.map( row => {
  283. let text = `${row.configid} - ${( guild.roles.find( role => {
  284. return role.id === row.role.replace( /-/g, '' ).split('|')[0];
  285. } )?.name || guild.channels.find( channel => {
  286. return channel.id === row.channel.split('|')[1];
  287. } )?.name || row.usergroup.split('|')[( row.usergroup.startsWith('AND|') ? 1 : 0 )] )}`;
  288. return $('<a class="channel">').attr('id', `channel-${row.configid}`).append(
  289. $('<img>').attr('src', '/src/channel.svg'),
  290. $('<div>').text(text)
  291. ).attr('title', text).attr('href', `/guild/${guild.id}/verification/${row.configid}${suffix}`);
  292. } ),
  293. ( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ? '' :
  294. $('<a class="channel" id="channel-new">').append(
  295. $('<img>').attr('src', '/src/channel.svg'),
  296. $('<div>').text(dashboardLang.get('verification.new'))
  297. ).attr('href', `/guild/${guild.id}/verification/new${suffix}`) ),
  298. ( !rows.length ? '' :
  299. $('<a class="channel" id="channel-notice">').append(
  300. $('<img>').attr('src', '/src/channel.svg'),
  301. $('<div>').text(dashboardLang.get('verification.notice'))
  302. ).attr('href', `/guild/${guild.id}/verification/notice${suffix}`) )
  303. );
  304. if ( args[4] === 'new' && !( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ) ) {
  305. $('.channel#channel-new').addClass('selected');
  306. createForm($, dashboardLang.get('verification.form.new'), dashboardLang, {
  307. channel: '', role: '', usergroup: 'user',
  308. editcount: 0, postcount: 0, accountage: 0,
  309. rename: false, defaultrole
  310. }, guild.channels, guild.roles, wiki).attr('action', `/guild/${guild.id}/verification/new`).appendTo('#text');
  311. }
  312. else if ( rows.some( row => row.configid.toString() === args[4] ) ) {
  313. let row = rows.find( row => row.configid.toString() === args[4] );
  314. $(`.channel#channel-${row.configid}`).addClass('selected');
  315. createForm($, dashboardLang.get('verification.form.entry', false, row.configid), dashboardLang, row, guild.channels, guild.roles, wiki).attr('action', `/guild/${guild.id}/verification/${row.configid}`).appendTo('#text');
  316. }
  317. else if ( args[4] === 'notice' && rows.length ) {
  318. $(`.channel#channel-notice`).addClass('selected');
  319. return db.query( 'SELECT logchannel, flags, onsuccess, onmatch FROM verifynotice WHERE guild = $1', [guild.id] ).then( ({rows:[row]}) => {
  320. let curCat = null;
  321. $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  322. $('<h2>').text(dashboardLang.get('verification.form.notice')),
  323. $('<fieldset>').append(
  324. $('<div>').append(
  325. $('<label for="wb-settings-channel">').text(dashboardLang.get('verification.form.logging')),
  326. $('<select id="wb-settings-channel" name="channel">').append(
  327. $('<option class="wb-settings-channel-default defaultSelect">').val('').text(dashboardLang.get('verification.form.select_channel')),
  328. ...guild.channels.filter( guildChannel => {
  329. return ( ( hasPerm(guildChannel.botPermissions, 'VIEW_CHANNEL', 'SEND_MESSAGES') && hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL') ) || guildChannel.isCategory );
  330. } ).map( guildChannel => {
  331. if ( guildChannel.isCategory ) {
  332. curCat = $('<optgroup>').attr('label', guildChannel.name);
  333. return curCat;
  334. }
  335. var optionChannel = $(`<option class="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – #${guildChannel.name}`);
  336. if ( guildChannel.id === row?.logchannel ) optionChannel.attr('selected', '');
  337. if ( !curCat ) return optionChannel;
  338. optionChannel.appendTo(curCat);
  339. } ).filter( catChannel => {
  340. if ( !catChannel ) return false;
  341. if ( catChannel.is('optgroup') && !catChannel.children('option').length ) return false;
  342. return true;
  343. } )
  344. ),
  345. $('<div id="wb-settings-logall-hide">').append(
  346. $('<label for="wb-settings-flag_logall">').text(dashboardLang.get('verification.form.flag_logall')),
  347. $('<input type="checkbox" id="wb-settings-flag_logall" name="flag_logall">').attr('checked', ( (row?.flags & 1 << 1) === 1 << 1 ? '' : null ))
  348. ).attr('style', ( row?.logchannel ? '' : 'display: none;'))
  349. ),
  350. $('<div>').append(
  351. $('<label for="wb-settings-flag_private">').text(dashboardLang.get('verification.form.flag_private')),
  352. $('<input type="checkbox" id="wb-settings-flag_private" name="flag_private">').attr('checked', ( (row?.flags & 1 << 0) === 1 << 0 ? '' : null ))
  353. ),
  354. $('<div>').append(
  355. $('<label for="wb-settings-success">').text(dashboardLang.get('verification.form.success')).append(
  356. $('<div>').html('&nbsp;')
  357. ),
  358. $('<textarea id="wb-settings-success" name="success" spellcheck="true" maxlength="1000" cols="65">').attr('rows', ( row?.onsuccess || '' ).split('\n').length + 3).attr('placeholder', dashboardLang.get('verification.form.success_placeholder')).text(row?.onsuccess || '')
  359. ),
  360. $('<div>').append(
  361. $('<label for="wb-settings-match">').text(dashboardLang.get('verification.form.match')).append(
  362. $('<div>').html('&nbsp;')
  363. ),
  364. $('<textarea id="wb-settings-match" name="match" spellcheck="true" maxlength="1000" cols="65">').attr('rows', ( row?.onmatch || '' ).split('\n').length + 3).attr('placeholder', dashboardLang.get('verification.form.match_placeholder')).text(row?.onmatch || '')
  365. ),
  366. $('<input type="submit" id="wb-settings-save" name="save_settings">').val(dashboardLang.get('general.save'))
  367. )
  368. ).attr('action', `/guild/${guild.id}/verification/notice`).appendTo('#text');
  369. if ( process.env.READONLY ) {
  370. $('input, textarea').attr('readonly', '');
  371. $('textarea, option, optgroup').attr('disabled', '');
  372. $('input[type="submit"]').remove();
  373. }
  374. $('<div class="description">').html(dashboardLang.get('verification.help_notice')).appendTo('#text');
  375. let body = $.html();
  376. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  377. res.write( body );
  378. return res.end();
  379. }, dberror => {
  380. console.log( '- Dashboard: Error while getting the verification notices: ' + dberror );
  381. createNotice($, 'error', dashboardLang);
  382. $('#text .description').html(dashboardLang.get('verification.explanation'));
  383. $('#text code.prefix').prepend(escapeText(process.env.prefix));
  384. $('.channel#verification').addClass('selected');
  385. let body = $.html();
  386. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  387. res.write( body );
  388. return res.end();
  389. } );
  390. }
  391. else {
  392. $('.channel#verification').addClass('selected');
  393. $('#text .description').html(dashboardLang.get('verification.explanation'));
  394. $('#text code.prefix').prepend(escapeText(prefix));
  395. }
  396. let body = $.html();
  397. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  398. res.write( body );
  399. return res.end();
  400. }, dberror => {
  401. console.log( '- Dashboard: Error while getting the verifications: ' + dberror );
  402. createNotice($, 'error', dashboardLang);
  403. $('#text .description').html(dashboardLang.get('verification.explanation'));
  404. $('#text code.prefix').prepend(escapeText(process.env.prefix));
  405. $('.channel#verification').addClass('selected');
  406. let body = $.html();
  407. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  408. res.write( body );
  409. return res.end();
  410. } );
  411. }
  412. /**
  413. * Change verifications
  414. * @param {Function} res - The server response
  415. * @param {import('./util.js').Settings} userSettings - The settings of the user
  416. * @param {String} guild - The id of the guild
  417. * @param {String|Number} type - The setting to change
  418. * @param {Object} settings - The new settings
  419. * @param {String[]} [settings.usergroup]
  420. * @param {String} [settings.usergroup_and]
  421. * @param {Number} settings.editcount
  422. * @param {Number} [settings.postcount]
  423. * @param {String} settings.posteditcount
  424. * @param {Number} settings.accountage
  425. * @param {String} [settings.rename]
  426. * @param {String} [settings.save_settings]
  427. * @param {String} [settings.delete_settings]
  428. */
  429. function update_verification(res, userSettings, guild, type, settings) {
  430. if ( type === 'default' ) {
  431. return res(`/guild/${guild}/verification`, 'savefail');
  432. }
  433. if ( type === 'notice' ) return update_notices(res, userSettings, guild, type, settings);
  434. if ( !settings.save_settings === !settings.delete_settings ) {
  435. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  436. }
  437. /** @type {String[]} */
  438. var channels = [];
  439. /** @type {{id: String, prefix: String}[]} */
  440. var roles = [];
  441. if ( settings.save_settings ) {
  442. channels = Object.keys(settings).filter( channel => {
  443. return /^channel-\d$/.test(channel) && /^\d+$/.test(settings[channel]);
  444. } ).map( channel => settings[channel] );
  445. roles = Object.keys(settings).filter( role => {
  446. return /^role-\d$/.test(role) && /^\d+$/.test(settings[role]);
  447. } ).map( role => {
  448. return {id: settings[role], prefix: ( settings[role + '-change'] === '-' ? '-' : '' )};
  449. } );
  450. if ( !channels.length || !roles.length ) {
  451. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  452. }
  453. if ( !/^\d+ \d+$/.test(`${settings.editcount} ${settings.accountage}`) ) {
  454. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  455. }
  456. if ( !( ['and','or','both'].includes( settings.posteditcount ) && ( /^\d+$/.test(settings.postcount) || settings.posteditcount === 'both' ) ) ) {
  457. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  458. }
  459. channels = channels.filter( (channel, i, self) => {
  460. return self.indexOf(channel) === i;
  461. } );
  462. if ( !settings.usergroup ) settings.usergroup = 'user';
  463. settings.usergroup = settings.usergroup.replace( /_/g, ' ' ).trim().toLowerCase();
  464. settings.usergroup = settings.usergroup.split(/\s*[,|]\s*/).map( usergroup => {
  465. if ( usergroup === '*' ) return 'user';
  466. return usergroup.replace( / /g, '_' );
  467. } ).filter( (usergroup, i, self) => {
  468. return ( usergroup.length && self.indexOf(usergroup) === i );
  469. } );
  470. if ( !settings.usergroup.length ) settings.usergroup.push('user');
  471. if ( settings.usergroup.length > 10 || settings.usergroup.some( usergroup => {
  472. return ( usergroup.length > 100 );
  473. } ) ) return res(`/guild/${guild}/verification/${type}`, 'invalidusergroup');
  474. settings.editcount = parseInt(settings.editcount, 10);
  475. settings.accountage = parseInt(settings.accountage, 10);
  476. if ( settings.editcount > 1000000 || settings.accountage > 1000000 ) {
  477. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  478. }
  479. if ( settings.posteditcount === 'both' ) settings.postcount = null;
  480. else settings.postcount = parseInt(settings.postcount, 10);
  481. if ( settings.posteditcount === 'or' ) settings.postcount = settings.postcount * -1;
  482. if ( settings.postcount > 1000000 || settings.postcount < -1000000 ) {
  483. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  484. }
  485. if ( type === 'new' ) {
  486. let curGuild = userSettings.guilds.isMember.get(guild);
  487. if ( channels.some( channel => {
  488. return !curGuild.channels.some( guildChannel => {
  489. return ( guildChannel.id === channel && !guildChannel.isCategory );
  490. } );
  491. } ) || roles.some( role => {
  492. return !curGuild.roles.some( guildRole => {
  493. return ( guildRole.id === role.id && guildRole.lower );
  494. } );
  495. } ) ) return res(`/guild/${guild}/verification/new`, 'savefail');
  496. }
  497. }
  498. if ( settings.delete_settings && type === 'new' ) {
  499. return res(`/guild/${guild}/verification/new`, 'savefail');
  500. }
  501. if ( type !== 'new' ) type = parseInt(type, 10);
  502. sendMsg( {
  503. type: 'getMember',
  504. member: userSettings.user.id,
  505. guild: guild
  506. } ).then( response => {
  507. if ( !response ) {
  508. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  509. userSettings.guilds.isMember.delete(guild);
  510. return res(`/guild/${guild}`, 'savefail');
  511. }
  512. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  513. userSettings.guilds.isMember.delete(guild);
  514. return res('/', 'savefail');
  515. }
  516. if ( settings.delete_settings ) return db.query( 'DELETE FROM verification WHERE guild = $1 AND configid = $2 RETURNING channel, role, editcount, postcount, usergroup, accountage, rename', [guild, type] ).then( ({rows:[row]}) => {
  517. console.log( `- Dashboard: Verification successfully removed: ${guild}#${type}` );
  518. res(`/guild/${guild}/verification`, 'save');
  519. if ( slashCommand?.id ) db.query( 'SELECT COUNT(1) FROM verification WHERE guild = $1', [guild] ).then( ({rows:[{count}]}) => {
  520. if ( count > 0 ) return;
  521. got.put( 'https://discord.com/api/v8/applications/' + process.env.bot + '/guilds/' + guild + '/commands/' + slashCommand.id + '/permissions', {
  522. headers:{
  523. Authorization: 'Bot ' + process.env.token
  524. },
  525. json: {
  526. permissions: []
  527. },
  528. timeout: {
  529. request: 10000
  530. }
  531. } ).then( response=> {
  532. if ( response.statusCode !== 200 || !response.body ) {
  533. console.log( '- Dashboard: ' + response.statusCode + ': Error while disabling the slash command: ' + response.body?.message );
  534. return;
  535. }
  536. console.log( '- Dashboard: Slash command successfully disabled.' );
  537. }, error => {
  538. console.log( '- Dashboard: Error while disabling the slash command: ' + error );
  539. } );
  540. }, dberror => {
  541. console.log( '- Dashboard: Error while disabling the slash command: ' + dberror );
  542. } );
  543. if ( row ) db.query( 'SELECT lang FROM discord WHERE guild = $1 AND channel IS NULL', [guild] ).then( ({rows:[channel]}) => {
  544. var lang = new Lang(channel.lang);
  545. var text = lang.get('verification.dashboard.removed', `<@${userSettings.user.id}>`, type);
  546. if ( row ) {
  547. text += '\n' + lang.get('verification.channel') + ' <#' + row.channel.split('|').filter( channel => channel.length ).join('>, <#') + '>';
  548. let rolesRow = [
  549. row.role.split('|').filter( role => !role.startsWith( '-' ) ),
  550. row.role.split('|').filter( role => role.startsWith( '-' ) ).map( role => role.replace( '-', '' ) )
  551. ];
  552. if ( rolesRow[0].length ) text += '\n' + lang.get('verification.role_add') + ' <@&' + rolesRow[0].join('>, <@&') + '>';
  553. if ( rolesRow[1].length ) text += '\n' + lang.get('verification.role_remove') + ' <@&' + rolesRow[1].join('>, <@&') + '>';
  554. if ( row.postcount === null ) {
  555. text += '\n' + lang.get('verification.posteditcount') + ' `' + row.editcount + '`';
  556. }
  557. else {
  558. text += '\n' + lang.get('verification.editcount') + ' `' + row.editcount + '`';
  559. text += '\n' + lang.get('verification.postcount') + ' `' + Math.abs(row.postcount) + '`';
  560. if ( row.postcount < 0 ) text += ' ' + lang.get('verification.postcount_or');
  561. }
  562. 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') + ' `') ) + '`';
  563. text += '\n' + lang.get('verification.accountage') + ' `' + row.accountage + '` ' + lang.get('verification.indays');
  564. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled')) + '`*';
  565. }
  566. text += `\n<${new URL(`/guild/${guild}/verification`, process.env.dashboard).href}>`;
  567. sendMsg( {
  568. type: 'notifyGuild', guild, text
  569. } ).catch( error => {
  570. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  571. } );
  572. }, dberror => {
  573. console.log( '- Dashboard: Error while notifying the guild: ' + dberror );
  574. } );
  575. }, dberror => {
  576. console.log( '- Dashboard: Error while removing the verification: ' + dberror );
  577. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  578. } );
  579. if ( !hasPerm(response.botPermissions, 'MANAGE_ROLES') ) {
  580. return res(`/guild/${guild}/verification`, 'savefail');
  581. }
  582. if ( type === 'new' ) return db.query( 'SELECT wiki, lang, ARRAY_REMOVE(ARRAY_AGG(configid ORDER BY configid), NULL) count FROM discord LEFT JOIN verification ON discord.guild = verification.guild WHERE discord.guild = $1 AND discord.channel IS NULL GROUP BY wiki, lang', [guild] ).then( ({rows:[row]}) => {
  583. if ( !row ) return res(`/guild/${guild}/verification`, 'savefail');
  584. if ( row.count.length >= verificationLimit[( response.patreon ? 'patreon' : 'default' )] ) {
  585. return res(`/guild/${guild}/verification`, 'savefail');
  586. }
  587. return got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  588. var body = gresponse.body;
  589. if ( gresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages ) {
  590. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  591. return;
  592. }
  593. var groups = body.query.allmessages.filter( group => {
  594. if ( group.name === 'group-all' ) return false;
  595. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  596. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  597. return true;
  598. } ).map( group => {
  599. return {
  600. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  601. content: group['*'].replace( / /g, '_' ).toLowerCase()
  602. };
  603. } );
  604. settings.usergroup = settings.usergroup.map( usergroup => {
  605. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  606. if ( groups.some( group => group.content === usergroup ) ) {
  607. return groups.find( group => group.content === usergroup ).name;
  608. }
  609. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  610. if ( usergroup === '*' ) return 'user';
  611. return usergroup;
  612. } );
  613. }, error => {
  614. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  615. } ).finally( () => {
  616. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  617. var configid = 1;
  618. for ( let i of row.count ) {
  619. if ( configid === i ) configid++;
  620. else break;
  621. }
  622. db.query( 'INSERT INTO verification(guild, configid, channel, role, editcount, postcount, usergroup, accountage, rename) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9)', [guild, configid, '|' + channels.join('|') + '|', roles.map( role => role.prefix + role.id ).join('|'), settings.editcount, settings.postcount, settings.usergroup.join('|'), settings.accountage, ( settings.rename ? 1 : 0 )] ).then( () => {
  623. console.log( `- Dashboard: Verification successfully added: ${guild}#${configid}` );
  624. res(`/guild/${guild}/verification/${configid}`, 'save');
  625. if ( !row.count.length && slashCommand?.id ) got.put( 'https://discord.com/api/v8/applications/' + process.env.bot + '/guilds/' + guild + '/commands/' + slashCommand.id + '/permissions', {
  626. headers:{
  627. Authorization: 'Bot ' + process.env.token
  628. },
  629. json: {
  630. permissions: [
  631. {
  632. id: guild,
  633. type: 1,
  634. permission: true
  635. }
  636. ]
  637. },
  638. timeout: {
  639. request: 10000
  640. }
  641. } ).then( response=> {
  642. if ( response.statusCode !== 200 || !response.body ) {
  643. console.log( '- Dashboard: ' + response.statusCode + ': Error while enabling the slash command: ' + response.body?.message );
  644. return;
  645. }
  646. console.log( '- Dashboard: Slash command successfully enabled.' );
  647. }, error => {
  648. console.log( '- Dashboard: Error while enabling the slash command: ' + error );
  649. } );
  650. var lang = new Lang(row.lang);
  651. var text = lang.get('verification.dashboard.added', `<@${userSettings.user.id}>`, configid);
  652. text += '\n' + lang.get('verification.channel') + ' <#' + channels.join('>, <#') + '>';
  653. let rolesRow = [
  654. roles.filter( role => !role.prefix ).map( role => '<@&' + role.id + '>' ),
  655. roles.filter( role => role.prefix ).map( role => '<@&' + role.id + '>' )
  656. ];
  657. if ( rolesRow[0].length ) text += '\n' + lang.get('verification.role_add') + ' ' + rolesRow[0].join(', ');
  658. if ( rolesRow[1].length ) text += '\n' + lang.get('verification.role_remove') + ' ' + rolesRow[1].join(', ');
  659. if ( settings.postcount === null ) {
  660. text += '\n' + lang.get('verification.posteditcount') + ' `' + settings.editcount + '`';
  661. }
  662. else {
  663. text += '\n' + lang.get('verification.editcount') + ' `' + settings.editcount + '`';
  664. text += '\n' + lang.get('verification.postcount') + ' `' + Math.abs(settings.postcount) + '`';
  665. if ( settings.postcount < 0 ) text += ' ' + lang.get('verification.postcount_or');
  666. }
  667. 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') + ' `') ) + '`';
  668. text += '\n' + lang.get('verification.accountage') + ' `' + settings.accountage + '` ' + lang.get('verification.indays');
  669. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled')) + '`*';
  670. text += `\n<${new URL(`/guild/${guild}/verification/${configid}`, process.env.dashboard).href}>`;
  671. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  672. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  673. }
  674. if ( roles.some( role => {
  675. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  676. return ( guildRole.id === role.id && guildRole.lower );
  677. } );
  678. } ) ) {
  679. text += '\n';
  680. roles.forEach( role => {
  681. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  682. return ( guildRole.id === role.id );
  683. } ) ) {
  684. text += '\n' + lang.get('verification.role_deleted', `<@&${role.id}>`);
  685. }
  686. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  687. return ( guildRole.id === role.id && !guildRole.lower );
  688. } ) ) {
  689. text += '\n' + lang.get('verification.role_too_high', `<@&${role.id}>`, `<@${process.env.bot}>`);
  690. }
  691. } );
  692. }
  693. sendMsg( {
  694. type: 'notifyGuild', guild, text
  695. } ).catch( error => {
  696. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  697. } );
  698. }, dberror => {
  699. console.log( '- Dashboard: Error while adding the verification: ' + dberror );
  700. return res(`/guild/${guild}/verification/new`, 'savefail');
  701. } );
  702. } );
  703. }, dberror => {
  704. console.log( '- Dashboard: Error while checking for verifications: ' + dberror );
  705. return res(`/guild/${guild}/verification/new`, 'savefail');
  706. } );
  707. return db.query( 'SELECT wiki, lang, verification.channel, verification.role, editcount, postcount, usergroup, accountage, rename FROM discord LEFT JOIN verification ON discord.guild = verification.guild AND verification.configid = $1 WHERE discord.guild = $2 AND discord.channel IS NULL', [type, guild] ).then( ({rows:[row]}) => {
  708. if ( !row?.channel ) return res(`/guild/${guild}/verification`, 'savefail');
  709. row.channel = row.channel.split('|').filter( channel => channel.length );
  710. var newChannel = channels.filter( channel => !row.channel.includes( channel ) );
  711. /** @type {String[][]} */
  712. var rolesRow = [
  713. row.role.split('|').filter( role => !role.startsWith( '-' ) ),
  714. row.role.split('|').filter( role => role.startsWith( '-' ) ).map( role => role.replace( '-', '' ) )
  715. ];
  716. var newRole = roles.filter( role => {
  717. return !rolesRow[0].includes( role.id ) && !rolesRow[1].includes( role.id );
  718. } );
  719. row.usergroup = row.usergroup.split('|');
  720. var newUsergroup = settings.usergroup.filter( group => !row.usergroup.includes( group ) );
  721. if ( newChannel.length || newRole.length ) {
  722. let curGuild = userSettings.guilds.isMember.get(guild);
  723. if ( newChannel.some( channel => {
  724. return !curGuild.channels.some( guildChannel => {
  725. return ( guildChannel.id === channel && !guildChannel.isCategory );
  726. } );
  727. } ) || newRole.some( role => {
  728. return !curGuild.roles.some( guildRole => {
  729. return ( guildRole.id === role.id && guildRole.lower );
  730. } );
  731. } ) ) return res(`/guild/${guild}/verification/${type}`, 'savefail');
  732. }
  733. ( newUsergroup.length ? got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  734. var body = gresponse.body;
  735. if ( gresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages ) {
  736. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  737. return;
  738. }
  739. var groups = body.query.allmessages.filter( group => {
  740. if ( group.name === 'group-all' ) return false;
  741. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  742. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  743. return true;
  744. } ).map( group => {
  745. return {
  746. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  747. content: group['*'].replace( / /g, '_' ).toLowerCase()
  748. };
  749. } );
  750. settings.usergroup = settings.usergroup.map( usergroup => {
  751. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  752. if ( groups.some( group => group.content === usergroup ) ) {
  753. return groups.find( group => group.content === usergroup ).name;
  754. }
  755. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  756. if ( usergroup === '*' ) return 'user';
  757. return usergroup;
  758. } );
  759. }, error => {
  760. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  761. } ) : Promise.resolve() ).finally( () => {
  762. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  763. var lang = new Lang(row.lang);
  764. var diff = [];
  765. if ( newChannel.length || row.channel.some( channel => {
  766. return !channels.includes( channel );
  767. } ) ) {
  768. diff.push(lang.get('verification.channel') + ` ~~<#${row.channel.join('>, <#')}>~~ → <#${channels.join('>, <#')}>`);
  769. }
  770. if ( roles.some( role => {
  771. if ( role.prefix ) return false;
  772. return !rolesRow[0].includes( role.id );
  773. } ) || rolesRow[0].some( roleid => {
  774. return !roles.some( role => !role.prefix && role.id === roleid );
  775. } ) ) {
  776. diff.push(lang.get('verification.role_add') + ' ~~' + ( rolesRow[0].length ? '<@&' + rolesRow[0].join('>, <@&') + '>' : '*`' + lang.get('verification.role_none') + '`*' ) + '~~ → ' + ( roles.some( role => !role.prefix ) ? roles.filter( role => !role.prefix ).map( role => '<@&' + role.id + '>' ).join(', ') : '*`' + lang.get('verification.role_none') + '`*' ));
  777. }
  778. if ( roles.some( role => {
  779. if ( !role.prefix ) return false;
  780. return !rolesRow[1].includes( role.id );
  781. } ) || rolesRow[1].some( roleid => {
  782. return !roles.some( role => role.prefix && role.id === roleid );
  783. } ) ) {
  784. diff.push(lang.get('verification.role_remove') + ' ~~' + ( rolesRow[1].length ? '<@&' + rolesRow[1].join('>, <@&') + '>' : '*`' + lang.get('verification.role_none') + '`*' ) + '~~ → ' + ( roles.some( role => role.prefix ) ? roles.filter( role => role.prefix ).map( role => '<@&' + role.id + '>' ).join(', ') : '*`' + lang.get('verification.role_none') + '`*' ));
  785. }
  786. if ( row.postcount !== settings.postcount && ( row.postcount === null || settings.postcount === null ) ) {
  787. if ( row.postcount === null ) {
  788. diff.push('~~' + lang.get('verification.posteditcount') + ` \`${row.editcount}\`~~`);
  789. diff.push('→ ' + lang.get('verification.editcount') + ` \`${settings.editcount}\``);
  790. diff.push('→ ' + lang.get('verification.postcount') + ` \`${Math.abs(settings.postcount)}\`` + ( settings.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ));
  791. }
  792. if ( settings.postcount === null ) {
  793. diff.push('~~' + lang.get('verification.editcount') + ` \`${row.editcount}\`~~`);
  794. diff.push('~~' + lang.get('verification.postcount') + ` \`${Math.abs(row.postcount)}\`` + ( row.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ) + '~~');
  795. diff.push('→ ' + lang.get('verification.posteditcount') + ` \`${settings.editcount}\``);
  796. }
  797. }
  798. else {
  799. if ( row.editcount !== settings.editcount ) {
  800. diff.push(lang.get('verification.editcount') + ` ~~\`${row.editcount}\`~~ → \`${settings.editcount}\``);
  801. }
  802. if ( row.postcount !== settings.postcount ) {
  803. if ( ( row.postcount >= 0 && settings.postcount < 0 ) || ( row.postcount < 0 && settings.postcount >= 0 ) ) {
  804. diff.push('~~' + lang.get('verification.postcount') + ` \`${Math.abs(row.postcount)}\`` + ( row.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ) + '~~');
  805. diff.push('→ ' + lang.get('verification.postcount') + ` \`${Math.abs(settings.postcount)}\`` + ( settings.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ));
  806. }
  807. else diff.push(lang.get('verification.postcount') + ` ~~\`${Math.abs(row.postcount)}\`~~ → \`${Math.abs(settings.postcount)}\`` + ( settings.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ));
  808. }
  809. }
  810. if ( newUsergroup.length || row.usergroup.some( usergroup => {
  811. return !settings.usergroup.includes( usergroup );
  812. } ) ) {
  813. 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') + ' `') ) + '`');
  814. }
  815. if ( row.accountage !== settings.accountage ) {
  816. diff.push(lang.get('verification.accountage') + ` ~~\`${row.accountage}\`~~ → \`${settings.accountage}\``);
  817. }
  818. if ( row.rename !== ( settings.rename ? 1 : 0 ) ) {
  819. diff.push(lang.get('verification.rename') + ` ~~*\`${lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled'))}\`*~~ → *\`${lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled'))}\`*`);
  820. }
  821. if ( !diff.length ) return res(`/guild/${guild}/verification/${type}`, 'save');
  822. db.query( 'UPDATE verification SET channel = $1, role = $2, editcount = $3, postcount = $4, usergroup = $5, accountage = $6, rename = $7 WHERE guild = $8 AND configid = $9', ['|' + channels.join('|') + '|', roles.map( role => role.prefix + role.id ).join('|'), settings.editcount, settings.postcount, settings.usergroup.join('|'), settings.accountage, ( settings.rename ? 1 : 0 ), guild, type] ).then( () => {
  823. console.log( `- Dashboard: Verification successfully updated: ${guild}#${type}` );
  824. res(`/guild/${guild}/verification/${type}`, 'save');
  825. var text = lang.get('verification.dashboard.updated', `<@${userSettings.user.id}>`, type);
  826. text += '\n' + diff.join('\n');
  827. text += `\n<${new URL(`/guild/${guild}/verification/${type}`, process.env.dashboard).href}>`;
  828. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  829. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  830. }
  831. if ( roles.some( role => {
  832. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  833. return ( guildRole.id === role.id && guildRole.lower );
  834. } );
  835. } ) ) {
  836. text += '\n';
  837. roles.forEach( role => {
  838. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  839. return ( guildRole.id === role.id );
  840. } ) ) {
  841. text += '\n' + lang.get('verification.role_deleted', `<@&${role.id}>`);
  842. }
  843. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  844. return ( guildRole.id === role.id && !guildRole.lower );
  845. } ) ) {
  846. text += '\n' + lang.get('verification.role_too_high', `<@&${role.id}>`, `<@${process.env.bot}>`);
  847. }
  848. } );
  849. }
  850. sendMsg( {
  851. type: 'notifyGuild', guild, text
  852. } ).catch( error => {
  853. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  854. } );
  855. }, dberror => {
  856. console.log( '- Dashboard: Error while updating the verification: ' + dberror );
  857. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  858. } );
  859. } );
  860. }, dberror => {
  861. console.log( '- Dashboard: Error while checking for verifications: ' + dberror );
  862. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  863. } );
  864. }, error => {
  865. console.log( '- Dashboard: Error while getting the member: ' + error );
  866. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  867. } );
  868. }
  869. /**
  870. * Change verification notices
  871. * @param {Function} res - The server response
  872. * @param {import('./util.js').Settings} userSettings - The settings of the user
  873. * @param {String} guild - The id of the guild
  874. * @param {String} type - The setting to change
  875. * @param {Object} settings - The new settings
  876. * @param {String} [settings.channel]
  877. * @param {String} [settings.flag_logall]
  878. * @param {String} [settings.flag_private]
  879. * @param {String} [settings.success]
  880. * @param {String} [settings.match]
  881. * @param {String} settings.save_settings
  882. */
  883. function update_notices(res, userSettings, guild, type, settings) {
  884. if ( !settings.save_settings ) {
  885. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  886. }
  887. if ( settings.channel && !/^\d+$/.test(settings.channel) ) {
  888. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  889. }
  890. if ( settings.success && settings.success.trim().length > 1000 ) {
  891. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  892. }
  893. if ( settings.match && settings.match.trim().length > 1000 ) {
  894. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  895. }
  896. settings.channel = ( settings.channel || null );
  897. settings.success = ( settings.success?.trim().replace( /`ˋ`/g, '```' ) || null );
  898. settings.match = ( settings.match?.trim().replace( /`ˋ`/g, '```' ) || null );
  899. sendMsg( {
  900. type: 'getMember',
  901. member: userSettings.user.id,
  902. guild: guild,
  903. newchannel: settings.channel
  904. } ).then( response => {
  905. if ( !response ) {
  906. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  907. userSettings.guilds.isMember.delete(guild);
  908. return res(`/guild/${guild}`, 'savefail');
  909. }
  910. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  911. userSettings.guilds.isMember.delete(guild);
  912. return res('/', 'savefail');
  913. }
  914. if ( settings.channel && ( response.message === 'noChannel' || !( hasPerm(response.botPermissionsNew, 'VIEW_CHANNEL', 'SEND_MESSAGES') && hasPerm(response.userPermissions, 'VIEW_CHANNEL') ) ) ) {
  915. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  916. }
  917. return db.connect().then( client => {
  918. return client.query( 'SELECT logchannel, flags, onsuccess, onmatch FROM verifynotice WHERE guild = $1', [guild] ).then( ({rows:[row]}) => {
  919. var flags = ( settings.flag_private ? 1 << 0 : 0 ) + ( settings.flag_logall ? 1 << 1 : 0 );
  920. if ( !row ) {
  921. if ( !( settings.channel || flags || settings.success || settings.match ) ) {
  922. return res(`/guild/${guild}/verification/${type}`, 'save');
  923. }
  924. return client.query( 'INSERT INTO verifynotice(guild, logchannel, flags, onsuccess, onmatch) VALUES($1, $2, $3, $4, $5)', [guild, settings.channel, flags, settings.success, settings.match] ).then( () => {
  925. console.log( `- Dashboard: Verification notices successfully added: ${guild}` );
  926. res(`/guild/${guild}/verification/${type}`, 'save');
  927. return client.query( 'SELECT lang FROM discord WHERE guild = $1 AND channel IS NULL', [guild] ).then( ({rows:[channel]}) => {
  928. var lang = new Lang(channel?.lang);
  929. var text = lang.get('verification.dashboard.added_notice', `<@${userSettings.user.id}>`) + '\n';
  930. if ( settings.channel ) text += `${lang.get('verification.logging')} <#${settings.channel}>\n`;
  931. if ( settings.flag_logall ) text += `${lang.get('verification.flag_logall')} *\`${lang.get('verification.enabled')}\`*\n`;
  932. if ( settings.flag_private ) text += `${lang.get('verification.flag_private')} *\`${lang.get('verification.enabled')}\`*\n`;
  933. if ( settings.success ) text += `${lang.get('verification.success')} \`\`\`md\n${settings.success.replace( /```/g, '`ˋ`' )}\n\`\`\``;
  934. if ( settings.match ) text += `${lang.get('verification.match')} \`\`\`md\n${settings.match.replace( /```/g, '`ˋ`' )}\n\`\`\``;
  935. text += `<${new URL(`/guild/${guild}/verification/${type}`, process.env.dashboard).href}>`;
  936. if ( settings.success?.includes( '](' ) || settings.match?.includes( '](' ) ) {
  937. text += '\n\n' + lang.get('verification.notice_embed');
  938. }
  939. sendMsg( {
  940. type: 'notifyGuild', guild, text
  941. } ).catch( error => {
  942. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  943. } );
  944. }, dberror => {
  945. console.log( '- Dashboard: Error while notifying the guild: ' + dberror );
  946. } );
  947. }, dberror => {
  948. console.log( '- Dashboard: Error while adding the verification notices: ' + dberror );
  949. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  950. } );
  951. }
  952. if ( settings.channel === row.logchannel && flags === row.flags && settings.success === row.onsuccess && settings.match === row.onmatch ) {
  953. return res(`/guild/${guild}/verification/${type}`, 'save');
  954. }
  955. return client.query( 'UPDATE verifynotice SET logchannel = $1, flags = $2, onsuccess = $3, onmatch = $4 WHERE guild = $5', [settings.channel, flags, settings.success, settings.match, guild] ).then( () => {
  956. console.log( `- Dashboard: Verification notices successfully updated: ${guild}` );
  957. res(`/guild/${guild}/verification/${type}`, 'save');
  958. return client.query( 'SELECT lang FROM discord WHERE guild = $1 AND channel IS NULL', [guild] ).then( ({rows:[channel]}) => {
  959. var lang = new Lang(channel?.lang);
  960. var text = lang.get('verification.dashboard.updated_notice', `<@${userSettings.user.id}>`) + '\n';
  961. if ( settings.channel !== row.logchannel ) {
  962. text += lang.get('verification.logging') + ' ~~' + ( row.logchannel ? `<#${row.logchannel}>` : `*\`${lang.get('verification.disabled')}\`*` ) + '~~ → ' + ( settings.channel ? `<#${settings.channel}>` : `*\`${lang.get('verification.disabled')}\`*` ) + '\n';
  963. }
  964. if ( ( (flags & 1 << 1) === 1 << 1 ) !== ( (row.flags & 1 << 1) === 1 << 1 ) ) {
  965. text += lang.get('verification.flag_logall') + ' ~~*`' + lang.get('verification.' + ( (row.flags & 1 << 1) === 1 << 1 ? 'enabled' : 'disabled')) + '`*~~ → *`' + lang.get('verification.' + ( settings.flag_logall ? 'enabled' : 'disabled')) + '`*\n';
  966. }
  967. if ( ( (flags & 1 << 0) === 1 << 0 ) !== ( (row.flags & 1 << 0) === 1 << 0 ) ) {
  968. text += lang.get('verification.flag_private') + ' ~~*`' + lang.get('verification.' + ( (row.flags & 1 << 0) === 1 << 0 ? 'enabled' : 'disabled')) + '`*~~ → *`' + lang.get('verification.' + ( settings.flag_private ? 'enabled' : 'disabled')) + '`*\n';
  969. }
  970. if ( settings.success !== row.onsuccess ) {
  971. text += lang.get('verification.success') + ' ' + ( row.onsuccess ? '~~```md\n' + row.onsuccess.replace( /\\/g, '\\$&' ).replace( /```/g, '`ˋ`' ) + '\n```~~' : `~~*\`${lang.get('verification.disabled')}\`*~~ → ` ) + ( settings.success ? '```md\n' + settings.success.replace( /\\/g, '\\$&' ).replace( /```/g, '`ˋ`' ) + '\n```' : ` → *\`${lang.get('verification.disabled')}\`*\n` );
  972. }
  973. if ( settings.match !== row.onmatch ) {
  974. text += lang.get('verification.match') + ' ' + ( row.onmatch ? '~~```md\n' + row.onmatch.replace( /\\/g, '\\$&' ).replace( /```/g, '`ˋ`' ) + '\n```~~' : `~~*\`${lang.get('verification.disabled')}\`*~~ → ` ) + ( settings.match ? '```md\n' + settings.match.replace( /\\/g, '\\$&' ).replace( /```/g, '`ˋ`' ) + '\n```' : ` → *\`${lang.get('verification.disabled')}\`*\n` );
  975. }
  976. text += `<${new URL(`/guild/${guild}/verification/${type}`, process.env.dashboard).href}>`;
  977. if ( settings.success?.includes( '](' ) || settings.match?.includes( '](' ) ) {
  978. text += '\n\n' + lang.get('verification.notice_embed');
  979. }
  980. sendMsg( {
  981. type: 'notifyGuild', guild, text
  982. } ).catch( error => {
  983. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  984. } );
  985. }, dberror => {
  986. console.log( '- Dashboard: Error while notifying the guild: ' + dberror );
  987. } );
  988. }, dberror => {
  989. console.log( '- Dashboard: Error while updating the verification notices: ' + dberror );
  990. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  991. } );
  992. }, dberror => {
  993. console.log( '- Dashboard: Error while getting the current verification notices: ' + dberror );
  994. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  995. } ).finally( () => {
  996. client.release();
  997. } );
  998. }, dberror => {
  999. console.log( '- Error while connecting to the database client: ' + dberror );
  1000. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  1001. } );
  1002. }, error => {
  1003. console.log( '- Dashboard: Error while getting the member: ' + error );
  1004. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  1005. } );
  1006. }
  1007. export {
  1008. dashboard_verification as get,
  1009. update_verification as post
  1010. };