parse_page.js 18 KB

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