functions.js 16 KB

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