inline.js 13 KB

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