util.js 12 KB

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