special_page.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. const {MessageEmbed, Util} = require('discord.js');
  2. const logging = require('../util/logging.js');
  3. const {timeoptions} = require('../util/default.json');
  4. const {toMarkdown, escapeFormatting} = require('../util/functions.js');
  5. const overwrites = {
  6. randompage: (fn, lang, msg, wiki, querystring, fragment, reaction, spoiler, args, embed, query) => {
  7. let namespaces = Object.values(query.namespaces);
  8. let contentNamespaces = namespaces.filter( ns => ns.content !== undefined );
  9. let namespaceData = [contentNamespaces.map( ns => ns.id ).join('|'), contentNamespaces.map( ns => ( ns['*'] || '*' ) ).join(', ')];
  10. if ( args[0] ) {
  11. args[0] = args[0].replace( /_/g, ' ' ).toLowerCase().trim();
  12. let namespaceMap = {};
  13. namespaces.forEach( namespace => {
  14. if ( namespace.id < 0 ) return;
  15. if ( namespace.canonical ) namespaceMap[namespace.canonical.toLowerCase()] = namespace.id;
  16. namespaceMap[namespace['*'].toLowerCase()] = namespace.id;
  17. } );
  18. query.namespacealiases.forEach( namespace => {
  19. if ( namespace.id < 0 ) return;
  20. namespaceMap[namespace['*'].toLowerCase()] = namespace.id;
  21. } );
  22. if ( namespaceMap.hasOwnProperty(args[0]) ) {
  23. namespaceData = [namespaceMap[args[0]].toString(), ( namespaces.find( namespace => namespace.id === namespaceMap[args[0]] )?.['*'] || '*' )];
  24. }
  25. else if ( args[0] === '*' ) namespaceData = ['*', '*'];
  26. }
  27. fn.random(lang, msg, wiki, reaction, spoiler, namespaceData, querystring, fragment, embed);
  28. },
  29. statistics: (fn, lang, msg, wiki, querystring, fragment, reaction, spoiler) => {
  30. fn.overview(lang, msg, wiki, reaction, spoiler, querystring, fragment);
  31. },
  32. diff: (fn, lang, msg, wiki, querystring, fragment, reaction, spoiler, args, embed) => {
  33. fn.diff(lang, msg, args, wiki, reaction, spoiler, embed);
  34. }
  35. }
  36. const queryfunctions = {
  37. title: (query, wiki) => query.querypage.results.map( result => {
  38. return '[' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, '', '', true) + ')';
  39. } ).join('\n'),
  40. times: (query, wiki, lang) => query.querypage.results.map( result => {
  41. return parseInt(result.value, 10).toLocaleString(lang.get('dateformat')) + '× [' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, '', '', true) + ')';
  42. } ).join('\n'),
  43. size: (query, wiki, lang) => query.querypage.results.map( result => {
  44. return lang.get('diff.info.bytes', parseInt(result.value, 10).toLocaleString(lang.get('dateformat')), result.value) + ': [' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, '', '', true) + ')';
  45. } ).join('\n'),
  46. redirect: (query, wiki) => query.querypage.results.map( result => {
  47. return '[' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, 'redirect=no', '', true) + ')' + ( result.databaseResult && result.databaseResult.rd_title ? ' → ' + escapeFormatting(result.databaseResult.rd_title) : '' );
  48. } ).join('\n'),
  49. doubleredirect: (query, wiki) => query.querypage.results.map( result => {
  50. return '[' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, 'redirect=no', '', true) + ')' + ( result.databaseResult && result.databaseResult.b_title && result.databaseResult.c_title ? ' → ' + escapeFormatting(result.databaseResult.b_title) + ' → ' + escapeFormatting(result.databaseResult.c_title) : '' );
  51. } ).join('\n'),
  52. timestamp: (query, wiki, lang) => query.querypage.results.map( result => {
  53. try {
  54. var dateformat = new Intl.DateTimeFormat(lang.get('dateformat'), Object.assign({
  55. timeZone: query.general.timezone
  56. }, timeoptions));
  57. }
  58. catch ( error ) {
  59. var dateformat = new Intl.DateTimeFormat(lang.get('dateformat'), Object.assign({
  60. timeZone: 'UTC'
  61. }, timeoptions));
  62. }
  63. let lastEditDate = new Date(result.timestamp);
  64. return dateformat.format(lastEditDate) + ' <t:' + Math.trunc(lastEditDate.getTime() / 1000) + ':R>: [' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, '', '', true) + ')';
  65. } ).join('\n'),
  66. media: (query, wiki, lang) => query.querypage.results.map( result => {
  67. var ms = result.title.split(';');
  68. return '**' + ms[1] + '**: ' + lang.get('search.category.files', parseInt(ms[2], 10).toLocaleString(lang.get('dateformat')), parseInt(ms[2], 10)) + ' (' + lang.get('diff.info.bytes', parseInt(ms[3], 10).toLocaleString(lang.get('dateformat')), parseInt(ms[3], 10)) + ')';
  69. } ).join('\n'),
  70. category: (query, wiki, lang) => query.querypage.results.map( result => {
  71. return parseInt(result.value, 10).toLocaleString(lang.get('dateformat')) + '× [' + escapeFormatting(result.title) + '](' + wiki.toLink('Category:' + result.title, '', '', true) + ')';
  72. } ).join('\n'),
  73. gadget: (query, wiki, lang) => query.querypage.results.map( result => {
  74. result.title = result.title.replace( /^(?:.*:)?gadget-/, '' );
  75. return '**' + escapeFormatting(result.title) + '**: ' + parseInt(result.value, 10).toLocaleString(lang.get('dateformat')) + ' users (' + result.ns.toLocaleString(lang.get('dateformat')) + ' active)';
  76. } ).join('\n'),
  77. recentchanges: (query, wiki) => query.recentchanges.map( result => {
  78. return '[' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, ( result.type === 'edit' ? {diff:result.revid,oldid:result.old_revid} : '' ), '', true) + ')';
  79. } ).join('\n')
  80. }
  81. const querypages = {
  82. ancientpages: ['&list=querypage&qplimit=10&qppage=Ancientpages', queryfunctions.timestamp],
  83. brokenredirects: ['&list=querypage&qplimit=10&qppage=BrokenRedirects', queryfunctions.redirect],
  84. deadendpages: ['&list=querypage&qplimit=10&qppage=Deadendpages', queryfunctions.title],
  85. doubleredirects: ['&list=querypage&qplimit=10&qppage=DoubleRedirects', queryfunctions.doubleredirect],
  86. fewestrevisions: ['&list=querypage&qplimit=10&qppage=Fewestrevisions', queryfunctions.times],
  87. listduplicatedfiles: ['&list=querypage&qplimit=10&qppage=ListDuplicatedFiles', queryfunctions.times],
  88. listredirects: ['&list=querypage&qplimit=10&qppage=Listredirects', queryfunctions.redirect],
  89. lonelypages: ['&list=querypage&qplimit=10&qppage=Lonelypages', queryfunctions.title],
  90. longpages: ['&list=querypage&qplimit=10&qppage=Longpages', queryfunctions.size],
  91. mediastatistics: ['&list=querypage&qplimit=10&qppage=MediaStatistics', queryfunctions.media],
  92. mostcategories: ['&list=querypage&qplimit=10&qppage=Mostcategories', queryfunctions.times],
  93. mostimages: ['&list=querypage&qplimit=10&qppage=Mostimages', queryfunctions.times],
  94. mostinterwikis: ['&list=querypage&qplimit=10&qppage=Mostinterwikis', queryfunctions.times],
  95. mostlinked: ['&list=querypage&qplimit=10&qppage=Mostlinked', queryfunctions.times],
  96. mostlinkedcategories: ['&list=querypage&qplimit=10&qppage=Mostlinkedcategories', queryfunctions.times],
  97. mostlinkedtemplates: ['&list=querypage&qplimit=10&qppage=Mostlinkedtemplates', queryfunctions.times],
  98. mostrevisions: ['&list=querypage&qplimit=10&qppage=Mostrevisions', queryfunctions.times],
  99. shortpages: ['&list=querypage&qplimit=10&qppage=Shortpages', queryfunctions.size],
  100. uncategorizedcategories: ['&list=querypage&qplimit=10&qppage=Uncategorizedcategories', queryfunctions.title],
  101. uncategorizedpages: ['&list=querypage&qplimit=10&qppage=Uncategorizedpages', queryfunctions.title],
  102. uncategorizedimages: ['&list=querypage&qplimit=10&qppage=Uncategorizedimages', queryfunctions.title],
  103. uncategorizedtemplates: ['&list=querypage&qplimit=10&qppage=Uncategorizedtemplates', queryfunctions.title],
  104. unusedcategories: ['&list=querypage&qplimit=10&qppage=Unusedcategories', queryfunctions.title],
  105. unusedimages: ['&list=querypage&qplimit=10&qppage=Unusedimages', queryfunctions.title],
  106. unusedtemplates: ['&list=querypage&qplimit=10&qppage=Unusedtemplates', queryfunctions.title],
  107. unwatchedpages: ['&list=querypage&qplimit=10&qppage=Unwatchedpages', queryfunctions.title],
  108. wantedcategories: ['&list=querypage&qplimit=10&qppage=Wantedcategories', queryfunctions.times],
  109. wantedfiles: ['&list=querypage&qplimit=10&qppage=Wantedfiles', queryfunctions.times],
  110. wantedpages: ['&list=querypage&qplimit=10&qppage=Wantedpages', queryfunctions.times],
  111. wantedtemplates: ['&list=querypage&qplimit=10&qppage=Wantedtemplates', queryfunctions.times],
  112. withoutinterwiki: ['&list=querypage&qplimit=10&qppage=Withoutinterwiki', queryfunctions.title],
  113. gadgetusage: ['&list=querypage&qplimit=10&qppage=GadgetUsage', queryfunctions.gadget],
  114. recentchanges: ['&list=recentchanges&rctype=edit|new|log&rclimit=10', queryfunctions.recentchanges],
  115. disambiguations: ['&list=querypage&qplimit=10&qppage=Disambiguations', queryfunctions.title],
  116. mostpopularcategories: ['&list=querypage&qplimit=10&qppage=Mostpopularcategories', queryfunctions.category],
  117. mostlinkedfilesincontent: ['&list=querypage&qplimit=10&qppage=MostLinkedFilesInContent', queryfunctions.times],
  118. unusedvideos: ['&list=querypage&qplimit=10&qppage=UnusedVideos', queryfunctions.title],
  119. withoutimages: ['&list=querypage&qplimit=10&qppage=Withoutimages', queryfunctions.title],
  120. nonportableinfoboxes: ['&list=querypage&qplimit=10&qppage=Nonportableinfoboxes', queryfunctions.title],
  121. popularpages: ['&list=querypage&qplimit=10&qppage=Popularpages', queryfunctions.title],
  122. pageswithoutinfobox: ['&list=querypage&qplimit=10&qppage=Pageswithoutinfobox', queryfunctions.title],
  123. templateswithouttype: ['&list=querypage&qplimit=10&qppage=Templateswithouttype', queryfunctions.title],
  124. allinfoboxes: ['&list=querypage&qplimit=10&qppage=AllInfoboxes', queryfunctions.title]
  125. }
  126. const descriptions = {
  127. block: 'blockiptext&amargs=16|19',
  128. checkuser: 'checkuser-summary&amargs=16|19',
  129. resettokens: 'resettokens-text',
  130. allmessages: 'allmessagestext',
  131. expandtemplates: 'expand_templates_intro',
  132. apisandbox: 'apisandbox-intro',
  133. abusefilter: 'abusefilter-intro',
  134. gadgets: 'gadgets-pagetext',
  135. categorytree: 'categorytree-header',
  136. drafts: 'drafts-view-summary&amargs=30',
  137. analytics: 'analytics_confidential',
  138. mostlinkedfilesincontent: 'mostimagesincontent-summary',
  139. popularpages: 'insights-list-description-popularpages'
  140. }
  141. /**
  142. * Processes special pages.
  143. * @param {import('../util/i18n.js')} lang - The user language.
  144. * @param {import('discord.js').Message} msg - The Discord message.
  145. * @param {Object} querypage - The details of the special page.
  146. * @param {String} querypage.title - The title of the special page.
  147. * @param {String} querypage.uselang - The language of the special page.
  148. * @param {String} specialpage - The canonical name of the special page.
  149. * @param {Object} query - The siteinfo from the wiki.
  150. * @param {import('../util/wiki.js')} wiki - The wiki for the page.
  151. * @param {URLSearchParams} querystring - The querystring for the link.
  152. * @param {String} fragment - The section for the link.
  153. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  154. * @param {String} spoiler - If the response is in a spoiler.
  155. */
  156. function special_page(lang, msg, {title, uselang = lang.lang}, specialpage, query, wiki, querystring, fragment, reaction, spoiler) {
  157. var pagelink = wiki.toLink(title, querystring, fragment);
  158. var embed = new MessageEmbed().setAuthor( query.general.sitename ).setTitle( escapeFormatting(title) ).setURL( pagelink ).setThumbnail( new URL(query.general.logo, wiki).href );
  159. if ( overwrites.hasOwnProperty(specialpage) ) {
  160. var args = title.split('/').slice(1,3);
  161. overwrites[specialpage](this, lang, msg, wiki, querystring, fragment, reaction, spoiler, args, embed, query);
  162. return;
  163. }
  164. logging(wiki, msg.guild?.id, 'general', 'special');
  165. if ( specialpage === 'recentchanges' && msg.isAdmin() ) {
  166. embed.addField( lang.get('rcscript.title'), lang.get('rcscript.ad', ( patreons[msg?.guild?.id] || process.env.prefix ), '[RcGcDw](https://gitlab.com/piotrex43/RcGcDw)') );
  167. }
  168. got.get( wiki + 'api.php?uselang=' + uselang + '&action=query&meta=allmessages|siteinfo&siprop=general&amenableparser=true&amtitle=' + encodeURIComponent( title ) + '&ammessages=' + encodeURIComponent( specialpage ) + '|' + ( descriptions.hasOwnProperty(specialpage) ? descriptions[specialpage] : encodeURIComponent( specialpage ) + '-summary' ) + ( querypages.hasOwnProperty(specialpage) ? querypages[specialpage][0] : '' ) + '&format=json' ).then( response => {
  169. var body = response.body;
  170. if ( body && body.warnings ) log_warn(body.warnings);
  171. if ( response.statusCode !== 200 || body?.batchcomplete === undefined ) {
  172. console.log( '- ' + response.statusCode + ': Error while getting the special page: ' + ( body && body.error && body.error.info ) );
  173. return;
  174. }
  175. if ( body.query.allmessages?.[0]?.['*']?.trim?.() ) {
  176. let displaytitle = escapeFormatting(body.query.allmessages[0]['*'].trim());
  177. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  178. embed.setTitle( displaytitle );
  179. }
  180. if ( body.query.allmessages?.[1]?.['*']?.trim?.() ) {
  181. var description = toMarkdown(body.query.allmessages[1]['*'], wiki, title, true);
  182. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  183. embed.setDescription( description );
  184. }
  185. if ( msg.channel.isGuild() && patreons[msg.guild?.id] && querypages.hasOwnProperty(specialpage) ) {
  186. var text = Util.splitMessage( querypages[specialpage][1](body.query, wiki, lang), {maxLength:1000} )[0];
  187. embed.addField( lang.get('search.special'), ( text || lang.get('search.empty') ) );
  188. if ( body.query.querypage.cached !== undefined ) {
  189. embed.setFooter( lang.get('search.cached') ).setTimestamp(new Date(body.query.querypage.cachedtimestamp));
  190. }
  191. }
  192. }, error => {
  193. console.log( '- Error while getting the special page: ' + error );
  194. } ).finally( () => {
  195. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  196. if ( reaction ) reaction.removeEmoji();
  197. } );
  198. }
  199. module.exports = special_page;