parse_page.js 18 KB

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