general.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. const htmlparser = require('htmlparser2');
  2. const {MessageEmbed} = require('discord.js');
  3. const {limit: {interwiki: interwikiLimit}, wikiProjects} = require('../../../util/default.json');
  4. const Wiki = require('../../../util/wiki.js');
  5. const fs = require('fs');
  6. var fn = {
  7. special_page: require('../../../functions/special_page.js'),
  8. discussion: require('../../../functions/discussion.js')
  9. };
  10. fs.readdir( './cmds/wiki/fandom', (error, files) => {
  11. if ( error ) return error;
  12. files.filter( file => ( file !== 'general.js' && file.endsWith('.js') ) ).forEach( file => {
  13. var command = require('./' + file);
  14. fn[command.name] = command.run;
  15. } );
  16. } );
  17. /**
  18. * Checks a Fandom wiki.
  19. * @param {import('../../../util/i18n.js')} lang - The user language.
  20. * @param {import('discord.js').Message} msg - The Discord message.
  21. * @param {String} title - The page title.
  22. * @param {Wiki} wiki - The wiki for the page.
  23. * @param {String} cmd - The command at this point.
  24. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  25. * @param {String} [spoiler] - If the response is in a spoiler.
  26. * @param {URLSearchParams} [querystring] - The querystring for the link.
  27. * @param {String} [fragment] - The section for the link.
  28. * @param {String} [interwiki] - The fallback interwiki link.
  29. * @param {Number} [selfcall] - The amount of followed interwiki links.
  30. */
  31. function fandom_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = new URLSearchParams(), fragment = '', interwiki = '', selfcall = 0) {
  32. var full_title = title;
  33. if ( title.includes( '#' ) ) {
  34. fragment = title.split('#').slice(1).join('#');
  35. title = title.split('#')[0];
  36. }
  37. if ( /\?\w+=/.test(title) ) {
  38. var querystart = title.search(/\?\w+=/);
  39. querystring = new URLSearchParams(querystring + '&' + title.substring(querystart + 1));
  40. title = title.substring(0, querystart);
  41. }
  42. if ( title.length > 250 ) {
  43. title = title.substring(0, 250);
  44. msg.reactEmoji('⚠️');
  45. }
  46. var invoke = title.split(' ')[0].toLowerCase();
  47. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  48. var args = title.split(' ').slice(1);
  49. if ( aliasInvoke === 'random' && !args.join('') && !querystring.toString() && !fragment ) {
  50. return fn.random(lang, msg, wiki, reaction, spoiler);
  51. }
  52. if ( aliasInvoke === 'overview' && !args.join('') && !querystring.toString() && !fragment ) {
  53. return fn.overview(lang, msg, wiki, reaction, spoiler);
  54. }
  55. if ( aliasInvoke === 'test' && !args.join('') && !querystring.toString() && !fragment ) {
  56. this.test(lang, msg, args, '', wiki);
  57. if ( reaction ) reaction.removeEmoji();
  58. return;
  59. }
  60. if ( aliasInvoke === 'page' ) {
  61. msg.sendChannel( spoiler + '<' + wiki.toLink(args.join('_'), querystring, fragment) + '>' + spoiler );
  62. if ( reaction ) reaction.removeEmoji();
  63. return;
  64. }
  65. if ( aliasInvoke === 'diff' && args.join('') && !querystring.toString() && !fragment ) {
  66. return fn.diff(lang, msg, args, wiki, reaction, spoiler);
  67. }
  68. var noRedirect = ( querystring.getAll('redirect').pop() === 'no' || ( querystring.has('action') && querystring.getAll('action').pop() !== 'view' ) );
  69. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=description&amenableparser=true&siprop=general|namespaces|specialpagealiases|wikidesc&iwurl=true' + ( noRedirect ? '' : '&redirects=true' ) + '&prop=imageinfo|categoryinfo&converttitles=true&titles=' + encodeURIComponent( title.replace( /\|/g, '\ufffd' ) ) + '&format=json' ).then( response => {
  70. var body = response.body;
  71. if ( body && body.warnings ) log_warn(body.warnings);
  72. if ( response.statusCode !== 200 || !body || !body.query ) {
  73. if ( interwiki ) msg.sendChannel( spoiler + ' ' + interwiki + ' ' + spoiler );
  74. else if ( wiki.noWiki(response.url, response.statusCode) ) {
  75. console.log( '- This wiki doesn\'t exist!' );
  76. msg.reactEmoji('nowiki');
  77. }
  78. else {
  79. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  80. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring.toString() || fragment || !title ? title : 'Special:Search' ), ( querystring.toString() || fragment || !title ? querystring : {search:title} ), fragment) + '>' + spoiler );
  81. }
  82. if ( reaction ) reaction.removeEmoji();
  83. return;
  84. }
  85. wiki.updateWiki(body.query.general);
  86. if ( aliasInvoke === 'search' ) {
  87. return fn.search(lang, msg, full_title.split(' ').slice(1).join(' '), wiki, body.query, reaction, spoiler);
  88. }
  89. if ( aliasInvoke === 'discussion' && !querystring.toString() && !fragment ) {
  90. return fn.discussion(lang, msg, wiki, args.join(' '), body.query, reaction, spoiler);
  91. }
  92. if ( body.query.pages ) {
  93. var querypages = Object.values(body.query.pages);
  94. var querypage = querypages[0];
  95. if ( body.query.redirects && body.query.redirects[0].from.split(':')[0] === body.query.namespaces['-1']['*'] && body.query.specialpagealiases.filter( sp => ['Mypage','Mytalk','MyLanguage'].includes( sp.realname ) ).map( sp => sp.aliases[0] ).includes( body.query.redirects[0].from.split(':').slice(1).join(':').split('/')[0].replace( / /g, '_' ) ) ) {
  96. querypage.title = body.query.redirects[0].from;
  97. delete body.query.redirects[0].tofragment;
  98. delete querypage.missing;
  99. querypage.ns = -1;
  100. querypage.special = '';
  101. }
  102. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  103. if ( querypage.ns === 2 && ( !querypage.title.includes( '/' ) || /^[^:]+:(?:(?:\d{1,3}\.){3}\d{1,3}\/\d{2}|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}\/\d{2,3})$/.test(querypage.title) ) ) {
  104. var userparts = querypage.title.split(':');
  105. querypage.noRedirect = noRedirect;
  106. fn.user(lang, msg, userparts[0] + ':', userparts.slice(1).join(':'), wiki, querystring, fragment, querypage, contribs, reaction, spoiler);
  107. }
  108. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  109. var username = querypage.title.split('/').slice(1).join('/');
  110. got.get( wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json' ).then( uresponse => {
  111. var ubody = uresponse.body;
  112. if ( uresponse.statusCode !== 200 || !ubody || !ubody.query ) {
  113. console.log( '- ' + uresponse.statusCode + ': Error while getting the user: ' + ( ubody && ubody.error && ubody.error.info ) );
  114. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring, fragment) + '>' + spoiler );
  115. if ( reaction ) reaction.removeEmoji();
  116. }
  117. else {
  118. querypage = Object.values(ubody.query.pages)[0];
  119. if ( querypage.ns === 2 ) {
  120. username = querypage.title.split(':').slice(1).join(':');
  121. querypage.title = contribs + username;
  122. delete querypage.missing;
  123. querypage.ns = -1;
  124. querypage.special = '';
  125. querypage.noRedirect = noRedirect;
  126. fn.user(lang, msg, contribs, username, wiki, querystring, fragment, querypage, contribs, reaction, spoiler);
  127. }
  128. else {
  129. msg.reactEmoji('error');
  130. if ( reaction ) reaction.removeEmoji();
  131. }
  132. }
  133. }, error => {
  134. console.log( '- Error while getting the user: ' + error );
  135. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring, fragment) + '>' + spoiler );
  136. if ( reaction ) reaction.removeEmoji();
  137. } );
  138. }
  139. else if ( querypage.ns === 1201 && querypage.missing !== undefined ) {
  140. var thread = querypage.title.split(':');
  141. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=user&rvdir=newer&rvlimit=1&pageids=' + thread.slice(1).join(':') + '&format=json' ).then( thresponse => {
  142. var thbody = thresponse.body;
  143. if ( thresponse.statusCode !== 200 || !thbody || !thbody.query || !thbody.query.pages ) {
  144. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.error && thbody.error.info ) );
  145. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring, fragment) + '>' + spoiler );
  146. if ( reaction ) reaction.removeEmoji();
  147. }
  148. else {
  149. querypage = thbody.query.pages[thread.slice(1).join(':')];
  150. if ( querypage.missing !== undefined ) {
  151. msg.reactEmoji('🤷');
  152. if ( reaction ) reaction.removeEmoji();
  153. }
  154. else {
  155. var pagelink = wiki.toLink(thread.join(':'), querystring, fragment);
  156. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( thread.join(':').escapeFormatting() ).setURL( pagelink ).setFooter( querypage.revisions[0].user );
  157. got.get( wiki.toDescLink(querypage.title), {
  158. responseType: 'text'
  159. } ).then( descresponse => {
  160. var descbody = descresponse.body;
  161. if ( descresponse.statusCode !== 200 || !descbody ) {
  162. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  163. } else {
  164. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  165. var parser = new htmlparser.Parser( {
  166. onopentag: (tagname, attribs) => {
  167. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  168. var description = attribs.content.escapeFormatting();
  169. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  170. embed.setDescription( description );
  171. }
  172. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  173. thumbnail = attribs.content;
  174. }
  175. }
  176. } );
  177. parser.write( descbody );
  178. parser.end();
  179. embed.setThumbnail( thumbnail );
  180. }
  181. }, error => {
  182. console.log( '- Error while getting the description: ' + error );
  183. } ).finally( () => {
  184. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  185. if ( reaction ) reaction.removeEmoji();
  186. } );
  187. }
  188. }
  189. }, error => {
  190. console.log( '- Error while getting the thread: ' + error );
  191. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring, fragment) + '>' + spoiler );
  192. if ( reaction ) reaction.removeEmoji();
  193. } );
  194. }
  195. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  196. got.get( wiki + 'api/v1/Search/List?minArticleQuality=0&namespaces=4,12,14,' + Object.values(body.query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join(',') + '&limit=1&query=' + encodeURIComponent( title ) + '&format=json&cache=' + Date.now() ).then( wsresponse => {
  197. var wsbody = wsresponse.body;
  198. if ( wsresponse.statusCode !== 200 || !wsbody || wsbody.exception || !wsbody.total || !wsbody.items || !wsbody.items.length ) {
  199. if ( wsbody && ( !wsbody.total || ( wsbody.items && !wsbody.items.length ) || ( wsbody.exception && wsbody.exception.code === 404 ) ) ) msg.reactEmoji('🤷');
  200. else {
  201. console.log( '- ' + wsresponse.statusCode + ': Error while getting the search results: ' + ( wsbody && wsbody.exception && wsbody.exception.details ) );
  202. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', {search:title}) + '>' + spoiler );
  203. }
  204. if ( reaction ) reaction.removeEmoji();
  205. }
  206. else {
  207. querypage = wsbody.items[0];
  208. if ( querypage.ns && !querypage.title.startsWith( body.query.namespaces[querypage.ns]['*'] + ':' ) ) {
  209. querypage.title = body.query.namespaces[querypage.ns]['*'] + ':' + querypage.title;
  210. }
  211. var text = '';
  212. var prefix = ( msg.channel.isGuild() && patreons[msg.guild.id] || process.env.prefix );
  213. var linksuffix = ( querystring.toString() ? '?' + querystring : '' ) + ( fragment ? '#' + fragment : '' );
  214. if ( title.replace( /[_-]/g, ' ' ).toLowerCase() === querypage.title.replace( /-/g, ' ' ).toLowerCase() ) {
  215. text = '';
  216. }
  217. else if ( wsbody.total === 1 ) {
  218. text = '\n' + lang.get('search.infopage', '`' + prefix + cmd + ( lang.localNames.page || 'page' ) + ' ' + title + linksuffix + '`');
  219. }
  220. else {
  221. text = '\n' + lang.get('search.infosearch', '`' + prefix + cmd + ( lang.localNames.page || 'page' ) + ' ' + title + linksuffix + '`', '`' + prefix + cmd + ( lang.localNames.search || 'search' ) + ' ' + title + linksuffix + '`');
  222. }
  223. got.get( wiki + 'api.php?action=query&prop=imageinfo|categoryinfo&titles=' + encodeURIComponent( querypage.title ) + '&format=json' ).then( srresponse => {
  224. var srbody = srresponse.body;
  225. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  226. if ( srresponse.statusCode !== 200 || !srbody || !srbody.query || !srbody.query.pages ) {
  227. console.log( '- ' + srresponse.statusCode + ': Error while getting the search results: ' + ( srbody && srbody.error && srbody.error.info ) );
  228. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring, fragment) + '>' + spoiler );
  229. if ( reaction ) reaction.removeEmoji();
  230. }
  231. else {
  232. querypage = Object.values(srbody.query.pages)[0];
  233. var pagelink = wiki.toLink(querypage.title, querystring, fragment);
  234. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  235. if ( querypage.imageinfo ) {
  236. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  237. var pageimage = wiki.toLink('Special:FilePath/' + filename, {version:Date.now()});
  238. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  239. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  240. }
  241. if ( querypage.categoryinfo ) {
  242. var category = [lang.get('search.category.content')];
  243. if ( querypage.categoryinfo.size === 0 ) {
  244. category.push(lang.get('search.category.empty'));
  245. }
  246. if ( querypage.categoryinfo.pages > 0 ) {
  247. category.push(lang.get('search.category.pages', querypage.categoryinfo.pages));
  248. }
  249. if ( querypage.categoryinfo.files > 0 ) {
  250. category.push(lang.get('search.category.files', querypage.categoryinfo.files));
  251. }
  252. if ( querypage.categoryinfo.subcats > 0 ) {
  253. category.push(lang.get('search.category.subcats', querypage.categoryinfo.subcats));
  254. }
  255. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  256. else text += '\n\n' + category.join('\n');
  257. }
  258. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  259. embed.setDescription( body.query.allmessages[0]['*'] );
  260. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  261. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  262. if ( reaction ) reaction.removeEmoji();
  263. }
  264. else got.get( wiki.toDescLink(querypage.title), {
  265. responseType: 'text'
  266. } ).then( descresponse => {
  267. var descbody = descresponse.body;
  268. if ( descresponse.statusCode !== 200 || !descbody ) {
  269. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  270. } else {
  271. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  272. var parser = new htmlparser.Parser( {
  273. onopentag: (tagname, attribs) => {
  274. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  275. var description = attribs.content.escapeFormatting();
  276. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  277. embed.setDescription( description );
  278. }
  279. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  280. thumbnail = attribs.content;
  281. }
  282. }
  283. }, {decodeEntities:true} );
  284. parser.write( descbody );
  285. parser.end();
  286. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  287. }
  288. }, error => {
  289. console.log( '- Error while getting the description: ' + error );
  290. } ).finally( () => {
  291. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  292. if ( reaction ) reaction.removeEmoji();
  293. } );
  294. }
  295. }, error => {
  296. console.log( '- Error while getting the search results: ' + error );
  297. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring, fragment) + '>' + spoiler );
  298. if ( reaction ) reaction.removeEmoji();
  299. } );
  300. }
  301. }, error => {
  302. console.log( '- Error while getting the search results: ' + error );
  303. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', {search:title}) + '>' + spoiler );
  304. if ( reaction ) reaction.removeEmoji();
  305. } );
  306. }
  307. else if ( querypage.ns === -1 ) {
  308. var pagelink = wiki.toLink(querypage.title, querystring, fragment);
  309. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  310. var specialpage = body.query.specialpagealiases.find( sp => body.query.namespaces['-1']['*'] + ':' + sp.aliases[0].replace( /\_/g, ' ' ) === querypage.title.split('/')[0] );
  311. specialpage = ( specialpage ? specialpage.realname : querypage.title.replace( body.query.namespaces['-1']['*'] + ':', '' ).split('/')[0] ).toLowerCase();
  312. fn.special_page(lang, msg, querypage.title, specialpage, embed, wiki, reaction, spoiler);
  313. }
  314. else {
  315. var pagelink = wiki.toLink(querypage.title, querystring, ( fragment || ( body.query.redirects && body.query.redirects[0].tofragment || '' ) ));
  316. var text = '';
  317. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  318. if ( querypage.imageinfo ) {
  319. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  320. var pageimage = wiki.toLink('Special:FilePath/' + filename, {version:Date.now()});
  321. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  322. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  323. }
  324. if ( querypage.categoryinfo ) {
  325. var category = [lang.get('search.category.content')];
  326. if ( querypage.categoryinfo.size === 0 ) {
  327. category.push(lang.get('search.category.empty'));
  328. }
  329. if ( querypage.categoryinfo.pages > 0 ) {
  330. category.push(lang.get('search.category.pages', querypage.categoryinfo.pages));
  331. }
  332. if ( querypage.categoryinfo.files > 0 ) {
  333. category.push(lang.get('search.category.files', querypage.categoryinfo.files));
  334. }
  335. if ( querypage.categoryinfo.subcats > 0 ) {
  336. category.push(lang.get('search.category.subcats', querypage.categoryinfo.subcats));
  337. }
  338. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  339. else text += '\n\n' + category.join('\n');
  340. }
  341. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  342. embed.setDescription( body.query.allmessages[0]['*'] );
  343. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  344. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  345. if ( reaction ) reaction.removeEmoji();
  346. }
  347. else got.get( wiki.toDescLink(querypage.title), {
  348. responseType: 'text'
  349. } ).then( descresponse => {
  350. var descbody = descresponse.body;
  351. if ( descresponse.statusCode !== 200 || !descbody ) {
  352. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  353. } else {
  354. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  355. var parser = new htmlparser.Parser( {
  356. onopentag: (tagname, attribs) => {
  357. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  358. var description = attribs.content.escapeFormatting();
  359. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  360. embed.setDescription( description );
  361. }
  362. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  363. thumbnail = attribs.content;
  364. }
  365. }
  366. }, {decodeEntities:true} );
  367. parser.write( descbody );
  368. parser.end();
  369. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  370. }
  371. }, error => {
  372. console.log( '- Error while getting the description: ' + error );
  373. } ).finally( () => {
  374. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  375. if ( reaction ) reaction.removeEmoji();
  376. } );
  377. }
  378. }
  379. else if ( body.query.interwiki ) {
  380. if ( msg.channel.isGuild() && pause[msg.guild.id] ) {
  381. if ( reaction ) reaction.removeEmoji();
  382. console.log( '- Aborted, paused.' );
  383. return;
  384. }
  385. var iw = new URL(body.query.interwiki[0].url.replace( /\\/g, '%5C' ).replace( /@(here|everyone)/g, '%40$1' ), wiki);
  386. querystring.forEach( (value, name) => {
  387. iw.searchParams.append(name, value);
  388. } );
  389. if ( fragment ) iw.hash = Wiki.toSection(fragment);
  390. else fragment = iw.hash.substring(1);
  391. var maxselfcall = interwikiLimit[( msg?.guild?.id in patreons ? 'patreon' : 'default' )];
  392. if ( selfcall < maxselfcall && ['http:','https:'].includes( iw.protocol ) ) {
  393. selfcall++;
  394. if ( iw.hostname.endsWith( '.fandom.com' ) || iw.hostname.endsWith( '.wikia.org' ) ) {
  395. let regex = iw.pathname.match( /^(\/(?!wiki\/)[a-z-]{2,12})?(?:\/wiki\/|\/?$)/ );
  396. if ( regex ) {
  397. let path = ( regex[1] || '' );
  398. let iwtitle = decodeURIComponent( iw.pathname.replace( regex[0], '' ) ).replace( /_/g, ' ' );
  399. cmd = ( iw.hostname.endsWith( '.wikia.org' ) ? '??' : '?' ) + ( path ? path.substring(1) + '.' : '' ) + iw.hostname.replace( /\.(?:fandom\.com|wikia\.org)/, ' ' );
  400. return this.general(lang, msg, iwtitle, new Wiki(iw.origin + path + '/'), cmd, reaction, spoiler, iw.searchParams, fragment, iw.href, selfcall);
  401. }
  402. }
  403. if ( iw.hostname.endsWith( '.gamepedia.com' ) ) {
  404. let iwtitle = decodeURIComponent( iw.pathname.substring(1) ).replace( /_/g, ' ' );
  405. cmd = '!' + iw.hostname.replace( '.gamepedia.com', ' ' );
  406. if ( cmd !== '!www ' ) return this.general(lang, msg, iwtitle, new Wiki(iw.origin), cmd, reaction, spoiler, iw.searchParams, fragment, iw.href, selfcall);
  407. }
  408. let project = wikiProjects.find( project => iw.hostname.endsWith( project.name ) );
  409. if ( project ) {
  410. let regex = ( iw.host + iw.pathname ).match( new RegExp( '^' + project.regex + '(?:' + project.articlePath + '|/?$)' ) );
  411. if ( regex ) {
  412. let iwtitle = decodeURIComponent( ( iw.host + iw.pathname ).replace( regex[0], '' ) ).replace( /_/g, ' ' );
  413. cmd = '!!' + regex[1] + ' ';
  414. return this.general(lang, msg, iwtitle, new Wiki('https://' + regex[1] + project.scriptPath), cmd, reaction, spoiler, iw.searchParams, fragment, iw.href, selfcall);
  415. }
  416. }
  417. }
  418. msg.sendChannel( spoiler + ' ' + iw + ' ' + spoiler ).then( message => {
  419. if ( message && selfcall === maxselfcall ) message.reactEmoji('⚠️');
  420. } );
  421. if ( reaction ) reaction.removeEmoji();
  422. }
  423. else if ( body.query.redirects ) {
  424. var pagelink = wiki.toLink(body.query.redirects[0].to, querystring, ( fragment || body.query.redirects[0].tofragment || '' ));
  425. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.redirects[0].to.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  426. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  427. if ( reaction ) reaction.removeEmoji();;
  428. }
  429. else {
  430. var pagelink = wiki.toLink(body.query.general.mainpage, querystring, fragment);
  431. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.general.mainpage.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  432. if ( body.query.allmessages[0]['*'] ) {
  433. embed.setDescription( body.query.allmessages[0]['*'] );
  434. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  435. if ( reaction ) reaction.removeEmoji();
  436. }
  437. else got.get( wiki.toDescLink(body.query.general.mainpage), {
  438. responseType: 'text'
  439. } ).then( descresponse => {
  440. var descbody = descresponse.body;
  441. if ( descresponse.statusCode !== 200 || !descbody ) {
  442. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  443. } else {
  444. var parser = new htmlparser.Parser( {
  445. onopentag: (tagname, attribs) => {
  446. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  447. var description = attribs.content.escapeFormatting();
  448. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  449. embed.setDescription( description );
  450. }
  451. }
  452. }, {decodeEntities:true} );
  453. parser.write( descbody );
  454. parser.end();
  455. }
  456. }, error => {
  457. console.log( '- Error while getting the description: ' + error );
  458. } ).finally( () => {
  459. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  460. if ( reaction ) reaction.removeEmoji();
  461. } );
  462. }
  463. }, error => {
  464. if ( interwiki ) msg.sendChannel( spoiler + ' ' + interwiki + ' ' + spoiler );
  465. else if ( wiki.noWiki(error.message) ) {
  466. console.log( '- This wiki doesn\'t exist!' );
  467. msg.reactEmoji('nowiki');
  468. }
  469. else {
  470. console.log( '- Error while getting the search results: ' + error );
  471. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring.toString() || fragment || !title ? title : 'Special:Search' ), ( querystring.toString() || fragment || !title ? querystring : {search:title} ), fragment) + '>' + spoiler );
  472. }
  473. if ( reaction ) reaction.removeEmoji();
  474. } );
  475. }
  476. module.exports = fandom_check_wiki;