parse_page.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. * @returns {Promise<import('discord.js').Message>} The edited message.
  83. */
  84. function parse_page(lang, msg, content, embed, wiki, reaction, {title, contentmodel, pageprops: {infoboxes, disambiguation} = {}, uselang = lang.lang, noRedirect = false}, thumbnail = '', fragment = '', pagelink = '') {
  85. if ( reaction ) reaction.removeEmoji();
  86. if ( !msg?.showEmbed?.() || embed.description ) {
  87. return msg.sendChannel( content, {embed} );
  88. }
  89. return 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 message.edit( content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  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. return message.edit( content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  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. return 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 message.edit( content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  166. }
  167. if ( !embed.forceTitle ) {
  168. var displaytitle = htmlToDiscord( response.body.parse.displaytitle );
  169. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  170. embed.setTitle( displaytitle );
  171. }
  172. var $ = cheerio.load(response.body.parse.text['*'].replace( /\n?<br(?: ?\/)?>\n?/g, '<br>' ));
  173. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  174. let infobox = $('aside.portable-infobox');
  175. embed.fields.forEach( field => {
  176. if ( embed.length > 5400 ) return;
  177. if ( /^`.+`$/.test(field.name) ) {
  178. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  179. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  180. if ( label ) {
  181. label = htmlToPlain(label).trim();
  182. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  183. if ( label ) field.name = label;
  184. }
  185. }
  186. if ( /^`.+`$/.test(field.value) ) {
  187. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  188. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  189. if ( value ) {
  190. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  191. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  192. if ( value ) field.value = value;
  193. }
  194. }
  195. } );
  196. }
  197. if ( !fragment && !embed.fields.length && $(infoboxList.join(', ')).length ) {
  198. let infobox = $(infoboxList.join(', ')).first();
  199. if ( embed.thumbnail?.url === thumbnail ) {
  200. let image = infobox.find([
  201. 'tr:eq(1) img',
  202. 'div.images img',
  203. 'figure.pi-image img',
  204. 'div.infobox-imagearea img'
  205. ].join(', ')).toArray().find( img => {
  206. let imgURL = img.attribs.src;
  207. if ( !imgURL ) return false;
  208. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  209. } )?.attribs.src?.replace( /^(?:https?:)?\/\//, 'https://' );
  210. if ( image ) embed.setThumbnail( new URL(image, wiki).href );
  211. }
  212. let rows = infobox.find([
  213. '> tbody > tr',
  214. '> tbody > tr > th.mainheader',
  215. '> table > tbody > tr',
  216. 'div.section > div.title',
  217. 'div.section > table > tbody > tr',
  218. 'h2.pi-header',
  219. 'div.pi-data',
  220. 'table.infobox-rows > tbody > tr',
  221. 'div.infobox-rows:not(.subinfobox) > div.infobox-row'
  222. ].join(', '));
  223. let tdLabel = true;
  224. for ( let i = 0; i < rows.length; i++ ) {
  225. if ( embed.fields.length >= 25 || embed.length > 5400 ) break;
  226. let row = rows.eq(i);
  227. if ( row.is('th.mainheader, div.title, h2.pi-header') ) {
  228. row.find(removeClasses.join(', ')).remove();
  229. let label = htmlToPlain(row).trim();
  230. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  231. if ( label ) {
  232. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  233. embed.spliceFields( embed.fields.length - 1, 1, {
  234. name: '\u200b',
  235. value: '**' + label + '**',
  236. inline: false
  237. } );
  238. }
  239. else embed.addField( '\u200b', '**' + label + '**', false );
  240. }
  241. }
  242. else if ( row.is('tr, div.pi-data, div.infobox-row') ) {
  243. let label = row.children(( tdLabel ? 'td, ' : '' ) + 'th, h3.pi-data-label, div.infobox-cell-header').eq(0);
  244. label.find(removeClasses.join(', ')).remove();
  245. let value = row.children('td, div.pi-data-value, div.infobox-cell-data').eq(( label.is('td') ? 1 : 0 ));
  246. value.find(removeClasses.join(', ')).remove();
  247. if ( !label.is('td') && label.html()?.trim() && value.html()?.trim() ) tdLabel = false;
  248. label = htmlToPlain(label).trim().split('\n')[0];
  249. value = htmlToDiscord(value, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  250. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  251. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  252. if ( label && value ) embed.addField( label, value, true );
  253. }
  254. }
  255. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  256. embed.spliceFields( embed.fields.length - 1, 1 );
  257. }
  258. }
  259. if ( embed.thumbnail?.url === thumbnail ) {
  260. let image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  261. if ( !image ) {
  262. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  263. img = $(img).prop('src')?.toLowerCase();
  264. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  265. } ).first().prop('src');
  266. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  267. img = $(img).prop('src')?.toLowerCase();
  268. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  269. } ).first().prop('src');
  270. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  271. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  272. } );
  273. }
  274. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  275. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  276. }
  277. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  278. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  279. let newFragment = '';
  280. let exactMatch = true;
  281. let allSections = $('h1, h2, h3, h4, h5, h6').children('span');
  282. var section = allSections.filter( (i, span) => {
  283. return ( '#' + span.attribs.id === toSection(fragment) );
  284. } ).parent();
  285. if ( !section.length ) {
  286. section = $('[id="' + toSection(fragment, false).replace( '#', '' ) + '"]');
  287. newFragment = section.attr('id');
  288. if ( section.is(':empty') ) section = section.parent();
  289. }
  290. if ( !section.length ) exactMatch = false;
  291. if ( !section.length ) section = allSections.filter( (i, span) => {
  292. return ( '#' + span.attribs.id.toLowerCase() === toSection(fragment).toLowerCase() );
  293. } );
  294. if ( !section.length ) section = allSections.filter( (i, span) => {
  295. return ( $(span).parent().text().trim() === fragment );
  296. } );
  297. if ( !section.length ) section = allSections.filter( (i, span) => {
  298. return ( $(span).parent().text().trim().toLowerCase() === fragment.toLowerCase() );
  299. } );
  300. if ( !section.length ) section = allSections.filter( (i, span) => {
  301. return $(span).parent().text().toLowerCase().includes( fragment.toLowerCase() );
  302. } );
  303. if ( !exactMatch && section.length ) {
  304. newFragment = section.attr('id');
  305. section = section.parent();
  306. }
  307. if ( section.length ) {
  308. section = section.first();
  309. var sectionLevel = section[0].tagName.replace('h', '');
  310. if ( !['1','2','3','4','5','6'].includes( sectionLevel ) ) sectionLevel = '10';
  311. var sectionContent = $('<div>').append(
  312. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  313. );
  314. section.find('div, ' + removeClasses.join(', ')).remove();
  315. sectionContent.find(infoboxList.join(', ')).remove();
  316. sectionContent.find('div, ' + removeClasses.join(', ')).not(removeClassesExceptions.join(', ')).remove();
  317. var name = htmlToPlain(section).trim();
  318. if ( !name.length ) name = fragment.escapeFormatting();
  319. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  320. var value = htmlToDiscord(sectionContent, embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  321. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  322. if ( name.length && value.length ) {
  323. embed.spliceFields( 0, 0, {name, value} );
  324. if ( newFragment ) {
  325. embed.setURL( pagelink.replace( toSection(fragment), '#' + newFragment ) );
  326. content = content.replace( '<' + pagelink + '>', '<' + embed.url + '>' );
  327. }
  328. }
  329. else if ( embed.backupField ) {
  330. embed.spliceFields( 0, 0, embed.backupField );
  331. }
  332. }
  333. else if ( embed.backupField ) {
  334. embed.spliceFields( 0, 0, embed.backupField );
  335. }
  336. }
  337. if ( !embed.description && embed.length < 5000 ) {
  338. if ( contentmodel !== 'wikitext' || disambiguation === undefined || fragment ) {
  339. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  340. $('h1, h2, h3, h4, h5, h6').remove();
  341. }
  342. $(infoboxList.join(', ')).remove();
  343. $('div, ' + removeClasses.join(', '), $('.mw-parser-output')).not(removeClassesExceptions.join(', ')).remove();
  344. var description = htmlToDiscord($.html(), embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  345. if ( description ) {
  346. if ( disambiguation !== undefined && !fragment && embed.length < 4250 ) {
  347. if ( description.length > 1500 ) description = limitLength(description, 1500, 250);
  348. }
  349. else if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  350. embed.setDescription( description );
  351. }
  352. else if ( embed.backupDescription ) {
  353. embed.setDescription( embed.backupDescription );
  354. }
  355. }
  356. return message.edit( content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  357. }, error => {
  358. console.log( '- Error while parsing the page: ' + error );
  359. if ( embed.backupDescription && embed.length < 5000 ) {
  360. embed.setDescription( embed.backupDescription );
  361. }
  362. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  363. embed.spliceFields( 0, 0, embed.backupField );
  364. }
  365. return message.edit( content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  366. } );
  367. } );
  368. }
  369. module.exports = parse_page;