parse_page.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. const cheerio = require('cheerio');
  2. const {toSection} = require('../util/wiki.js');
  3. const {htmlToPlain, htmlToDiscord, limitLength} = require('../util/functions.js');
  4. // Max length of 10 characters
  5. const contentModels = {
  6. Scribunto: 'lua',
  7. javascript: 'js',
  8. json: 'json',
  9. css: 'css'
  10. };
  11. const contentFormats = {
  12. 'application/json': 'json',
  13. 'text/javascript': 'js',
  14. 'text/css': 'css'
  15. };
  16. // Max length of 10 characters
  17. const infoboxList = [
  18. '.infobox',
  19. '.portable-infobox',
  20. '.infoboxtable',
  21. '.notaninfobox'
  22. ];
  23. const removeClasses = [
  24. 'table',
  25. 'div',
  26. 'script',
  27. 'input',
  28. 'style',
  29. 'script',
  30. 'noscript',
  31. 'ul.gallery',
  32. '.mw-editsection',
  33. 'sup.reference',
  34. 'ol.references',
  35. '.error',
  36. '.nomobile',
  37. '.noprint',
  38. '.noexcerpt',
  39. '.sortkey'
  40. ];
  41. const keepMainPageTag = [
  42. 'div.main-page-tag-lcs',
  43. 'div.lcs-container'
  44. ];
  45. /**
  46. * Parses a wiki page to get it's description.
  47. * @param {import('discord.js').Message} msg - The Discord message.
  48. * @param {String} content - The content for the message.
  49. * @param {import('discord.js').MessageEmbed} embed - The embed for the message.
  50. * @param {import('../util/wiki.js')} wiki - The wiki for the page.
  51. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  52. * @param {Object} querypage - The details of the page.
  53. * @param {String} querypage.title - The title of the page.
  54. * @param {String} querypage.contentmodel - The content model of the page.
  55. * @param {String} thumbnail - The default thumbnail for the wiki.
  56. * @param {String} [fragment] - The section title to embed.
  57. */
  58. function parse_page(msg, content, embed, wiki, reaction, {title, contentmodel}, thumbnail, fragment = '') {
  59. if ( !msg?.showEmbed?.() || ( embed.description && embed.thumbnail?.url !== thumbnail && !embed.brokenInfobox && !fragment ) ) {
  60. msg.sendChannel( content, {embed} );
  61. if ( reaction ) reaction.removeEmoji();
  62. return;
  63. }
  64. if ( contentmodel !== 'wikitext' ) return got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=content&rvslots=main&converttitles=true&titles=%1F' + encodeURIComponent( title ) + '&format=json' ).then( response => {
  65. var body = response.body;
  66. if ( body && body.warnings ) log_warn(body.warnings);
  67. var revision = Object.values(( body?.query?.pages || {} ))?.[0]?.revisions?.[0];
  68. revision = ( revision?.slots?.main || revision );
  69. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !revision?.['*'] ) {
  70. console.log( '- ' + response.statusCode + ': Error while getting the page content: ' + ( body && body.error && body.error.info ) );
  71. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  72. embed.spliceFields( 0, 0, embed.backupField );
  73. }
  74. if ( embed.backupDescription && embed.length < 5000 ) {
  75. embed.setDescription( embed.backupDescription );
  76. }
  77. return;
  78. }
  79. if ( !embed.description && embed.length < 4000 ) {
  80. var description = revision['*'];
  81. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  82. if ( regex ) {
  83. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  84. if ( descArray.length ) {
  85. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  86. if ( description ) {
  87. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  88. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  89. embed.setDescription( description );
  90. }
  91. }
  92. }
  93. else if ( description.trim() ) {
  94. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  95. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  96. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  97. embed.setDescription( description );
  98. }
  99. else if ( embed.backupDescription ) {
  100. embed.setDescription( embed.backupDescription );
  101. }
  102. }
  103. }, error => {
  104. console.log( '- Error while getting the page content: ' + error );
  105. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  106. embed.spliceFields( 0, 0, embed.backupField );
  107. }
  108. if ( embed.backupDescription && embed.length < 5000 ) {
  109. embed.setDescription( embed.backupDescription );
  110. }
  111. } ).finally( () => {
  112. msg.sendChannel( content, {embed} );
  113. if ( reaction ) reaction.removeEmoji();
  114. } );
  115. 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 => {
  116. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  117. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  118. if ( embed.backupDescription && embed.length < 5000 ) {
  119. embed.setDescription( embed.backupDescription );
  120. }
  121. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  122. embed.spliceFields( 0, 0, embed.backupField );
  123. }
  124. return;
  125. }
  126. var $ = cheerio.load(response.body.parse.text['*'].replace( /<br\/?>/g, '\n' ));
  127. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  128. var infobox = $('aside.portable-infobox');
  129. embed.fields.forEach( field => {
  130. if ( embed.length > 5400 ) return;
  131. if ( /^`.+`$/.test(field.name) ) {
  132. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  133. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  134. if ( label ) {
  135. label = htmlToPlain(label).trim();
  136. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  137. if ( label ) field.name = label;
  138. }
  139. }
  140. if ( /^`.+`$/.test(field.value) ) {
  141. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  142. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  143. if ( value ) {
  144. value = htmlToDiscord(value, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  145. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  146. if ( value ) field.value = value;
  147. }
  148. }
  149. } );
  150. }
  151. if ( embed.thumbnail?.url === thumbnail ) {
  152. var image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  153. if ( !image ) {
  154. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  155. img = $(img).prop('src')?.toLowerCase();
  156. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  157. } ).first().prop('src');
  158. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  159. img = $(img).prop('src')?.toLowerCase();
  160. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  161. } ).first().prop('src');
  162. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  163. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  164. } );
  165. }
  166. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  167. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  168. }
  169. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  170. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  171. var section = $('h1, h2, h3, h4, h5, h6').children('span').filter( (i, span) => {
  172. return ( '#' + span.attribs.id === toSection(fragment) );
  173. } ).parent();
  174. if ( section.length ) {
  175. var sectionLevel = section[0].tagName.replace('h', '');
  176. var sectionContent = $('<div>').append(
  177. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  178. );
  179. section.find(removeClasses.join(', ')).remove();
  180. sectionContent.find(infoboxList.join(', ')).remove();
  181. sectionContent.find(removeClasses.join(', ')).remove();
  182. var name = htmlToPlain(section).trim();
  183. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  184. var value = htmlToDiscord(sectionContent, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  185. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  186. if ( name.length && value.length ) {
  187. embed.spliceFields( 0, 0, {name, value} );
  188. }
  189. else if ( embed.backupField ) {
  190. embed.spliceFields( 0, 0, embed.backupField );
  191. }
  192. }
  193. else if ( embed.backupField ) {
  194. embed.spliceFields( 0, 0, embed.backupField );
  195. }
  196. }
  197. if ( !embed.description && embed.length < 5000 ) {
  198. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  199. $('h1, h2, h3, h4, h5, h6').remove();
  200. $(infoboxList.join(', ')).remove();
  201. $(removeClasses.join(', '), $('.mw-parser-output')).not(keepMainPageTag.join(', ')).remove();
  202. var description = htmlToDiscord($.html(), wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  203. if ( description ) {
  204. if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  205. embed.setDescription( description );
  206. }
  207. else if ( embed.backupDescription ) {
  208. embed.setDescription( embed.backupDescription );
  209. }
  210. }
  211. }, error => {
  212. console.log( '- Error while parsing the page: ' + error );
  213. if ( embed.backupDescription && embed.length < 5000 ) {
  214. embed.setDescription( embed.backupDescription );
  215. }
  216. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  217. embed.spliceFields( 0, 0, embed.backupField );
  218. }
  219. } ).finally( () => {
  220. msg.sendChannel( content, {embed} );
  221. if ( reaction ) reaction.removeEmoji();
  222. } );
  223. }
  224. module.exports = parse_page;