parse_page.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. const cheerio = require('cheerio');
  2. const {toSection} = require('../util/wiki.js');
  3. const {htmlToPlain} = require('../util/functions.js');
  4. const infoboxList = [
  5. '.infobox',
  6. '.portable-infobox',
  7. '.infoboxtable',
  8. '.notaninfobox'
  9. ];
  10. const removeClasses = [
  11. 'table',
  12. 'div',
  13. 'script',
  14. 'input',
  15. 'style',
  16. 'script',
  17. 'noscript',
  18. 'ul.gallery',
  19. '.mw-editsection',
  20. 'sup.reference',
  21. 'ol.references',
  22. '.error',
  23. '.nomobile',
  24. '.noprint',
  25. '.noexcerpt',
  26. '.sortkey'
  27. ];
  28. const keepMainPageTag = [
  29. 'div.main-page-tag-lcs',
  30. 'div.lcs-container'
  31. ];
  32. /**
  33. * Parses a wiki page to get it's description.
  34. * @param {import('discord.js').Message} msg - The Discord message.
  35. * @param {String} title - The title of the page.
  36. * @param {import('discord.js').MessageEmbed} embed - The embed for the page.
  37. * @param {import('../util/wiki.js')} wiki - The wiki for the page.
  38. * @param {String} thumbnail - The default thumbnail for the wiki.
  39. * @param {String} [fragment] - The section title to embed.
  40. */
  41. function parse_page(msg, title, embed, wiki, thumbnail, fragment = '') {
  42. if ( !msg || ( embed.description && embed.thumbnail?.url !== thumbnail && !embed.brokenInfobox && !fragment ) ) {
  43. return;
  44. }
  45. got.get( wiki + 'api.php?action=parse&prop=text|images' + ( fragment ? '' : '&section=0' ) + '&disablelimitreport=true&disableeditsection=true&disabletoc=true&sectionpreview=true&page=' + encodeURIComponent( title ) + '&format=json' ).then( response => {
  46. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  47. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  48. return;
  49. }
  50. var change = false;
  51. var $ = cheerio.load(response.body.parse.text['*'].replace( /<br\/?>/g, '\n' ));
  52. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  53. var infobox = $('aside.portable-infobox');
  54. embed.fields.forEach( field => {
  55. if ( embed.length > 5500 ) return;
  56. if ( /^`.+`$/.test(field.name) ) {
  57. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  58. label = htmlToPlain(label).trim();
  59. if ( label.length > 50 ) label = label.substring(0, 50) + '\u2026';
  60. if ( label ) field.name = label;
  61. }
  62. if ( /^`.+`$/.test(field.value) ) {
  63. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  64. value = htmlToPlain(value).trim();
  65. if ( value.length > 250 ) value = value.substring(0, 250) + '\u2026';
  66. if ( value ) field.value = value;
  67. }
  68. } );
  69. change = true;
  70. }
  71. if ( embed.thumbnail?.url === thumbnail ) {
  72. var image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  73. if ( !image ) {
  74. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  75. img = $(img).prop('src')?.toLowerCase();
  76. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  77. } ).first().prop('src');
  78. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  79. img = $(img).prop('src')?.toLowerCase();
  80. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  81. } ).first().prop('src');
  82. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  83. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  84. } );
  85. }
  86. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  87. if ( thumbnail ) {
  88. embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  89. change = true;
  90. }
  91. }
  92. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  93. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  94. var section = $('h1, h2, h3, h4, h5, h6').children('span').filter( (i, span) => {
  95. return ( '#' + span.attribs.id === toSection(fragment) );
  96. } ).parent();
  97. if ( section.length ) {
  98. var sectionLevel = section[0].tagName.replace('h', '');
  99. var sectionContent = $('<div>').append(
  100. section.nextUntil([
  101. 'h1 span.mw-headline',
  102. 'h2 span.mw-headline',
  103. 'h3 span.mw-headline',
  104. 'h4 span.mw-headline',
  105. 'h5 span.mw-headline',
  106. 'h6 span.mw-headline'
  107. ].slice(0, sectionLevel).join(', '))
  108. );
  109. section.find(removeClasses.join(', ')).remove();
  110. sectionContent.find(infoboxList.join(', ')).remove();
  111. sectionContent.find(removeClasses.join(', ')).remove();
  112. var name = htmlToPlain(section).trim();
  113. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  114. var value = htmlToPlain(sectionContent).trim();
  115. if ( value.length > 1000 ) value = value.substring(0, 1000) + '\u2026';
  116. if ( name.length && value.length ) {
  117. embed.spliceFields( 0, 0, {name, value} );
  118. change = true;
  119. }
  120. }
  121. }
  122. if ( !embed.description && embed.length < 5000 ) {
  123. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  124. $('h1, h2, h3, h4, h5, h6').remove();
  125. $(infoboxList.join(', ')).remove();
  126. $(removeClasses.join(', '), $('.mw-parser-output')).not(keepMainPageTag.join(', ')).remove();
  127. var description = $.text().trim().replace( /\n{3,}/g, '\n\n' ).escapeFormatting();
  128. if ( description ) {
  129. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  130. embed.setDescription( description );
  131. change = true;
  132. }
  133. }
  134. if ( change ) msg.edit( msg.content, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  135. }, error => {
  136. console.log( '- Error while parsing the page: ' + error );
  137. } );
  138. }
  139. module.exports = parse_page;