1
0

verification.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. const {limit: {verification: verificationLimit}, usergroups} = require('../util/default.json');
  2. const Lang = require('../util/i18n.js');
  3. const {got, db, sendMsg, createNotice, escapeText, hasPerm} = require('./util.js');
  4. const fieldset = {
  5. channel: '<label for="wb-settings-channel">Channel:</label>'
  6. + '<select id="wb-settings-channel" name="channel" required></select>'
  7. + '<button type="button" id="wb-settings-channel-more" class="addmore">Add more</button>',
  8. role: '<label for="wb-settings-role">Role:</label>'
  9. + '<select id="wb-settings-role" name="role" required></select>'
  10. + '<button type="button" id="wb-settings-role-more" class="addmore">Add more</button>',
  11. usergroup: '<label for="wb-settings-usergroup">Wiki user group:</label>'
  12. + '<input type="text" id="wb-settings-usergroup" name="usergroup" list="wb-settings-usergroup-list" autocomplete="on">'
  13. + '<datalist id="wb-settings-usergroup-list">'
  14. + usergroups.sorted.filter( group => group !== '__CUSTOM__' ).map( group => {
  15. return `<option value="${group}"></option>`
  16. } ).join('')
  17. + usergroups.global.filter( group => group !== '__CUSTOM__' ).map( group => {
  18. return `<option value="${group}"></option>`
  19. } ).join('')
  20. + '</datalist>'
  21. + '<div id="wb-settings-usergroup-multiple">'
  22. + '<label for="wb-settings-usergroup-and">Require all user groups:</label>'
  23. + '<input type="checkbox" id="wb-settings-usergroup-and" name="usergroup_and">'
  24. + '</div>',
  25. editcount: '<label for="wb-settings-editcount">Minimal edit count:</label>'
  26. + '<input type="number" id="wb-settings-editcount" name="editcount" min="0" max="1000000" required>',
  27. postcount: '<div id="wb-settings-postcount-input">'
  28. + '<label for="wb-settings-postcount">Minimal post count:</label>'
  29. + '<input type="number" id="wb-settings-postcount" name="postcount" min="0" max="1000000" required>'
  30. + '</div><div class="wb-settings-postcount">'
  31. + '<span>Only Fandom wikis:</span>'
  32. + '<input type="radio" id="wb-settings-postcount-and" name="posteditcount" value="and" required>'
  33. + '<label for="wb-settings-postcount-and">Require both edit and post count.</label>'
  34. + '</div><div class="wb-settings-postcount">'
  35. + '<input type="radio" id="wb-settings-postcount-or" name="posteditcount" value="or" required>'
  36. + '<label for="wb-settings-postcount-or">Require either edit or post count.</label>'
  37. + '</div><div class="wb-settings-postcount">'
  38. + '<input type="radio" id="wb-settings-postcount-both" name="posteditcount" value="both" required>'
  39. + '<label for="wb-settings-postcount-both">Require combined edit and post count.</label>'
  40. + '</div>',
  41. accountage: '<label for="wb-settings-accountage">Account age (in days):</label>'
  42. + '<input type="number" id="wb-settings-accountage" name="accountage" min="0" max="1000000" required>',
  43. rename: '<label for="wb-settings-rename">Rename users:</label>'
  44. + '<input type="checkbox" id="wb-settings-rename" name="rename">',
  45. save: '<input type="submit" id="wb-settings-save" name="save_settings">',
  46. delete: '<input type="submit" id="wb-settings-delete" name="delete_settings" formnovalidate>'
  47. };
  48. /**
  49. * Create a settings form
  50. * @param {import('cheerio')} $ - The response body
  51. * @param {String} header - The form header
  52. * @param {import('./i18n.js')} dashboardLang - The user language
  53. * @param {Object} settings - The current settings
  54. * @param {String} settings.channel
  55. * @param {String} settings.role
  56. * @param {String} settings.usergroup
  57. * @param {Number} settings.editcount
  58. * @param {Number} settings.postcount
  59. * @param {Number} settings.accountage
  60. * @param {Boolean} settings.rename
  61. * @param {String} [settings.defaultrole]
  62. * @param {import('./util.js').Channel[]} guildChannels - The guild channels
  63. * @param {import('./util.js').Role[]} guildRoles - The guild roles
  64. */
  65. function createForm($, header, dashboardLang, settings, guildChannels, guildRoles) {
  66. var readonly = ( process.env.READONLY ? true : false );
  67. var fields = [];
  68. let channel = $('<div>').append(fieldset.channel);
  69. channel.find('label').text(dashboardLang.get('verification.form.channel'));
  70. let curCat = null;
  71. channel.find('#wb-settings-channel').append(
  72. $('<option class="wb-settings-channel-default defaultSelect" hidden>').val('').text(dashboardLang.get('verification.form.select_channel')),
  73. ...guildChannels.filter( guildChannel => {
  74. return ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL') || guildChannel.isCategory || settings.channel.includes( '|' + guildChannel.id + '|' ) );
  75. } ).map( guildChannel => {
  76. if ( guildChannel.isCategory ) {
  77. curCat = $('<optgroup>').attr('label', guildChannel.name);
  78. return curCat;
  79. }
  80. var optionChannel = $(`<option class="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – #${guildChannel.name}`);
  81. if ( !hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL') ) {
  82. optionChannel.addClass('wb-settings-error');
  83. }
  84. if ( !curCat ) return optionChannel;
  85. optionChannel.appendTo(curCat);
  86. } ).filter( catChannel => {
  87. if ( !catChannel ) return false;
  88. if ( catChannel.is('optgroup') && !catChannel.children('option').length ) return false;
  89. return true;
  90. } )
  91. );
  92. if ( settings.channel ) {
  93. let settingsChannels = settings.channel.split('|').filter( guildChannel => guildChannel.length );
  94. channel.find('#wb-settings-channel').append(
  95. ...settingsChannels.filter( guildChannel => {
  96. return !channel.find(`.wb-settings-channel-${guildChannel}`).length;
  97. } ).map( guildChannel => {
  98. return $(`<option class="wb-settings-channel-${guildChannel}">`).val(guildChannel).text(`${guildChannel} – #UNKNOWN`).addClass('wb-settings-error');
  99. } )
  100. );
  101. if ( settingsChannels.length > 1 ) channel.find('#wb-settings-channel').after(
  102. ...settingsChannels.slice(1).map( guildChannel => {
  103. var additionalChannel = channel.find('#wb-settings-channel').clone();
  104. additionalChannel.addClass('wb-settings-additional-select');
  105. additionalChannel.find(`.wb-settings-channel-default`).removeAttr('hidden');
  106. additionalChannel.find(`.wb-settings-channel-${guildChannel}`).attr('selected', '');
  107. return additionalChannel.removeAttr('id').removeAttr('required');
  108. } )
  109. );
  110. channel.find(`#wb-settings-channel .wb-settings-channel-${settingsChannels[0]}`).attr('selected', '');
  111. }
  112. else {
  113. channel.find('.wb-settings-channel-default').attr('selected', '');
  114. channel.find('button.addmore').attr('hidden', '');
  115. }
  116. fields.push(channel);
  117. let role = $('<div>').append(fieldset.role);
  118. role.find('label').text(dashboardLang.get('verification.form.role'));
  119. role.find('#wb-settings-role').append(
  120. $('<option class="wb-settings-role-default defaultSelect" hidden>').val('').text(dashboardLang.get('verification.form.select_role')),
  121. ...guildRoles.filter( guildRole => {
  122. return guildRole.lower || settings.role.split('|').includes( guildRole.id );
  123. } ).map( guildRole => {
  124. var optionRole = $(`<option class="wb-settings-role-${guildRole.id}">`).val(guildRole.id);
  125. if ( !guildRole.lower ) optionRole.addClass('wb-settings-error');
  126. return optionRole.text(`${guildRole.id} – @${guildRole.name}`);
  127. } )
  128. );
  129. if ( settings.role ) {
  130. let settingsRoles = settings.role.split('|');
  131. role.find('#wb-settings-role').append(
  132. ...settingsRoles.filter( guildRole => {
  133. return !role.find(`.wb-settings-role-${guildRole}`).length;
  134. } ).map( guildRole => {
  135. return $(`<option class="wb-settings-role-${guildRole}">`).val(guildRole).text(`${guildRole} – @UNKNOWN`).addClass('wb-settings-error');
  136. } )
  137. );
  138. if ( settingsRoles.length > 1 ) role.find('#wb-settings-role').after(
  139. ...settingsRoles.slice(1).map( guildRole => {
  140. var additionalRole = role.find('#wb-settings-role').clone();
  141. additionalRole.addClass('wb-settings-additional-select');
  142. additionalRole.find(`.wb-settings-role-default`).removeAttr('hidden');
  143. additionalRole.find(`.wb-settings-role-${guildRole}`).attr('selected', '');
  144. return additionalRole.removeAttr('id').removeAttr('required');
  145. } )
  146. );
  147. role.find(`#wb-settings-role .wb-settings-role-${settingsRoles[0]}`).attr('selected', '');
  148. }
  149. else {
  150. if ( role.find(`.wb-settings-role-${settings.defaultrole}`).length ) {
  151. role.find(`.wb-settings-role-${settings.defaultrole}`).attr('selected', '');
  152. }
  153. else role.find('.wb-settings-role-default').attr('selected', '');
  154. role.find('button.addmore').attr('hidden', '');
  155. }
  156. fields.push(role);
  157. let usergroup = $('<div>').append(fieldset.usergroup);
  158. usergroup.find('label').eq(0).text(dashboardLang.get('verification.form.usergroup'));
  159. usergroup.find('label').eq(1).text(dashboardLang.get('verification.form.usergroup_and'));
  160. if ( settings.usergroup.startsWith( 'AND|' ) ) {
  161. settings.usergroup = settings.usergroup.substring(4);
  162. usergroup.find('#wb-settings-usergroup-and').attr('checked', '');
  163. }
  164. usergroup.find('#wb-settings-usergroup').val(settings.usergroup.split('|').join(', '));
  165. if ( !settings.usergroup.includes( '|' ) ) {
  166. usergroup.find('#wb-settings-usergroup-multiple').attr('style', 'display: none;');
  167. }
  168. fields.push(usergroup);
  169. let editcount = $('<div>').append(fieldset.editcount);
  170. editcount.find('label').text(dashboardLang.get('verification.form.editcount'));
  171. editcount.find('#wb-settings-editcount').val(settings.editcount);
  172. fields.push(editcount);
  173. let postcount = $('<div>').append(fieldset.postcount);
  174. postcount.find('label').eq(0).text(dashboardLang.get('verification.form.postcount'));
  175. postcount.find('span').text(dashboardLang.get('verification.form.postcount_fandom'));
  176. postcount.find('label').eq(1).text(dashboardLang.get('verification.form.postcount_and'));
  177. postcount.find('label').eq(2).text(dashboardLang.get('verification.form.postcount_or'));
  178. postcount.find('label').eq(3).text(dashboardLang.get('verification.form.postcount_both'));
  179. postcount.find('#wb-settings-postcount').val(Math.abs(settings.postcount));
  180. if ( settings.postcount === null ) {
  181. postcount.find('#wb-settings-postcount-both').attr('checked', '');
  182. postcount.find('#wb-settings-postcount-input').attr('style', 'display: none;');
  183. }
  184. else if ( settings.postcount < 0 ) postcount.find('#wb-settings-postcount-or').attr('checked', '');
  185. else postcount.find('#wb-settings-postcount-and').attr('checked', '');
  186. fields.push(postcount);
  187. let accountage = $('<div>').append(fieldset.accountage);
  188. accountage.find('label').text(dashboardLang.get('verification.form.accountage'));
  189. accountage.find('#wb-settings-accountage').val(settings.accountage);
  190. fields.push(accountage);
  191. if ( settings.rename || guildChannels.some( guildChannel => {
  192. return hasPerm(guildChannel.botPermissions, 'MANAGE_NICKNAMES');
  193. } ) ) {
  194. let rename = $('<div>').append(fieldset.rename);
  195. rename.find('label').text(dashboardLang.get('verification.form.rename'));
  196. if ( settings.rename ) rename.find('#wb-settings-rename').attr('checked', '');
  197. fields.push(rename);
  198. }
  199. fields.push($(fieldset.save).val(dashboardLang.get('general.save')));
  200. if ( settings.channel ) {
  201. fields.push($(fieldset.delete).val(dashboardLang.get('general.delete')).attr('onclick', `return confirm('${dashboardLang.get('verification.form.confirm').replace( /'/g, '\\$&' )}');`));
  202. }
  203. var form = $('<fieldset>').append(...fields);
  204. if ( readonly ) {
  205. form.find('input').attr('readonly', '');
  206. form.find('input[type="checkbox"], option, optgroup').attr('disabled', '');
  207. form.find('input[type="submit"], button.addmore').remove();
  208. }
  209. form.find('button.addmore').text(dashboardLang.get('verification.form.more'));
  210. return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  211. $('<h2>').text(header),
  212. form
  213. );
  214. }
  215. /**
  216. * Let a user change verifications
  217. * @param {import('http').ServerResponse} res - The server response
  218. * @param {import('cheerio')} $ - The response body
  219. * @param {import('./util.js').Guild} guild - The current guild
  220. * @param {String[]} args - The url parts
  221. * @param {import('./i18n.js')} dashboardLang - The user language
  222. */
  223. function dashboard_verification(res, $, guild, args, dashboardLang) {
  224. db.all( '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 = ? AND discord.channel IS NULL ORDER BY configid ASC', [guild.id], function(dberror, rows) {
  225. if ( dberror ) {
  226. console.log( '- Dashboard: Error while getting the verifications: ' + dberror );
  227. createNotice($, 'error', dashboardLang);
  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 ( rows.length === 0 ) {
  237. createNotice($, 'nosettings', dashboardLang, [guild.id]);
  238. $('#text .description').html(dashboardLang.get('verification.explanation'));
  239. $('#text code.prefix').prepend(escapeText(process.env.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. if ( !hasPerm(guild.botPermissions, 'MANAGE_ROLES') ) {
  247. createNotice($, 'missingperm', dashboardLang, ['Manage Roles']);
  248. $('#text .description').html(dashboardLang.get('verification.explanation'));
  249. $('#text code.prefix').prepend(escapeText(rows[0].prefix));
  250. $('.channel#verification').addClass('selected');
  251. let body = $.html();
  252. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  253. res.write( body );
  254. return res.end();
  255. }
  256. var wiki = rows[0].wiki;
  257. var defaultrole = rows[0].defaultrole;
  258. var prefix = rows[0].prefix;
  259. if ( rows.length === 1 && rows[0].configid === null ) rows.pop();
  260. $('<p>').html(dashboardLang.get('verification.desc', true, $('<code>').text(guild.name))).appendTo('#text .description');
  261. let suffix = ( args[0] === 'owner' ? '?owner=true' : '' );
  262. $('#channellist #verification').after(
  263. ...rows.map( row => {
  264. return $('<a class="channel">').attr('id', `channel-${row.configid}`).append(
  265. $('<img>').attr('src', '/src/channel.svg'),
  266. $('<div>').text(`${row.configid} - ${( guild.roles.find( role => {
  267. return role.id === row.role.split('|')[0];
  268. } )?.name || guild.channels.find( channel => {
  269. return channel.id === row.channel.split('|')[1];
  270. } )?.name || row.usergroup.split('|')[( row.usergroup.startsWith('AND|') ? 1 : 0 )] )}`)
  271. ).attr('href', `/guild/${guild.id}/verification/${row.configid}${suffix}`);
  272. } ),
  273. ( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ? '' :
  274. $('<a class="channel" id="channel-new">').append(
  275. $('<img>').attr('src', '/src/channel.svg'),
  276. $('<div>').text(dashboardLang.get('verification.new'))
  277. ).attr('href', `/guild/${guild.id}/verification/new${suffix}`) )
  278. );
  279. if ( args[4] === 'new' && !( process.env.READONLY || rows.length >= verificationLimit[( guild.patreon ? 'patreon' : 'default' )] ) ) {
  280. $('.channel#channel-new').addClass('selected');
  281. createForm($, dashboardLang.get('verification.form.new'), dashboardLang, {
  282. channel: '', role: '', usergroup: 'user',
  283. editcount: 0, postcount: 0, accountage: 0,
  284. rename: false, defaultrole
  285. }, guild.channels, guild.roles).attr('action', `/guild/${guild.id}/verification/new`).appendTo('#text');
  286. }
  287. else if ( rows.some( row => row.configid.toString() === args[4] ) ) {
  288. let row = rows.find( row => row.configid.toString() === args[4] );
  289. $(`.channel#channel-${row.configid}`).addClass('selected');
  290. 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');
  291. }
  292. else {
  293. $('.channel#verification').addClass('selected');
  294. $('#text .description').html(dashboardLang.get('verification.explanation'));
  295. $('#text code.prefix').prepend(escapeText(prefix));
  296. }
  297. let body = $.html();
  298. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  299. res.write( body );
  300. return res.end();
  301. } );
  302. }
  303. /**
  304. * Change verifications
  305. * @param {Function} res - The server response
  306. * @param {import('./util.js').Settings} userSettings - The settings of the user
  307. * @param {String} guild - The id of the guild
  308. * @param {String|Number} type - The setting to change
  309. * @param {Object} settings - The new settings
  310. * @param {String[]} settings.channel
  311. * @param {String[]} settings.role
  312. * @param {String[]} [settings.usergroup]
  313. * @param {String} [settings.usergroup_and]
  314. * @param {Number} settings.editcount
  315. * @param {Number} [settings.postcount]
  316. * @param {String} settings.posteditcount
  317. * @param {Number} settings.accountage
  318. * @param {String} [settings.rename]
  319. * @param {String} [settings.save_settings]
  320. * @param {String} [settings.delete_settings]
  321. */
  322. function update_verification(res, userSettings, guild, type, settings) {
  323. if ( type === 'default' ) {
  324. return res(`/guild/${guild}/verification`, 'savefail');
  325. }
  326. if ( !settings.save_settings === !settings.delete_settings ) {
  327. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  328. }
  329. if ( settings.save_settings ) {
  330. if ( !/^[\d|]+ [\d|]+$/.test(`${settings.channel} ${settings.role}`) ) {
  331. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  332. }
  333. if ( !/^\d+ \d+$/.test(`${settings.editcount} ${settings.accountage}`) ) {
  334. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  335. }
  336. if ( !( ['and','or','both'].includes( settings.posteditcount ) && ( /^\d+$/.test(settings.postcount) || settings.posteditcount === 'both' ) ) ) {
  337. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  338. }
  339. settings.channel = settings.channel.split('|').filter( (channel, i, self) => {
  340. return ( channel.length && self.indexOf(channel) === i );
  341. } );
  342. if ( !settings.channel.length || settings.channel.length > 10 ) {
  343. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  344. }
  345. settings.role = settings.role.split('|').filter( (role, i, self) => {
  346. return ( role.length && self.indexOf(role) === i );
  347. } );
  348. if ( !settings.role.length || settings.role.length > 10 ) {
  349. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  350. }
  351. if ( !settings.usergroup ) settings.usergroup = 'user';
  352. settings.usergroup = settings.usergroup.replace( /_/g, ' ' ).trim().toLowerCase();
  353. settings.usergroup = settings.usergroup.split(/\s*[,|]\s*/).map( usergroup => {
  354. if ( usergroup === '*' ) return 'user';
  355. return usergroup.replace( / /g, '_' );
  356. } ).filter( (usergroup, i, self) => {
  357. return ( usergroup.length && self.indexOf(usergroup) === i );
  358. } );
  359. if ( !settings.usergroup.length ) settings.usergroup.push('user');
  360. if ( settings.usergroup.length > 10 || settings.usergroup.some( usergroup => {
  361. return ( usergroup.length > 100 );
  362. } ) ) return res(`/guild/${guild}/verification/${type}`, 'invalidusergroup');
  363. settings.editcount = parseInt(settings.editcount, 10);
  364. settings.accountage = parseInt(settings.accountage, 10);
  365. if ( settings.editcount > 1000000 || settings.accountage > 1000000 ) {
  366. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  367. }
  368. if ( settings.posteditcount === 'both' ) settings.postcount = null;
  369. else settings.postcount = parseInt(settings.postcount, 10);
  370. if ( settings.posteditcount === 'or' ) settings.postcount = settings.postcount * -1;
  371. if ( settings.postcount > 1000000 || settings.postcount < -1000000 ) {
  372. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  373. }
  374. if ( type === 'new' ) {
  375. let curGuild = userSettings.guilds.isMember.get(guild);
  376. if ( settings.channel.some( channel => {
  377. return !curGuild.channels.some( guildChannel => {
  378. return ( guildChannel.id === channel && !guildChannel.isCategory );
  379. } );
  380. } ) || settings.role.some( role => {
  381. return !curGuild.roles.some( guildRole => {
  382. return ( guildRole.id === role && guildRole.lower );
  383. } );
  384. } ) ) return res(`/guild/${guild}/verification/new`, 'savefail');
  385. }
  386. }
  387. if ( settings.delete_settings && type === 'new' ) {
  388. return res(`/guild/${guild}/verification/new`, 'savefail');
  389. }
  390. if ( type !== 'new' ) type = parseInt(type, 10);
  391. sendMsg( {
  392. type: 'getMember',
  393. member: userSettings.user.id,
  394. guild: guild
  395. } ).then( response => {
  396. if ( !response ) {
  397. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  398. userSettings.guilds.isMember.delete(guild);
  399. return res(`/guild/${guild}`, 'savefail');
  400. }
  401. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  402. userSettings.guilds.isMember.delete(guild);
  403. return res('/', 'savefail');
  404. }
  405. if ( settings.delete_settings ) return db.get( 'SELECT lang, verification.channel, verification.role, editcount, postcount, usergroup, accountage, rename FROM discord LEFT JOIN verification ON discord.guild = verification.guild AND configid = ? WHERE discord.guild = ? AND discord.channel IS NULL', [type, guild], function(dberror, row) {
  406. if ( !dberror && !row?.channel ) return res(`/guild/${guild}/verification`, 'save');
  407. db.run( 'DELETE FROM verification WHERE guild = ? AND configid = ?', [guild, type], function (delerror) {
  408. if ( delerror ) {
  409. console.log( '- Dashboard: Error while removing the verification: ' + delerror );
  410. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  411. }
  412. console.log( `- Dashboard: Verification successfully removed: ${guild}#${type}` );
  413. res(`/guild/${guild}/verification`, 'save');
  414. if ( dberror ) {
  415. console.log( '- Dashboard: Error while notifying the guild: ' + dberror );
  416. return;
  417. }
  418. var lang = new Lang(row.lang);
  419. var text = lang.get('verification.dashboard.removed', `<@${userSettings.user.id}>`, type);
  420. if ( row ) {
  421. text += '\n' + lang.get('verification.channel') + ' <#' + row.channel.split('|').filter( channel => channel.length ).join('>, <#') + '>';
  422. text += '\n' + lang.get('verification.role') + ' <@&' + row.role.split('|').join('>, <@&') + '>';
  423. if ( row.postcount === null ) {
  424. text += '\n' + lang.get('verification.posteditcount') + ' `' + row.editcount + '`';
  425. }
  426. else {
  427. text += '\n' + lang.get('verification.editcount') + ' `' + row.editcount + '`';
  428. text += '\n' + lang.get('verification.postcount') + ' `' + Math.abs(row.postcount) + '`';
  429. if ( row.postcount < 0 ) text += ' ' + lang.get('verification.postcount_or');
  430. }
  431. 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') + ' `') ) + '`';
  432. text += '\n' + lang.get('verification.accountage') + ' `' + row.accountage + '` ' + lang.get('verification.indays');
  433. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled')) + '`*';
  434. }
  435. text += `\n<${new URL(`/guild/${guild}/verification`, process.env.dashboard).href}>`;
  436. sendMsg( {
  437. type: 'notifyGuild', guild, text
  438. } ).catch( error => {
  439. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  440. } );
  441. } );
  442. } );
  443. if ( !hasPerm(response.botPermissions, 'MANAGE_ROLES') ) {
  444. return res(`/guild/${guild}/verification`, 'savefail');
  445. }
  446. if ( type === 'new' ) return db.get( 'SELECT wiki, lang, GROUP_CONCAT(configid) count FROM discord LEFT JOIN verification ON discord.guild = verification.guild WHERE discord.guild = ? AND discord.channel IS NULL', [guild], function(curerror, row) {
  447. if ( curerror ) {
  448. console.log( '- Dashboard: Error while checking for verifications: ' + curerror );
  449. return res(`/guild/${guild}/verification/new`, 'savefail');
  450. }
  451. if ( !row ) return res(`/guild/${guild}/verification`, 'savefail');
  452. if ( row.count === null ) row.count = [];
  453. else row.count = row.count.split(',').map( configid => parseInt(configid, 10) );
  454. if ( row.count.length >= verificationLimit[( response.patreon ? 'patreon' : 'default' )] ) {
  455. return res(`/guild/${guild}/verification`, 'savefail');
  456. }
  457. return got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  458. var body = gresponse.body;
  459. if ( gresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages ) {
  460. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  461. return;
  462. }
  463. var groups = body.query.allmessages.filter( group => {
  464. if ( group.name === 'group-all' ) return false;
  465. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  466. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  467. return true;
  468. } ).map( group => {
  469. return {
  470. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  471. content: group['*'].replace( / /g, '_' ).toLowerCase()
  472. };
  473. } );
  474. settings.usergroup = settings.usergroup.map( usergroup => {
  475. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  476. if ( groups.some( group => group.content === usergroup ) ) {
  477. return groups.find( group => group.content === usergroup ).name;
  478. }
  479. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  480. if ( usergroup === '*' ) return 'user';
  481. return usergroup;
  482. } );
  483. }, error => {
  484. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  485. } ).finally( () => {
  486. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  487. var configid = 1;
  488. for ( let i of row.count ) {
  489. if ( configid === i ) configid++;
  490. else break;
  491. }
  492. db.run( 'INSERT INTO verification(guild, configid, channel, role, editcount, postcount, usergroup, accountage, rename) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)', [guild, configid, '|' + settings.channel.join('|') + '|', settings.role.join('|'), settings.editcount, settings.postcount, settings.usergroup.join('|'), settings.accountage, ( settings.rename ? 1 : 0 )], function (dberror) {
  493. if ( dberror ) {
  494. console.log( '- Dashboard: Error while adding the verification: ' + dberror );
  495. return res(`/guild/${guild}/verification/new`, 'savefail');
  496. }
  497. console.log( `- Dashboard: Verification successfully added: ${guild}#${configid}` );
  498. res(`/guild/${guild}/verification/${configid}`, 'save');
  499. var lang = new Lang(row.lang);
  500. var text = lang.get('verification.dashboard.added', `<@${userSettings.user.id}>`, configid);
  501. text += '\n' + lang.get('verification.channel') + ' <#' + settings.channel.join('>, <#') + '>';
  502. text += '\n' + lang.get('verification.role') + ' <@&' + settings.role.join('>, <@&') + '>';
  503. if ( settings.postcount === null ) {
  504. text += '\n' + lang.get('verification.posteditcount') + ' `' + settings.editcount + '`';
  505. }
  506. else {
  507. text += '\n' + lang.get('verification.editcount') + ' `' + settings.editcount + '`';
  508. text += '\n' + lang.get('verification.postcount') + ' `' + Math.abs(settings.postcount) + '`';
  509. if ( settings.postcount < 0 ) text += ' ' + lang.get('verification.postcount_or');
  510. }
  511. 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') + ' `') ) + '`';
  512. text += '\n' + lang.get('verification.accountage') + ' `' + settings.accountage + '` ' + lang.get('verification.indays');
  513. text += '\n' + lang.get('verification.rename') + ' *`' + lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled')) + '`*';
  514. text += `\n<${new URL(`/guild/${guild}/verification/${configid}`, process.env.dashboard).href}>`;
  515. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  516. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  517. }
  518. if ( settings.role.some( role => {
  519. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  520. return ( guildRole.id === role && guildRole.lower );
  521. } );
  522. } ) ) {
  523. text += '\n';
  524. settings.role.forEach( role => {
  525. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  526. return ( guildRole.id === role );
  527. } ) ) {
  528. text += '\n' + lang.get('verification.role_deleted', `<@&${role}>`);
  529. }
  530. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  531. return ( guildRole.id === role && !guildRole.lower );
  532. } ) ) {
  533. text += '\n' + lang.get('verification.role_too_high', `<@&${role}>`, `<@${process.env.bot}>`);
  534. }
  535. } );
  536. }
  537. sendMsg( {
  538. type: 'notifyGuild', guild, text
  539. } ).catch( error => {
  540. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  541. } );
  542. } );
  543. } );
  544. } );
  545. return db.get( '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 = ? WHERE discord.guild = ? AND discord.channel IS NULL', [type, guild], function(curerror, row) {
  546. if ( curerror ) {
  547. console.log( '- Dashboard: Error while checking for verifications: ' + curerror );
  548. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  549. }
  550. if ( !row?.channel ) return res(`/guild/${guild}/verification`, 'savefail');
  551. row.channel = row.channel.split('|').filter( channel => channel.length );
  552. var newChannel = settings.channel.filter( channel => !row.channel.includes( channel ) );
  553. row.role = row.role.split('|');
  554. var newRole = settings.role.filter( role => !row.role.includes( role ) );
  555. row.usergroup = row.usergroup.split('|');
  556. var newUsergroup = settings.usergroup.filter( group => !row.usergroup.includes( group ) );
  557. if ( newChannel.length || newRole.length ) {
  558. let curGuild = userSettings.guilds.isMember.get(guild);
  559. if ( newChannel.some( channel => {
  560. return !curGuild.channels.some( guildChannel => {
  561. return ( guildChannel.id === channel && !guildChannel.isCategory );
  562. } );
  563. } ) || newRole.some( role => {
  564. return !curGuild.roles.some( guildRole => {
  565. return ( guildRole.id === role && guildRole.lower );
  566. } );
  567. } ) ) return res(`/guild/${guild}/verification/${type}`, 'savefail');
  568. }
  569. ( newUsergroup.length ? got.get( row.wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json' ).then( gresponse => {
  570. var body = gresponse.body;
  571. if ( gresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages ) {
  572. console.log( '- Dashboard: ' + gresponse.statusCode + ': Error while getting the usergroups: ' + body?.error?.info );
  573. return;
  574. }
  575. var groups = body.query.allmessages.filter( group => {
  576. if ( group.name === 'group-all' ) return false;
  577. if ( group.name === 'group-membership-link-with-expiry' ) return false;
  578. if ( group.name.endsWith( '.css' ) || group.name.endsWith( '.js' ) ) return false;
  579. return true;
  580. } ).map( group => {
  581. return {
  582. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  583. content: group['*'].replace( / /g, '_' ).toLowerCase()
  584. };
  585. } );
  586. settings.usergroup = settings.usergroup.map( usergroup => {
  587. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  588. if ( groups.some( group => group.content === usergroup ) ) {
  589. return groups.find( group => group.content === usergroup ).name;
  590. }
  591. if ( /^admins?$/.test(usergroup) ) return 'sysop';
  592. if ( usergroup === '*' ) return 'user';
  593. return usergroup;
  594. } );
  595. }, error => {
  596. console.log( '- Dashboard: Error while getting the usergroups: ' + error );
  597. } ) : Promise.resolve() ).finally( () => {
  598. if ( settings.usergroup_and ) settings.usergroup.unshift('AND');
  599. var lang = new Lang(row.lang);
  600. var diff = [];
  601. if ( newChannel.length || row.channel.some( channel => {
  602. return !settings.channel.includes( channel );
  603. } ) ) {
  604. diff.push(lang.get('verification.channel') + ` ~~<#${row.channel.join('>, <#')}>~~ → <#${settings.channel.join('>, <#')}>`);
  605. }
  606. if ( newRole.length || row.role.some( role => {
  607. return !settings.role.includes( role );
  608. } ) ) {
  609. diff.push(lang.get('verification.role') + ` ~~<@&${row.role.join('>, <@&')}>~~ → <@&${settings.role.join('>, <@&')}>`);
  610. }
  611. if ( row.postcount !== settings.postcount && ( row.postcount === null || settings.postcount === null ) ) {
  612. if ( row.postcount === null ) {
  613. diff.push('~~' + lang.get('verification.posteditcount') + ` \`${row.editcount}\`~~`);
  614. diff.push('→ ' + lang.get('verification.editcount') + ` \`${settings.editcount}\``);
  615. diff.push('→ ' + lang.get('verification.postcount') + ` \`${Math.abs(settings.postcount)}\`` + ( settings.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ));
  616. }
  617. if ( settings.postcount === null ) {
  618. diff.push('~~' + lang.get('verification.editcount') + ` \`${row.editcount}\`~~`);
  619. diff.push('~~' + lang.get('verification.postcount') + ` \`${Math.abs(row.postcount)}\`` + ( row.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ) + '~~');
  620. diff.push('→ ' + lang.get('verification.posteditcount') + ` \`${settings.editcount}\``);
  621. }
  622. }
  623. else {
  624. if ( row.editcount !== settings.editcount ) {
  625. diff.push(lang.get('verification.editcount') + ` ~~\`${row.editcount}\`~~ → \`${settings.editcount}\``);
  626. }
  627. if ( row.postcount !== settings.postcount ) {
  628. if ( ( row.postcount >= 0 && settings.postcount < 0 ) || ( row.postcount < 0 && settings.postcount >= 0 ) ) {
  629. diff.push('~~' + lang.get('verification.postcount') + ` \`${Math.abs(row.postcount)}\`` + ( row.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ) + '~~');
  630. diff.push('→ ' + lang.get('verification.postcount') + ` \`${Math.abs(settings.postcount)}\`` + ( settings.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ));
  631. }
  632. else diff.push(lang.get('verification.postcount') + ` ~~\`${Math.abs(row.postcount)}\`~~ → \`${Math.abs(settings.postcount)}\`` + ( settings.postcount < 0 ? ' ' + lang.get('verification.postcount_or') : '' ));
  633. }
  634. }
  635. if ( newUsergroup.length || row.usergroup.some( usergroup => {
  636. return !settings.usergroup.includes( usergroup );
  637. } ) ) {
  638. 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') + ' `') ) + '`');
  639. }
  640. if ( row.accountage !== settings.accountage ) {
  641. diff.push(lang.get('verification.accountage') + ` ~~\`${row.accountage}\`~~ → \`${settings.accountage}\``);
  642. }
  643. if ( row.rename !== ( settings.rename ? 1 : 0 ) ) {
  644. diff.push(lang.get('verification.rename') + ` ~~*\`${lang.get('verification.' + ( row.rename ? 'enabled' : 'disabled'))}\`*~~ → *\`${lang.get('verification.' + ( settings.rename ? 'enabled' : 'disabled'))}\`*`);
  645. }
  646. if ( !diff.length ) return res(`/guild/${guild}/verification/${type}`, 'save');
  647. db.run( 'UPDATE verification SET channel = ?, role = ?, editcount = ?, postcount = ?, usergroup = ?, accountage = ?, rename = ? WHERE guild = ? AND configid = ?', ['|' + settings.channel.join('|') + '|', settings.role.join('|'), settings.editcount, settings.postcount, settings.usergroup.join('|'), settings.accountage, ( settings.rename ? 1 : 0 ), guild, type], function (dberror) {
  648. if ( dberror ) {
  649. console.log( '- Dashboard: Error while updating the verification: ' + dberror );
  650. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  651. }
  652. console.log( `- Dashboard: Verification successfully updated: ${guild}#${type}` );
  653. res(`/guild/${guild}/verification/${type}`, 'save');
  654. var text = lang.get('verification.dashboard.updated', `<@${userSettings.user.id}>`, type);
  655. text += '\n' + diff.join('\n');
  656. text += `\n<${new URL(`/guild/${guild}/verification/${type}`, process.env.dashboard).href}>`;
  657. if ( settings.rename && !hasPerm(response.botPermissions, 'MANAGE_NICKNAMES') ) {
  658. text += '\n\n' + lang.get('verification.rename_no_permission', `<@${process.env.bot}>`);
  659. }
  660. if ( settings.role.some( role => {
  661. return !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  662. return ( guildRole.id === role && guildRole.lower );
  663. } );
  664. } ) ) {
  665. text += '\n';
  666. settings.role.forEach( role => {
  667. if ( !userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  668. return ( guildRole.id === role );
  669. } ) ) {
  670. text += '\n' + lang.get('verification.role_deleted', `<@&${role}>`);
  671. }
  672. else if ( userSettings.guilds.isMember.get(guild).roles.some( guildRole => {
  673. return ( guildRole.id === role && !guildRole.lower );
  674. } ) ) {
  675. text += '\n' + lang.get('verification.role_too_high', `<@&${role}>`, `<@${process.env.bot}>`);
  676. }
  677. } );
  678. }
  679. sendMsg( {
  680. type: 'notifyGuild', guild, text
  681. } ).catch( error => {
  682. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  683. } );
  684. } );
  685. } );
  686. } );
  687. }, error => {
  688. console.log( '- Dashboard: Error while getting the member: ' + error );
  689. return res(`/guild/${guild}/verification/${type}`, 'savefail');
  690. } );
  691. }
  692. module.exports = {
  693. get: dashboard_verification,
  694. post: update_verification
  695. };