parse_page.js 23 KB

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