inline.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. const logging = require('../util/logging.js');
  2. const Wiki = require('../util/wiki.js');
  3. const {limitLength, partialURIdecode, allowDelete} = require('../util/functions.js');
  4. /**
  5. * Post a message with inline wiki links.
  6. * @param {Object} interaction - The interaction.
  7. * @param {import('../util/i18n.js')} lang - The user language.
  8. * @param {import('../util/wiki.js')} wiki - The wiki for the interaction.
  9. * @param {import('discord.js').TextChannel} [channel] - The channel for the interaction.
  10. */
  11. function slash_inline(interaction, lang, wiki, channel) {
  12. var text = ( interaction.data.options?.[0]?.value || '' ).replace( /\]\(/g, ']\\(' );
  13. text = text.replace( /\x1F/g, '' ).replace( /(?<!@)\u200b/g, '' ).trim();
  14. if ( !text ) {
  15. return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
  16. json: {
  17. type: 4,
  18. data: {
  19. content: lang.get('interaction.inline'),
  20. allowed_mentions: {
  21. parse: []
  22. },
  23. flags: 64
  24. }
  25. }
  26. } ).then( response => {
  27. if ( response.statusCode !== 204 ) {
  28. console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
  29. }
  30. }, log_error );
  31. }
  32. var allowed_mentions = {
  33. parse: ['users']
  34. };
  35. if ( interaction.guild_id ) {
  36. if ( ( (interaction.member.permissions & 1 << 3) === 1 << 3 ) // ADMINISTRATOR
  37. || ( (interaction.member.permissions & 1 << 17) === 1 << 17 ) ) { // MENTION_EVERYONE
  38. allowed_mentions.parse = ['users', 'roles', 'everyone'];
  39. }
  40. else if ( channel?.guild ) {
  41. allowed_mentions.roles = channel.guild.roles.cache.filter( role => role.mentionable ).map( role => role.id ).slice(0, 100);
  42. }
  43. if ( channel?.guild && ( (interaction.member.permissions & 1 << 3) !== 1 << 3 ) // ADMINISTRATOR
  44. && ( (interaction.member.permissions & 1 << 18) !== 1 << 18 ) ) { // USE_EXTERNAL_EMOJIS
  45. text = text.replace( /(?<!\\)<a?(:\w+:)\d+>/g, (replacement, emoji, id) => {
  46. if ( channel.guild.emojis.cache.has(id) ) {
  47. return replacement;
  48. }
  49. return emoji;
  50. } );
  51. }
  52. }
  53. if ( text.length > 1800 ) text = text.substring(0, 1800) + '\u2026';
  54. var message = {
  55. content: text.replace( /(?<!\\)<a?(:\w+:)\d+>/g, (replacement, emoji, id) => {
  56. if ( channel?.guild?.emojis.cache.has(id) ) {
  57. return replacement;
  58. }
  59. return emoji;
  60. } ),
  61. allowed_mentions
  62. };
  63. return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
  64. json: {
  65. type: 4,
  66. data: {
  67. content: text.replace( /(?<!\\)<a?(:\w+:)\d+>/g, (replacement, emoji, id) => {
  68. if ( channel?.guild?.emojis.cache.has(id) ) {
  69. return replacement;
  70. }
  71. return emoji;
  72. } ),
  73. allowed_mentions,
  74. flags: 0
  75. }
  76. }
  77. } ).then( aresponse => {
  78. if ( aresponse.statusCode !== 204 ) {
  79. console.log( '- Slash: ' + aresponse.statusCode + ': Error while sending the response: ' + aresponse.body?.message );
  80. return;
  81. }
  82. if ( !text.includes( '{{' ) && !( text.includes( '[[' ) && text.includes( ']]' ) ) && !text.includes( 'PMID' ) && !text.includes( 'RFC' ) && !text.includes( 'ISBN' ) ) {
  83. return sendMessage(interaction, message, channel);
  84. }
  85. var textReplacement = [];
  86. var magiclinks = [];
  87. var replacedText = text.replace( /(?<!\\)(?:<a?(:\w+:)\d+>|<#(\d+)>|<@!?(\d+)>|<@&(\d+)>|```.+?```|``.+?``|`.+?`)/gs, (replacement, emoji, textchannel, user, role) => {
  88. textReplacement.push(replacement);
  89. var arg = '';
  90. if ( emoji ) arg = emoji;
  91. if ( channel ) {
  92. if ( textchannel ) {
  93. let tempchannel = channel.client.channels.cache.get(textchannel);
  94. if ( tempchannel ) arg = '#' + tempchannel.name;
  95. }
  96. if ( user ) {
  97. let tempuser = channel.guild?.members.cache.get(user);
  98. if ( tempuser ) arg = '@' + tempuser.displayName;
  99. else {
  100. tempuser = channel.client.users.cache.get(user);
  101. if ( tempuser ) arg = '@' + tempuser.username;
  102. }
  103. }
  104. if ( role ) {
  105. let temprole = channel.guild?.roles.cache.get(role);
  106. if ( temprole ) arg = '@' + temprole.name;
  107. }
  108. }
  109. return '\x1F<replacement\x1F' + textReplacement.length + ( arg ? '\x1F' + arg : '' ) + '>\x1F';
  110. } ).replace( /\b(PMID|RFC) +([0-9]+)\b/g, (replacement, type, id) => {
  111. magiclinks.push({type, id, replacementId: textReplacement.length});
  112. textReplacement.push(replacement);
  113. return '\x1F<replacement\x1F' + textReplacement.length + '\x1F' + replacement + '>\x1F';
  114. } ).replace( /\bISBN +((?:97[89][- ]?)?(?:[0-9][- ]?){9}[0-9Xx])\b/g, (replacement, id) => {
  115. let isbn = id.replace( /[- ]/g, '' ).replace( /x/g, 'X' );
  116. magiclinks.push({type: 'ISBN', id, isbn, replacementId: textReplacement.length});
  117. textReplacement.push(replacement);
  118. return '\x1F<replacement\x1F' + textReplacement.length + '\x1F' + replacement + '>\x1F';
  119. } );
  120. var templates = [];
  121. var links = [];
  122. var breakInline = false;
  123. replacedText.replace( /\x1F<replacement\x1F\d+\x1F(.+?)>\x1F/g, '$1' ).replace( /(?:%[\dA-F]{2})+/g, partialURIdecode ).split('\n').forEach( line => {
  124. if ( line.startsWith( '>>> ' ) ) breakInline = true;
  125. if ( line.startsWith( '> ' ) || breakInline ) return;
  126. var inlineLink = null;
  127. var regex = /(?<!\\|\{)\{\{(?:\s*(?:subst|safesubst|raw|msg|msgnw):)?([^<>\[\]\|\{\}\x01-\x1F\x7F#]+)(?<!\\)(?:\||\}\})/g;
  128. while ( ( inlineLink = regex.exec(line) ) !== null ) {
  129. let title = inlineLink[1].trim();
  130. if ( !title.replace( /:/g, '' ).trim().length || title.startsWith( '/' ) ) continue;
  131. if ( title.startsWith( 'int:' ) ) templates.push({
  132. raw: title,
  133. title: title.replace( /^int:/, 'MediaWiki:' ),
  134. template: title.replace( /^int:/, 'MediaWiki:' )
  135. });
  136. else templates.push({raw: title, title, template: 'Template:' + title});
  137. }
  138. inlineLink = null;
  139. regex = /(?<!\\)\[\[([^<>\[\]\|\{\}\x01-\x1F\x7F]+)(?:\|(?:(?!\[\[|\]\\\]).)*?)?(?<!\\)\]\]/g;
  140. while ( ( inlineLink = regex.exec(line) ) !== null ) {
  141. inlineLink[1] = inlineLink[1].trim();
  142. let title = inlineLink[1].split('#')[0].trim();
  143. let section = inlineLink[1].split('#').slice(1).join('#');
  144. if ( !title.replace( /:/g, '' ).trim().length || title.startsWith( '/' ) ) continue;
  145. links.push({raw: title, title, section});
  146. }
  147. } );
  148. if ( !templates.length && !links.length && !magiclinks.length ) {
  149. return sendMessage(interaction, message, channel);
  150. }
  151. return got.get( wiki + 'api.php?action=query&meta=siteinfo' + ( magiclinks.length ? '|allmessages&ammessages=pubmedurl|rfcurl&amenableparser=true' : '' ) + '&siprop=general&iwurl=true&titles=' + encodeURIComponent( [
  152. ...templates.map( link => link.title + '|' + link.template ),
  153. ...links.map( link => link.title ),
  154. ...( magiclinks.length ? ['Special:BookSources'] : [] )
  155. ].join('|') ) + '&format=json' ).then( response => {
  156. var body = response.body;
  157. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query ) {
  158. if ( wiki.noWiki(response.url, response.statusCode) ) {
  159. console.log( '- This wiki doesn\'t exist!' );
  160. }
  161. else {
  162. console.log( '- ' + response.statusCode + ': Error while following the links: ' + body?.error?.info );
  163. }
  164. return sendMessage(interaction, message, channel);
  165. }
  166. logging(wiki, interaction.guild_id, 'slash', 'inline');
  167. wiki.updateWiki(body.query.general);
  168. if ( body.query.normalized ) {
  169. body.query.normalized.forEach( title => {
  170. templates.filter( link => link.title === title.from ).forEach( link => link.title = title.to );
  171. templates.filter( link => link.template === title.from ).forEach( link => link.template = title.to );
  172. links.filter( link => link.title === title.from ).forEach( link => link.title = title.to );
  173. } );
  174. }
  175. if ( body.query.interwiki ) {
  176. body.query.interwiki.forEach( interwiki => {
  177. templates.filter( link => link.title === interwiki.title ).forEach( link => {
  178. link.url = decodeURI(interwiki.url)
  179. } );
  180. links.filter( link => link.title === interwiki.title ).forEach( link => {
  181. link.url = ( link.section ? decodeURI(interwiki.url.split('#')[0]) + Wiki.toSection(link.section) : decodeURI(interwiki.url) );
  182. } );
  183. } );
  184. }
  185. if ( body.query.pages ) {
  186. Object.values(body.query.pages).forEach( page => {
  187. templates.filter( link => link.title === page.title ).forEach( link => {
  188. if ( page.invalid !== undefined || ( page.missing !== undefined && page.known === undefined ) ) {
  189. link.title = '';
  190. }
  191. else if ( page.ns === 0 && !link.raw.startsWith( ':' ) ) {
  192. link.title = '';
  193. }
  194. } );
  195. templates.filter( link => link.template === page.title ).forEach( link => {
  196. if ( page.invalid !== undefined || ( page.missing !== undefined && page.known === undefined ) ) {
  197. link.template = '';
  198. }
  199. } );
  200. links.filter( link => link.title === page.title ).forEach( link => {
  201. link.ns = page.ns;
  202. if ( page.invalid !== undefined ) return links.splice(links.indexOf(link), 1);
  203. if ( page.missing !== undefined && page.known === undefined ) {
  204. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) {
  205. return;
  206. }
  207. if ( wiki.isMiraheze() && page.ns === 0 && /^Mh:[a-z\d]+:/.test(page.title) ) {
  208. var iw_parts = page.title.split(':');
  209. var iw = new Wiki('https://' + iw_parts[1] + '.miraheze.org/w/');
  210. link.url = iw.toLink(iw_parts.slice(2).join(':'), '', link.section, true);
  211. return;
  212. }
  213. return links.splice(links.indexOf(link), 1);
  214. }
  215. } );
  216. } );
  217. }
  218. if ( magiclinks.length && body.query?.allmessages?.length === 2 ) {
  219. magiclinks = magiclinks.filter( link => body.query.general.magiclinks.hasOwnProperty(link.type) );
  220. if ( magiclinks.length ) magiclinks.forEach( link => {
  221. if ( link.type === 'PMID' && body.query.allmessages[0]?.['*']?.includes( '$1' ) ) {
  222. link.url = new URL(body.query.allmessages[0]['*'].replace( /\$1/g, link.id ), wiki).href;
  223. }
  224. if ( link.type === 'RFC' && body.query.allmessages[1]?.['*']?.includes( '$1' ) ) {
  225. link.url = new URL(body.query.allmessages[1]['*'].replace( /\$1/g, link.id ), wiki).href;
  226. }
  227. if ( link.type === 'ISBN' ) {
  228. let title = 'Special:BookSources';
  229. title = ( body.query.normalized?.find( title => title.from === title )?.to || title );
  230. link.url = wiki.toLink(title + '/' + link.isbn, '', '', true);
  231. }
  232. if ( link.url ) {
  233. console.log( ( interaction.guild_id || '@' + interaction.user.id ) + ': Slash: ' + link.type + ' ' + link.id );
  234. textReplacement[link.replacementId] = '[' + link.type + ' ' + link.id + '](<' + link.url + '>)';
  235. }
  236. } );
  237. }
  238. templates = templates.filter( link => link.title || link.template );
  239. if ( templates.length || links.length || magiclinks.length ) {
  240. breakInline = false;
  241. if ( templates.length || links.length ) replacedText = replacedText.split('\n').map( line => {
  242. if ( line.startsWith( '>>> ' ) ) breakInline = true;
  243. if ( line.startsWith( '> ' ) || breakInline ) return line;
  244. let regex = null;
  245. if ( line.includes( '{{' ) ) {
  246. regex = /(?<!\\|\{)(\{\{(?:\s*(?:subst|safesubst|raw|msg|msgnw):)?\s*)((?:[^<>\[\]\|\{\}\x01-\x1F\x7F#]|\x1F<replacement\x1F\d+\x1F.+?>\x1F)+?)(\s*(?<!\\)\||\}\})/g;
  247. line = line.replace( regex, (fullLink, linkprefix, title, linktrail) => {
  248. title = title.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode ).replace( /\x1F<replacement\x1F\d+\x1F(.+?)>\x1F/g, '$1' ).trim();
  249. let link = templates.find( link => link.raw === title );
  250. if ( !link ) return fullLink;
  251. console.log( ( interaction.guild_id || '@' + interaction.user.id ) + ': Slash: ' + fullLink );
  252. if ( title.startsWith( 'int:' ) ) {
  253. title = title.replace( /^int:\s*/, replacement => {
  254. linkprefix += replacement;
  255. return '';
  256. } );
  257. }
  258. return linkprefix + '[' + title + '](<' + ( link.url || wiki.toLink(link.title || link.template, '', '', true) ) + '>)' + linktrail;
  259. } );
  260. }
  261. if ( line.includes( '[[' ) && line.includes( ']]' ) ) {
  262. regex = new RegExp( '([' + body.query.general.linkprefixcharset.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ) + ']+)?' + '(?<!\\\\)\\[\\[' + '((?:[^' + "<>\\[\\]\\|\{\}\\x01-\\x1F\\x7F" + ']|' + '\\x1F<replacement\\x1F\\d+\\x1F.+?>\\x1F' + ')+)' + '(?:\\|((?:(?!\\[\\[|\\]\\(|\\]\\\\\\]).)*?))?' + '(?<!\\\\)\\]\\]' + body.query.general.linktrail.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ).replace( /^\/\^(\(\[.+?\]\+\))\(\.\*\)\$\/sDu?$/, '$1?' ), 'gu' );
  263. line = line.replace( regex, (fullLink, linkprefix = '', title, display, linktrail = '') => {
  264. title = title.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode ).replace( /\x1F<replacement\x1F\d+\x1F(.+?)>\x1F/g, '$1' ).split('#')[0].trim();
  265. let link = links.find( link => link.raw === title );
  266. if ( !link ) return fullLink;
  267. console.log( ( interaction.guild_id || '@' + interaction.user.id ) + ': Slash: ' + fullLink );
  268. if ( display === undefined ) display = title.replace( /^\s*:?/, '' );
  269. if ( !display.trim() ) {
  270. display = title.replace( /^\s*:/, '' );
  271. if ( display.includes( ',' ) && !/ ([^\(\)]+)$/.test(display) ) {
  272. display = display.replace( /^([^,]+), .*$/, '$1' );
  273. }
  274. display = display.replace( / \([^\(\)]+\)$/, '' );
  275. if ( link.url || link.ns !== 0 ) {
  276. display = display.split(':').slice(1).join(':');
  277. }
  278. }
  279. return '[' + ( linkprefix + display + linktrail ).replace( /\x1F<replacement\x1F\d+\x1F((?:PMID|RFC|ISBN) .+?)>\x1F/g, '$1' ).replace( /[\[\]\(\)]/g, '\\$&' ) + '](<' + ( link.url || wiki.toLink(link.title, '', link.section, true) ) + '>)';
  280. } );
  281. }
  282. return line;
  283. } ).join('\n');
  284. text = replacedText.replace( /\x1F<replacement\x1F(\d+)(?:\x1F.+?)?>\x1F/g, (replacement, id) => {
  285. return textReplacement[id - 1];
  286. } );
  287. if ( text.length > 1900 ) text = limitLength(text, 1900, 100);
  288. message.content = text;
  289. return sendMessage(interaction, message, channel);
  290. }
  291. else return sendMessage(interaction, message, channel);
  292. }, error => {
  293. if ( wiki.noWiki(error.message) ) {
  294. console.log( '- This wiki doesn\'t exist!' );
  295. }
  296. else {
  297. console.log( '- Error while following the links: ' + error );
  298. }
  299. return sendMessage(interaction, message, channel);
  300. } );
  301. }, log_error );
  302. }
  303. /**
  304. * Sends an interaction response.
  305. * @param {Object} interaction - The interaction.
  306. * @param {Object} message - The message.
  307. * @param {String} message.content - The message content.
  308. * @param {{parse: String[], roles?: String[]}} message.allowed_mentions - The allowed mentions.
  309. * @param {import('discord.js').TextChannel} [channel] - The channel for the interaction.
  310. * @returns {Promise<import('discord.js').Message?>}
  311. */
  312. function sendMessage(interaction, message, channel) {
  313. return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
  314. json: message
  315. } ).then( response => {
  316. if ( response.statusCode !== 200 ) {
  317. console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
  318. return;
  319. }
  320. return channel?.messages.fetch(response.body.id).then( msg => {
  321. if ( msg ) allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
  322. return msg;
  323. }, () => {} );
  324. }, log_error );
  325. }
  326. module.exports = {
  327. name: 'inline',
  328. run: slash_inline
  329. };