verification.js 52 KB

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