parse_page.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. const cheerio = require('cheerio');
  2. const {toSection} = require('../util/wiki.js');
  3. const {htmlToPlain, htmlToDiscord, limitLength} = require('../util/functions.js');
  4. const parsedContentModels = [
  5. 'wikitext',
  6. 'wikibase-item',
  7. 'wikibase-lexeme',
  8. 'wikibase-property'
  9. ];
  10. // Max length of 10 characters
  11. const contentModels = {
  12. Scribunto: 'lua',
  13. javascript: 'js',
  14. json: 'json',
  15. css: 'css'
  16. };
  17. const contentFormats = {
  18. 'application/json': 'json',
  19. 'text/javascript': 'js',
  20. 'text/css': 'css'
  21. };
  22. // Max length of 10 characters
  23. const infoboxList = [
  24. '.infobox',
  25. '.portable-infobox',
  26. '.infoboxtable',
  27. '.notaninfobox',
  28. '.tpl-infobox'
  29. ];
  30. const removeClasses = [
  31. 'table',
  32. 'script',
  33. 'input',
  34. 'style',
  35. 'script',
  36. 'noscript',
  37. 'ul.gallery',
  38. '.mw-editsection',
  39. 'sup.reference',
  40. 'ol.references',
  41. '.error',
  42. '.nomobile',
  43. '.noprint',
  44. '.noexcerpt',
  45. '.sortkey',
  46. 'wb\\:sectionedit'
  47. ];
  48. const removeClassExceptions = [
  49. 'div.main-page-tag-lcs',
  50. 'div.lcs-container',
  51. 'div.wikibase-entityview',
  52. 'div.wikibase-entityview-main',
  53. 'div.wikibase-entitytermsview',
  54. 'div.wikibase-entitytermsview-heading',
  55. 'div.wikibase-entitytermsview-heading-description',
  56. 'div#wb-lexeme-header',
  57. 'div#wb-lexeme-header div:not([class]):not([id])',
  58. 'div.language-lexical-category-widget'
  59. ];
  60. /**
  61. * Parses a wiki page to get it's description.
  62. * @param {import('discord.js').Message} msg - The Discord message.
  63. * @param {String} content - The content for the message.
  64. * @param {import('discord.js').MessageEmbed} embed - The embed for the message.
  65. * @param {import('../util/wiki.js')} wiki - The wiki for the page.
  66. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  67. * @param {Object} querypage - The details of the page.
  68. * @param {String} querypage.title - The title of the page.
  69. * @param {String} querypage.contentmodel - The content model of the page.
  70. * @param {Object} [querypage.pageprops] - The properties of the page.
  71. * @param {String} [querypage.pageprops.disambiguation] - The disambiguation property of the page.
  72. * @param {String} thumbnail - The default thumbnail for the wiki.
  73. * @param {String} [fragment] - The section title to embed.
  74. */
  75. function parse_page(msg, content, embed, wiki, reaction, {title, contentmodel, pageprops: {disambiguation} = {}}, thumbnail, fragment = '') {
  76. if ( !msg?.showEmbed?.() || ( embed.description && embed.thumbnail?.url !== thumbnail && !embed.brokenInfobox && !fragment ) ) {
  77. msg.sendChannel( content, {embed} );
  78. if ( reaction ) reaction.removeEmoji();
  79. return;
  80. }
  81. if ( !parsedContentModels.includes( contentmodel ) ) return got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=content&rvslots=main&converttitles=true&titles=%1F' + encodeURIComponent( title ) + '&format=json' ).then( response => {
  82. var body = response.body;
  83. if ( body && body.warnings ) log_warn(body.warnings);
  84. var revision = Object.values(( body?.query?.pages || {} ))?.[0]?.revisions?.[0];
  85. revision = ( revision?.slots?.main || revision );
  86. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !revision?.['*'] ) {
  87. console.log( '- ' + response.statusCode + ': Error while getting the page content: ' + ( body && body.error && body.error.info ) );
  88. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  89. embed.spliceFields( 0, 0, embed.backupField );
  90. }
  91. if ( embed.backupDescription && embed.length < 5000 ) {
  92. embed.setDescription( embed.backupDescription );
  93. }
  94. return;
  95. }
  96. if ( !embed.description && embed.length < 4000 ) {
  97. var description = revision['*'];
  98. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  99. if ( regex ) {
  100. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  101. if ( descArray.length ) {
  102. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  103. if ( description ) {
  104. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  105. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  106. embed.setDescription( description );
  107. }
  108. }
  109. }
  110. else if ( description.trim() ) {
  111. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  112. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  113. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  114. embed.setDescription( description );
  115. }
  116. else if ( embed.backupDescription ) {
  117. embed.setDescription( embed.backupDescription );
  118. }
  119. }
  120. }, error => {
  121. console.log( '- Error while getting the page content: ' + error );
  122. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  123. embed.spliceFields( 0, 0, embed.backupField );
  124. }
  125. if ( embed.backupDescription && embed.length < 5000 ) {
  126. embed.setDescription( embed.backupDescription );
  127. }
  128. } ).finally( () => {
  129. msg.sendChannel( content, {embed} );
  130. if ( reaction ) reaction.removeEmoji();
  131. } );
  132. got.get( wiki + 'api.php?action=parse&prop=text|images|displaytitle' + ( contentmodel !== 'wikitext' || fragment || disambiguation !== undefined ? '' : '&section=0' ) + '&disablelimitreport=true&disableeditsection=true&disabletoc=true&sectionpreview=true&page=' + encodeURIComponent( title ) + '&format=json' ).then( response => {
  133. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  134. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  135. if ( embed.backupDescription && embed.length < 5000 ) {
  136. embed.setDescription( embed.backupDescription );
  137. }
  138. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  139. embed.spliceFields( 0, 0, embed.backupField );
  140. }
  141. return;
  142. }
  143. var displaytitle = htmlToDiscord( response.body.parse.displaytitle );
  144. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  145. embed.setTitle( displaytitle );
  146. var $ = cheerio.load(response.body.parse.text['*'].replace( /\n?<br(?: ?\/)?>\n?/g, '<br>' ));
  147. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  148. let infobox = $('aside.portable-infobox');
  149. embed.fields.forEach( field => {
  150. if ( embed.length > 5400 ) return;
  151. if ( /^`.+`$/.test(field.name) ) {
  152. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  153. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  154. if ( label ) {
  155. label = htmlToPlain(label).trim();
  156. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  157. if ( label ) field.name = label;
  158. }
  159. }
  160. if ( /^`.+`$/.test(field.value) ) {
  161. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  162. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  163. if ( value ) {
  164. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  165. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  166. if ( value ) field.value = value;
  167. }
  168. }
  169. } );
  170. }
  171. if ( !fragment && !embed.fields.length && $(infoboxList.join(', ')).length ) {
  172. let infobox = $(infoboxList.join(', ')).first();
  173. if ( embed.thumbnail?.url === thumbnail ) {
  174. let image = infobox.find([
  175. 'tr:eq(1) img',
  176. 'div.images img',
  177. 'figure.pi-image img',
  178. 'div.infobox-imagearea img'
  179. ].join(', ')).toArray().find( img => {
  180. let imgURL = img.attribs.src;
  181. if ( !imgURL ) return false;
  182. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  183. } )?.attribs.src?.replace( /^(?:https?:)?\/\//, 'https://' );
  184. if ( image ) embed.setThumbnail( new URL(image, wiki).href );
  185. }
  186. let rows = infobox.find([
  187. '> tbody > tr',
  188. '> tbody > tr > th.mainheader',
  189. '> table > tbody > tr',
  190. 'div.section > div.title',
  191. 'div.section > table > tbody > tr',
  192. 'h2.pi-header',
  193. 'div.pi-data',
  194. 'table.infobox-rows > tbody > tr',
  195. 'div.infobox-rows:not(.subinfobox) > div.infobox-row'
  196. ].join(', '));
  197. let tdLabel = true;
  198. for ( let i = 0; i < rows.length; i++ ) {
  199. if ( embed.fields.length >= 25 || embed.length > 5400 ) break;
  200. let row = rows.eq(i);
  201. if ( row.is('th.mainheader, div.title, h2.pi-header') ) {
  202. row.find(removeClasses.join(', ')).remove();
  203. let label = htmlToPlain(row).trim();
  204. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  205. if ( label ) {
  206. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  207. embed.spliceFields( embed.fields.length - 1, 1, {
  208. name: '\u200b',
  209. value: '**' + label + '**',
  210. inline: false
  211. } );
  212. }
  213. else embed.addField( '\u200b', '**' + label + '**', false );
  214. }
  215. }
  216. else if ( row.is('tr, div.pi-data, div.infobox-row') ) {
  217. let label = row.children(( tdLabel ? 'td, ' : '' ) + 'th, h3.pi-data-label, div.infobox-cell-header').eq(0);
  218. label.find(removeClasses.join(', ')).remove();
  219. let value = row.children('td, div.pi-data-value, div.infobox-cell-data').eq(( label.is('td') ? 1 : 0 ));
  220. value.find(removeClasses.join(', ')).remove();
  221. if ( !label.is('td') && label.html()?.trim() && value.html()?.trim() ) tdLabel = false;
  222. label = htmlToPlain(label).trim().split('\n')[0];
  223. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  224. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  225. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  226. if ( label && value ) embed.addField( label, value, true );
  227. }
  228. }
  229. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  230. embed.spliceFields( embed.fields.length - 1, 1 );
  231. }
  232. }
  233. if ( embed.thumbnail?.url === thumbnail ) {
  234. let image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  235. if ( !image ) {
  236. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  237. img = $(img).prop('src')?.toLowerCase();
  238. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  239. } ).first().prop('src');
  240. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  241. img = $(img).prop('src')?.toLowerCase();
  242. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  243. } ).first().prop('src');
  244. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  245. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  246. } );
  247. }
  248. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  249. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  250. }
  251. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  252. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  253. var section = $('h1, h2, h3, h4, h5, h6').children('span').filter( (i, span) => {
  254. return ( '#' + span.attribs.id === toSection(fragment) );
  255. } ).parent();
  256. if ( section.length ) {
  257. var sectionLevel = section[0].tagName.replace('h', '');
  258. var sectionContent = $('<div>').append(
  259. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  260. );
  261. section.find('div, ' + removeClasses.join(', ')).remove();
  262. sectionContent.find(infoboxList.join(', ')).remove();
  263. sectionContent.find('div, ' + removeClasses.join(', ')).remove();
  264. var name = htmlToPlain(section).trim();
  265. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  266. var value = htmlToDiscord(sectionContent, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  267. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  268. if ( name.length && value.length ) {
  269. embed.spliceFields( 0, 0, {name, value} );
  270. }
  271. else if ( embed.backupField ) {
  272. embed.spliceFields( 0, 0, embed.backupField );
  273. }
  274. }
  275. else if ( embed.backupField ) {
  276. embed.spliceFields( 0, 0, embed.backupField );
  277. }
  278. }
  279. if ( !embed.description && embed.length < 5000 ) {
  280. if ( contentmodel !== 'wikitext' || disambiguation === undefined || fragment ) {
  281. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  282. $('h1, h2, h3, h4, h5, h6').remove();
  283. }
  284. $(infoboxList.join(', ')).remove();
  285. $('div, ' + removeClasses.join(', '), $('.mw-parser-output')).not(removeClassExceptions.join(', ')).remove();
  286. var description = htmlToDiscord($.html(), embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  287. if ( description ) {
  288. if ( disambiguation !== undefined && !fragment && embed.length < 4250 ) {
  289. if ( description.length > 1500 ) description = limitLength(description, 1500, 250);
  290. }
  291. else if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  292. embed.setDescription( description );
  293. }
  294. else if ( embed.backupDescription ) {
  295. embed.setDescription( embed.backupDescription );
  296. }
  297. }
  298. }, error => {
  299. console.log( '- Error while parsing the page: ' + error );
  300. if ( embed.backupDescription && embed.length < 5000 ) {
  301. embed.setDescription( embed.backupDescription );
  302. }
  303. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  304. embed.spliceFields( 0, 0, embed.backupField );
  305. }
  306. } ).finally( () => {
  307. msg.sendChannel( content, {embed} );
  308. if ( reaction ) reaction.removeEmoji();
  309. } );
  310. }
  311. module.exports = parse_page;