parse_page.js 5.4 KB

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