parse_page.js 17 KB

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