functions.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 ( text.endsWith( ' ' ) && 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 ( text.endsWith( ' ' ) && htmltext.startsWith( ' ' ) ) htmltext = htmltext.replace( /^ +/, '' );
  307. text += escapeFormatting(htmltext, ...escapeArgs);
  308. }
  309. }
  310. },
  311. onclosetag: (tagname) => {
  312. if ( tagname === ignoredTag ) {
  313. ignoredTag = '';
  314. return;
  315. }
  316. if ( code ) {
  317. if ( tagname === 'code' ) {
  318. code = false;
  319. text += '`';
  320. }
  321. if ( tagname === 'pre' ) {
  322. code = false;
  323. text += '\n```';
  324. }
  325. return;
  326. }
  327. if ( syntaxhighlight && tagname === 'div' ) syntaxhighlight = '';
  328. if ( tagname === 'b' ) text += '**';
  329. if ( tagname === 'i' ) text += '*';
  330. if ( tagname === 's' ) text += '~~';
  331. if ( tagname === 'u' ) text += '__';
  332. if ( tagname === 'ul' ) listlevel--;
  333. if ( tagname === 'dl' ) listlevel--;
  334. if ( tagname === 'dt' ) text += '**';
  335. if ( tagname === 'h1' ) text += '__***';
  336. if ( tagname === 'h2' ) text += '__**';
  337. if ( tagname === 'h3' ) text += '**';
  338. if ( tagname === 'h4' ) text += '__';
  339. if ( tagname === 'h5' ) text += '*';
  340. if ( tagname === 'h6' ) text += '';
  341. if ( !pagelink ) return;
  342. if ( tagname === 'a' && href ) {
  343. if ( text.endsWith( '[' ) ) text = text.substring(0, text.length - 1);
  344. else text += '](<' + href + '>)';
  345. href = '';
  346. }
  347. },
  348. oncomment: (commenttext) => {
  349. if ( pagelink && /^(?:IW)?LINK'" \d+:\d+$/.test(commenttext) ) {
  350. text += '*UNKNOWN LINK*';
  351. }
  352. }
  353. } );
  354. parser.write( html );
  355. parser.end();
  356. return text;
  357. };
  358. /**
  359. * Escapes formatting.
  360. * @param {String} [text] - The text to modify.
  361. * @param {Boolean} [isMarkdown] - The text contains markdown links.
  362. * @param {Boolean} [keepLinks] - Don't escape non-markdown links.
  363. * @returns {String}
  364. */
  365. function escapeFormatting(text = '', isMarkdown = false, keepLinks = false) {
  366. if ( !isMarkdown ) text = text.replace( /[()\\]/g, '\\$&' );
  367. if ( !keepLinks ) text = text.replace( /\/\//g, '\\$&' );
  368. return text.replace( /[`_*~:<>{}@|]/g, '\\$&' );
  369. };
  370. /**
  371. * Limit text length without breaking link formatting.
  372. * @param {String} [text] - The text to modify.
  373. * @param {Number} [limit] - The character limit.
  374. * @param {Number} [maxExtra] - The maximal allowed character limit if needed.
  375. * @returns {String}
  376. */
  377. function limitLength(text = '', limit = 1000, maxExtra = 20) {
  378. var suffix = '\u2026';
  379. var link = null;
  380. var regex = /(?<!\\)\[((?:[^\[\]]|\\[\[\]])*?[^\\])\]\(<?(?:[^()]|\\[()])+?[^\\]>?\)/g;
  381. while ( ( link = regex.exec(text) ) !== null ) {
  382. if ( link.index < limit && link.index + link[0].length > limit ) {
  383. if ( link.index + link[0].length < limit + maxExtra ) suffix = link[0];
  384. else if ( link.index + link[1].length < limit + maxExtra ) suffix = link[1];
  385. if ( link.index + link[0].length < text.length ) suffix += '\u2026';
  386. limit = link.index;
  387. break;
  388. }
  389. else if ( link.index >= limit ) break;
  390. }
  391. return text.substring(0, limit) + suffix;
  392. };
  393. /**
  394. * Try to URI decode.
  395. * @param {String} m - The character to decode.
  396. * @returns {String}
  397. */
  398. function partialURIdecode(m) {
  399. var text = '';
  400. try {
  401. text = decodeURIComponent( m );
  402. }
  403. catch ( replaceError ) {
  404. if ( isDebug ) console.log( '- Failed to decode ' + m + ':' + replaceError );
  405. text = m;
  406. }
  407. return text;
  408. };
  409. /**
  410. * Allow users to delete their command responses.
  411. * @param {import('discord.js').Message} msg - The response.
  412. * @param {String} author - The user id.
  413. */
  414. function allowDelete(msg, author) {
  415. msg.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:300000} ).then( reaction => {
  416. if ( reaction.size ) {
  417. msg.delete().catch(log_error);
  418. }
  419. } );
  420. };
  421. module.exports = {
  422. got,
  423. parse_infobox,
  424. toFormatting,
  425. toMarkdown,
  426. toPlaintext,
  427. htmlToPlain,
  428. htmlToDiscord,
  429. escapeFormatting,
  430. limitLength,
  431. partialURIdecode,
  432. allowDelete
  433. };