parse_page.js 16 KB

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