parse_page.js 18 KB

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