util.js 14 KB

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