functions.js 17 KB

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