functions.js 16 KB

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