util.js 11 KB

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