parse_page.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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 {Object} [querypage.pageprops] - The properties of the page.
  56. * @param {String} [querypage.pageprops.disambiguation] - The disambiguation property of the page.
  57. * @param {String} thumbnail - The default thumbnail for the wiki.
  58. * @param {String} [fragment] - The section title to embed.
  59. */
  60. function parse_page(msg, content, embed, wiki, reaction, {title, contentmodel, pageprops: {disambiguation} = {}}, thumbnail, fragment = '') {
  61. if ( !msg?.showEmbed?.() || ( embed.description && embed.thumbnail?.url !== thumbnail && !embed.brokenInfobox && !fragment ) ) {
  62. msg.sendChannel( content, {embed} );
  63. if ( reaction ) reaction.removeEmoji();
  64. return;
  65. }
  66. 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 => {
  67. var body = response.body;
  68. if ( body && body.warnings ) log_warn(body.warnings);
  69. var revision = Object.values(( body?.query?.pages || {} ))?.[0]?.revisions?.[0];
  70. revision = ( revision?.slots?.main || revision );
  71. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !revision?.['*'] ) {
  72. console.log( '- ' + response.statusCode + ': Error while getting the page content: ' + ( body && body.error && body.error.info ) );
  73. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  74. embed.spliceFields( 0, 0, embed.backupField );
  75. }
  76. if ( embed.backupDescription && embed.length < 5000 ) {
  77. embed.setDescription( embed.backupDescription );
  78. }
  79. return;
  80. }
  81. if ( !embed.description && embed.length < 4000 ) {
  82. var description = revision['*'];
  83. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  84. if ( regex ) {
  85. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  86. if ( descArray.length ) {
  87. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  88. if ( description ) {
  89. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  90. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  91. embed.setDescription( description );
  92. }
  93. }
  94. }
  95. else if ( description.trim() ) {
  96. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  97. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  98. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  99. embed.setDescription( description );
  100. }
  101. else if ( embed.backupDescription ) {
  102. embed.setDescription( embed.backupDescription );
  103. }
  104. }
  105. }, error => {
  106. console.log( '- Error while getting the page content: ' + error );
  107. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  108. embed.spliceFields( 0, 0, embed.backupField );
  109. }
  110. if ( embed.backupDescription && embed.length < 5000 ) {
  111. embed.setDescription( embed.backupDescription );
  112. }
  113. } ).finally( () => {
  114. msg.sendChannel( content, {embed} );
  115. if ( reaction ) reaction.removeEmoji();
  116. } );
  117. got.get( wiki + 'api.php?action=parse&prop=text|images' + ( fragment || disambiguation !== undefined ? '' : '&section=0' ) + '&disablelimitreport=true&disableeditsection=true&disabletoc=true&sectionpreview=true&page=' + encodeURIComponent( title ) + '&format=json' ).then( response => {
  118. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  119. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  120. if ( embed.backupDescription && embed.length < 5000 ) {
  121. embed.setDescription( embed.backupDescription );
  122. }
  123. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  124. embed.spliceFields( 0, 0, embed.backupField );
  125. }
  126. return;
  127. }
  128. var $ = cheerio.load(response.body.parse.text['*'].replace( /<br\/?>/g, '\n' ));
  129. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  130. let infobox = $('aside.portable-infobox');
  131. embed.fields.forEach( field => {
  132. if ( embed.length > 5400 ) return;
  133. if ( /^`.+`$/.test(field.name) ) {
  134. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  135. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  136. if ( label ) {
  137. label = htmlToPlain(label).trim();
  138. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  139. if ( label ) field.name = label;
  140. }
  141. }
  142. if ( /^`.+`$/.test(field.value) ) {
  143. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  144. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  145. if ( value ) {
  146. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  147. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  148. if ( value ) field.value = value;
  149. }
  150. }
  151. } );
  152. }
  153. if ( !fragment && !embed.fields.length && $(infoboxList.join(', ')).length ) {
  154. let infobox = $(infoboxList.join(', ')).first();
  155. if ( embed.thumbnail?.url === thumbnail ) {
  156. let image = infobox.find([
  157. 'tr:eq(1) img',
  158. 'div.images img',
  159. 'figure.pi-image img',
  160. 'div.infobox-imagearea img'
  161. ].join(', ')).toArray().find( img => {
  162. let imgURL = img.attribs.src;
  163. if ( !imgURL ) return false;
  164. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  165. } )?.attribs.src?.replace( /^(?:https?:)?\/\//, 'https://' );
  166. if ( image ) embed.setThumbnail( new URL(image, wiki).href );
  167. }
  168. let rows = infobox.find([
  169. '> tbody > tr',
  170. '> table > tbody > tr',
  171. 'div.section > div.title',
  172. 'div.section > table > tbody > tr',
  173. 'h2.pi-header',
  174. 'div.pi-data',
  175. 'table.infobox-rows > tbody > tr',
  176. 'div.infobox-rows:not(.subinfobox) > div.infobox-row'
  177. ].join(', '));
  178. let tdLabel = true;
  179. for ( let i = 0; i < rows.length; i++ ) {
  180. if ( embed.fields.length >= 25 || embed.length > 5400 ) break;
  181. let row = rows.eq(i);
  182. if ( row.is('tr, div.pi-data, div.infobox-row') ) {
  183. let label = row.children(( tdLabel ? 'td, ' : '' ) + 'th, h3.pi-data-label, div.infobox-cell-header').eq(0);
  184. label.find(removeClasses.join(', ')).remove();
  185. let value = row.children('td, div.pi-data-value, div.infobox-cell-data').eq(( label.is('td') ? 1 : 0 ));
  186. value.find(removeClasses.join(', ')).remove();
  187. if ( !label.is('td') && label.html()?.trim() && value.html()?.trim() ) tdLabel = false;
  188. label = htmlToPlain(label).trim().split('\n')[0];
  189. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  190. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  191. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  192. if ( label && value ) embed.addField( label, value, true );
  193. }
  194. else if ( row.is('div.title, h2.pi-header') ) {
  195. row.find(removeClasses.join(', ')).remove();
  196. let label = htmlToPlain(row).trim();
  197. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  198. if ( label ) {
  199. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  200. embed.spliceFields( embed.fields.length - 1, 1, {
  201. name: '\u200b',
  202. value: '**' + label + '**',
  203. inline: false
  204. } );
  205. }
  206. else embed.addField( '\u200b', '**' + label + '**', false );
  207. }
  208. }
  209. }
  210. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  211. embed.spliceFields( embed.fields.length - 1, 1 );
  212. }
  213. }
  214. if ( embed.thumbnail?.url === thumbnail ) {
  215. let image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  216. if ( !image ) {
  217. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  218. img = $(img).prop('src')?.toLowerCase();
  219. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  220. } ).first().prop('src');
  221. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  222. img = $(img).prop('src')?.toLowerCase();
  223. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  224. } ).first().prop('src');
  225. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  226. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  227. } );
  228. }
  229. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  230. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  231. }
  232. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  233. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  234. var section = $('h1, h2, h3, h4, h5, h6').children('span').filter( (i, span) => {
  235. return ( '#' + span.attribs.id === toSection(fragment) );
  236. } ).parent();
  237. if ( section.length ) {
  238. var sectionLevel = section[0].tagName.replace('h', '');
  239. var sectionContent = $('<div>').append(
  240. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  241. );
  242. section.find('div, ' + removeClasses.join(', ')).remove();
  243. sectionContent.find(infoboxList.join(', ')).remove();
  244. sectionContent.find('div, ' + removeClasses.join(', ')).remove();
  245. var name = htmlToPlain(section).trim();
  246. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  247. var value = htmlToDiscord(sectionContent, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  248. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  249. if ( name.length && value.length ) {
  250. embed.spliceFields( 0, 0, {name, value} );
  251. }
  252. else if ( embed.backupField ) {
  253. embed.spliceFields( 0, 0, embed.backupField );
  254. }
  255. }
  256. else if ( embed.backupField ) {
  257. embed.spliceFields( 0, 0, embed.backupField );
  258. }
  259. }
  260. if ( !embed.description && embed.length < 5000 ) {
  261. if ( disambiguation === undefined || fragment ) {
  262. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  263. $('h1, h2, h3, h4, h5, h6').remove();
  264. }
  265. $(infoboxList.join(', ')).remove();
  266. $('div, ' + removeClasses.join(', '), $('.mw-parser-output')).not(keepMainPageTag.join(', ')).remove();
  267. var description = htmlToDiscord($.html(), embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  268. if ( description ) {
  269. if ( disambiguation !== undefined && !fragment && embed.length < 4250 ) {
  270. if ( description.length > 1500 ) description = limitLength(description, 1500, 250);
  271. }
  272. else if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  273. embed.setDescription( description );
  274. }
  275. else if ( embed.backupDescription ) {
  276. embed.setDescription( embed.backupDescription );
  277. }
  278. }
  279. }, error => {
  280. console.log( '- Error while parsing the page: ' + error );
  281. if ( embed.backupDescription && embed.length < 5000 ) {
  282. embed.setDescription( embed.backupDescription );
  283. }
  284. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  285. embed.spliceFields( 0, 0, embed.backupField );
  286. }
  287. } ).finally( () => {
  288. msg.sendChannel( content, {embed} );
  289. if ( reaction ) reaction.removeEmoji();
  290. } );
  291. }
  292. module.exports = parse_page;