functions.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. const htmlparser = require('htmlparser2');
  2. const got = require('got').extend( {
  3. throwHttpErrors: false,
  4. timeout: 5000,
  5. headers: {
  6. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ')'
  7. },
  8. responseType: 'json'
  9. } );
  10. const slashCommands = require('../interactions/commands.json');
  11. /**
  12. * @type {Map<String, {state: String, wiki: String, channel: import('discord.js').TextChannel, user: String}>}
  13. */
  14. const oauthVerify = new Map();
  15. /**
  16. * Parse infobox content
  17. * @param {Object} infobox - The content of the infobox.
  18. * @param {import('discord.js').MessageEmbed} embed - The message embed.
  19. * @param {String} [thumbnail] - The default thumbnail for the wiki.
  20. * @param {String} [pagelink] - The article path for relative links.
  21. * @returns {import('discord.js').MessageEmbed?}
  22. */
  23. function parse_infobox(infobox, embed, thumbnail, pagelink = '') {
  24. if ( !infobox || embed.fields.length >= 25 || embed.length > 5400 ) return;
  25. if ( infobox.parser_tag_version === 2 ) {
  26. infobox.data.forEach( group => {
  27. parse_infobox(group, embed, thumbnail, pagelink);
  28. } );
  29. embed.fields = embed.fields.filter( (field, i, fields) => {
  30. if ( field.name !== '\u200b' || !field.value.startsWith( '__**' ) ) return true;
  31. return ( fields[i + 1]?.name && ( fields[i + 1].name !== '\u200b' || !fields[i + 1].value.startsWith( '__**' ) ) );
  32. } );
  33. return embed;
  34. }
  35. switch ( infobox.type ) {
  36. case 'data':
  37. var {label = '', value = '', source = '', 'item-name': name = ''} = infobox.data;
  38. label = htmlToPlain(label).trim();
  39. value = htmlToDiscord(value, pagelink).trim();
  40. if ( label.includes( '*UNKNOWN LINK*' ) ) {
  41. if ( !( source || name ) ) break;
  42. label = '`' + ( source || name ) + '`';
  43. embed.brokenInfobox = true;
  44. }
  45. if ( value.includes( '*UNKNOWN LINK*' ) ) {
  46. if ( !( source || name ) ) break;
  47. value = '`' + ( source || name ) + '`';
  48. embed.brokenInfobox = true;
  49. }
  50. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  51. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  52. if ( label && value ) embed.addField( label, value, true );
  53. break;
  54. case 'panel':
  55. var embedLength = embed.fields.length;
  56. infobox.data.value.forEach( group => {
  57. parse_infobox(group, embed, thumbnail, pagelink);
  58. } );
  59. embed.fields = embed.fields.filter( (field, i, fields) => {
  60. if ( i < embedLength || field.name !== '\u200b' ) return true;
  61. if ( !field.value.startsWith( '__**' ) ) return true;
  62. return ( fields[i + 1]?.name && fields[i + 1].name !== '\u200b' );
  63. } ).filter( (field, i, fields) => {
  64. if ( i < embedLength || field.name !== '\u200b' ) return true;
  65. if ( field.value.startsWith( '__**' ) ) return true;
  66. return ( fields[i + 1]?.name && ( fields[i + 1].name !== '\u200b' || !fields[i + 1].value.startsWith( '__**' ) ) );
  67. } );
  68. break;
  69. case 'section':
  70. var {label = ''} = infobox.data;
  71. label = htmlToPlain(label).trim();
  72. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  73. if ( label ) embed.addField( '\u200b', '**' + label + '**', false );
  74. case 'group':
  75. infobox.data.value.forEach( group => {
  76. parse_infobox(group, embed, thumbnail, pagelink);
  77. } );
  78. break;
  79. case 'header':
  80. var {value = ''} = infobox.data;
  81. value = htmlToPlain(value).trim();
  82. if ( value.length > 100 ) value = value.substring(0, 100) + '\u2026';
  83. if ( value ) embed.addField( '\u200b', '__**' + value + '**__', false );
  84. break;
  85. case 'image':
  86. if ( embed.thumbnail?.url !== thumbnail ) return;
  87. var image = infobox.data.find( img => {
  88. return ( /^(?:https?:)?\/\//.test(img.url) && /\.(?:png|jpg|jpeg|gif)$/.test(img.name) );
  89. } );
  90. if ( image ) embed.setThumbnail( image.url.replace( /^(?:https?:)?\/\//, 'https://' ) );
  91. break;
  92. }
  93. }
  94. /**
  95. * Make wikitext formatting usage.
  96. * @param {String} [text] - The text to modify.
  97. * @param {Boolean} [showEmbed] - If the text is used in an embed.
  98. * @param {import('./wiki.js')} [wiki] - The wiki.
  99. * @param {String} [title] - The page title.
  100. * @param {Boolean} [fullWikitext] - If the text can contain full wikitext.
  101. * @returns {String}
  102. */
  103. function toFormatting(text = '', showEmbed = false, wiki, title = '', fullWikitext = false) {
  104. if ( showEmbed ) return toMarkdown(text, wiki, title, fullWikitext);
  105. else return toPlaintext(text, fullWikitext);
  106. };
  107. /**
  108. * Turns wikitext formatting into markdown.
  109. * @param {String} [text] - The text to modify.
  110. * @param {import('./wiki.js')} wiki - The wiki.
  111. * @param {String} [title] - The page title.
  112. * @param {Boolean} [fullWikitext] - If the text can contain full wikitext.
  113. * @returns {String}
  114. */
  115. function toMarkdown(text = '', wiki, title = '', fullWikitext = false) {
  116. text = text.replace( /[()\\]/g, '\\$&' );
  117. var link = null;
  118. var regex = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g;
  119. while ( ( link = regex.exec(text) ) !== null ) {
  120. var pagetitle = ( link[1] || link[2] );
  121. var page = wiki.toLink(( /^[#\/]/.test(pagetitle) ? title + ( pagetitle.startsWith( '/' ) ? pagetitle : '' ) : pagetitle ), '', ( pagetitle.startsWith( '#' ) ? pagetitle.substring(1) : '' ), true);
  122. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + page + ')' );
  123. }
  124. if ( title !== '' ) {
  125. regex = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g;
  126. while ( ( link = regex.exec(text) ) !== null ) {
  127. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink(title, '', link[1], true) + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  128. }
  129. }
  130. if ( fullWikitext ) {
  131. regex = /\[(?:https?:)?\/\/([^ ]+) ([^\]]+)\]/g;
  132. while ( ( link = regex.exec(text) ) !== null ) {
  133. text = text.replaceSave( link[0], '[' + link[2] + '](https://' + link[1] + ')' );
  134. }
  135. return htmlToDiscord(text, '', true, true).replaceSave( /'''/g, '**' ).replaceSave( /''/g, '*' );
  136. }
  137. return escapeFormatting(text, true);
  138. };
  139. /**
  140. * Removes wikitext formatting.
  141. * @param {String} [text] - The text to modify.
  142. * @param {Boolean} [fullWikitext] - If the text can contain full wikitext.
  143. * @returns {String}
  144. */
  145. function toPlaintext(text = '', fullWikitext = false) {
  146. text = text.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' );
  147. if ( fullWikitext ) {
  148. return htmlToDiscord( text.replace( /\[(?:https?:)?\/\/(?:[^ ]+) ([^\]]+)\]/g, '$1' ) );
  149. }
  150. else return escapeFormatting(text);
  151. };
  152. /**
  153. * Change HTML text to plain text.
  154. * @param {String} html - The text in HTML.
  155. * @returns {String}
  156. */
  157. function htmlToPlain(html) {
  158. var text = '';
  159. var ignoredTag = '';
  160. var parser = new htmlparser.Parser( {
  161. onopentag: (tagname, attribs) => {
  162. if ( tagname === 'sup' && attribs.class === 'reference' ) ignoredTag = 'sup';
  163. if ( tagname === 'span' && attribs.class === 'smwttcontent' ) ignoredTag = 'span';
  164. },
  165. ontext: (htmltext) => {
  166. if ( !ignoredTag ) {
  167. htmltext = htmltext.replace( /[\r\n\t ]+/g, ' ' );
  168. if ( /[\n ]$/.test(text) && htmltext.startsWith( ' ' ) ) htmltext = htmltext.replace( /^ +/, '' );
  169. text += escapeFormatting(htmltext);
  170. }
  171. },
  172. onclosetag: (tagname) => {
  173. if ( tagname === ignoredTag ) ignoredTag = '';
  174. }
  175. } );
  176. parser.write( html );
  177. parser.end();
  178. return text;
  179. };
  180. /**
  181. * Change HTML text to markdown text.
  182. * @param {String} html - The text in HTML.
  183. * @param {String} [pagelink] - The article path for relative links.
  184. * @param {Boolean[]} [escapeArgs] - Arguments for the escaping of text formatting.
  185. * @returns {String}
  186. */
  187. function htmlToDiscord(html, pagelink = '', ...escapeArgs) {
  188. var text = '';
  189. var code = false;
  190. var href = '';
  191. var ignoredTag = '';
  192. var syntaxhighlight = '';
  193. var listlevel = -1;
  194. var parser = new htmlparser.Parser( {
  195. onopentag: (tagname, attribs) => {
  196. if ( ignoredTag || code ) return;
  197. if ( tagname === 'sup' && attribs.class === 'reference' ) ignoredTag = 'sup';
  198. if ( tagname === 'span' && attribs.class === 'smwttcontent' ) ignoredTag = 'span';
  199. if ( tagname === 'code' ) {
  200. code = true;
  201. text += '`';
  202. }
  203. if ( tagname === 'pre' ) {
  204. code = true;
  205. text += '```' + syntaxhighlight + '\n';
  206. }
  207. if ( tagname === 'div' && attribs.class ) {
  208. let classes = attribs.class.split(' ');
  209. if ( classes.includes( 'mw-highlight' ) ) {
  210. syntaxhighlight = ( classes.find( syntax => syntax.startsWith( 'mw-highlight-lang-' ) )?.replace( 'mw-highlight-lang-', '' ) || '' );
  211. }
  212. }
  213. if ( tagname === 'b' ) text += '**';
  214. if ( tagname === 'i' ) text += '*';
  215. if ( tagname === 's' ) text += '~~';
  216. if ( tagname === 'u' ) text += '__';
  217. if ( tagname === 'br' ) {
  218. text += '\n';
  219. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel + 3);
  220. }
  221. if ( tagname === 'hr' ) {
  222. text = text.replace( / +$/, '' );
  223. if ( !text.endsWith( '\n' ) ) text += '\n';
  224. text += '─'.repeat(10) + '\n';
  225. }
  226. if ( tagname === 'p' && !text.endsWith( '\n' ) ) text += '\n';
  227. if ( tagname === 'ul' ) listlevel++;
  228. if ( tagname === 'li' ) {
  229. text = text.replace( / +$/, '' );
  230. if ( !text.endsWith( '\n' ) ) text += '\n';
  231. if ( attribs.class !== 'mw-empty-elt' ) {
  232. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel);
  233. text += '• ';
  234. }
  235. }
  236. if ( tagname === 'dl' ) listlevel++;
  237. if ( tagname === 'dt' ) {
  238. text = text.replace( / +$/, '' );
  239. if ( !text.endsWith( '\n' ) ) text += '\n';
  240. if ( attribs.class !== 'mw-empty-elt' ) {
  241. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel);
  242. text += '**';
  243. }
  244. }
  245. if ( tagname === 'dd' ) {
  246. text = text.replace( / +$/, '' );
  247. if ( !text.endsWith( '\n' ) ) text += '\n';
  248. if ( listlevel > -1 && attribs.class !== 'mw-empty-elt' ) text += '\u200b '.repeat(4 * (listlevel + 1));
  249. }
  250. if ( tagname === 'img' ) {
  251. if ( attribs.alt && attribs.src ) {
  252. let showAlt = true;
  253. if ( attribs['data-image-name'] === attribs.alt ) showAlt = false;
  254. else {
  255. let regex = new RegExp( '/([\\da-f])/\\1[\\da-f]/' + attribs.alt.replace( / /g, '_' ).replace( /\W/g, '\\$&' ) + '(?:/|\\?|$)' );
  256. if ( attribs.src.startsWith( 'data:' ) && attribs['data-src'] ) attribs.src = attribs['data-src'];
  257. if ( regex.test(attribs.src.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode )) ) showAlt = false;
  258. }
  259. if ( showAlt ) {
  260. if ( href && !code ) attribs.alt = attribs.alt.replace( /[\[\]]/g, '\\$&' );
  261. if ( code ) text += attribs.alt.replace( /`/g, 'ˋ' );
  262. else text += escapeFormatting(attribs.alt, ...escapeArgs);
  263. }
  264. }
  265. }
  266. if ( tagname === 'h1' ) {
  267. text = text.replace( / +$/, '' );
  268. if ( !text.endsWith( '\n' ) ) text += '\n';
  269. text += '***__';
  270. }
  271. if ( tagname === 'h2' ) {
  272. text = text.replace( / +$/, '' );
  273. if ( !text.endsWith( '\n' ) ) text += '\n';
  274. text += '**__';
  275. }
  276. if ( tagname === 'h3' ) {
  277. text = text.replace( / +$/, '' );
  278. if ( !text.endsWith( '\n' ) ) text += '\n';
  279. text += '**';
  280. }
  281. if ( tagname === 'h4' ) {
  282. text = text.replace( / +$/, '' );
  283. if ( !text.endsWith( '\n' ) ) text += '\n';
  284. text += '__';
  285. }
  286. if ( tagname === 'h5' ) {
  287. text = text.replace( / +$/, '' );
  288. if ( !text.endsWith( '\n' ) ) text += '\n';
  289. text += '*';
  290. }
  291. if ( tagname === 'h6' ) {
  292. text = text.replace( / +$/, '' );
  293. if ( !text.endsWith( '\n' ) ) text += '\n';
  294. text += '';
  295. }
  296. if ( !pagelink ) return;
  297. if ( tagname === 'a' && attribs.href && attribs.class !== 'new' && /^(?:(?:https?:)?\/\/|\/|#)/.test(attribs.href) ) {
  298. href = new URL(attribs.href, pagelink).href.replace( /[()]/g, '\\$&' );
  299. if ( text.endsWith( '](<' + href + '>)' ) ) {
  300. text = text.substring(0, text.length - ( href.length + 5 ));
  301. }
  302. else text += '[';
  303. }
  304. },
  305. ontext: (htmltext) => {
  306. if ( !ignoredTag ) {
  307. if ( href && !code ) htmltext = htmltext.replace( /[\[\]]/g, '\\$&' );
  308. if ( code ) text += htmltext.replace( /`/g, 'ˋ' );
  309. else {
  310. htmltext = htmltext.replace( /[\r\n\t ]+/g, ' ' );
  311. if ( /[\n ]$/.test(text) && htmltext.startsWith( ' ' ) ) {
  312. htmltext = htmltext.replace( /^ +/, '' );
  313. }
  314. text += escapeFormatting(htmltext, ...escapeArgs);
  315. }
  316. }
  317. },
  318. onclosetag: (tagname) => {
  319. if ( tagname === ignoredTag ) {
  320. ignoredTag = '';
  321. return;
  322. }
  323. if ( code ) {
  324. if ( tagname === 'code' ) {
  325. code = false;
  326. text += '`';
  327. }
  328. if ( tagname === 'pre' ) {
  329. code = false;
  330. text += '\n```';
  331. }
  332. return;
  333. }
  334. if ( syntaxhighlight && tagname === 'div' ) syntaxhighlight = '';
  335. if ( tagname === 'b' ) text += '**';
  336. if ( tagname === 'i' ) text += '*';
  337. if ( tagname === 's' ) text += '~~';
  338. if ( tagname === 'u' ) text += '__';
  339. if ( tagname === 'ul' ) listlevel--;
  340. if ( tagname === 'dl' ) listlevel--;
  341. if ( tagname === 'dt' ) text += '**';
  342. if ( tagname === 'h1' ) text += '__***';
  343. if ( tagname === 'h2' ) text += '__**';
  344. if ( tagname === 'h3' ) text += '**';
  345. if ( tagname === 'h4' ) text += '__';
  346. if ( tagname === 'h5' ) text += '*';
  347. if ( tagname === 'h6' ) text += '';
  348. if ( !pagelink ) return;
  349. if ( tagname === 'a' && href ) {
  350. if ( text.endsWith( '[' ) ) text = text.substring(0, text.length - 1);
  351. else text += '](<' + href + '>)';
  352. href = '';
  353. }
  354. },
  355. oncomment: (commenttext) => {
  356. if ( pagelink && /^(?:IW)?LINK'" \d+:\d+$/.test(commenttext) ) {
  357. text += '*UNKNOWN LINK*';
  358. }
  359. }
  360. } );
  361. parser.write( html );
  362. parser.end();
  363. return text;
  364. };
  365. /**
  366. * Escapes formatting.
  367. * @param {String} [text] - The text to modify.
  368. * @param {Boolean} [isMarkdown] - The text contains markdown links.
  369. * @param {Boolean} [keepLinks] - Don't escape non-markdown links.
  370. * @returns {String}
  371. */
  372. function escapeFormatting(text = '', isMarkdown = false, keepLinks = false) {
  373. if ( !isMarkdown ) text = text.replace( /\\/g, '\\\\' ).replace( /\]\(/g, ']\\(' );
  374. if ( !keepLinks ) text = text.replace( /\/\//g, '/\\/' );
  375. return text.replace( /[`_*~:<>{}@|]/g, '\\$&' );
  376. };
  377. /**
  378. * Limit text length without breaking link formatting.
  379. * @param {String} [text] - The text to modify.
  380. * @param {Number} [limit] - The character limit.
  381. * @param {Number} [maxExtra] - The maximal allowed character limit if needed.
  382. * @returns {String}
  383. */
  384. function limitLength(text = '', limit = 1000, maxExtra = 20) {
  385. var suffix = '\u2026';
  386. var link = null;
  387. var regex = /(?<!\\)\[((?:[^\[\]]|\\[\[\]])*?[^\\])\]\(<?(?:[^()]|\\[()])+?[^\\]>?\)/g;
  388. while ( ( link = regex.exec(text) ) !== null ) {
  389. if ( link.index < limit && link.index + link[0].length > limit ) {
  390. if ( link.index + link[0].length < limit + maxExtra ) suffix = link[0];
  391. else if ( link.index + link[1].length < limit + maxExtra ) suffix = link[1];
  392. if ( link.index + link[0].length < text.length ) suffix += '\u2026';
  393. limit = link.index;
  394. break;
  395. }
  396. else if ( link.index >= limit ) break;
  397. }
  398. return text.substring(0, limit) + suffix;
  399. };
  400. /**
  401. * Try to URI decode.
  402. * @param {String} m - The character to decode.
  403. * @returns {String}
  404. */
  405. function partialURIdecode(m) {
  406. var text = '';
  407. try {
  408. text = decodeURIComponent( m );
  409. }
  410. catch ( replaceError ) {
  411. if ( isDebug ) console.log( '- Failed to decode ' + m + ':' + replaceError );
  412. text = m;
  413. }
  414. return text;
  415. };
  416. /**
  417. * Allow users to delete their command responses.
  418. * @param {import('discord.js').Message} msg - The response.
  419. * @param {String} author - The user id.
  420. */
  421. function allowDelete(msg, author) {
  422. msg.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:300000} ).then( reaction => {
  423. if ( reaction.size ) {
  424. msg.delete().catch(log_error);
  425. }
  426. } );
  427. };
  428. /**
  429. * Sends an interaction response.
  430. * @param {Object} interaction - The interaction.
  431. * @param {Object} message - The message.
  432. * @param {String} message.content - The message content.
  433. * @param {{parse: String[], roles?: String[], users?: String[]}} message.allowed_mentions - The allowed mentions.
  434. * @param {import('discord.js').TextChannel} channel - The channel for the interaction.
  435. * @param {Boolean} [letDelete] - Let the interaction user delete the message.
  436. * @returns {Promise<import('discord.js').Message?>}
  437. */
  438. function sendMessage(interaction, message, channel, letDelete = true) {
  439. return interaction.client.api.webhooks(interaction.application_id, interaction.token).messages('@original').patch( {
  440. data: message
  441. } ).then( msg => {
  442. if ( !channel ) return;
  443. var responseMessage = channel.messages.add(msg);
  444. if ( letDelete ) allowDelete(responseMessage, ( interaction.member?.user.id || interaction.user.id ));
  445. return responseMessage;
  446. }, log_error );
  447. };
  448. module.exports = {
  449. got,
  450. slashCommands,
  451. oauthVerify,
  452. parse_infobox,
  453. toFormatting,
  454. toMarkdown,
  455. toPlaintext,
  456. htmlToPlain,
  457. htmlToDiscord,
  458. escapeFormatting,
  459. limitLength,
  460. partialURIdecode,
  461. allowDelete,
  462. sendMessage
  463. };