parse_page.js 23 KB

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