parse_page.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. '.tpl-infobox'
  23. ];
  24. const removeClasses = [
  25. 'table',
  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. let 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 ( !fragment && !embed.fields.length && $(infoboxList.join(', ')).length ) {
  152. let infobox = $(infoboxList.join(', ')).first();
  153. if ( embed.thumbnail?.url === thumbnail ) {
  154. let image = infobox.find([
  155. 'tr:eq(1) img',
  156. 'div.images img',
  157. 'figure.pi-image img',
  158. 'div.infobox-imagearea img'
  159. ].join(', ')).toArray().find( img => {
  160. let imgURL = img.attribs.src;
  161. if ( !imgURL ) return false;
  162. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  163. } )?.attribs.src?.replace( /^(?:https?:)?\/\//, 'https://' );
  164. if ( image ) embed.setThumbnail( new URL(image, wiki).href );
  165. }
  166. let rows = infobox.find([
  167. '> tbody > tr',
  168. '> table > tbody > tr',
  169. 'div.section > div.title',
  170. 'div.section > table > tbody > tr',
  171. 'h2.pi-header',
  172. 'div.pi-data',
  173. 'table.infobox-rows > tbody > tr'
  174. ].join(', '));
  175. let tdLabel = true;
  176. for ( let i = 0; i < rows.length; i++ ) {
  177. if ( embed.fields.length >= 25 || embed.length > 5400 ) break;
  178. let row = rows.eq(i);
  179. if ( row.is('tr, div.pi-data') ) {
  180. let label = row.children(( tdLabel ? 'td, ' : '' ) + 'th, h3.pi-data-label').eq(0);
  181. label.find(removeClasses.join(', ')).remove();
  182. let value = row.children('td, div.pi-data-value').eq(( label.is('td') ? 1 : 0 ));
  183. value.find(removeClasses.join(', ')).remove();
  184. if ( !label.is('td') && label.html()?.trim() && value.html()?.trim() ) tdLabel = false;
  185. label = htmlToPlain(label).trim().split('\n')[0];
  186. value = htmlToDiscord(value, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  187. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  188. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  189. if ( label && value ) embed.addField( label, value, true );
  190. }
  191. else if ( row.is('div.title, h2.pi-header') ) {
  192. row.find(removeClasses.join(', ')).remove();
  193. let label = htmlToPlain(row).trim();
  194. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  195. if ( label ) {
  196. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  197. embed.spliceFields( embed.fields.length - 1, 1, {
  198. name: '\u200b',
  199. value: '**' + label + '**',
  200. inline: false
  201. } );
  202. }
  203. else embed.addField( '\u200b', '**' + label + '**', false );
  204. }
  205. }
  206. }
  207. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  208. embed.spliceFields( embed.fields.length - 1, 1 );
  209. }
  210. }
  211. if ( embed.thumbnail?.url === thumbnail ) {
  212. let image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  213. if ( !image ) {
  214. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  215. img = $(img).prop('src')?.toLowerCase();
  216. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  217. } ).first().prop('src');
  218. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  219. img = $(img).prop('src')?.toLowerCase();
  220. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  221. } ).first().prop('src');
  222. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  223. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  224. } );
  225. }
  226. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  227. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  228. }
  229. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  230. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  231. var section = $('h1, h2, h3, h4, h5, h6').children('span').filter( (i, span) => {
  232. return ( '#' + span.attribs.id === toSection(fragment) );
  233. } ).parent();
  234. if ( section.length ) {
  235. var sectionLevel = section[0].tagName.replace('h', '');
  236. var sectionContent = $('<div>').append(
  237. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  238. );
  239. section.find('div, ' + removeClasses.join(', ')).remove();
  240. sectionContent.find(infoboxList.join(', ')).remove();
  241. sectionContent.find('div, ' + removeClasses.join(', ')).remove();
  242. var name = htmlToPlain(section).trim();
  243. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  244. var value = htmlToDiscord(sectionContent, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  245. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  246. if ( name.length && value.length ) {
  247. embed.spliceFields( 0, 0, {name, value} );
  248. }
  249. else if ( embed.backupField ) {
  250. embed.spliceFields( 0, 0, embed.backupField );
  251. }
  252. }
  253. else if ( embed.backupField ) {
  254. embed.spliceFields( 0, 0, embed.backupField );
  255. }
  256. }
  257. if ( !embed.description && embed.length < 5000 ) {
  258. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  259. $('h1, h2, h3, h4, h5, h6').remove();
  260. $(infoboxList.join(', ')).remove();
  261. $('div, ' + removeClasses.join(', '), $('.mw-parser-output')).not(keepMainPageTag.join(', ')).remove();
  262. var description = htmlToDiscord($.html(), wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  263. if ( description ) {
  264. if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  265. embed.setDescription( description );
  266. }
  267. else if ( embed.backupDescription ) {
  268. embed.setDescription( embed.backupDescription );
  269. }
  270. }
  271. }, error => {
  272. console.log( '- Error while parsing the page: ' + error );
  273. if ( embed.backupDescription && embed.length < 5000 ) {
  274. embed.setDescription( embed.backupDescription );
  275. }
  276. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  277. embed.spliceFields( 0, 0, embed.backupField );
  278. }
  279. } ).finally( () => {
  280. msg.sendChannel( content, {embed} );
  281. if ( reaction ) reaction.removeEmoji();
  282. } );
  283. }
  284. module.exports = parse_page;