parse_page.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import cheerio from 'cheerio';
  2. import {MessageEmbed} from 'discord.js';
  3. import {toSection} from '../util/wiki.js';
  4. import {got, parse_infobox, htmlToPlain, htmlToDiscord, escapeFormatting, limitLength} from '../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.introduction',
  59. 'div.wikibase-entityview',
  60. 'div.wikibase-entityview-main',
  61. 'div.wikibase-entitytermsview',
  62. 'div.wikibase-entitytermsview-heading',
  63. 'div.wikibase-entitytermsview-heading-description',
  64. 'div#wb-lexeme-header',
  65. 'div#wb-lexeme-header div:not([class]):not([id])',
  66. 'div.language-lexical-category-widget'
  67. ];
  68. /**
  69. * Parses a wiki page to get it's description.
  70. * @param {import('../util/i18n.js').default} lang - The user language.
  71. * @param {import('discord.js').Message} msg - The Discord message.
  72. * @param {String} content - The content for the message.
  73. * @param {import('discord.js').MessageEmbed} embed - The embed for the message.
  74. * @param {import('../util/wiki.js').default} wiki - The wiki for the page.
  75. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  76. * @param {Object} querypage - The details of the page.
  77. * @param {Number} querypage.ns - The namespace of the page.
  78. * @param {String} querypage.title - The title of the page.
  79. * @param {String} querypage.contentmodel - The content model of the page.
  80. * @param {String} querypage.pagelanguage - The language of the page.
  81. * @param {String} [querypage.missing] - If the page doesn't exist.
  82. * @param {String} [querypage.known] - If the page is known.
  83. * @param {Object} [querypage.pageprops] - The properties of the page.
  84. * @param {String} [querypage.pageprops.infoboxes] - The JSON data for portable infoboxes on the page.
  85. * @param {String} [querypage.pageprops.disambiguation] - The disambiguation property of the page.
  86. * @param {String} [querypage.pageprops.uselang] - The language of the page description.
  87. * @param {Boolean} [querypage.pageprops.noRedirect] - If the page is allowed to be redirected.
  88. * @param {String} [thumbnail] - The default thumbnail for the wiki.
  89. * @param {String} [fragment] - The section title to embed.
  90. * @param {String} [pagelink] - The link to the page.
  91. * @returns {Promise<import('discord.js').Message>} The edited message.
  92. */
  93. export default function parse_page(lang, msg, content, embed, wiki, reaction, {ns, title, contentmodel, pagelanguage, missing, known, pageprops: {infoboxes, disambiguation} = {}, uselang = lang.lang, noRedirect = false}, thumbnail = '', fragment = '', pagelink = '') {
  94. if ( reaction ) reaction.removeEmoji();
  95. if ( !msg?.showEmbed?.() || ( missing !== undefined && ( ns !== 8 || known === undefined ) ) || !embed || embed.description ) {
  96. if ( missing !== undefined && embed ) {
  97. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  98. embed.spliceFields( 0, 0, embed.backupField );
  99. }
  100. if ( embed.backupDescription && embed.length < 5000 ) {
  101. embed.setDescription( embed.backupDescription );
  102. }
  103. }
  104. return msg.sendChannel( {content: content, embeds: [embed]} );
  105. }
  106. return msg.sendChannel( {
  107. content,
  108. embeds: [new MessageEmbed(embed).setDescription( '<a:loading:641343250661113886> **' + lang.get('search.loading') + '**' )]
  109. } ).then( message => {
  110. if ( !message ) return;
  111. if ( ns === 8 ) {
  112. title = title.split(':').slice(1).join(':');
  113. if ( title.endsWith( '/' + pagelanguage ) ) title = title.substring(0, title.length - ( pagelanguage.length + 1 ));
  114. return got.get( wiki + 'api.php?action=query&meta=allmessages&amprop=default&amincludelocal=true&amlang=' + encodeURIComponent( pagelanguage ) + '&ammessages=' + encodeURIComponent( title ) + '&format=json', {
  115. timeout: {
  116. request: 10_000
  117. }
  118. } ).then( response => {
  119. var body = response.body;
  120. if ( body && body.warnings ) log_warning(body.warnings);
  121. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query?.allmessages?.[0] ) {
  122. console.log( '- ' + response.statusCode + ': Error while getting the system message: ' + body?.error?.info );
  123. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  124. embed.spliceFields( 0, 0, embed.backupField );
  125. }
  126. if ( embed.backupDescription && embed.length < 5000 ) {
  127. embed.setDescription( embed.backupDescription );
  128. }
  129. return;
  130. }
  131. if ( !embed.description && embed.length < 4000 ) {
  132. var description = body.query.allmessages[0]['*'];
  133. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  134. if ( regex ) {
  135. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  136. if ( descArray.length ) {
  137. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  138. if ( description ) {
  139. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  140. description = '```' + ( contentModels[contentmodel] || '' ) + '\n' + description + '\n```';
  141. embed.setDescription( description );
  142. }
  143. }
  144. }
  145. else {
  146. let defaultDescription = body.query.allmessages[0].default;
  147. if ( description.trim() ) {
  148. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  149. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  150. description = '```' + ( contentModels[contentmodel] || '' ) + '\n' + description + '\n```';
  151. embed.setDescription( description );
  152. }
  153. else if ( embed.backupDescription ) {
  154. embed.setDescription( embed.backupDescription );
  155. }
  156. if ( defaultDescription?.trim() ) {
  157. defaultDescription = defaultDescription.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  158. if ( defaultDescription.length > 250 ) defaultDescription = defaultDescription.substring(0, 250) + '\u2026';
  159. defaultDescription = '```' + ( contentModels[contentmodel] || '' ) + '\n' + defaultDescription + '\n```';
  160. embed.addField( lang.get('search.messagedefault'), defaultDescription );
  161. }
  162. else if ( body.query.allmessages[0].defaultmissing !== undefined ) {
  163. embed.addField( lang.get('search.messagedefault'), lang.get('search.messagedefaultnone') );
  164. }
  165. }
  166. }
  167. }, error => {
  168. console.log( '- Error while getting the system message: ' + error );
  169. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  170. embed.spliceFields( 0, 0, embed.backupField );
  171. }
  172. if ( embed.backupDescription && embed.length < 5000 ) {
  173. embed.setDescription( embed.backupDescription );
  174. }
  175. } ).then( () => {
  176. return message.edit( {content, embeds: [embed]} ).catch(log_error);
  177. } );
  178. }
  179. 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', {
  180. timeout: {
  181. request: 10_000
  182. }
  183. } ).then( response => {
  184. var body = response.body;
  185. if ( body && body.warnings ) log_warning(body.warnings);
  186. var revision = Object.values(( body?.query?.pages || {} ))?.[0]?.revisions?.[0];
  187. revision = ( revision?.slots?.main || revision );
  188. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !revision?.['*'] ) {
  189. console.log( '- ' + response.statusCode + ': Error while getting the page content: ' + ( body && body.error && body.error.info ) );
  190. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  191. embed.spliceFields( 0, 0, embed.backupField );
  192. }
  193. if ( embed.backupDescription && embed.length < 5000 ) {
  194. embed.setDescription( embed.backupDescription );
  195. }
  196. return;
  197. }
  198. if ( !embed.description && embed.length < 4000 ) {
  199. var description = revision['*'];
  200. var regex = /^L(\d+)(?:-L?(\d+))?$/.exec(fragment);
  201. if ( regex ) {
  202. let descArray = description.split('\n').slice(regex[1] - 1, ( regex[2] || regex[1] ));
  203. if ( descArray.length ) {
  204. description = descArray.join('\n').replace( /^\n+/, '' ).replace( /\n+$/, '' );
  205. if ( description ) {
  206. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  207. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  208. embed.setDescription( description );
  209. }
  210. }
  211. }
  212. else if ( description.trim() ) {
  213. description = description.replace( /^\n+/, '' ).replace( /\n+$/, '' );
  214. if ( description.length > 500 ) description = description.substring(0, 500) + '\u2026';
  215. description = '```' + ( contentModels[revision.contentmodel] || contentFormats[revision.contentformat] || '' ) + '\n' + description + '\n```';
  216. embed.setDescription( description );
  217. }
  218. else if ( embed.backupDescription ) {
  219. embed.setDescription( embed.backupDescription );
  220. }
  221. }
  222. }, error => {
  223. console.log( '- Error while getting the page content: ' + error );
  224. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  225. embed.spliceFields( 0, 0, embed.backupField );
  226. }
  227. if ( embed.backupDescription && embed.length < 5000 ) {
  228. embed.setDescription( embed.backupDescription );
  229. }
  230. } ).then( () => {
  231. return message.edit( {content, embeds: [embed]} ).catch(log_error);
  232. } );
  233. if ( !fragment && !embed.fields.length && infoboxes ) {
  234. try {
  235. var infobox = JSON.parse(infoboxes)?.[0];
  236. parse_infobox(infobox, embed, thumbnail, embed.url);
  237. }
  238. catch ( error ) {
  239. console.log( '- Failed to parse the infobox: ' + error );
  240. }
  241. }
  242. let extraImages = [];
  243. 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', {
  244. timeout: {
  245. request: 10_000
  246. }
  247. } ).then( response => {
  248. if ( response.statusCode !== 200 || !response?.body?.parse?.text ) {
  249. console.log( '- ' + response.statusCode + ': Error while parsing the page: ' + response?.body?.error?.info );
  250. if ( embed.backupDescription && embed.length < 5000 ) {
  251. embed.setDescription( embed.backupDescription );
  252. }
  253. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  254. embed.spliceFields( 0, 0, embed.backupField );
  255. }
  256. return;
  257. }
  258. if ( !embed.forceTitle ) {
  259. var displaytitle = htmlToDiscord( response.body.parse.displaytitle );
  260. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  261. embed.setTitle( displaytitle );
  262. }
  263. var $ = cheerio.load(response.body.parse.text['*'].replace( /\n?<br(?: ?\/)?>\n?/g, '<br>' ));
  264. if ( embed.brokenInfobox && $('aside.portable-infobox').length ) {
  265. let infobox = $('aside.portable-infobox');
  266. embed.fields.forEach( field => {
  267. if ( embed.length > 5400 ) return;
  268. if ( /^`.+`$/.test(field.name) ) {
  269. let label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-label, .pi-data-label[data-source="$1"]' )).html();
  270. if ( !label ) label = infobox.find(field.name.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-label, .pi-data-label[data-item-name="$1"]' )).html();
  271. if ( label ) {
  272. label = htmlToPlain(label).trim();
  273. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  274. if ( label ) field.name = label;
  275. }
  276. }
  277. if ( /^`.+`$/.test(field.value) ) {
  278. let value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-source="$1"] .pi-data-value, .pi-data-value[data-source="$1"]' )).html();
  279. if ( !value ) value = infobox.find(field.value.replace( /^`(.+)`$/, '[data-item-name="$1"] .pi-data-value, .pi-data-value[data-item-name="$1"]' )).html();
  280. if ( value ) {
  281. value = htmlToDiscord(value, embed.url).trim().replace( /\n{3,}/g, '\n\n' );
  282. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  283. if ( value ) field.value = value;
  284. }
  285. }
  286. } );
  287. }
  288. if ( !fragment && !embed.fields.length && $(infoboxList.join(', ')).length ) {
  289. let infobox = $(infoboxList.join(', ')).first();
  290. if ( embed.thumbnail?.url === thumbnail ) {
  291. let image = infobox.find([
  292. 'tr:eq(1) img',
  293. 'div.images img',
  294. 'figure.pi-image img',
  295. 'div.infobox-imagearea img'
  296. ].join(', ')).toArray().find( img => {
  297. let imgURL = img.attribs.src;
  298. if ( !imgURL ) return false;
  299. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  300. } )?.attribs.src?.replace( /^(?:https?:)?\/\//, 'https://' );
  301. if ( image ) embed.setThumbnail( new URL(image, wiki).href );
  302. }
  303. let rows = infobox.find([
  304. '> tbody > tr',
  305. '> tbody > tr > th.mainheader',
  306. '> tbody > tr > th.infobox-header',
  307. '> table > tbody > tr',
  308. 'div.section > div.title',
  309. 'div.section > table > tbody > tr',
  310. 'h2.pi-header',
  311. 'div.pi-data',
  312. 'table.infobox-rows > tbody > tr',
  313. 'div.infobox-rows:not(.subinfobox) > div.infobox-row'
  314. ].join(', '));
  315. let tdLabel = true;
  316. for ( let i = 0; i < rows.length; i++ ) {
  317. if ( embed.fields.length >= 25 || embed.length > 5400 ) break;
  318. let row = rows.eq(i);
  319. if ( row.is('th.mainheader, th.infobox-header, div.title, h2.pi-header') ) {
  320. row.find(removeClasses.join(', ')).remove();
  321. let label = htmlToDiscord(row, embed.url).trim();
  322. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  323. if ( label ) {
  324. if ( !label.includes( '**' ) ) label = '**' + label + '**';
  325. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  326. embed.spliceFields( embed.fields.length - 1, 1, {
  327. name: '\u200b',
  328. value: label,
  329. inline: false
  330. } );
  331. }
  332. else embed.addField( '\u200b', label, false );
  333. }
  334. }
  335. else if ( row.is('tr, div.pi-data, div.infobox-row') ) {
  336. let label = row.children(( tdLabel ? 'td, ' : '' ) + 'th, h3.pi-data-label, div.infobox-cell-header').eq(0);
  337. label.find(removeClasses.join(', ')).remove();
  338. let value = row.children('td, div.pi-data-value, div.infobox-cell-data').eq(( label.is('td') ? 1 : 0 ));
  339. value.find(removeClasses.join(', ')).remove();
  340. if ( !label.is('td') && label.html()?.trim() && value.html()?.trim() ) tdLabel = false;
  341. label = htmlToPlain(label).trim().split('\n')[0];
  342. value = htmlToDiscord(value, embed.url).trim().replace( /\n{3,}/g, '\n\n' );
  343. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  344. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  345. if ( label && value ) embed.addField( label, value, true );
  346. }
  347. }
  348. if ( embed.fields.length && embed.fields[embed.fields.length - 1].name === '\u200b' ) {
  349. embed.spliceFields( embed.fields.length - 1, 1 );
  350. }
  351. }
  352. if ( embed.thumbnail?.url === thumbnail ) {
  353. let image = response.body.parse.images.find( pageimage => ( /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase()) && pageimage.toLowerCase().includes( title.toLowerCase().replace( / /g, '_' ) ) ) );
  354. if ( !image ) {
  355. thumbnail = $(infoboxList.join(', ')).find('img').filter( (i, img) => {
  356. img = $(img).prop('src')?.toLowerCase();
  357. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  358. } ).first().prop('src');
  359. if ( !thumbnail ) thumbnail = $('img').filter( (i, img) => {
  360. img = $(img).prop('src')?.toLowerCase();
  361. return ( /^(?:https?:)?\/\//.test(img) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/.test(img) );
  362. } ).first().prop('src');
  363. if ( !thumbnail ) image = response.body.parse.images.find( pageimage => {
  364. return /\.(?:png|jpg|jpeg|gif)$/.test(pageimage.toLowerCase());
  365. } );
  366. }
  367. if ( image ) thumbnail = wiki.toLink('Special:FilePath/' + image);
  368. if ( thumbnail ) embed.setThumbnail( thumbnail.replace( /^(?:https?:)?\/\//, 'https://' ) );
  369. }
  370. if ( fragment && embed.length < 4750 && embed.fields.length < 25 &&
  371. toSection(embed.fields[0]?.name.replace( /^\**_*(.*?)_*\**$/g, '$1' )) !== toSection(fragment) ) {
  372. let newFragment = '';
  373. let exactMatch = true;
  374. let allSections = $('h1, h2, h3, h4, h5, h6').children('span');
  375. var section = allSections.filter( (i, span) => {
  376. return ( '#' + span.attribs.id === toSection(fragment) );
  377. } ).parent();
  378. if ( !section.length ) {
  379. section = $('[id="' + toSection(fragment, false).replace( '#', '' ) + '"]');
  380. newFragment = section.attr('id');
  381. if ( section.is(':empty') ) {
  382. section = section.parent();
  383. if ( ['h1','h2','h3','h4','h5','h6'].includes( section.prev()[0]?.tagName ) ) {
  384. section = section.prev();
  385. if ( section.children('span').first().attr('id') ) {
  386. newFragment = section.children('span').first().attr('id');
  387. }
  388. }
  389. }
  390. }
  391. if ( !section.length ) exactMatch = false;
  392. if ( !section.length ) section = allSections.filter( (i, span) => {
  393. return ( '#' + span.attribs.id?.toLowerCase() === toSection(fragment).toLowerCase() );
  394. } );
  395. if ( !section.length ) section = allSections.filter( (i, span) => {
  396. return ( $(span).parent().text().trim() === fragment );
  397. } );
  398. if ( !section.length ) section = allSections.filter( (i, span) => {
  399. return ( $(span).parent().text().trim().toLowerCase() === fragment.toLowerCase() );
  400. } );
  401. if ( !section.length ) section = allSections.filter( (i, span) => {
  402. return $(span).parent().text().toLowerCase().includes( fragment.toLowerCase() );
  403. } );
  404. if ( !exactMatch && section.length ) {
  405. newFragment = section.attr('id');
  406. section = section.parent();
  407. }
  408. if ( section.length ) {
  409. section = section.first();
  410. var sectionLevel = section[0].tagName.replace('h', '');
  411. if ( !['1','2','3','4','5','6'].includes( sectionLevel ) ) sectionLevel = '10';
  412. var sectionContent = $('<div>').append(
  413. section.nextUntil(['h1','h2','h3','h4','h5','h6'].slice(0, sectionLevel).join(', '))
  414. );
  415. section.find('div, ' + removeClasses.join(', ')).remove();
  416. extraImages.push(...new Set([
  417. ...sectionContent.find(infoboxList.join(', ')).find([
  418. 'tr:eq(1) img',
  419. 'div.images img',
  420. 'figure.pi-image img',
  421. 'div.infobox-imagearea img'
  422. ].join(', ')).toArray(),
  423. ...sectionContent.find('ul.gallery > li.gallerybox img').toArray()
  424. ].filter( img => {
  425. let imgURL = ( img.attribs.src?.startsWith?.( 'data:' ) ? img.attribs['data-src'] : img.attribs.src );
  426. if ( !imgURL ) return false;
  427. return ( /^(?:https?:)?\/\//.test(imgURL) && /\.(?:png|jpg|jpeg|gif)(?:\/|\?|$)/i.test(imgURL) );
  428. } ).map( img => {
  429. let imgURL = ( img.attribs.src?.startsWith?.( 'data:' ) ? img.attribs['data-src'] : img.attribs.src );
  430. imgURL = imgURL.replace( /\/thumb(\/[\da-f]\/[\da-f]{2}\/([^\/]+))\/\d+px-\2/, '$1' ).replace( /\/scale-to-width-down\/\d+/, '' );
  431. return new URL(imgURL.replace( /^(?:https?:)?\/\//, 'https://' ), wiki).href;
  432. } )));
  433. sectionContent.find(infoboxList.join(', ')).remove();
  434. sectionContent.find('div, ' + removeClasses.join(', ')).not(removeClassesExceptions.join(', ')).remove();
  435. var name = htmlToPlain(section).trim();
  436. if ( !name.length ) name = escapeFormatting(fragment);
  437. if ( name.length > 250 ) name = name.substring(0, 250) + '\u2026';
  438. var value = htmlToDiscord(sectionContent, embed.url).trim().replace( /\n{3,}/g, '\n\n' );
  439. if ( value.length > 1000 ) value = limitLength(value, 1000, 20);
  440. if ( name.length && value.length ) {
  441. embed.spliceFields( 0, 0, {name, value} );
  442. if ( newFragment ) {
  443. embed.setURL( pagelink.replace( toSection(fragment), toSection(newFragment) ) );
  444. content = content.replace( '<' + pagelink + '>', '<' + embed.url + '>' );
  445. }
  446. }
  447. else if ( embed.backupField ) {
  448. embed.spliceFields( 0, 0, embed.backupField );
  449. }
  450. }
  451. else if ( embed.backupField ) {
  452. embed.spliceFields( 0, 0, embed.backupField );
  453. }
  454. }
  455. if ( !embed.description && embed.length < 5000 ) {
  456. if ( contentmodel !== 'wikitext' || disambiguation === undefined || fragment ) {
  457. $('h1, h2, h3, h4, h5, h6').nextAll().remove();
  458. $('h1, h2, h3, h4, h5, h6').remove();
  459. }
  460. $(infoboxList.join(', ')).remove();
  461. $('div, ' + removeClasses.join(', '), $('.mw-parser-output')).not(removeClassesExceptions.join(', ')).remove();
  462. var description = htmlToDiscord($.html(), embed.url, true).trim().replace( /\n{3,}/g, '\n\n' );
  463. if ( description ) {
  464. if ( disambiguation !== undefined && !fragment && embed.length < 4250 ) {
  465. if ( description.length > 1500 ) description = limitLength(description, 1500, 250);
  466. }
  467. else if ( fragment && description.length > 500 ) description = limitLength(description, 500, 250);
  468. else if ( description.length > 1000 ) description = limitLength(description, 1000, 500);
  469. embed.setDescription( description );
  470. }
  471. else if ( embed.backupDescription ) {
  472. embed.setDescription( embed.backupDescription );
  473. }
  474. }
  475. }, error => {
  476. console.log( '- Error while parsing the page: ' + error );
  477. if ( embed.backupDescription && embed.length < 5000 ) {
  478. embed.setDescription( embed.backupDescription );
  479. }
  480. if ( embed.backupField && embed.length < 4750 && embed.fields.length < 25 ) {
  481. embed.spliceFields( 0, 0, embed.backupField );
  482. }
  483. } ).then( () => {
  484. let embeds = [embed];
  485. if ( extraImages.length ) {
  486. if ( !embed.image ) embed.setImage( extraImages.shift() );
  487. extraImages.slice(0, 10).forEach( extraImage => {
  488. let imageEmbed = new MessageEmbed().setURL( embed.url ).setImage( extraImage );
  489. if ( embeds.length < 5 && embeds.reduce( (acc, val) => acc + val.length, imageEmbed.length ) <= 5500 ) embeds.push(imageEmbed);
  490. } );
  491. }
  492. return message.edit( {content, embeds} ).catch(log_error);
  493. } );
  494. } );
  495. }