parse_page.js 19 KB

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