1
0

functions.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. const htmlparser = require('htmlparser2');
  2. const got = require('got').extend( {
  3. throwHttpErrors: false,
  4. timeout: 5000,
  5. headers: {
  6. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ( process.env.invite ? '; ' + process.env.invite : '' ) + ')'
  7. },
  8. responseType: 'json'
  9. } );
  10. /**
  11. * @type {Map<String, {state: String, wiki: String, channel: import('discord.js').TextChannel, user: String}>}
  12. */
  13. const oauthVerify = new Map();
  14. /**
  15. * Parse infobox content
  16. * @param {Object} infobox - The content of the infobox.
  17. * @param {import('discord.js').MessageEmbed} embed - The message embed.
  18. * @param {String} [thumbnail] - The default thumbnail for the wiki.
  19. * @param {String} [pagelink] - The article path for relative links.
  20. * @returns {import('discord.js').MessageEmbed?}
  21. */
  22. function parse_infobox(infobox, embed, thumbnail, pagelink = '') {
  23. if ( !infobox || embed.fields.length >= 25 || embed.length > 5400 ) return;
  24. if ( infobox.parser_tag_version === 5 ) {
  25. infobox.data.forEach( group => {
  26. parse_infobox(group, embed, thumbnail, pagelink);
  27. } );
  28. embed.fields = embed.fields.filter( (field, i, fields) => {
  29. if ( field.name !== '\u200b' || !field.value.startsWith( '__**' ) ) return true;
  30. return ( fields[i + 1]?.name && ( fields[i + 1].name !== '\u200b' || !fields[i + 1].value.startsWith( '__**' ) ) );
  31. } );
  32. return embed;
  33. }
  34. switch ( infobox.type ) {
  35. case 'data':
  36. var {label = '', value = '', source = '', 'item-name': name = ''} = infobox.data;
  37. label = htmlToPlain(label, true).trim();
  38. value = htmlToDiscord(value, pagelink).trim();
  39. if ( label.includes( '*UNKNOWN LINK*' ) ) {
  40. if ( !( source || name ) ) break;
  41. label = '`' + ( source || name ) + '`';
  42. embed.brokenInfobox = true;
  43. }
  44. if ( value.includes( '*UNKNOWN LINK*' ) ) {
  45. if ( !( source || name ) ) break;
  46. value = '`' + ( source || name ) + '`';
  47. embed.brokenInfobox = true;
  48. }
  49. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  50. if ( value.length > 500 ) value = limitLength(value, 500, 250);
  51. if ( label && value ) embed.addField( label, value, true );
  52. break;
  53. case 'panel':
  54. var embedLength = embed.fields.length;
  55. infobox.data.value.forEach( group => {
  56. parse_infobox(group, embed, thumbnail, pagelink);
  57. } );
  58. embed.fields = embed.fields.filter( (field, i, fields) => {
  59. if ( i < embedLength || field.name !== '\u200b' ) return true;
  60. if ( !field.value.startsWith( '__**' ) ) return true;
  61. return ( fields[i + 1]?.name && fields[i + 1].name !== '\u200b' );
  62. } ).filter( (field, i, fields) => {
  63. if ( i < embedLength || field.name !== '\u200b' ) return true;
  64. if ( field.value.startsWith( '__**' ) ) return true;
  65. return ( fields[i + 1]?.name && ( fields[i + 1].name !== '\u200b' || !fields[i + 1].value.startsWith( '__**' ) ) );
  66. } );
  67. break;
  68. case 'section':
  69. var {label = ''} = infobox.data;
  70. label = htmlToPlain(label).trim();
  71. if ( label.length > 100 ) label = label.substring(0, 100) + '\u2026';
  72. if ( label ) embed.addField( '\u200b', '**' + label + '**', false );
  73. case 'group':
  74. infobox.data.value.forEach( group => {
  75. parse_infobox(group, embed, thumbnail, pagelink);
  76. } );
  77. break;
  78. case 'header':
  79. var {value = ''} = infobox.data;
  80. value = htmlToPlain(value).trim();
  81. if ( value.length > 100 ) value = value.substring(0, 100) + '\u2026';
  82. if ( value ) embed.addField( '\u200b', '__**' + value + '**__', false );
  83. break;
  84. case 'image':
  85. if ( embed.thumbnail?.url !== thumbnail ) return;
  86. var image = infobox.data.find( img => {
  87. return ( /^(?:https?:)?\/\//.test(img.url) && /\.(?:png|jpg|jpeg|gif)$/.test(img.name) );
  88. } );
  89. if ( image ) embed.setThumbnail( image.url.replace( /^(?:https?:)?\/\//, 'https://' ) );
  90. break;
  91. }
  92. }
  93. /**
  94. * Make wikitext formatting usage.
  95. * @param {String} [text] - The text to modify.
  96. * @param {Boolean} [showEmbed] - If the text is used in an embed.
  97. * @param {import('./wiki.js')} [wiki] - The wiki.
  98. * @param {String} [title] - The page title.
  99. * @param {Boolean} [fullWikitext] - If the text can contain full wikitext.
  100. * @returns {String}
  101. */
  102. function toFormatting(text = '', showEmbed = false, wiki, title = '', fullWikitext = false) {
  103. if ( showEmbed ) return toMarkdown(text, wiki, title, fullWikitext);
  104. else return toPlaintext(text, fullWikitext);
  105. };
  106. /**
  107. * Turns wikitext formatting into markdown.
  108. * @param {String} [text] - The text to modify.
  109. * @param {import('./wiki.js')} wiki - The wiki.
  110. * @param {String} [title] - The page title.
  111. * @param {Boolean} [fullWikitext] - If the text can contain full wikitext.
  112. * @returns {String}
  113. */
  114. function toMarkdown(text = '', wiki, title = '', fullWikitext = false) {
  115. text = text.replace( /[()\\]/g, '\\$&' );
  116. var link = null;
  117. var regex = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g;
  118. while ( ( link = regex.exec(text) ) !== null ) {
  119. var pagetitle = ( link[1] || link[2] );
  120. var page = wiki.toLink(( /^[#\/]/.test(pagetitle) ? title + ( pagetitle.startsWith( '/' ) ? pagetitle : '' ) : pagetitle ), '', ( pagetitle.startsWith( '#' ) ? pagetitle.substring(1) : '' ), true);
  121. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + page + ')' );
  122. }
  123. if ( title !== '' ) {
  124. regex = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g;
  125. while ( ( link = regex.exec(text) ) !== null ) {
  126. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink(title, '', link[1], true) + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  127. }
  128. }
  129. if ( fullWikitext ) {
  130. regex = /\[(?:https?:)?\/\/([^ ]+) ([^\]]+)\]/g;
  131. while ( ( link = regex.exec(text) ) !== null ) {
  132. text = text.replaceSave( link[0], '[' + link[2] + '](https://' + link[1] + ')' );
  133. }
  134. return htmlToDiscord(text, '', true, true).replaceSave( /'''/g, '**' ).replaceSave( /''/g, '*' );
  135. }
  136. return escapeFormatting(text, true);
  137. };
  138. /**
  139. * Removes wikitext formatting.
  140. * @param {String} [text] - The text to modify.
  141. * @param {Boolean} [fullWikitext] - If the text can contain full wikitext.
  142. * @returns {String}
  143. */
  144. function toPlaintext(text = '', fullWikitext = false) {
  145. text = text.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' );
  146. if ( fullWikitext ) {
  147. return htmlToDiscord( text.replace( /\[(?:https?:)?\/\/(?:[^ ]+) ([^\]]+)\]/g, '$1' ) );
  148. }
  149. else return escapeFormatting(text);
  150. };
  151. /**
  152. * Change HTML text to plain text.
  153. * @param {String} html - The text in HTML.
  154. * @returns {String}
  155. */
  156. function htmlToPlain(html, includeComments = false) {
  157. var text = '';
  158. var ignoredTag = '';
  159. var parser = new htmlparser.Parser( {
  160. onopentag: (tagname, attribs) => {
  161. if ( tagname === 'sup' && attribs.class === 'reference' ) ignoredTag = 'sup';
  162. if ( tagname === 'span' && attribs.class === 'smwttcontent' ) ignoredTag = 'span';
  163. if ( tagname === 'br' ) text += ' ';
  164. },
  165. ontext: (htmltext) => {
  166. if ( !ignoredTag ) {
  167. htmltext = htmltext.replace( /[\r\n\t ]+/g, ' ' );
  168. if ( /[\n ]$/.test(text) && htmltext.startsWith( ' ' ) ) htmltext = htmltext.replace( /^ +/, '' );
  169. text += escapeFormatting(htmltext);
  170. }
  171. },
  172. onclosetag: (tagname) => {
  173. if ( tagname === ignoredTag ) ignoredTag = '';
  174. },
  175. oncomment: (commenttext) => {
  176. if ( includeComments && /^(?:IW)?LINK'" \d+:\d+$/.test(commenttext) ) {
  177. text += '*UNKNOWN LINK*';
  178. }
  179. }
  180. } );
  181. parser.write( String(html) );
  182. parser.end();
  183. return text;
  184. };
  185. /**
  186. * Change HTML text to markdown text.
  187. * @param {String} html - The text in HTML.
  188. * @param {String} [pagelink] - The article path for relative links.
  189. * @param {Boolean[]} [escapeArgs] - Arguments for the escaping of text formatting.
  190. * @returns {String}
  191. */
  192. function htmlToDiscord(html, pagelink = '', ...escapeArgs) {
  193. var text = '';
  194. var code = false;
  195. var href = '';
  196. var ignoredTag = '';
  197. var syntaxhighlight = '';
  198. var listlevel = -1;
  199. var parser = new htmlparser.Parser( {
  200. onopentag: (tagname, attribs) => {
  201. if ( ignoredTag || code ) return;
  202. if ( tagname === 'sup' && attribs.class === 'reference' ) ignoredTag = 'sup';
  203. if ( tagname === 'span' && attribs.class === 'smwttcontent' ) ignoredTag = 'span';
  204. if ( tagname === 'code' ) {
  205. code = true;
  206. text += '`';
  207. }
  208. if ( tagname === 'pre' ) {
  209. code = true;
  210. text += '```' + syntaxhighlight + '\n';
  211. }
  212. if ( tagname === 'div' && attribs.class ) {
  213. let classes = attribs.class.split(' ');
  214. if ( classes.includes( 'mw-highlight' ) ) {
  215. syntaxhighlight = ( classes.find( syntax => syntax.startsWith( 'mw-highlight-lang-' ) )?.replace( 'mw-highlight-lang-', '' ) || '' );
  216. }
  217. }
  218. if ( tagname === 'b' || tagname === 'strong' ) text += '**';
  219. if ( tagname === 'i' ) text += '*';
  220. if ( tagname === 's' ) text += '~~';
  221. if ( tagname === 'u' ) text += '__';
  222. if ( tagname === 'br' ) {
  223. text += '\n';
  224. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel + 3);
  225. }
  226. if ( tagname === 'hr' ) {
  227. text = text.replace( / +$/, '' );
  228. if ( !text.endsWith( '\n' ) ) text += '\n';
  229. text += '─'.repeat(10) + '\n';
  230. }
  231. if ( tagname === 'p' && !text.endsWith( '\n' ) ) text += '\n';
  232. if ( tagname === 'ul' || tagname === 'ol' ) listlevel++;
  233. if ( tagname === 'li' ) {
  234. text = text.replace( / +$/, '' );
  235. if ( !text.endsWith( '\n' ) ) text += '\n';
  236. if ( attribs.class !== 'mw-empty-elt' ) {
  237. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel);
  238. text += '• ';
  239. }
  240. }
  241. if ( tagname === 'dl' ) listlevel++;
  242. if ( tagname === 'dt' ) {
  243. text = text.replace( / +$/, '' );
  244. if ( !text.endsWith( '\n' ) ) text += '\n';
  245. if ( attribs.class !== 'mw-empty-elt' ) {
  246. if ( listlevel > -1 ) text += '\u200b '.repeat(4 * listlevel);
  247. text += '**';
  248. }
  249. }
  250. if ( tagname === 'dd' ) {
  251. text = text.replace( / +$/, '' );
  252. if ( !text.endsWith( '\n' ) ) text += '\n';
  253. if ( listlevel > -1 && attribs.class !== 'mw-empty-elt' ) text += '\u200b '.repeat(4 * (listlevel + 1));
  254. }
  255. if ( tagname === 'img' ) {
  256. if ( attribs.alt && attribs.src ) {
  257. let showAlt = true;
  258. if ( attribs['data-image-name'] === attribs.alt ) showAlt = false;
  259. else {
  260. let regex = new RegExp( '/([\\da-f])/\\1[\\da-f]/' + attribs.alt.replace( / /g, '_' ).replace( /\W/g, '\\$&' ) + '(?:/|\\?|$)' );
  261. if ( attribs.src.startsWith( 'data:' ) && attribs['data-src'] ) attribs.src = attribs['data-src'];
  262. if ( regex.test(attribs.src.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode )) ) showAlt = false;
  263. }
  264. if ( showAlt ) {
  265. if ( href && !code ) attribs.alt = attribs.alt.replace( /[\[\]]/g, '\\$&' );
  266. if ( code ) text += attribs.alt.replace( /`/g, 'ˋ' );
  267. else text += escapeFormatting(attribs.alt, ...escapeArgs);
  268. }
  269. }
  270. }
  271. if ( tagname === 'h1' ) {
  272. text = text.replace( / +$/, '' );
  273. if ( !text.endsWith( '\n' ) ) text += '\n';
  274. text += '***__';
  275. }
  276. if ( tagname === 'h2' ) {
  277. text = text.replace( / +$/, '' );
  278. if ( !text.endsWith( '\n' ) ) text += '\n';
  279. text += '**__';
  280. }
  281. if ( tagname === 'h3' ) {
  282. text = text.replace( / +$/, '' );
  283. if ( !text.endsWith( '\n' ) ) text += '\n';
  284. text += '**';
  285. }
  286. if ( tagname === 'h4' ) {
  287. text = text.replace( / +$/, '' );
  288. if ( !text.endsWith( '\n' ) ) text += '\n';
  289. text += '__';
  290. }
  291. if ( tagname === 'h5' ) {
  292. text = text.replace( / +$/, '' );
  293. if ( !text.endsWith( '\n' ) ) text += '\n';
  294. text += '*';
  295. }
  296. if ( tagname === 'h6' ) {
  297. text = text.replace( / +$/, '' );
  298. if ( !text.endsWith( '\n' ) ) text += '\n';
  299. text += '';
  300. }
  301. if ( !pagelink ) return;
  302. if ( tagname === 'a' && attribs.href && attribs.class !== 'new' && /^(?:(?:https?:)?\/\/|\/|#)/.test(attribs.href) ) {
  303. href = new URL(attribs.href, pagelink).href.replace( /[()]/g, '\\$&' );
  304. if ( text.endsWith( '](<' + href + '>)' ) ) {
  305. text = text.substring(0, text.length - ( href.length + 5 ));
  306. }
  307. else text += '[';
  308. }
  309. },
  310. ontext: (htmltext) => {
  311. if ( !ignoredTag ) {
  312. if ( href && !code ) htmltext = htmltext.replace( /[\[\]]/g, '\\$&' );
  313. if ( code ) text += htmltext.replace( /`/g, 'ˋ' );
  314. else {
  315. htmltext = htmltext.replace( /[\r\n\t ]+/g, ' ' );
  316. if ( /[\n ]$/.test(text) && htmltext.startsWith( ' ' ) ) {
  317. htmltext = htmltext.replace( /^ +/, '' );
  318. }
  319. text += escapeFormatting(htmltext, ...escapeArgs);
  320. }
  321. }
  322. },
  323. onclosetag: (tagname) => {
  324. if ( tagname === ignoredTag ) {
  325. ignoredTag = '';
  326. return;
  327. }
  328. if ( code ) {
  329. if ( tagname === 'code' ) {
  330. code = false;
  331. text += '`';
  332. }
  333. if ( tagname === 'pre' ) {
  334. code = false;
  335. text += '\n```';
  336. }
  337. return;
  338. }
  339. if ( syntaxhighlight && tagname === 'div' ) syntaxhighlight = '';
  340. if ( tagname === 'b' ) text += '**';
  341. if ( tagname === 'i' ) text += '*';
  342. if ( tagname === 's' ) text += '~~';
  343. if ( tagname === 'u' ) text += '__';
  344. if ( tagname === 'ul' || tagname === 'ol' ) listlevel--;
  345. if ( tagname === 'dl' ) listlevel--;
  346. if ( tagname === 'dt' ) text += '**';
  347. if ( tagname === 'h1' ) text += '__***';
  348. if ( tagname === 'h2' ) text += '__**';
  349. if ( tagname === 'h3' ) text += '**';
  350. if ( tagname === 'h4' ) text += '__';
  351. if ( tagname === 'h5' ) text += '*';
  352. if ( tagname === 'h6' ) text += '';
  353. if ( !pagelink ) return;
  354. if ( tagname === 'a' && href ) {
  355. if ( text.endsWith( '[' ) ) text = text.substring(0, text.length - 1);
  356. else text += '](<' + href + '>)';
  357. href = '';
  358. }
  359. },
  360. oncomment: (commenttext) => {
  361. if ( pagelink && /^(?:IW)?LINK'" \d+:\d+$/.test(commenttext) ) {
  362. text += '*UNKNOWN LINK*';
  363. }
  364. }
  365. } );
  366. parser.write( String(html) );
  367. parser.end();
  368. return text;
  369. };
  370. /**
  371. * Escapes formatting.
  372. * @param {String} [text] - The text to modify.
  373. * @param {Boolean} [isMarkdown] - The text contains markdown links.
  374. * @param {Boolean} [keepLinks] - Don't escape non-markdown links.
  375. * @returns {String}
  376. */
  377. function escapeFormatting(text = '', isMarkdown = false, keepLinks = false) {
  378. if ( !isMarkdown ) text = text.replace( /\\/g, '\\\\' ).replace( /\]\(/g, ']\\(' );
  379. if ( !keepLinks ) text = text.replace( /\/\//g, '/\\/' );
  380. return text.replace( /[`_*~:<>{}@|]/g, '\\$&' );
  381. };
  382. /**
  383. * Limit text length without breaking link formatting.
  384. * @param {String} [text] - The text to modify.
  385. * @param {Number} [limit] - The character limit.
  386. * @param {Number} [maxExtra] - The maximal allowed character limit if needed.
  387. * @returns {String}
  388. */
  389. function limitLength(text = '', limit = 1000, maxExtra = 20) {
  390. var suffix = '\u2026';
  391. var link = null;
  392. var regex = /(?<!\\)\[((?:[^\[\]]|\\[\[\]])*?[^\\])\]\(<?(?:[^()]|\\[()])+?[^\\]>?\)/g;
  393. while ( ( link = regex.exec(text) ) !== null ) {
  394. if ( link.index < limit && link.index + link[0].length > limit ) {
  395. if ( link.index + link[0].length < limit + maxExtra ) suffix = link[0];
  396. else if ( link.index + link[1].length < limit + maxExtra ) suffix = link[1];
  397. if ( link.index + link[0].length < text.length ) suffix += '\u2026';
  398. limit = link.index;
  399. break;
  400. }
  401. else if ( link.index >= limit ) break;
  402. }
  403. return text.substring(0, limit) + suffix;
  404. };
  405. /**
  406. * Try to URI decode.
  407. * @param {String} m - The character to decode.
  408. * @returns {String}
  409. */
  410. function partialURIdecode(m) {
  411. var text = '';
  412. try {
  413. text = decodeURIComponent( m );
  414. }
  415. catch ( replaceError ) {
  416. if ( isDebug ) console.log( '- Failed to decode ' + m + ':' + replaceError );
  417. text = m;
  418. }
  419. return text;
  420. };
  421. /**
  422. * Allow users to delete their command responses.
  423. * @param {import('discord.js').Message} msg - The response.
  424. * @param {String} author - The user id.
  425. */
  426. function allowDelete(msg, author) {
  427. msg?.awaitReactions?.( {
  428. filter: (reaction, user) => ( reaction.emoji.name === '🗑️' && user.id === author ),
  429. max: 1, time: 300000
  430. } ).then( reaction => {
  431. if ( reaction.size ) msg.delete().catch(log_error);
  432. } );
  433. };
  434. /**
  435. * Sends an interaction response.
  436. * @param {import('discord.js').CommandInteraction|import('discord.js').ButtonInteraction} interaction - The interaction.
  437. * @param {import('discord.js').MessageOptions} message - The message.
  438. * @param {Boolean} [letDelete] - Let the interaction user delete the message.
  439. * @returns {Promise<import('discord.js').Message?>}
  440. */
  441. function sendMessage(interaction, message, letDelete = true) {
  442. if ( message?.embeds?.length && !message.embeds[0] ) message.embeds = [];
  443. return interaction.editReply( message ).then( msg => {
  444. if ( letDelete && (msg.flags & 64) !== 64 ) allowDelete(msg, interaction.user.id);
  445. return msg;
  446. }, log_error );
  447. };
  448. module.exports = {
  449. got,
  450. oauthVerify,
  451. parse_infobox,
  452. toFormatting,
  453. toMarkdown,
  454. toPlaintext,
  455. htmlToPlain,
  456. htmlToDiscord,
  457. escapeFormatting,
  458. limitLength,
  459. partialURIdecode,
  460. allowDelete,
  461. sendMessage
  462. };