parse_page.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import cheerio from 'cheerio';
  2. import {MessageEmbed} from 'discord.js';
  3. import {toSection} from '../util/wiki.js';
  4. import {got, parse_infobox, htmlToPlain, htmlToDiscord, escapeFormatting, limitLength} from '../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').default} 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').default} 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. export default 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: {
  110. request: 10000
  111. }
  112. } ).then( response => {
  113. var body = response.body;
  114. if ( body && body.warnings ) log_warning(body.warnings);
  115. var revision = Object.values(( body?.query?.pages || {} ))?.[0]?.revisions?.[0];
  116. revision = ( revision?.slots?.main || revision );
  117. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !revision?.['*'] ) {
  118. console.log( '- ' + response.statusCode + ': Error while getting the page content: ' + ( body && body.error && body.error.info ) );
  119. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  120. embed.spliceFields( 0, 0, embed.backupField );
  121. }
  122. if ( embed.backupDescription && embed.length < 5000 ) {
  123. embed.setDescription( embed.backupDescription );
  124. }
  125. return;
  126. }
  127. if ( !embed.description && embed.length < 4000 ) {
  128. var description = revision['*'];
  129. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  130. if ( regex ) {
  131. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  132. if ( descArray.length ) {
  133. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  134. if ( description ) {
  135. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  136. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  137. embed.setDescription( description );
  138. }
  139. }
  140. }
  141. else if ( description.trim() ) {
  142. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  143. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  144. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  145. embed.setDescription( description );
  146. }
  147. else if ( embed.backupDescription ) {
  148. embed.setDescription( embed.backupDescription );
  149. }
  150. }
  151. }, error => {
  152. console.log( '- Error while getting the page content: ' + error );
  153. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  154. embed.spliceFields( 0, 0, embed.backupField );
  155. }
  156. if ( embed.backupDescription && embed.length < 5000 ) {
  157. embed.setDescription( embed.backupDescription );
  158. }
  159. } ).then( () => {
  160. return message.edit( {content, embeds: [embed]} ).catch(log_error);
  161. } );
  162. if ( !fragment && !embed.fields.length && infoboxes ) {
  163. try {
  164. var infobox = JSON.parse(infoboxes)?.[0];
  165. parse_infobox(infobox, embed, thumbnail, embed.url);
  166. }
  167. catch ( error ) {
  168. console.log( '- Failed to parse the infobox: ' + error );
  169. }
  170. }
  171. let extraImages = [];
  172. 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', {
  173. timeout: {
  174. request: 10000
  175. }
  176. } ).then( response => {
  177. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  178. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  179. if ( embed.backupDescription && embed.length < 5000 ) {
  180. embed.setDescription( embed.backupDescription );
  181. }
  182. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  183. embed.spliceFields( 0, 0, embed.backupField );
  184. }
  185. return;
  186. }
  187. if ( !embed.forceTitle ) {
  188. var displaytitle = htmlToDiscord( response.body.parse.displaytitle );
  189. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  190. embed.setTitle( displaytitle );
  191. }
  192. var $ = cheerio.load(response.body.parse.text['*'].replace( /\n?<br(?: ?\/)?>\n?/g, '<br>' ));
  193. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  194. let infobox = $('aside.portable-infobox');
  195. embed.fields.forEach( field => {
  196. if ( embed.length > 5400 ) return;
  197. if ( /^`.+`$/.test(field.name) ) {
  198. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  199. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  200. if ( label ) {
  201. label = htmlToPlain(label).trim();
  202. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  203. if ( label ) field.name = label;
  204. }
  205. }
  206. if ( /^`.+`$/.test(field.value) ) {
  207. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  208. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  209. if ( value ) {
  210. value = htmlToDiscord(value, embed.url).trim().replace( /\n{3,}/g, '\n\n' );
  211. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  212. if ( value ) field.value = value;
  213. }
  214. }
  215. } );
  216. }
  217. if ( !fragment && !embed.fields.length && $(infoboxList.join(', ')).length ) {
  218. let infobox = $(infoboxList.join(', ')).first();
  219. if ( embed.thumbnail?.url === thumbnail ) {
  220. let image = infobox.find([
  221. 'tr:eq(1) img',
  222. 'div.images img',
  223. 'figure.pi-image img',
  224. 'div.infobox-imagearea img'
  225. ].join(', ')).toArray().find( img => {
  226. let imgURL = img.attribs.src;
  227. if ( !imgURL ) return false;
  228. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  229. } )?.attribs.src?.replace( /^(?:https?:)?\/\//, 'https://' );
  230. if ( image ) embed.setThumbnail( new URL(image, wiki).href );
  231. }
  232. let rows = infobox.find([
  233. '> tbody > tr',
  234. '> tbody > tr > th.mainheader',
  235. '> tbody > tr > th.infobox-header',
  236. '> table > tbody > tr',
  237. 'div.section > div.title',
  238. 'div.section > table > tbody > tr',
  239. 'h2.pi-header',
  240. 'div.pi-data',
  241. 'table.infobox-rows > tbody > tr',
  242. 'div.infobox-rows:not(.subinfobox) > div.infobox-row'
  243. ].join(', '));
  244. let tdLabel = true;
  245. for ( let i = 0; i < rows.length; i++ ) {
  246. if ( embed.fields.length >= 25 || embed.length > 5400 ) break;
  247. let row = rows.eq(i);
  248. if ( row.is('th.mainheader, th.infobox-header, div.title, h2.pi-header') ) {
  249. row.find(removeClasses.join(', ')).remove();
  250. let label = htmlToDiscord(row, embed.url).trim();
  251. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  252. if ( label ) {
  253. if ( !label.includes( '**' ) ) label = '**' + label + '**';
  254. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  255. embed.spliceFields( embed.fields.length - 1, 1, {
  256. name: '\u200b',
  257. value: label,
  258. inline: false
  259. } );
  260. }
  261. else embed.addField( '\u200b', label, false );
  262. }
  263. }
  264. else if ( row.is('tr, div.pi-data, div.infobox-row') ) {
  265. let label = row.children(( tdLabel ? 'td, ' : '' ) + 'th, h3.pi-data-label, div.infobox-cell-header').eq(0);
  266. label.find(removeClasses.join(', ')).remove();
  267. let value = row.children('td, div.pi-data-value, div.infobox-cell-data').eq(( label.is('td') ? 1 : 0 ));
  268. value.find(removeClasses.join(', ')).remove();
  269. if ( !label.is('td') && label.html()?.trim() && value.html()?.trim() ) tdLabel = false;
  270. label = htmlToPlain(label).trim().split('\n')[0];
  271. value = htmlToDiscord(value, embed.url).trim().replace( /\n{3,}/g, '\n\n' );
  272. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  273. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  274. if ( label && value ) embed.addField( label, value, true );
  275. }
  276. }
  277. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  278. embed.spliceFields( embed.fields.length - 1, 1 );
  279. }
  280. }
  281. if ( embed.thumbnail?.url === thumbnail ) {
  282. let image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  283. if ( !image ) {
  284. thumbnail = $(infoboxList.join(', ')).find('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 ) thumbnail = $('img').filter( (i, img) => {
  289. img = $(img).prop('src')?.toLowerCase();
  290. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  291. } ).first().prop('src');
  292. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  293. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  294. } );
  295. }
  296. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  297. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  298. }
  299. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  300. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  301. let newFragment = '';
  302. let exactMatch = true;
  303. let allSections = $('h1, h2, h3, h4, h5, h6').children('span');
  304. var section = allSections.filter( (i, span) => {
  305. return ( '#' + span.attribs.id === toSection(fragment) );
  306. } ).parent();
  307. if ( !section.length ) {
  308. section = $('[id="' + toSection(fragment, false).replace( '#', '' ) + '"]');
  309. newFragment = section.attr('id');
  310. if ( section.is(':empty') ) {
  311. section = section.parent();
  312. if ( ['h1','h2','h3','h4','h5','h6'].includes( section.prev()[0]?.tagName ) ) {
  313. section = section.prev();
  314. if ( section.children('span').first().attr('id') ) {
  315. newFragment = section.children('span').first().attr('id');
  316. }
  317. }
  318. }
  319. }
  320. if ( !section.length ) exactMatch = false;
  321. if ( !section.length ) section = allSections.filter( (i, span) => {
  322. return ( '#' + span.attribs.id?.toLowerCase() === toSection(fragment).toLowerCase() );
  323. } );
  324. if ( !section.length ) section = allSections.filter( (i, span) => {
  325. return ( $(span).parent().text().trim() === fragment );
  326. } );
  327. if ( !section.length ) section = allSections.filter( (i, span) => {
  328. return ( $(span).parent().text().trim().toLowerCase() === fragment.toLowerCase() );
  329. } );
  330. if ( !section.length ) section = allSections.filter( (i, span) => {
  331. return $(span).parent().text().toLowerCase().includes( fragment.toLowerCase() );
  332. } );
  333. if ( !exactMatch && section.length ) {
  334. newFragment = section.attr('id');
  335. section = section.parent();
  336. }
  337. if ( section.length ) {
  338. section = section.first();
  339. var sectionLevel = section[0].tagName.replace('h', '');
  340. if ( !['1','2','3','4','5','6'].includes( sectionLevel ) ) sectionLevel = '10';
  341. var sectionContent = $('<div>').append(
  342. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  343. );
  344. section.find('div, ' + removeClasses.join(', ')).remove();
  345. extraImages.push(...new Set([
  346. ...sectionContent.find(infoboxList.join(', ')).find([
  347. 'tr:eq(1) img',
  348. 'div.images img',
  349. 'figure.pi-image img',
  350. 'div.infobox-imagearea img'
  351. ].join(', ')).toArray(),
  352. ...sectionContent.find('ul.gallery > li.gallerybox img').toArray()
  353. ].filter( img => {
  354. let imgURL = ( img.attribs.src?.startsWith?.( 'data:' ) ? img.attribs['data-src'] : img.attribs.src );
  355. if ( !imgURL ) return false;
  356. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  357. } ).map( img => {
  358. let imgURL = ( img.attribs.src?.startsWith?.( 'data:' ) ? img.attribs['data-src'] : img.attribs.src );
  359. imgURL = imgURL.replace( /\/thumb(\/[\da-f]\/[\da-f]{2}\/([^\/]+))\/\d+px-\2/, '$1' ).replace( /\/scale-to-width-down\/\d+/, '' );
  360. return new URL(imgURL.replace( /^(?:https?:)?\/\//, 'https://' ), wiki).href;
  361. } )));
  362. sectionContent.find(infoboxList.join(', ')).remove();
  363. sectionContent.find('div, ' + removeClasses.join(', ')).not(removeClassesExceptions.join(', ')).remove();
  364. var name = htmlToPlain(section).trim();
  365. if ( !name.length ) name = escapeFormatting(fragment);
  366. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  367. var value = htmlToDiscord(sectionContent, embed.url).trim().replace( /\n{3,}/g, '\n\n' );
  368. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  369. if ( name.length && value.length ) {
  370. embed.spliceFields( 0, 0, {name, value} );
  371. if ( newFragment ) {
  372. embed.setURL( pagelink.replace( toSection(fragment), toSection(newFragment) ) );
  373. content = content.replace( '<' + pagelink + '>', '<' + embed.url + '>' );
  374. }
  375. }
  376. else if ( embed.backupField ) {
  377. embed.spliceFields( 0, 0, embed.backupField );
  378. }
  379. }
  380. else if ( embed.backupField ) {
  381. embed.spliceFields( 0, 0, embed.backupField );
  382. }
  383. }
  384. if ( !embed.description && embed.length < 5000 ) {
  385. if ( contentmodel !== 'wikitext' || disambiguation === undefined || fragment ) {
  386. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  387. $('h1, h2, h3, h4, h5, h6').remove();
  388. }
  389. $(infoboxList.join(', ')).remove();
  390. $('div, ' + removeClasses.join(', '), $('.mw-parser-output')).not(removeClassesExceptions.join(', ')).remove();
  391. var description = htmlToDiscord($.html(), embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  392. if ( description ) {
  393. if ( disambiguation !== undefined && !fragment && embed.length < 4250 ) {
  394. if ( description.length > 1500 ) description = limitLength(description, 1500, 250);
  395. }
  396. else if ( fragment && description.length > 500 ) description = limitLength(description, 500, 250);
  397. else if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  398. embed.setDescription( description );
  399. }
  400. else if ( embed.backupDescription ) {
  401. embed.setDescription( embed.backupDescription );
  402. }
  403. }
  404. }, error => {
  405. console.log( '- Error while parsing the page: ' + error );
  406. if ( embed.backupDescription && embed.length < 5000 ) {
  407. embed.setDescription( embed.backupDescription );
  408. }
  409. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  410. embed.spliceFields( 0, 0, embed.backupField );
  411. }
  412. } ).then( () => {
  413. let embeds = [embed];
  414. if ( extraImages.length ) {
  415. if ( !embed.image ) embed.setImage( extraImages.shift() );
  416. extraImages.slice(0, 10).forEach( extraImage => {
  417. let imageEmbed = new MessageEmbed().setURL( embed.url ).setImage( extraImage );
  418. if ( embeds.length < 5 && embeds.reduce( (acc, val) => acc + val.length, imageEmbed.length ) <= 5500 ) embeds.push(imageEmbed);
  419. } );
  420. }
  421. return message.edit( {content, embeds} ).catch(log_error);
  422. } );
  423. } );
  424. }