parse_page.js 10 KB

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