parse_page.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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} [querypage.pageprops.uselang] - The language of the page description.
  78. * @param {Boolean} [querypage.pageprops.noRedirect] - If the page is allowed to be redirected.
  79. * @param {String} thumbnail - The default thumbnail for the wiki.
  80. * @param {String} [fragment] - The section title to embed.
  81. * @param {String} [pagelink] - The link to the page.
  82. */
  83. function parse_page(lang, msg, content, embed, wiki, reaction, {title, contentmodel, pageprops: {infoboxes, disambiguation} = {}, uselang = lang.lang, noRedirect = false}, thumbnail, fragment = '', pagelink = '') {
  84. if ( reaction ) reaction.removeEmoji();
  85. if ( !msg?.showEmbed?.() ) {
  86. msg.sendChannel( content, {embed} );
  87. return;
  88. }
  89. msg.sendChannel( content, {
  90. embed: new MessageEmbed(embed).setDescription( '<a:loading:641343250661113886> **' + lang.get('search.loading') + '**' )
  91. } ).then( message => {
  92. if ( !message ) return;
  93. 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', {
  94. timeout: 10000
  95. } ).then( response => {
  96. var body = response.body;
  97. if ( body && body.warnings ) log_warn(body.warnings);
  98. var revision = Object.values(( body?.query?.pages || {} ))?.[0]?.revisions?.[0];
  99. revision = ( revision?.slots?.main || revision );
  100. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !revision?.['*'] ) {
  101. console.log( '- ' + response.statusCode + ': Error while getting the page content: ' + ( body && body.error && body.error.info ) );
  102. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  103. embed.spliceFields( 0, 0, embed.backupField );
  104. }
  105. if ( embed.backupDescription && embed.length < 5000 ) {
  106. embed.setDescription( embed.backupDescription );
  107. }
  108. return;
  109. }
  110. if ( !embed.description && embed.length < 4000 ) {
  111. var description = revision['*'];
  112. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  113. if ( regex ) {
  114. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  115. if ( descArray.length ) {
  116. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  117. if ( description ) {
  118. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  119. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  120. embed.setDescription( description );
  121. }
  122. }
  123. }
  124. else if ( description.trim() ) {
  125. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  126. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  127. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  128. embed.setDescription( description );
  129. }
  130. else if ( embed.backupDescription ) {
  131. embed.setDescription( embed.backupDescription );
  132. }
  133. }
  134. }, error => {
  135. console.log( '- Error while getting the page content: ' + error );
  136. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  137. embed.spliceFields( 0, 0, embed.backupField );
  138. }
  139. if ( embed.backupDescription && embed.length < 5000 ) {
  140. embed.setDescription( embed.backupDescription );
  141. }
  142. } ).finally( () => {
  143. message.edit( content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  144. } );
  145. if ( !fragment && !embed.fields.length && infoboxes ) {
  146. try {
  147. var infobox = JSON.parse(infoboxes)?.[0];
  148. parse_infobox(infobox, embed, thumbnail, embed.url);
  149. }
  150. catch ( error ) {
  151. console.log( '- Failed to parse the infobox: ' + error );
  152. }
  153. }
  154. 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', {
  155. timeout: 10000
  156. } ).then( response => {
  157. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  158. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  159. if ( embed.backupDescription && embed.length < 5000 ) {
  160. embed.setDescription( embed.backupDescription );
  161. }
  162. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  163. embed.spliceFields( 0, 0, embed.backupField );
  164. }
  165. return;
  166. }
  167. var displaytitle = htmlToDiscord( response.body.parse.displaytitle );
  168. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  169. embed.setTitle( displaytitle );
  170. var $ = cheerio.load(response.body.parse.text['*'].replace( /\n?<br(?: ?\/)?>\n?/g, '<br>' ));
  171. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  172. let infobox = $('aside.portable-infobox');
  173. embed.fields.forEach( field => {
  174. if ( embed.length > 5400 ) return;
  175. if ( /^`.+`$/.test(field.name) ) {
  176. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  177. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  178. if ( label ) {
  179. label = htmlToPlain(label).trim();
  180. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  181. if ( label ) field.name = label;
  182. }
  183. }
  184. if ( /^`.+`$/.test(field.value) ) {
  185. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  186. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  187. if ( value ) {
  188. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  189. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  190. if ( value ) field.value = value;
  191. }
  192. }
  193. } );
  194. }
  195. if ( !fragment && !embed.fields.length && $(infoboxList.join(', ')).length ) {
  196. let infobox = $(infoboxList.join(', ')).first();
  197. if ( embed.thumbnail?.url === thumbnail ) {
  198. let image = infobox.find([
  199. 'tr:eq(1) img',
  200. 'div.images img',
  201. 'figure.pi-image img',
  202. 'div.infobox-imagearea img'
  203. ].join(', ')).toArray().find( img => {
  204. let imgURL = img.attribs.src;
  205. if ( !imgURL ) return false;
  206. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  207. } )?.attribs.src?.replace( /^(?:https?:)?\/\//, 'https://' );
  208. if ( image ) embed.setThumbnail( new URL(image, wiki).href );
  209. }
  210. let rows = infobox.find([
  211. '> tbody > tr',
  212. '> tbody > tr > th.mainheader',
  213. '> table > tbody > tr',
  214. 'div.section > div.title',
  215. 'div.section > table > tbody > tr',
  216. 'h2.pi-header',
  217. 'div.pi-data',
  218. 'table.infobox-rows > tbody > tr',
  219. 'div.infobox-rows:not(.subinfobox) > div.infobox-row'
  220. ].join(', '));
  221. let tdLabel = true;
  222. for ( let i = 0; i < rows.length; i++ ) {
  223. if ( embed.fields.length >= 25 || embed.length > 5400 ) break;
  224. let row = rows.eq(i);
  225. if ( row.is('th.mainheader, div.title, h2.pi-header') ) {
  226. row.find(removeClasses.join(', ')).remove();
  227. let label = htmlToPlain(row).trim();
  228. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  229. if ( label ) {
  230. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  231. embed.spliceFields( embed.fields.length - 1, 1, {
  232. name: '\u200b',
  233. value: '**' + label + '**',
  234. inline: false
  235. } );
  236. }
  237. else embed.addField( '\u200b', '**' + label + '**', false );
  238. }
  239. }
  240. else if ( row.is('tr, div.pi-data, div.infobox-row') ) {
  241. let label = row.children(( tdLabel ? 'td, ' : '' ) + 'th, h3.pi-data-label, div.infobox-cell-header').eq(0);
  242. label.find(removeClasses.join(', ')).remove();
  243. let value = row.children('td, div.pi-data-value, div.infobox-cell-data').eq(( label.is('td') ? 1 : 0 ));
  244. value.find(removeClasses.join(', ')).remove();
  245. if ( !label.is('td') && label.html()?.trim() && value.html()?.trim() ) tdLabel = false;
  246. label = htmlToPlain(label).trim().split('\n')[0];
  247. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  248. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  249. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  250. if ( label && value ) embed.addField( label, value, true );
  251. }
  252. }
  253. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  254. embed.spliceFields( embed.fields.length - 1, 1 );
  255. }
  256. }
  257. if ( embed.thumbnail?.url === thumbnail ) {
  258. let image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  259. if ( !image ) {
  260. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  261. img = $(img).prop('src')?.toLowerCase();
  262. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  263. } ).first().prop('src');
  264. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  265. img = $(img).prop('src')?.toLowerCase();
  266. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  267. } ).first().prop('src');
  268. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  269. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  270. } );
  271. }
  272. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  273. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  274. }
  275. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  276. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  277. let newFragment = '';
  278. let exactMatch = true;
  279. let allSections = $('h1, h2, h3, h4, h5, h6').children('span');
  280. var section = allSections.filter( (i, span) => {
  281. return ( '#' + span.attribs.id === toSection(fragment) );
  282. } ).parent();
  283. if ( !section.length ) {
  284. section = $('[id="' + toSection(fragment, false).replace( '#', '' ) + '"]');
  285. newFragment = section.attr('id');
  286. if ( section.is(':empty') ) section = section.parent();
  287. }
  288. if ( !section.length ) exactMatch = false;
  289. if ( !section.length ) section = allSections.filter( (i, span) => {
  290. return ( '#' + span.attribs.id.toLowerCase() === toSection(fragment).toLowerCase() );
  291. } );
  292. if ( !section.length ) section = allSections.filter( (i, span) => {
  293. return ( $(span).parent().text().trim() === fragment );
  294. } );
  295. if ( !section.length ) section = allSections.filter( (i, span) => {
  296. return ( $(span).parent().text().trim().toLowerCase() === fragment.toLowerCase() );
  297. } );
  298. if ( !section.length ) section = allSections.filter( (i, span) => {
  299. return $(span).parent().text().toLowerCase().includes( fragment.toLowerCase() );
  300. } );
  301. if ( !exactMatch && section.length ) {
  302. newFragment = section.attr('id');
  303. section = section.parent();
  304. }
  305. if ( section.length ) {
  306. section = section.first();
  307. var sectionLevel = section[0].tagName.replace('h', '');
  308. if ( !['1','2','3','4','5','6'].includes( sectionLevel ) ) sectionLevel = '10';
  309. var sectionContent = $('<div>').append(
  310. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  311. );
  312. section.find('div, ' + removeClasses.join(', ')).remove();
  313. sectionContent.find(infoboxList.join(', ')).remove();
  314. sectionContent.find('div, ' + removeClasses.join(', ')).not(removeClassesExceptions.join(', ')).remove();
  315. var name = htmlToPlain(section).trim();
  316. if ( !name.length ) name = fragment.escapeFormatting();
  317. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  318. var value = htmlToDiscord(sectionContent, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  319. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  320. if ( name.length && value.length ) {
  321. embed.spliceFields( 0, 0, {name, value} );
  322. if ( newFragment ) {
  323. embed.setURL( pagelink.replace( toSection(fragment), '#' + newFragment ) );
  324. content = content.replace( '<' + pagelink + '>', '<' + embed.url + '>' );
  325. }
  326. }
  327. else if ( embed.backupField ) {
  328. embed.spliceFields( 0, 0, embed.backupField );
  329. }
  330. }
  331. else if ( embed.backupField ) {
  332. embed.spliceFields( 0, 0, embed.backupField );
  333. }
  334. }
  335. if ( !embed.description && embed.length < 5000 ) {
  336. if ( contentmodel !== 'wikitext' || disambiguation === undefined || fragment ) {
  337. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  338. $('h1, h2, h3, h4, h5, h6').remove();
  339. }
  340. $(infoboxList.join(', ')).remove();
  341. $('div, ' + removeClasses.join(', '), $('.mw-parser-output')).not(removeClassesExceptions.join(', ')).remove();
  342. var description = htmlToDiscord($.html(), embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  343. if ( description ) {
  344. if ( disambiguation !== undefined && !fragment && embed.length < 4250 ) {
  345. if ( description.length > 1500 ) description = limitLength(description, 1500, 250);
  346. }
  347. else if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  348. embed.setDescription( description );
  349. }
  350. else if ( embed.backupDescription ) {
  351. embed.setDescription( embed.backupDescription );
  352. }
  353. }
  354. }, error => {
  355. console.log( '- Error while parsing the page: ' + error );
  356. if ( embed.backupDescription && embed.length < 5000 ) {
  357. embed.setDescription( embed.backupDescription );
  358. }
  359. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  360. embed.spliceFields( 0, 0, embed.backupField );
  361. }
  362. } ).finally( () => {
  363. message.edit( content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  364. } );
  365. } );
  366. }
  367. module.exports = parse_page;