parse_page.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. const cheerio = require('cheerio');
  2. const {toSection} = require('../util/wiki.js');
  3. const {htmlToPlain, htmlToDiscord, limitLength} = 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. var change = false;
  46. 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 => {
  47. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  48. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  49. if ( embed.backupDescription && embed.length < 5000 ) {
  50. embed.setDescription( embed.backupDescription );
  51. change = true;
  52. }
  53. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  54. embed.spliceFields( 0, 0, embed.backupField );
  55. change = true;
  56. }
  57. return;
  58. }
  59. var $ = cheerio.load(response.body.parse.text['*'].replace( /<br\/?>/g, '\n' ));
  60. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  61. var infobox = $('aside.portable-infobox');
  62. embed.fields.forEach( field => {
  63. if ( embed.length > 5400 ) return;
  64. if ( /^`.+`$/.test(field.name) ) {
  65. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  66. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  67. if ( label ) {
  68. label = htmlToPlain(label).trim();
  69. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  70. if ( label ) field.name = label;
  71. }
  72. }
  73. if ( /^`.+`$/.test(field.value) ) {
  74. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  75. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  76. if ( value ) {
  77. value = htmlToDiscord(value, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  78. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  79. if ( value ) field.value = value;
  80. }
  81. }
  82. } );
  83. change = true;
  84. }
  85. if ( embed.thumbnail?.url === thumbnail ) {
  86. var image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  87. if ( !image ) {
  88. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  89. img = $(img).prop('src')?.toLowerCase();
  90. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  91. } ).first().prop('src');
  92. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  93. img = $(img).prop('src')?.toLowerCase();
  94. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  95. } ).first().prop('src');
  96. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  97. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  98. } );
  99. }
  100. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  101. if ( thumbnail ) {
  102. embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  103. change = true;
  104. }
  105. }
  106. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  107. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  108. var section = $('h1, h2, h3, h4, h5, h6').children('span').filter( (i, span) => {
  109. return ( '#' + span.attribs.id === toSection(fragment) );
  110. } ).parent();
  111. if ( section.length ) {
  112. var sectionLevel = section[0].tagName.replace('h', '');
  113. var sectionContent = $('<div>').append(
  114. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  115. );
  116. section.find(removeClasses.join(', ')).remove();
  117. sectionContent.find(infoboxList.join(', ')).remove();
  118. sectionContent.find(removeClasses.join(', ')).remove();
  119. var name = htmlToPlain(section).trim();
  120. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  121. var value = htmlToDiscord(sectionContent, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  122. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  123. if ( name.length && value.length ) {
  124. embed.spliceFields( 0, 0, {name, value} );
  125. change = true;
  126. }
  127. else if ( embed.backupField ) {
  128. embed.spliceFields( 0, 0, embed.backupField );
  129. change = true;
  130. }
  131. }
  132. else if ( embed.backupField ) {
  133. embed.spliceFields( 0, 0, embed.backupField );
  134. change = true;
  135. }
  136. }
  137. if ( !embed.description && embed.length < 5000 ) {
  138. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  139. $('h1, h2, h3, h4, h5, h6').remove();
  140. $(infoboxList.join(', ')).remove();
  141. $(removeClasses.join(', '), $('.mw-parser-output')).not(keepMainPageTag.join(', ')).remove();
  142. var description = htmlToDiscord($.html(), wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  143. if ( description ) {
  144. if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  145. embed.setDescription( description );
  146. change = true;
  147. }
  148. else if ( embed.backupDescription ) {
  149. embed.setDescription( embed.backupDescription );
  150. change = true;
  151. }
  152. }
  153. }, error => {
  154. console.log( '- Error while parsing the page: ' + error );
  155. if ( embed.backupDescription && embed.length < 5000 ) {
  156. embed.setDescription( embed.backupDescription );
  157. change = true;
  158. }
  159. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  160. embed.spliceFields( 0, 0, embed.backupField );
  161. change = true;
  162. }
  163. } ).finally( () => {
  164. if ( change ) msg.edit( msg.content, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  165. } );
  166. }
  167. module.exports = parse_page;