verification.js 56 KB

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