inline.js 13 KB

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