verification.js 56 KB

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