1
0

settings.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. const cheerio = require('cheerio');
  2. const {defaultSettings} = require('../util/default.json');
  3. const Lang = require('../util/i18n.js');
  4. const allLangs = Lang.allLangs();
  5. const Wiki = require('../util/wiki.js');
  6. const {got, db, sendMsg, createNotice, hasPerm} = require('./util.js');
  7. const fieldset = {
  8. channel: '<label for="wb-settings-channel">Channel:</label>'
  9. + '<select id="wb-settings-channel" name="channel" required></select>',
  10. wiki: '<label for="wb-settings-wiki">Default Wiki:</label>'
  11. + '<input type="url" id="wb-settings-wiki" name="wiki" required autocomplete="url">'
  12. + '<button type="button" id="wb-settings-wiki-check">Check wiki</button>'
  13. + '<div id="wb-settings-wiki-check-notice"></div>',
  14. //+ '<button type="button" id="wb-settings-wiki-search" class="collapsible">Search wiki</button>'
  15. //+ '<fieldset style="display: none;">'
  16. //+ '<legend>Wiki search</legend>'
  17. //+ '</fieldset>',
  18. lang: '<label for="wb-settings-lang">Language:</label>'
  19. + '<select id="wb-settings-lang" name="lang" required autocomplete="language">'
  20. + Object.keys(allLangs.names).map( lang => {
  21. return `<option id="wb-settings-lang-${lang}" value="${lang}">${allLangs.names[lang]}</option>`
  22. } ).join('')
  23. + '</select>'
  24. + '<img id="wb-settings-lang-widget">',
  25. role: '<label for="wb-settings-role">Minimal Role:</label>'
  26. + '<select id="wb-settings-role" name="role"></select>',
  27. prefix: '<label for="wb-settings-prefix">Prefix:</label>'
  28. + '<input type="text" id="wb-settings-prefix" name="prefix" pattern="^\\s*[^\\s`\\\\]{1,100}\\s*$" minlength="1" maxlength="100" required autocomplete="on">'
  29. + '<br>'
  30. + '<label for="wb-settings-prefix-space">Prefix ends with space:</label>'
  31. + '<input type="checkbox" id="wb-settings-prefix-space" name="prefix_space">',
  32. inline: '<label for="wb-settings-inline">Inline commands:</label>'
  33. + '<input type="checkbox" id="wb-settings-inline" name="inline">',
  34. save: '<input type="submit" id="wb-settings-save" name="save_settings">',
  35. delete: '<input type="submit" id="wb-settings-delete" name="delete_settings" formnovalidate>'
  36. };
  37. /**
  38. * Create a settings form
  39. * @param {import('cheerio')} $ - The response body
  40. * @param {String} header - The form header
  41. * @param {import('./i18n.js')} dashboardLang - The user language
  42. * @param {Object} settings - The current settings
  43. * @param {Boolean} settings.patreon
  44. * @param {String} settings.channel
  45. * @param {String} settings.wiki
  46. * @param {String} settings.lang
  47. * @param {String} settings.role
  48. * @param {Boolean} settings.inline
  49. * @param {String} settings.prefix
  50. * @param {import('./util.js').Role[]} guildRoles - The guild roles
  51. * @param {import('./util.js').Channel[]} guildChannels - The guild channels
  52. */
  53. function createForm($, header, dashboardLang, settings, guildRoles, guildChannels = []) {
  54. var readonly = ( process.env.READONLY ? true : false );
  55. if ( settings.channel && guildChannels.length === 1 && guildChannels[0].userPermissions === 0 && guildChannels[0].name === 'UNKNOWN' ) {
  56. readonly = true;
  57. }
  58. var fields = [];
  59. if ( settings.channel ) {
  60. let channel = $('<div>').append(fieldset.channel);
  61. channel.find('label').text(dashboardLang.get('settings.form.channel'));
  62. if ( settings.channel === 'new' ) {
  63. let curCat = null;
  64. channel.find('#wb-settings-channel').append(
  65. $(`<option id="wb-settings-channel-default" selected hidden>`).val('').text(dashboardLang.get('settings.form.select_channel')),
  66. ...guildChannels.filter( guildChannel => {
  67. return ( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL', 'SEND_MESSAGES') || guildChannel.isCategory );
  68. } ).map( guildChannel => {
  69. if ( settings.patreon ) {
  70. var optionChannel = $(`<option id="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – ` + ( guildChannel.isCategory ? '' : '#' ) + guildChannel.name);
  71. if ( guildChannel.isCategory ) {
  72. curCat = true;
  73. optionChannel.addClass('wb-settings-optgroup');
  74. if ( !( hasPerm(guildChannel.userPermissions, 'VIEW_CHANNEL', 'SEND_MESSAGES') && guildChannel.allowedCat ) ) {
  75. optionChannel.attr('disabled', '').val('');
  76. }
  77. }
  78. else if ( curCat === true ) {
  79. optionChannel.prepend('&nbsp; &nbsp; ');
  80. }
  81. return optionChannel;
  82. }
  83. if ( guildChannel.isCategory ) {
  84. curCat = $('<optgroup>').attr('label', guildChannel.name);
  85. return curCat;
  86. }
  87. var optionChannel = $(`<option id="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – #${guildChannel.name}`);
  88. if ( !curCat ) return optionChannel;
  89. optionChannel.appendTo(curCat);
  90. } ).filter( (catChannel, i, guildChannelList) => {
  91. if ( !catChannel ) return false;
  92. if ( catChannel.is('optgroup') && !catChannel.children('option').length ) return false;
  93. if ( catChannel.hasClass('wb-settings-optgroup') && guildChannelList[i + 1]?.hasClass?.('wb-settings-optgroup') ) return !catChannel.attr('disabled');
  94. return true;
  95. } )
  96. );
  97. }
  98. else {
  99. channel.find('#wb-settings-channel').append(
  100. ...guildChannels.map( guildChannel => {
  101. return $(`<option id="wb-settings-channel-${guildChannel.id}">`).val(guildChannel.id).text(`${guildChannel.id} – ` + ( guildChannel.isCategory ? '' : '#' ) + guildChannel.name);
  102. } )
  103. );
  104. channel.find(`#wb-settings-channel-${settings.channel}`).attr('selected', '');
  105. if ( !hasPerm(guildChannels[0].userPermissions, 'VIEW_CHANNEL', 'SEND_MESSAGES') ) {
  106. readonly = true;
  107. }
  108. }
  109. fields.push(channel);
  110. }
  111. let wiki = $('<div>').append(fieldset.wiki);
  112. wiki.find('label').text(dashboardLang.get('settings.form.wiki'));
  113. wiki.find('#wb-settings-wiki-check').text(dashboardLang.get('settings.form.wiki_check'));
  114. wiki.find('#wb-settings-wiki').val(settings.wiki);
  115. fields.push(wiki);
  116. if ( !settings.channel || settings.patreon ) {
  117. let lang = $('<div>').append(fieldset.lang);
  118. lang.find('label').text(dashboardLang.get('settings.form.lang'));
  119. lang.find(`#wb-settings-lang-${settings.lang}`).attr('selected', '');
  120. fields.push(lang);
  121. let role = $('<div>').append(fieldset.role);
  122. role.find('label').text(dashboardLang.get('settings.form.role'));
  123. role.find('#wb-settings-role').append(
  124. ...guildRoles.map( guildRole => {
  125. return $(`<option id="wb-settings-role-${guildRole.id}">`).val(guildRole.id).text(`${guildRole.id} – @${guildRole.name}`)
  126. } ),
  127. $(`<option id="wb-settings-role-everyone">`).val('').text(`@everyone`)
  128. );
  129. if ( settings.role ) role.find(`#wb-settings-role-${settings.role}`).attr('selected', '');
  130. else role.find(`#wb-settings-role-everyone`).attr('selected', '');
  131. fields.push(role);
  132. let inline = $('<div>').append(fieldset.inline);
  133. inline.find('label').text(dashboardLang.get('settings.form.inline'));
  134. if ( !settings.inline ) inline.find('#wb-settings-inline').attr('checked', '');
  135. fields.push(inline);
  136. }
  137. if ( settings.patreon && !settings.channel ) {
  138. let prefix = $('<div>').append(fieldset.prefix);
  139. prefix.find('label').eq(0).text(dashboardLang.get('settings.form.prefix'));
  140. prefix.find('label').eq(1).text(dashboardLang.get('settings.form.prefix_space'));
  141. prefix.find('#wb-settings-prefix').val(settings.prefix.trim());
  142. if ( settings.prefix.endsWith( ' ' ) ) {
  143. prefix.find('#wb-settings-prefix-space').attr('checked', '');
  144. }
  145. fields.push(prefix);
  146. }
  147. fields.push($(fieldset.save).val(dashboardLang.get('general.save')));
  148. if ( settings.channel && settings.channel !== 'new' ) {
  149. fields.push($(fieldset.delete).val(dashboardLang.get('general.delete')).attr('onclick', `return confirm('${dashboardLang.get('settings.form.confirm').replace( /'/g, '\\$&' )}');`));
  150. }
  151. var form = $('<fieldset>').append(...fields);
  152. if ( readonly ) {
  153. form.find('input').attr('readonly', '');
  154. form.find('input[type="checkbox"], option').attr('disabled', '');
  155. form.find('input[type="submit"]').remove();
  156. }
  157. return $('<form id="wb-settings" method="post" enctype="application/x-www-form-urlencoded">').append(
  158. $('<h2>').text(header),
  159. form
  160. );
  161. }
  162. /**
  163. * Let a user change settings
  164. * @param {import('http').ServerResponse} res - The server response
  165. * @param {import('cheerio')} $ - The response body
  166. * @param {import('./util.js').Guild} guild - The current guild
  167. * @param {String[]} args - The url parts
  168. * @param {import('./i18n.js')} dashboardLang - The user language
  169. */
  170. function dashboard_settings(res, $, guild, args, dashboardLang) {
  171. db.query( 'SELECT channel, wiki, lang, role, inline, prefix, patreon FROM discord WHERE guild = $1 ORDER BY channel DESC NULLS LAST', [guild.id] ).then( ({rows}) => {
  172. $('<p>').html(dashboardLang.get('settings.desc', true, $('<code>').text(guild.name))).appendTo('#text .description');
  173. if ( !rows.length ) {
  174. $('.channel#settings').addClass('selected');
  175. createForm($, dashboardLang.get('settings.form.default'), dashboardLang, {
  176. prefix: process.env.prefix,
  177. wiki: defaultSettings.wiki,
  178. lang: ( guild.locale || defaultSettings.lang )
  179. }, guild.roles).attr('action', `/guild/${guild.id}/settings/default`).appendTo('#text');
  180. return;
  181. }
  182. let isPatreon = rows.some( row => row.patreon );
  183. let channellist = rows.filter( row => row.channel ).map( row => {
  184. let channel = guild.channels.find( channel => channel.id === row.channel.replace( /^#/, '' ) );
  185. return ( channel || {id: row.channel.replace( /^#/, '' ), name: 'UNKNOWN', userPermissions: 0, isCategory: row.channel.startsWith( '#' )} );
  186. } ).sort( (a, b) => {
  187. return guild.channels.indexOf(a) - guild.channels.indexOf(b);
  188. } );
  189. let suffix = ( args[0] === 'owner' ? '?owner=true' : '' );
  190. $('#channellist #settings').after(
  191. ...channellist.map( channel => {
  192. return $('<a class="channel">').attr('id', `channel-${channel.id}`).append(
  193. ...( channel.isCategory ? [
  194. $('<div class="category">').text(channel.name)
  195. ] : [
  196. $('<img>').attr('src', '/src/channel.svg'),
  197. $('<div>').text(channel.name)]
  198. )
  199. ).attr('href', `/guild/${guild.id}/settings/${channel.id}${suffix}`).attr('title', channel.id);
  200. } ),
  201. ( process.env.READONLY || !guild.channels.filter( channel => {
  202. return ( hasPerm(channel.userPermissions, 'VIEW_CHANNEL', 'SEND_MESSAGES') && !rows.some( row => row.channel === ( channel.isCategory ? '#' : '' ) + channel.id ) );
  203. } ).length ? '' :
  204. $('<a class="channel" id="channel-new">').append(
  205. $('<img>').attr('src', '/src/channel.svg'),
  206. $('<div>').text(dashboardLang.get('settings.new'))
  207. ).attr('href', `/guild/${guild.id}/settings/new${suffix}`) )
  208. );
  209. if ( args[4] === 'new' && !process.env.READONLY ) {
  210. $('.channel#channel-new').addClass('selected');
  211. createForm($, dashboardLang.get('settings.form.new'), dashboardLang, Object.assign({}, rows.find( row => !row.channel ), {
  212. patreon: isPatreon,
  213. channel: 'new'
  214. }), guild.roles, guild.channels.filter( channel => {
  215. return ( channel.isCategory || !rows.some( row => row.channel === ( channel.isCategory ? '#' : '' ) + channel.id ) );
  216. } ).map( channel => {
  217. if ( !channel.isCategory ) return channel;
  218. let {id, name, userPermissions, isCategory} = channel;
  219. return {
  220. id, name, userPermissions, isCategory,
  221. allowedCat: !rows.some( row => row.channel === '#' + channel.id )
  222. };
  223. } )).attr('action', `/guild/${guild.id}/settings/new`).appendTo('#text');
  224. }
  225. else if ( channellist.some( channel => channel.id === args[4] ) ) {
  226. let channel = channellist.find( channel => channel.id === args[4] );
  227. $(`.channel#channel-${channel.id}`).addClass('selected');
  228. createForm($, dashboardLang.get('settings.form.overwrite', false, `#${channel.name}`), dashboardLang, Object.assign({}, rows.find( row => {
  229. return row.channel === ( channel.isCategory ? '#' : '' ) + channel.id;
  230. } ), {
  231. patreon: isPatreon
  232. }), guild.roles, [channel]).attr('action', `/guild/${guild.id}/settings/${channel.id}`).appendTo('#text');
  233. }
  234. else {
  235. $('.channel#settings').addClass('selected');
  236. createForm($, dashboardLang.get('settings.form.default'), dashboardLang, rows.find( row => !row.channel ), guild.roles).attr('action', `/guild/${guild.id}/settings/default`).appendTo('#text');
  237. }
  238. }, dberror => {
  239. console.log( '- Dashboard: Error while getting the settings: ' + dberror );
  240. createNotice($, 'error', dashboardLang);
  241. $('<p>').text(dashboardLang.get('settings.failed')).appendTo('#text .description');
  242. $('.channel#settings').addClass('selected');
  243. } ).then( () => {
  244. let body = $.html();
  245. res.writeHead(200, {'Content-Length': Buffer.byteLength(body)});
  246. res.write( body );
  247. return res.end();
  248. } );
  249. }
  250. /**
  251. * Change settings
  252. * @param {Function} res - The server response
  253. * @param {import('./util.js').Settings} userSettings - The settings of the user
  254. * @param {String} guild - The id of the guild
  255. * @param {String} type - The setting to change
  256. * @param {Object} settings - The new settings
  257. * @param {String} [settings.channel]
  258. * @param {String} settings.wiki
  259. * @param {String} [settings.lang]
  260. * @param {String} [settings.role]
  261. * @param {String} [settings.inline]
  262. * @param {String} [settings.prefix]
  263. * @param {String} [settings.prefix_space]
  264. * @param {String} [settings.save_settings]
  265. * @param {String} [settings.delete_settings]
  266. */
  267. function update_settings(res, userSettings, guild, type, settings) {
  268. if ( type !== 'default' && type !== 'new' && type !== settings.channel ) {
  269. return res(`/guild/${guild}/settings`, 'savefail');
  270. }
  271. if ( !settings.save_settings === !settings.delete_settings ) {
  272. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  273. }
  274. if ( settings.save_settings ) {
  275. if ( !settings.wiki || ( settings.lang && !allLangs.names.hasOwnProperty(settings.lang) ) ) {
  276. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  277. }
  278. if ( settings.channel && !userSettings.guilds.isMember.get(guild).channels.some( channel => {
  279. return ( channel.id === settings.channel && ( !channel.isCategory || userSettings.guilds.isMember.get(guild).patreon ) );
  280. } ) ) return res(`/guild/${guild}/settings/${type}`, 'savefail');
  281. if ( settings.role && !userSettings.guilds.isMember.get(guild).roles.some( role => {
  282. return ( role.id === settings.role );
  283. } ) ) return res(`/guild/${guild}/settings/${type}`, 'savefail');
  284. }
  285. if ( settings.delete_settings && ( type === 'default' || type === 'new' ) ) {
  286. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  287. }
  288. sendMsg( {
  289. type: 'getMember',
  290. member: userSettings.user.id,
  291. guild: guild,
  292. channel: ( type !== 'default' ? settings.channel : undefined ),
  293. allowCategory: true
  294. } ).then( response => {
  295. if ( !response ) {
  296. userSettings.guilds.notMember.set(guild, userSettings.guilds.isMember.get(guild));
  297. userSettings.guilds.isMember.delete(guild);
  298. return res(`/guild/${guild}`, 'savefail');
  299. }
  300. if ( response === 'noMember' || !hasPerm(response.userPermissions, 'MANAGE_GUILD') ) {
  301. userSettings.guilds.isMember.delete(guild);
  302. return res('/', 'savefail');
  303. }
  304. if ( response.message === 'noChannel' ) return db.query( 'DELETE FROM discord WHERE guild = $1 AND ( channel = $2 OR channel = $3 )', [guild, type, `#${type}`] ).then( () => {
  305. console.log( `- Dashboard: Settings successfully removed: ${guild}#${type}` );
  306. if ( settings.delete_settings ) return res(`/guild/${guild}/settings`, 'save');
  307. else return res(`/guild/${guild}/settings`, 'savefail');
  308. }, delerror =>{
  309. console.log( '- Dashboard: Error while removing the settings: ' + delerror );
  310. return res(`/guild/${guild}/settings`, 'savefail');
  311. } );
  312. if ( type !== 'default' && !hasPerm(response.userPermissions, 'VIEW_CHANNEL', 'SEND_MESSAGES') ) {
  313. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  314. }
  315. if ( settings.delete_settings ) return db.query( 'DELETE FROM discord WHERE guild = $1 AND channel = $2 RETURNING wiki, lang, role, inline', [guild, ( response.isCategory ? '#' : '' ) + type] ).then( ({rows:[channel]}) => {
  316. console.log( `- Dashboard: Settings successfully removed: ${guild}#${type}` );
  317. res(`/guild/${guild}/settings`, 'save');
  318. if ( !channel ) return;
  319. db.query( 'SELECT channel, wiki, lang, role, inline FROM discord WHERE guild = $1 AND ( channel = $2 OR channel IS NULL ) ORDER BY channel DESC NULLS LAST', [guild, '#' + response.parentID] ).then( ({rows:[row, {lang: guildlang} = {}]}) => {
  320. var lang = new Lang(( guildlang || row.lang ));
  321. var text = lang.get('settings.dashboard.removed', `<@${userSettings.user.id}>`, `<#${type}>`);
  322. if ( channel.wiki !== row.wiki ) text += `\n${lang.get('settings.currentwiki')} <${channel.wiki}>`;
  323. if ( response.patreon ) {
  324. if ( channel.lang !== row.lang ) text += `\n${lang.get('settings.currentlang')} \`${allLangs.names[channel.lang]}\``;
  325. if ( channel.role !== row.role ) text += `\n${lang.get('settings.currentrole')} ` + ( channel.role ? `<@&${channel.role}>` : '@everyone' );
  326. if ( channel.inline !== row.inline ) text += `\n${lang.get('settings.currentinline')} ${( channel.inline ? '~~' : '' )}\`[[${( lang.localNames.page || 'page' )}]]\`${( channel.inline ? '~~' : '' )}`;
  327. }
  328. text += `\n<${new URL(`/guild/${guild}/settings`, process.env.dashboard).href}>`;
  329. sendMsg( {
  330. type: 'notifyGuild', guild, text
  331. } ).catch( error => {
  332. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  333. } );
  334. }, dberror => {
  335. console.log( '- Dashboard: Error while notifying the guild: ' + dberror );
  336. } );
  337. }, dberror => {
  338. console.log( '- Dashboard: Error while removing the settings: ' + dberror );
  339. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  340. } );
  341. var wiki = Wiki.fromInput(settings.wiki);
  342. var embed;
  343. return got.get( wiki + 'api.php?&action=query&meta=siteinfo&siprop=general|extensions&format=json', {
  344. responseType: 'text'
  345. } ).then( fresponse => {
  346. try {
  347. fresponse.body = JSON.parse(fresponse.body);
  348. }
  349. catch (error) {
  350. if ( fresponse.statusCode === 404 && typeof fresponse.body === 'string' ) {
  351. let api = cheerio.load(fresponse.body)('head link[rel="EditURI"]').prop('href');
  352. if ( api ) {
  353. wikinew = new Wiki(api.split('api.php?')[0], wikinew);
  354. return got.get( wikinew + 'api.php?action=query&meta=siteinfo&siprop=general|extensions&format=json' );
  355. }
  356. }
  357. }
  358. return fresponse;
  359. } ).then( fresponse => {
  360. return db.query( 'SELECT channel, wiki, lang, role, inline, prefix FROM discord WHERE guild = $1 AND ( channel = $2 OR channel IS NULL ) ORDER BY channel DESC NULLS LAST', [guild, '#' + response.parentID] ).then( ({rows:[row, {lang: guildlang} = {}]}) => {
  361. if ( row ) row.guildlang = ( guildlang || row.lang );
  362. var body = fresponse.body;
  363. if ( fresponse.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.general || !body?.query?.extensions ) {
  364. console.log( '- Dashboard: ' + fresponse.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  365. if ( row?.wiki === wiki.href ) return row;
  366. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  367. return Promise.reject('private');
  368. }
  369. return Promise.reject();
  370. }
  371. wiki.updateWiki(body.query.general);
  372. if ( !wiki.isFandom() ) {
  373. let notice = [];
  374. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) <= 30 ) {
  375. console.log( '- Dashboard: This wiki is using ' + body.query.general.generator + '.' );
  376. notice.push({
  377. name: 'MediaWiki',
  378. value: lang.get('test.MediaWiki', '[MediaWiki 1.30](https://www.mediawiki.org/wiki/MediaWiki_1.30)', body.query.general.generator)
  379. });
  380. }
  381. if ( !body.query.extensions.some( extension => extension.name === 'TextExtracts' ) ) {
  382. console.log( '- Dashboard: This wiki is missing Extension:TextExtracts.' );
  383. notice.push({
  384. name: 'TextExtracts',
  385. value: lang.get('test.TextExtracts', '[TextExtracts](https://www.mediawiki.org/wiki/Extension:TextExtracts)')
  386. });
  387. }
  388. if ( !body.query.extensions.some( extension => extension.name === 'PageImages' ) ) {
  389. console.log( '- Dashboard: This wiki is missing Extension:PageImages.' );
  390. notice.push({
  391. name: 'PageImages',
  392. value: lang.get('test.PageImages', '[PageImages](https://www.mediawiki.org/wiki/Extension:PageImages)')
  393. });
  394. }
  395. if ( notice.length ) {
  396. embed = {
  397. author: {name: body.query.general.sitename},
  398. title: lang.get('test.notice'),
  399. fields: notice
  400. }
  401. }
  402. }
  403. return row;
  404. }, dberror => {
  405. console.log( '- Dashboard: Error while getting the settings: ' + dberror );
  406. return Promise.reject();
  407. } );
  408. }, error => {
  409. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' || error.message === 'self signed certificate' ) {
  410. console.log( '- Dashboard: Error while testing the wiki: No HTTPS' );
  411. return Promise.reject('http');
  412. }
  413. console.log( '- Dashboard: Error while testing the wiki: ' + error );
  414. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  415. return Promise.reject('timeout');
  416. }
  417. return Promise.reject();
  418. } ).then( row => {
  419. var lang = new Lang(( type === 'default' && settings.lang || row?.guildlang ));
  420. if ( type === 'default' ) {
  421. if ( settings.channel || !settings.lang || ( !response.patreon !== !settings.prefix ) ) {
  422. return res(`/guild/${guild}/settings`, 'savefail');
  423. }
  424. if ( settings.prefix ) {
  425. if ( !/^\s*[^\s`\\]{1,100}\s*$/.test(settings.prefix) ) {
  426. return res(`/guild/${guild}/settings`, 'savefail');
  427. }
  428. settings.prefix = settings.prefix.trim().toLowerCase();
  429. if ( settings.prefix_space ) settings.prefix += ' ';
  430. }
  431. if ( !row ) return db.query( 'INSERT INTO discord(wiki, lang, role, inline, prefix, guild, main) VALUES($1, $2, $3, $4, $5, $6, $6)', [wiki.href, settings.lang, ( settings.role || null ), ( settings.inline ? null : 1 ), ( settings.prefix || process.env.prefix ), guild] ).then( () => {
  432. console.log( '- Dashboard: Settings successfully saved: ' + guild );
  433. res(`/guild/${guild}/settings`, 'save');
  434. var text = lang.get('settings.dashboard.updated', `<@${userSettings.user.id}>`);
  435. text += '\n' + lang.get('settings.currentwiki') + ` <${wiki.href}>`;
  436. text += '\n' + lang.get('settings.currentlang') + ` \`${allLangs.names[settings.lang]}\``;
  437. text += '\n' + lang.get('settings.currentrole') + ( settings.role ? ` <@&${settings.role}>` : ' @everyone' );
  438. if ( response.patreon ) {
  439. text += '\n' + lang.get('settings.currentprefix') + ` \`${settings.prefix.replace( /\\/g, '\\$&' )}\``;
  440. }
  441. text += '\n' + lang.get('settings.currentinline') + ` ${( settings.inline ? '' : '~~' )}\`[[${( lang.localNames.page || 'page' )}]]\`${( settings.inline ? '' : '~~' )}`;
  442. text += `\n<${new URL(`/guild/${guild}/settings`, process.env.dashboard).href}>`;
  443. sendMsg( {
  444. type: 'notifyGuild', guild, text, embed,
  445. file: [`./i18n/widgets/${settings.lang}.png`]
  446. } ).catch( error => {
  447. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  448. } );
  449. }, dberror => {
  450. console.log( '- Dashboard: Error while saving the settings: ' + dberror );
  451. return res(`/guild/${guild}/settings`, 'savefail');
  452. } );
  453. var diff = [];
  454. var file = [];
  455. var updateGuild = false;
  456. var updateChannel = false;
  457. if ( row.wiki !== wiki.href ) {
  458. updateGuild = true;
  459. diff.push(lang.get('settings.currentwiki') + ` ~~<${row.wiki}>~~ → <${wiki.href}>`);
  460. }
  461. if ( row.lang !== settings.lang ) {
  462. updateChannel = true;
  463. file.push(`./i18n/widgets/${settings.lang}.png`);
  464. diff.push(lang.get('settings.currentlang') + ` ~~\`${allLangs.names[row.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
  465. }
  466. if ( response.patreon && row.prefix !== settings.prefix ) {
  467. updateChannel = true;
  468. diff.push(lang.get('settings.currentprefix') + ` ~~\`${row.prefix.replace( /\\/g, '\\$&' )}\`~~ → \`${settings.prefix.replace( /\\/g, '\\$&' )}\``);
  469. }
  470. if ( row.role !== ( settings.role || null ) ) {
  471. updateChannel = true;
  472. diff.push(lang.get('settings.currentrole') + ` ~~${( row.role ? `<@&${row.role}>` : '@everyone' )}~~ → ${( settings.role ? `<@&${settings.role}>` : '@everyone' )}`);
  473. }
  474. if ( row.inline !== ( settings.inline ? null : 1 ) ) {
  475. updateChannel = true;
  476. let inlinepage = ( lang.localNames.page || 'page' );
  477. diff.push(lang.get('settings.currentinline') + ` ${( row.inline ? '~~' : '' )}\`[[${inlinepage}]]\`${( row.inline ? '~~' : '' )} → ${( settings.inline ? '' : '~~' )}\`[[${inlinepage}]]\`${( settings.inline ? '' : '~~' )}`);
  478. }
  479. if ( diff.length ) {
  480. var dbupdate = [];
  481. if ( response.patreon ) {
  482. dbupdate.push([
  483. 'UPDATE discord SET wiki = $1, lang = $2, role = $3, inline = $4, prefix = $5 WHERE guild = $6 AND channel IS NULL',
  484. [wiki.href, settings.lang, ( settings.role || null ), ( settings.inline ? null : 1 ), ( settings.prefix || process.env.prefix ), guild]
  485. ]);
  486. }
  487. else {
  488. if ( updateGuild ) {
  489. dbupdate.push([
  490. 'UPDATE discord SET wiki = $1 WHERE guild = $2 AND channel IS NULL',
  491. [wiki.href, guild]
  492. ]);
  493. }
  494. if ( updateChannel ) {
  495. dbupdate.push([
  496. 'UPDATE discord SET lang = $1, role = $2, inline = $3, prefix = $4 WHERE guild = $5',
  497. [settings.lang, ( settings.role || null ), ( settings.inline ? null : 1 ), ( settings.prefix || process.env.prefix ), guild]
  498. ]);
  499. }
  500. }
  501. return Promise.all(dbupdate.map( ([sql, sqlargs]) => {
  502. return db.query( sql, sqlargs );
  503. } )).then( () => {
  504. console.log( '- Dashboard: Settings successfully saved: ' + guild );
  505. res(`/guild/${guild}/settings`, 'save');
  506. var text = lang.get('settings.dashboard.updated', `<@${userSettings.user.id}>`);
  507. text += '\n' + diff.join('\n');
  508. text += `\n<${new URL(`/guild/${guild}/settings`, process.env.dashboard).href}>`;
  509. sendMsg( {
  510. type: 'notifyGuild', guild, text, file,
  511. embed: ( updateGuild ? embed : undefined ),
  512. prefix: settings.prefix, voice: settings.lang
  513. } ).catch( error => {
  514. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  515. } );
  516. }, dberror => {
  517. console.log( '- Dashboard: Error while saving the settings: ' + dberror );
  518. return res(`/guild/${guild}/settings`, 'savefail');
  519. } );
  520. }
  521. return res(`/guild/${guild}/settings`, 'save');
  522. }
  523. if ( !row || !settings.channel || settings.prefix ||
  524. ( !response.patreon && ( settings.lang || settings.role || settings.inline ) ) ) {
  525. return res(`/guild/${guild}/settings`, 'savefail');
  526. }
  527. if ( row.wiki === wiki.href && ( !response.patreon ||
  528. ( row.lang === settings.lang && row.inline === ( settings.inline ? null : 1 ) && row.role === ( settings.role || null ) ) ) ) {
  529. if ( type === 'new' ) {
  530. return res(`/guild/${guild}/settings/${type}`, 'nochange');
  531. }
  532. return db.query( 'DELETE FROM discord WHERE guild = $1 AND channel = $2 RETURNING wiki, lang, role, inline', [guild, ( response.isCategory ? '#' : '' ) + type] ).then( ({rows:[channel]}) => {
  533. console.log( `- Dashboard: Settings successfully removed: ${guild}#${type}` );
  534. res(`/guild/${guild}/settings`, 'save');
  535. var text = lang.get('settings.dashboard.removed', `<@${userSettings.user.id}>`, `<#${type}>`);
  536. if ( channel.wiki !== row.wiki ) text += `\n${lang.get('settings.currentwiki')} <${channel.wiki}>`;
  537. if ( response.patreon ) {
  538. if ( channel.lang !== row.lang ) text += `\n${lang.get('settings.currentlang')} \`${allLangs.names[channel.lang]}\``;
  539. if ( channel.role !== row.role ) text += `\n${lang.get('settings.currentrole')} ` + ( channel.role ? `<@&${channel.role}>` : '@everyone' );
  540. if ( channel.inline !== row.inline ) text += `\n${lang.get('settings.currentinline')} ${( channel.inline ? '~~' : '' )}\`[[${( lang.localNames.page || 'page' )}]]\`${( channel.inline ? '~~' : '' )}`;
  541. }
  542. text += `\n<${new URL(`/guild/${guild}/settings`, process.env.dashboard).href}>`;
  543. sendMsg( {
  544. type: 'notifyGuild', guild, text
  545. } ).catch( error => {
  546. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  547. } );
  548. }, dberror => {
  549. console.log( '- Dashboard: Error while removing the settings: ' + dberror );
  550. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  551. } );
  552. }
  553. return db.query( 'SELECT lang, wiki, role, inline FROM discord WHERE guild = $1 AND channel = $2', [guild, ( response.isCategory ? '#' : '' ) + settings.channel] ).then( ({rows:[channel]}) => {
  554. if ( !channel ) channel = row;
  555. var diff = [];
  556. var file = [];
  557. var useEmbed = false;
  558. if ( channel.wiki !== wiki.href ) {
  559. useEmbed = true;
  560. diff.push(lang.get('settings.currentwiki') + ` ~~<${channel.wiki}>~~ → <${wiki.href}>`);
  561. }
  562. if ( response.patreon && channel.lang !== settings.lang ) {
  563. file.push(`./i18n/widgets/${settings.lang}.png`);
  564. diff.push(lang.get('settings.currentlang') + ` ~~\`${allLangs.names[channel.lang]}\`~~ → \`${allLangs.names[settings.lang]}\``);
  565. }
  566. if ( response.patreon && channel.role !== ( settings.role || null ) ) {
  567. diff.push(lang.get('settings.currentrole') + ` ~~${( channel.role ? `<@&${channel.role}>` : '@everyone' )}~~ → ${( settings.role ? `<@&${settings.role}>` : '@everyone' )}`);
  568. }
  569. if ( response.patreon && channel.inline !== ( settings.inline ? null : 1 ) ) {
  570. let inlinepage = ( lang.localNames.page || 'page' );
  571. diff.push(lang.get('settings.currentinline') + ` ${( channel.inline ? '~~' : '' )}\`[[${inlinepage}]]\`${( channel.inline ? '~~' : '' )} → ${( settings.inline ? '' : '~~' )}\`[[${inlinepage}]]\`${( settings.inline ? '' : '~~' )}`);
  572. }
  573. if ( !diff.length ) {
  574. return res(`/guild/${guild}/settings/${settings.channel}`, 'save');
  575. }
  576. let sql = 'UPDATE discord SET wiki = $1, lang = $2, role = $3, inline = $4 WHERE guild = $5 AND channel = $6';
  577. let sqlargs = [wiki.href, ( settings.lang || channel.lang ), ( response.patreon ? ( settings.role || null ) : channel.role ), ( response.patreon ? ( settings.inline ? null : 1 ) : channel.inline ), guild, ( response.isCategory ? '#' : '' ) + settings.channel];
  578. if ( channel === row ) {
  579. sql = 'INSERT INTO discord(wiki, lang, role, inline, guild, channel, prefix) VALUES($1, $2, $3, $4, $5, $6, $7)';
  580. sqlargs.push(row.prefix);
  581. }
  582. return db.query( sql, sqlargs ).then( () => {
  583. console.log( `- Dashboard: Settings successfully saved: ${guild}#${settings.channel}` );
  584. res(`/guild/${guild}/settings/${settings.channel}`, 'save');
  585. var text = lang.get('settings.dashboard.channel', `<@${userSettings.user.id}>`, `<#${settings.channel}>`);
  586. text += '\n' + diff.join('\n');
  587. text += `\n<${new URL(`/guild/${guild}/settings/${settings.channel}`, process.env.dashboard).href}>`;
  588. sendMsg( {
  589. type: 'notifyGuild', guild, text, file,
  590. embed: ( useEmbed ? embed : undefined )
  591. } ).catch( error => {
  592. console.log( '- Dashboard: Error while notifying the guild: ' + error );
  593. } );
  594. }, dberror => {
  595. console.log( '- Dashboard: Error while saving the settings: ' + dberror );
  596. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  597. } );
  598. }, dberror => {
  599. console.log( '- Dashboard: Error while getting the channel settings: ' + dberror );
  600. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  601. } );
  602. }, error => {
  603. return res(`/guild/${guild}/settings/${type}`, 'savefail', error);
  604. } );
  605. }, error => {
  606. console.log( '- Dashboard: Error while getting the member: ' + error );
  607. return res(`/guild/${guild}/settings/${type}`, 'savefail');
  608. } );
  609. }
  610. module.exports = {
  611. get: dashboard_settings,
  612. post: update_settings
  613. };