util.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. const got = require('got').extend( {
  2. throwHttpErrors: false,
  3. timeout: 5000,
  4. headers: {
  5. 'User-Agent': 'Wiki-Bot/dashboard (Discord; ' + process.env.npm_package_name + ')'
  6. },
  7. responseType: 'json'
  8. } );
  9. const {Pool} = require('pg');
  10. const db = new Pool();
  11. db.on( 'error', dberror => {
  12. console.log( '- Dashboard: Error while connecting to the database: ' + dberror );
  13. } );
  14. const DiscordOauth2 = require('discord-oauth2');
  15. const oauth = new DiscordOauth2( {
  16. clientId: process.env.bot,
  17. clientSecret: process.env.secret,
  18. redirectUri: process.env.dashboard
  19. } );
  20. const slashCommands = require('../interactions/commands.json');
  21. got.get( `https://discord.com/api/v8/applications/${process.env.bot}/commands`, {
  22. headers: {
  23. Authorization: `Bot ${process.env.token}`
  24. },
  25. timeout: 10000
  26. } ).then( response=> {
  27. if ( response.statusCode !== 200 || !response.body ) {
  28. console.log( '- Dashboard: ' + response.statusCode + ': Error while getting the global slash commands: ' + response.body?.message );
  29. return;
  30. }
  31. console.log( '- Dashboard: Slash commands successfully loaded.' );
  32. response.body.forEach( command => {
  33. var slashCommand = slashCommands.find( slashCommand => slashCommand.name === command.name );
  34. if ( slashCommand ) {
  35. slashCommand.id = command.id;
  36. slashCommand.application_id = command.application_id;
  37. }
  38. else slashCommands.push(slashCommand);
  39. } );
  40. }, error => {
  41. console.log( '- Dashboard: Error while getting the global slash commands: ' + error );
  42. } );
  43. /**
  44. * @typedef UserSession
  45. * @property {String} state
  46. * @property {String} access_token
  47. * @property {String} user_id
  48. */
  49. /**
  50. * @typedef Settings
  51. * @property {User} user
  52. * @property {Object} guilds
  53. * @property {Number} guilds.count
  54. * @property {Map<String, Guild>} guilds.isMember
  55. * @property {Map<String, Guild>} guilds.notMember
  56. */
  57. /**
  58. * @typedef User
  59. * @property {String} id
  60. * @property {String} username
  61. * @property {String} discriminator
  62. * @property {String} avatar
  63. * @property {String} locale
  64. */
  65. /**
  66. * @typedef Guild
  67. * @property {String} id
  68. * @property {String} name
  69. * @property {String} acronym
  70. * @property {String} [icon]
  71. * @property {String} userPermissions
  72. * @property {Boolean} [patreon]
  73. * @property {String} [botPermissions]
  74. * @property {Channel[]} [channels]
  75. * @property {Role[]} [roles]
  76. * @property {String} [locale]
  77. */
  78. /**
  79. * @typedef Channel
  80. * @property {String} id
  81. * @property {String} name
  82. * @property {Boolean} isCategory
  83. * @property {Number} userPermissions
  84. * @property {Number} botPermissions
  85. */
  86. /**
  87. * @typedef Role
  88. * @property {String} id
  89. * @property {String} name
  90. * @property {Boolean} lower
  91. */
  92. /**
  93. * @type {Map<String, UserSession>}
  94. */
  95. const sessionData = new Map();
  96. /**
  97. * @type {Map<String, Settings>}
  98. */
  99. const settingsData = new Map();
  100. /**
  101. * @type {Map<Number, PromiseConstructor>}
  102. */
  103. const messages = new Map();
  104. var messageId = 1;
  105. process.on( 'message', message => {
  106. if ( message.id ) {
  107. if ( message.data.error ) messages.get(message.id).reject(message.data.error);
  108. else messages.get(message.id).resolve(message.data.response);
  109. return messages.delete(message.id);
  110. }
  111. if ( message === 'toggleDebug' ) global.isDebug = !global.isDebug;
  112. console.log( '- [Dashboard]: Message received!', message );
  113. } );
  114. /**
  115. * Send messages to the manager.
  116. * @param {Object} [message] - The message.
  117. * @returns {Promise<Object>}
  118. */
  119. function sendMsg(message) {
  120. var id = messageId++;
  121. var promise = new Promise( (resolve, reject) => {
  122. messages.set(id, {resolve, reject});
  123. process.send( {id, data: message} );
  124. } );
  125. return promise;
  126. }
  127. var botLists = [];
  128. if ( process.env.botlist ) {
  129. let supportedLists = {
  130. 'blist.xyz': {
  131. link: 'https://blist.xyz/bot/' + process.env.bot,
  132. widget: 'https://blist.xyz/api/v2/bot/' + process.env.bot + '/widget'
  133. },
  134. 'botlists.com': {
  135. link: 'https://botlists.com/bot/' + process.env.bot,
  136. widget: 'https://botlists.com/bot/' + process.env.bot + '/widget'
  137. },
  138. 'bots.ondiscord.xyz': {
  139. link: 'https://bots.ondiscord.xyz/bots/' + process.env.bot,
  140. widget: 'https://bots.ondiscord.xyz/bots/' + process.env.bot + '/embed?theme=dark&showGuilds=true'
  141. },
  142. 'botsfordiscord.com': {
  143. link: 'https://botsfordiscord.com/bots/' + process.env.bot,
  144. widget: 'https://botsfordiscord.com/api/bot/' + process.env.bot + '/widget?theme=dark'
  145. },
  146. 'discord.boats': {
  147. link: 'https://discord.boats/bot/' + process.env.bot,
  148. widget: 'https://discord.boats/api/widget/' + process.env.bot
  149. },
  150. 'infinitybotlist.com': {
  151. link: 'https://infinitybotlist.com/bots/' + process.env.bot,
  152. widget: 'https://infinitybotlist.com/bots/' + process.env.bot + '/widget?size=medium'
  153. },
  154. 'top.gg': {
  155. link: 'https://top.gg/bot/' + process.env.bot,
  156. widget: 'https://top.gg/api/widget/' + process.env.bot + '.svg'
  157. },
  158. 'voidbots.net': {
  159. link: 'https://voidbots.net/bot/' + process.env.bot,
  160. widget: 'https://voidbots.net/api/embed/' + process.env.bot + '?theme=dark'
  161. }
  162. };
  163. botLists = Object.keys(JSON.parse(process.env.botlist)).filter( botList => {
  164. return supportedLists.hasOwnProperty(botList);
  165. } ).map( botList => {
  166. return `<a href="${supportedLists[botList].link}" target="_blank">
  167. <img src="${supportedLists[botList].widget}" alt="${botList}" height="150px" loading="lazy" />
  168. </a>`;
  169. } );
  170. }
  171. /**
  172. * Add bot list widgets.
  173. * @param {import('cheerio')} $ - The cheerio static
  174. * @param {import('./i18n.js')} dashboardLang - The user language
  175. * @returns {import('cheerio')}
  176. */
  177. function addWidgets($, dashboardLang) {
  178. if ( !botLists.length ) return;
  179. return $('<div class="widgets">').append(
  180. $('<h3 id="bot-lists">').text(dashboardLang.get('general.botlist.title')),
  181. $('<p>').text(dashboardLang.get('general.botlist.text')),
  182. ...botLists
  183. ).appendTo('#text');
  184. }
  185. /**
  186. * Create a red notice
  187. * @param {import('cheerio')} $ - The cheerio static
  188. * @param {String} notice - The notice to create
  189. * @param {import('./i18n.js')} dashboardLang - The user language
  190. * @param {String[]} [args] - The arguments for the notice
  191. * @returns {import('cheerio')}
  192. */
  193. function createNotice($, notice, dashboardLang, args = []) {
  194. if ( !notice ) return;
  195. var type = 'info';
  196. var title = $('<b>');
  197. var text = $('<div>');
  198. var note;
  199. switch (notice) {
  200. case 'unauthorized':
  201. type = 'info';
  202. title.text(dashboardLang.get('notice.unauthorized.title'));
  203. text.text(dashboardLang.get('notice.unauthorized.text'));
  204. break;
  205. case 'save':
  206. type = 'success';
  207. title.text(dashboardLang.get('notice.save.title'));
  208. text.text(dashboardLang.get('notice.save.text'));
  209. break;
  210. case 'nosettings':
  211. type = 'info';
  212. title.text(dashboardLang.get('notice.nosettings.title'));
  213. text.text(dashboardLang.get('notice.nosettings.text'));
  214. if ( args[0] ) note = $('<a>').text(dashboardLang.get('notice.nosettings.note')).attr('href', `/guild/${args[0]}/settings`);
  215. break;
  216. case 'logout':
  217. type = 'success';
  218. title.text(dashboardLang.get('notice.logout.title'));
  219. text.text(dashboardLang.get('notice.logout.text'));
  220. break;
  221. case 'refresh':
  222. type = 'success';
  223. title.text(dashboardLang.get('notice.refresh.title'));
  224. text.text(dashboardLang.get('notice.refresh.text'));
  225. break;
  226. case 'missingperm':
  227. type = 'error';
  228. title.text(dashboardLang.get('notice.missingperm.title'));
  229. text.html(dashboardLang.get('notice.missingperm.text', true, $('<code>').text(args[0])));
  230. break;
  231. case 'loginfail':
  232. type = 'error';
  233. title.text(dashboardLang.get('notice.loginfail.title'));
  234. text.text(dashboardLang.get('notice.loginfail.text'));
  235. break;
  236. case 'sysmessage':
  237. type = 'info';
  238. title.text(dashboardLang.get('notice.sysmessage.title'));
  239. text.html(dashboardLang.get('notice.sysmessage.text', true, $('<a target="_blank">').append(
  240. $('<code>').text('MediaWiki:Custom-RcGcDw')
  241. ).attr('href', args[1]), $('<code class="user-select">').text(args[0])));
  242. note = $('<a target="_blank">').text(args[1]).attr('href', args[1]);
  243. break;
  244. case 'mwversion':
  245. type = 'error';
  246. title.text(dashboardLang.get('notice.mwversion.title'));
  247. text.text(dashboardLang.get('notice.mwversion.text', false, args[0], args[1]));
  248. note = $('<a target="_blank">').text('https://www.mediawiki.org/wiki/MediaWiki_1.30').attr('href', 'https://www.mediawiki.org/wiki/MediaWiki_1.30');
  249. break;
  250. case 'nochange':
  251. type = 'info';
  252. title.text(dashboardLang.get('notice.nochange.title'));
  253. text.text(dashboardLang.get('notice.nochange.text'));
  254. break;
  255. case 'invalidusergroup':
  256. type = 'error';
  257. title.text(dashboardLang.get('notice.invalidusergroup.title'));
  258. text.text(dashboardLang.get('notice.invalidusergroup.text'));
  259. break;
  260. case 'noverify':
  261. type = 'info';
  262. title.text(dashboardLang.get('notice.noverify.title'));
  263. text.html(dashboardLang.get('notice.noverify.text', true, $('<code>').text('/verify')));
  264. break;
  265. case 'noslash':
  266. type = 'error';
  267. title.text(dashboardLang.get('notice.noslash.title'));
  268. text.text(dashboardLang.get('notice.noslash.text'));
  269. note = $('<a target="_blank">').text(dashboardLang.get('notice.noslash.note')).attr('href', `https://discord.com/api/oauth2/authorize?client_id=${process.env.bot}&scope=applications.commands&guild_id=${args[0]}`);
  270. break;
  271. case 'wikiblocked':
  272. type = 'error';
  273. title.text(dashboardLang.get('notice.wikiblocked.title'));
  274. text.text(dashboardLang.get('notice.wikiblocked.text', false, args[0]));
  275. if ( args[1] ) note = $('<div>').append(
  276. dashboardLang.get('notice.wikiblocked.note', true) + ' ',
  277. $('<code>').text(args[1])
  278. );
  279. break;
  280. case 'savefail':
  281. type = 'error';
  282. title.text(dashboardLang.get('notice.savefail.title'));
  283. text.text(dashboardLang.get('notice.savefail.text'));
  284. if ( typeof args[0] === 'string' ) {
  285. note = $('<div>').text(dashboardLang.get('notice.savefail.note_' + args[0]));
  286. }
  287. break;
  288. case 'movefail':
  289. type = 'info';
  290. title.text(dashboardLang.get('notice.movefail.title'));
  291. text.text(dashboardLang.get('notice.movefail.text'));
  292. note = $('<div>').text(dashboardLang.get('notice.movefail.note'));
  293. break;
  294. case 'refreshfail':
  295. type = 'error';
  296. title.text(dashboardLang.get('notice.refreshfail.title'));
  297. text.text(dashboardLang.get('notice.refreshfail.text'));
  298. break;
  299. case 'error':
  300. type = 'error';
  301. title.text(dashboardLang.get('notice.error.title'));
  302. text.text(dashboardLang.get('notice.error.text'));
  303. break;
  304. case 'readonly':
  305. type = 'info';
  306. title.text(dashboardLang.get('notice.readonly.title'));
  307. text.text(dashboardLang.get('notice.readonly.text'));
  308. break;
  309. default:
  310. return;
  311. }
  312. return $(`<div class="notice notice-${type}">`).append(
  313. title,
  314. text,
  315. note
  316. ).appendTo('#text #notices');
  317. }
  318. /**
  319. * HTML escape text
  320. * @param {String} text - The text to escape
  321. * @returns {String}
  322. */
  323. function escapeText(text) {
  324. return text.replace( /&/g, '&amp;' ).replace( /</g, '&lt;' ).replace( />/g, '&gt;' );
  325. }
  326. const permissions = {
  327. ADMINISTRATOR: 1 << 3,
  328. MANAGE_CHANNELS: 1 << 4,
  329. MANAGE_GUILD: 1 << 5,
  330. ADD_REACTIONS: 1 << 6,
  331. VIEW_CHANNEL: 1 << 10,
  332. SEND_MESSAGES: 1 << 11,
  333. MANAGE_MESSAGES: 1 << 13,
  334. EMBED_LINKS: 1 << 14,
  335. ATTACH_FILES: 1 << 15,
  336. READ_MESSAGE_HISTORY: 1 << 16,
  337. MENTION_EVERYONE: 1 << 17,
  338. USE_EXTERNAL_EMOJIS: 1 << 18,
  339. MANAGE_NICKNAMES: 1 << 27,
  340. MANAGE_ROLES: 1 << 28,
  341. MANAGE_WEBHOOKS: 1 << 29
  342. }
  343. /**
  344. * Check if a permission is included in the BitField
  345. * @param {String|Number} all - BitField of multiple permissions
  346. * @param {String[]} permission - Name of the permission to check for
  347. * @returns {Boolean}
  348. */
  349. function hasPerm(all = 0, ...permission) {
  350. if ( (all & permissions.ADMINISTRATOR) === permissions.ADMINISTRATOR ) return true;
  351. return permission.map( perm => {
  352. let bit = permissions[perm];
  353. return ( (all & bit) === bit );
  354. } ).every( perm => perm );
  355. }
  356. module.exports = {got, db, oauth, slashCommands, sessionData, settingsData, sendMsg, addWidgets, createNotice, escapeText, hasPerm};