functions.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 reference = false;
  155. var parser = new htmlparser.Parser( {
  156. onopentag: (tagname, attribs) => {
  157. if ( tagname === 'sup' && attribs.class === 'reference' ) reference = true;
  158. },
  159. ontext: (htmltext) => {
  160. if ( !reference ) text += escapeFormatting(htmltext);
  161. },
  162. onclosetag: (tagname) => {
  163. if ( tagname === 'sup' ) reference = false;
  164. }
  165. } );
  166. parser.write( html );
  167. parser.end();
  168. return text;
  169. };
  170. /**
  171. * Change HTML text to markdown text.
  172. * @param {String} html - The text in HTML.
  173. * @param {String} [pagelink] - The article path for relative links.
  174. * @param {Boolean[]} [escapeArgs] - Arguments for the escaping of text formatting.
  175. * @returns {String}
  176. */
  177. function htmlToDiscord(html, pagelink = '', ...escapeArgs) {
  178. var text = '';
  179. var code = false;
  180. var href = '';
  181. var reference = false;
  182. var listlevel = -1;
  183. var parser = new htmlparser.Parser( {
  184. onopentag: (tagname, attribs) => {
  185. if ( code ) return;
  186. if ( tagname === 'code' ) {
  187. code = true;
  188. text += '`';
  189. }
  190. if ( tagname === 'pre' ) {
  191. code = true;
  192. text += '```\n';
  193. }
  194. if ( tagname === 'b' ) text += '**';
  195. if ( tagname === 'i' ) text += '*';
  196. if ( tagname === 's' ) text += '~~';
  197. if ( tagname === 'u' ) text += '__';
  198. if ( tagname === 'sup' && attribs.class === 'reference' ) reference = true;
  199. if ( tagname === 'br' ) {
  200. text += '\n';
  201. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel + 3);
  202. }
  203. if ( tagname === 'hr' ) {
  204. text = text.replace( / +$/, '' );
  205. if ( !text.endsWith( '\n' ) ) text += '\n';
  206. text += '─'.repeat(10) + '\n';
  207. }
  208. if ( tagname === 'p' && !text.endsWith( '\n' ) ) text += '\n';
  209. if ( tagname === 'ul' ) listlevel++;
  210. if ( tagname === 'li' ) {
  211. text = text.replace( / +$/, '' );
  212. if ( !text.endsWith( '\n' ) ) text += '\n';
  213. if ( attribs.class !== 'mw-empty-elt' ) {
  214. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel);
  215. text += '• ';
  216. }
  217. }
  218. if ( tagname === 'dl' ) listlevel++;
  219. if ( tagname === 'dt' ) {
  220. text = text.replace( / +$/, '' );
  221. if ( !text.endsWith( '\n' ) ) text += '\n';
  222. if ( attribs.class !== 'mw-empty-elt' ) {
  223. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel);
  224. text += '**';
  225. }
  226. }
  227. if ( tagname === 'dd' ) {
  228. text = text.replace( / +$/, '' );
  229. if ( !text.endsWith( '\n' ) ) text += '\n';
  230. if ( listlevel > -1 && attribs.class !== 'mw-empty-elt' ) text += '\u200b '.repeat(4 * (listlevel + 1));
  231. }
  232. if ( tagname === 'img' ) {
  233. if ( attribs.alt && attribs.src && !reference ) {
  234. let showAlt = true;
  235. if ( attribs['data-image-name'] === attribs.alt ) showAlt = false;
  236. else {
  237. let regex = new RegExp( '/([\\da-f])/\\1[\\da-f]/' + attribs.alt.replace( / /g, '_' ).replace( /\W/g, '\\$&' ) + '(?:/|\\?|$)' );
  238. if ( attribs.src.startsWith( 'data:' ) && attribs['data-src'] ) attribs.src = attribs['data-src'];
  239. if ( regex.test(attribs.src.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode )) ) showAlt = false;
  240. }
  241. if ( showAlt ) {
  242. if ( href && !code ) attribs.alt = attribs.alt.replace( /[\[\]]/g, '\\$&' );
  243. if ( code ) text += attribs.alt.replace( /`/g, 'ˋ' );
  244. else text += escapeFormatting(attribs.alt, ...escapeArgs);
  245. }
  246. }
  247. }
  248. if ( tagname === 'h1' ) {
  249. text = text.replace( / +$/, '' );
  250. if ( !text.endsWith( '\n' ) ) text += '\n';
  251. text += '***__';
  252. }
  253. if ( tagname === 'h2' ) {
  254. text = text.replace( / +$/, '' );
  255. if ( !text.endsWith( '\n' ) ) text += '\n';
  256. text += '**__';
  257. }
  258. if ( tagname === 'h3' ) {
  259. text = text.replace( / +$/, '' );
  260. if ( !text.endsWith( '\n' ) ) text += '\n';
  261. text += '**';
  262. }
  263. if ( tagname === 'h4' ) {
  264. text = text.replace( / +$/, '' );
  265. if ( !text.endsWith( '\n' ) ) text += '\n';
  266. text += '__';
  267. }
  268. if ( tagname === 'h5' ) {
  269. text = text.replace( / +$/, '' );
  270. if ( !text.endsWith( '\n' ) ) text += '\n';
  271. text += '*';
  272. }
  273. if ( tagname === 'h6' ) {
  274. text = text.replace( / +$/, '' );
  275. if ( !text.endsWith( '\n' ) ) text += '\n';
  276. text += '';
  277. }
  278. if ( !pagelink ) return;
  279. if ( tagname === 'a' && attribs.href && attribs.class !== 'new' && /^(?:(?:https?:)?\/\/|\/|#)/.test(attribs.href) ) {
  280. href = new URL(attribs.href, pagelink).href;
  281. text += '[';
  282. }
  283. },
  284. ontext: (htmltext) => {
  285. if ( !reference ) {
  286. if ( href && !code ) htmltext = htmltext.replace( /[\[\]]/g, '\\$&' );
  287. if ( code ) text += htmltext.replace( /`/g, 'ˋ' );
  288. else text += escapeFormatting(htmltext, ...escapeArgs);
  289. }
  290. },
  291. onclosetag: (tagname) => {
  292. if ( code ) {
  293. if ( tagname === 'code' ) {
  294. code = false;
  295. text += '`';
  296. }
  297. if ( tagname === 'pre' ) {
  298. code = false;
  299. text += '\n```';
  300. }
  301. return;
  302. }
  303. if ( tagname === 'b' ) text += '**';
  304. if ( tagname === 'i' ) text += '*';
  305. if ( tagname === 's' ) text += '~~';
  306. if ( tagname === 'u' ) text += '__';
  307. if ( tagname === 'sup' ) reference = false;
  308. if ( tagname === 'ul' ) listlevel--;
  309. if ( tagname === 'dl' ) listlevel--;
  310. if ( tagname === 'dt' ) text += '**';
  311. if ( tagname === 'h1' ) text += '__***';
  312. if ( tagname === 'h2' ) text += '__**';
  313. if ( tagname === 'h3' ) text += '**';
  314. if ( tagname === 'h4' ) text += '__';
  315. if ( tagname === 'h5' ) text += '*';
  316. if ( tagname === 'h6' ) text += '';
  317. if ( !pagelink ) return;
  318. if ( tagname === 'a' && href ) {
  319. if ( text.endsWith( '[' ) ) text = text.substring(0, text.length - 1);
  320. else text += '](<' + href.replace( /[()]/g, '\\$&' ) + '>)';
  321. href = '';
  322. }
  323. },
  324. oncomment: (commenttext) => {
  325. if ( pagelink && /^LINK'" \d+:\d+$/.test(commenttext) ) {
  326. text += '*UNKNOWN LINK*';
  327. }
  328. }
  329. } );
  330. parser.write( html );
  331. parser.end();
  332. return text;
  333. };
  334. /**
  335. * Escapes formatting.
  336. * @param {String} [text] - The text to modify.
  337. * @param {Boolean} [isMarkdown] - The text contains markdown links.
  338. * @param {Boolean} [keepLinks] - Don't escape non-markdown links.
  339. * @returns {String}
  340. */
  341. function escapeFormatting(text = '', isMarkdown = false, keepLinks = false) {
  342. if ( !isMarkdown ) text = text.replace( /[()\\]/g, '\\$&' );
  343. if ( !keepLinks ) text = text.replace( /\/\//g, '\\$&' );
  344. return text.replace( /[`_*~:<>{}@|]/g, '\\$&' );
  345. };
  346. /**
  347. * Limit text length without breaking link formatting.
  348. * @param {String} [text] - The text to modify.
  349. * @param {Number} [limit] - The character limit.
  350. * @param {Number} [maxExtra] - The maximal allowed character limit if needed.
  351. * @returns {String}
  352. */
  353. function limitLength(text = '', limit = 1000, maxExtra = 20) {
  354. var suffix = '\u2026';
  355. var link = null;
  356. var regex = /(?<!\\)\[((?:[^\[\]]|\\[\[\]])+?[^\\])\]\(<?(?:[^()]|\\[()])+?[^\\]>?\)/g;
  357. while ( ( link = regex.exec(text) ) !== null ) {
  358. if ( link.index < limit && link.index + link[0].length > limit ) {
  359. if ( link.index + link[0].length < limit + maxExtra ) suffix = link[0];
  360. else if ( link.index + link[1].length < limit + maxExtra ) suffix = link[1];
  361. if ( link.index + link[0].length < text.length ) suffix += '\u2026';
  362. limit = link.index;
  363. break;
  364. }
  365. else if ( link.index >= limit ) break;
  366. }
  367. return text.substring(0, limit) + suffix;
  368. };
  369. /**
  370. * Try to URI decode.
  371. * @param {String} m - The character to decode.
  372. * @returns {String}
  373. */
  374. function partialURIdecode(m) {
  375. var text = '';
  376. try {
  377. text = decodeURIComponent( m );
  378. }
  379. catch ( replaceError ) {
  380. if ( isDebug ) console.log( '- Failed to decode ' + m + ':' + replaceError );
  381. text = m;
  382. }
  383. return text;
  384. };
  385. module.exports = {
  386. got,
  387. parse_infobox,
  388. toFormatting,
  389. toMarkdown,
  390. toPlaintext,
  391. htmlToPlain,
  392. htmlToDiscord,
  393. escapeFormatting,
  394. limitLength,
  395. partialURIdecode
  396. };