parse_page.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. const cheerio = require('cheerio');
  2. const {toSection} = require('../util/wiki.js');
  3. const {htmlToPlain, htmlToDiscord, limitLength} = require('../util/functions.js');
  4. // Max length of 10 characters
  5. const contentModels = {
  6. Scribunto: 'lua',
  7. javascript: 'js',
  8. json: 'json',
  9. css: 'css'
  10. };
  11. const contentFormats = {
  12. 'application/json': 'json',
  13. 'text/javascript': 'js',
  14. 'text/css': 'css'
  15. };
  16. // Max length of 10 characters
  17. const infoboxList = [
  18. '.infobox',
  19. '.portable-infobox',
  20. '.infoboxtable',
  21. '.notaninfobox'
  22. ];
  23. const removeClasses = [
  24. 'table',
  25. 'div',
  26. 'script',
  27. 'input',
  28. 'style',
  29. 'script',
  30. 'noscript',
  31. 'ul.gallery',
  32. '.mw-editsection',
  33. 'sup.reference',
  34. 'ol.references',
  35. '.error',
  36. '.nomobile',
  37. '.noprint',
  38. '.noexcerpt',
  39. '.sortkey'
  40. ];
  41. const keepMainPageTag = [
  42. 'div.main-page-tag-lcs',
  43. 'div.lcs-container'
  44. ];
  45. /**
  46. * Parses a wiki page to get it's description.
  47. * @param {import('discord.js').Message} msg - The Discord message.
  48. * @param {Object} querypage - The details of the page.
  49. * @param {String} querypage.title - The title of the page.
  50. * @param {String} querypage.contentmodel - The content model of the page.
  51. * @param {import('discord.js').MessageEmbed} embed - The embed for the page.
  52. * @param {import('../util/wiki.js')} wiki - The wiki for the page.
  53. * @param {String} thumbnail - The default thumbnail for the wiki.
  54. * @param {String} [fragment] - The section title to embed.
  55. */
  56. function parse_page(msg, {title, contentmodel}, embed, wiki, thumbnail, fragment = '') {
  57. if ( !msg || ( embed.description && embed.thumbnail?.url !== thumbnail && !embed.brokenInfobox && !fragment ) ) {
  58. return;
  59. }
  60. var change = false;
  61. if ( contentmodel !== 'wikitext' ) {
  62. return got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=content&rvslots=main&converttitles=true&titles=%1F' + encodeURIComponent( title ) + '&format=json' ).then( response => {
  63. var body = response.body;
  64. if ( body && body.warnings ) log_warn(body.warnings);
  65. var revision = Object.values(( body?.query?.pages || {} ))?.[0]?.revisions?.[0];
  66. revision = ( revision?.slots?.main || revision );
  67. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !revision?.['*'] ) {
  68. console.log( '- ' + response.statusCode + ': Error while getting the page content: ' + ( body && body.error && body.error.info ) );
  69. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  70. embed.spliceFields( 0, 0, embed.backupField );
  71. change = true;
  72. }
  73. if ( embed.backupDescription && embed.length < 5000 ) {
  74. embed.setDescription( embed.backupDescription );
  75. change = true;
  76. }
  77. return;
  78. }
  79. if ( !embed.description && embed.length < 4000 ) {
  80. var description = revision['*'];
  81. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  82. if ( regex ) {
  83. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  84. if ( descArray.length ) {
  85. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  86. if ( description ) {
  87. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  88. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  89. embed.setDescription( description );
  90. change = true;
  91. }
  92. }
  93. }
  94. else if ( description.trim() ) {
  95. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  96. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  97. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  98. embed.setDescription( description );
  99. change = true;
  100. }
  101. else if ( embed.backupDescription ) {
  102. embed.setDescription( embed.backupDescription );
  103. change = true;
  104. }
  105. }
  106. }, error => {
  107. console.log( '- Error while getting the page content: ' + error );
  108. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  109. embed.spliceFields( 0, 0, embed.backupField );
  110. change = true;
  111. }
  112. if ( embed.backupDescription && embed.length < 5000 ) {
  113. embed.setDescription( embed.backupDescription );
  114. change = true;
  115. }
  116. } ).finally( () => {
  117. if ( change ) msg.edit( msg.content, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  118. } );
  119. }
  120. got.get( wiki + 'api.php?action=parse&prop=text|images' + ( fragment ? '' : '&section=0' ) + '&disablelimitreport=true&disableeditsection=true&disabletoc=true&sectionpreview=true&page=' + encodeURIComponent( title ) + '&format=json' ).then( response => {
  121. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  122. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  123. if ( embed.backupDescription && embed.length < 5000 ) {
  124. embed.setDescription( embed.backupDescription );
  125. change = true;
  126. }
  127. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  128. embed.spliceFields( 0, 0, embed.backupField );
  129. change = true;
  130. }
  131. return;
  132. }
  133. var $ = cheerio.load(response.body.parse.text['*'].replace( /<br\/?>/g, '\n' ));
  134. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  135. var infobox = $('aside.portable-infobox');
  136. embed.fields.forEach( field => {
  137. if ( embed.length > 5400 ) return;
  138. if ( /^`.+`$/.test(field.name) ) {
  139. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  140. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  141. if ( label ) {
  142. label = htmlToPlain(label).trim();
  143. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  144. if ( label ) field.name = label;
  145. }
  146. }
  147. if ( /^`.+`$/.test(field.value) ) {
  148. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  149. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  150. if ( value ) {
  151. value = htmlToDiscord(value, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  152. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  153. if ( value ) field.value = value;
  154. }
  155. }
  156. } );
  157. change = true;
  158. }
  159. if ( embed.thumbnail?.url === thumbnail ) {
  160. var image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  161. if ( !image ) {
  162. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  163. img = $(img).prop('src')?.toLowerCase();
  164. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  165. } ).first().prop('src');
  166. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  167. img = $(img).prop('src')?.toLowerCase();
  168. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  169. } ).first().prop('src');
  170. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  171. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  172. } );
  173. }
  174. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  175. if ( thumbnail ) {
  176. embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  177. change = true;
  178. }
  179. }
  180. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  181. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  182. var section = $('h1, h2, h3, h4, h5, h6').children('span').filter( (i, span) => {
  183. return ( '#' + span.attribs.id === toSection(fragment) );
  184. } ).parent();
  185. if ( section.length ) {
  186. var sectionLevel = section[0].tagName.replace('h', '');
  187. var sectionContent = $('<div>').append(
  188. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  189. );
  190. section.find(removeClasses.join(', ')).remove();
  191. sectionContent.find(infoboxList.join(', ')).remove();
  192. sectionContent.find(removeClasses.join(', ')).remove();
  193. var name = htmlToPlain(section).trim();
  194. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  195. var value = htmlToDiscord(sectionContent, wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  196. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  197. if ( name.length && value.length ) {
  198. embed.spliceFields( 0, 0, {name, value} );
  199. change = true;
  200. }
  201. else if ( embed.backupField ) {
  202. embed.spliceFields( 0, 0, embed.backupField );
  203. change = true;
  204. }
  205. }
  206. else if ( embed.backupField ) {
  207. embed.spliceFields( 0, 0, embed.backupField );
  208. change = true;
  209. }
  210. }
  211. if ( !embed.description && embed.length < 5000 ) {
  212. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  213. $('h1, h2, h3, h4, h5, h6').remove();
  214. $(infoboxList.join(', ')).remove();
  215. $(removeClasses.join(', '), $('.mw-parser-output')).not(keepMainPageTag.join(', ')).remove();
  216. var description = htmlToDiscord($.html(), wiki.articleURL.href, true).trim().replace( /\n{3,}/g, '\n\n' );
  217. if ( description ) {
  218. if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  219. embed.setDescription( description );
  220. change = true;
  221. }
  222. else if ( embed.backupDescription ) {
  223. embed.setDescription( embed.backupDescription );
  224. change = true;
  225. }
  226. }
  227. }, error => {
  228. console.log( '- Error while parsing the page: ' + error );
  229. if ( embed.backupDescription && embed.length < 5000 ) {
  230. embed.setDescription( embed.backupDescription );
  231. change = true;
  232. }
  233. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  234. embed.spliceFields( 0, 0, embed.backupField );
  235. change = true;
  236. }
  237. } ).finally( () => {
  238. if ( change ) msg.edit( msg.content, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  239. } );
  240. }
  241. module.exports = parse_page;