discussion.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. const htmlparser = require('htmlparser2');
  2. const {MessageEmbed, Util} = require('discord.js');
  3. const {limit: {discussion: discussionLimit}} = require('../util/default.json');
  4. const {htmlToDiscord, escapeFormatting} = require('../util/functions.js');
  5. /**
  6. * Processes discussion commands.
  7. * @param {import('../util/i18n.js')} lang - The user language.
  8. * @param {import('discord.js').Message} msg - The Discord message.
  9. * @param {import('../util/wiki.js')} wiki - The wiki for the page.
  10. * @param {String} title - The title of the discussion post.
  11. * @param {String} sitename - The sitename of the wiki.
  12. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  13. * @param {String} spoiler - If the response is in a spoiler.
  14. */
  15. function fandom_discussion(lang, msg, wiki, title, sitename, reaction, spoiler) {
  16. var limit = discussionLimit[( patreons[msg.guild?.id] ? 'patreon' : 'default' )];
  17. if ( !title ) {
  18. var pagelink = wiki + 'f';
  19. var embed = new MessageEmbed().setAuthor( sitename ).setTitle( lang.get('discussion.main') ).setURL( pagelink );
  20. got.get( wiki + 'f', {
  21. responseType: 'text'
  22. } ).then( descresponse => {
  23. var descbody = descresponse.body;
  24. if ( descresponse.statusCode !== 200 || !descbody ) {
  25. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  26. } else {
  27. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  28. var parser = new htmlparser.Parser( {
  29. onopentag: (tagname, attribs) => {
  30. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  31. var description = escapeFormatting(attribs.content);
  32. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  33. embed.setDescription( description );
  34. }
  35. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  36. thumbnail = attribs.content;
  37. }
  38. }
  39. } );
  40. parser.write( descbody );
  41. parser.end();
  42. embed.setThumbnail( thumbnail );
  43. }
  44. }, error => {
  45. console.log( '- Error while getting the description: ' + error );
  46. } ).finally( () => {
  47. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  48. if ( reaction ) reaction.removeEmoji();
  49. } );
  50. }
  51. else if ( title.split(' ')[0].toLowerCase() === 'post' || title.split(' ')[0].toLowerCase() === lang.get('discussion.post') ) {
  52. title = title.split(' ').slice(1).join(' ');
  53. got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=' + limit + '&format=json&cache=' + Date.now(), {
  54. headers: {
  55. Accept: 'application/hal+json'
  56. }
  57. } ).then( response => {
  58. var body = response.body;
  59. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded['doc:posts'] ) {
  60. console.log( '- ' + response.statusCode + ': Error while getting the posts: ' + ( body && body.title ) );
  61. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  62. if ( reaction ) reaction.removeEmoji();
  63. }
  64. else if ( body._embedded['doc:posts'].length ) {
  65. var posts = body._embedded['doc:posts'];
  66. var embed = new MessageEmbed().setAuthor( sitename );
  67. if ( posts.some( post => post.id === title ) ) {
  68. discussion_send(lang, msg, wiki, posts.find( post => post.id === title ), embed, spoiler);
  69. if ( reaction ) reaction.removeEmoji();
  70. }
  71. else if ( /^\d+$/.test(title) ) {
  72. got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPost&postId=' + title + '&format=json&cache=' + Date.now(), {
  73. headers: {
  74. Accept: 'application/hal+json'
  75. }
  76. } ).then( presponse => {
  77. var pbody = presponse.body;
  78. if ( presponse.statusCode !== 200 || !pbody || pbody.id !== title ) {
  79. if ( pbody && pbody.title === 'The requested resource was not found.' ) {
  80. if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  81. discussion_send(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  82. }
  83. else msg.reactEmoji('🤷');
  84. }
  85. else {
  86. console.log( '- ' + presponse.statusCode + ': Error while getting the post: ' + ( pbody && pbody.title ) );
  87. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  88. }
  89. if ( reaction ) reaction.removeEmoji();
  90. }
  91. else if ( pbody.title ) {
  92. discussion_send(lang, msg, wiki, pbody, embed, spoiler);
  93. if ( reaction ) reaction.removeEmoji();
  94. }
  95. else got.get( wiki + 'wikia.php?controller=DiscussionThread&method=getThread&threadId=' + pbody.threadId + '&format=json&cache=' + Date.now(), {
  96. headers: {
  97. Accept: 'application/hal+json'
  98. }
  99. } ).then( thresponse => {
  100. var thbody = thresponse.body;
  101. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== pbody.threadId ) {
  102. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  103. embed.setTitle( '~~' + pbody.threadId + '~~' );
  104. }
  105. else embed.setTitle( escapeFormatting(thbody.title) );
  106. }, error => {
  107. console.log( '- Error while getting the thread: ' + error );
  108. embed.setTitle( '~~' + pbody.threadId + '~~' );
  109. } ).finally( () => {
  110. discussion_send(lang, msg, wiki, pbody, embed, spoiler);
  111. if ( reaction ) reaction.removeEmoji();
  112. } );
  113. }, error => {
  114. console.log( '- Error while getting the post: ' + error );
  115. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  116. if ( reaction ) reaction.removeEmoji();
  117. } );
  118. }
  119. else if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  120. discussion_send(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  121. if ( reaction ) reaction.removeEmoji();
  122. }
  123. else {
  124. msg.reactEmoji('🤷');
  125. if ( reaction ) reaction.removeEmoji();
  126. }
  127. }
  128. else {
  129. msg.reactEmoji('🤷');
  130. if ( reaction ) reaction.removeEmoji();
  131. }
  132. }, error => {
  133. console.log( '- Error while getting the posts: ' + error );
  134. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  135. if ( reaction ) reaction.removeEmoji();
  136. } );
  137. }
  138. else {
  139. got.get( wiki + 'wikia.php?controller=DiscussionThread&method=getThreads&sortKey=trending&limit=' + limit + '&format=json&cache=' + Date.now(), {
  140. headers: {
  141. Accept: 'application/hal+json'
  142. }
  143. } ).then( response => {
  144. var body = response.body;
  145. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded.threads ) {
  146. console.log( '- ' + response.statusCode + ': Error while getting the threads: ' + ( body && body.title ) );
  147. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  148. if ( reaction ) reaction.removeEmoji();
  149. }
  150. else if ( body._embedded.threads.length ) {
  151. var threads = body._embedded.threads;
  152. var embed = new MessageEmbed().setAuthor( sitename );
  153. if ( threads.some( thread => thread.id === title ) ) {
  154. discussion_send(lang, msg, wiki, threads.find( thread => thread.id === title ), embed, spoiler);
  155. if ( reaction ) reaction.removeEmoji();
  156. }
  157. else if ( threads.some( thread => thread.title === title ) ) {
  158. discussion_send(lang, msg, wiki, threads.find( thread => thread.title === title ), embed, spoiler);
  159. if ( reaction ) reaction.removeEmoji();
  160. }
  161. else if ( threads.some( thread => thread.title.toLowerCase() === title.toLowerCase() ) ) {
  162. discussion_send(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase() === title.toLowerCase() ), embed, spoiler);
  163. if ( reaction ) reaction.removeEmoji();
  164. }
  165. else if ( threads.some( thread => thread.title.includes( title ) ) ) {
  166. discussion_send(lang, msg, wiki, threads.find( thread => thread.title.includes( title ) ), embed, spoiler);
  167. if ( reaction ) reaction.removeEmoji();
  168. }
  169. else if ( threads.some( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ) ) {
  170. discussion_send(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  171. if ( reaction ) reaction.removeEmoji();
  172. }
  173. else if ( /^\d+$/.test(title) ) {
  174. got.get( wiki + 'wikia.php?controller=DiscussionThread&method=getThread&threadId=' + title + '&format=json&cache=' + Date.now(), {
  175. headers: {
  176. Accept: 'application/hal+json'
  177. }
  178. } ).then( thresponse => {
  179. var thbody = thresponse.body;
  180. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== title ) {
  181. if ( thbody && thbody.status === 404 ) {
  182. if (threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  183. discussion_send(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  184. }
  185. else msg.reactEmoji('🤷');
  186. }
  187. else {
  188. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  189. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  190. }
  191. }
  192. else discussion_send(lang, msg, wiki, thbody, embed, spoiler);
  193. }, error => {
  194. console.log( '- Error while getting the thread: ' + error );
  195. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  196. } ).finally( () => {
  197. if ( reaction ) reaction.removeEmoji();
  198. } );
  199. }
  200. else if ( threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  201. discussion_send(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  202. if ( reaction ) reaction.removeEmoji();
  203. }
  204. else {
  205. msg.reactEmoji('🤷');
  206. if ( reaction ) reaction.removeEmoji();
  207. }
  208. }
  209. else {
  210. msg.reactEmoji('🤷');
  211. if ( reaction ) reaction.removeEmoji();
  212. }
  213. }, error => {
  214. console.log( '- Error while getting the threads: ' + error );
  215. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  216. if ( reaction ) reaction.removeEmoji();
  217. } );
  218. }
  219. }
  220. /**
  221. * Send discussion posts.
  222. * @param {import('../util/i18n.js')} lang - The user language.
  223. * @param {import('discord.js').Message} msg - The Discord message.
  224. * @param {import('../util/wiki.js')} wiki - The wiki for the page.
  225. * @param {Object} discussion - The discussion post.
  226. * @param {import('discord.js').MessageEmbed} embed - The embed for the page.
  227. * @param {String} spoiler - If the response is in a spoiler.
  228. */
  229. function discussion_send(lang, msg, wiki, discussion, embed, spoiler) {
  230. if ( discussion.title ) {
  231. embed.setTitle( escapeFormatting(discussion.title) );
  232. var pagelink = wiki + 'f/p/' + ( discussion.threadId || discussion.id );
  233. }
  234. else {
  235. if ( discussion._embedded.thread ) embed.setTitle( escapeFormatting(discussion._embedded.thread[0].title) );
  236. var pagelink = wiki + 'f/p/' + discussion.threadId + '/r/' + discussion.id;
  237. }
  238. var text = '<' + pagelink + '>';
  239. embed.setURL( pagelink ).setFooter( discussion.createdBy.name, discussion.createdBy.avatarUrl ).setTimestamp( discussion.creationDate.epochSecond * 1000 );
  240. var description = '';
  241. switch ( discussion.funnel ) {
  242. case 'IMAGE':
  243. embed.setImage( discussion._embedded.contentImages[0].url );
  244. break;
  245. case 'POLL':
  246. discussion.poll.answers.forEach( answer => embed.addField( escapeFormatting(answer.text), ( answer.image ? '[__' + lang.get('discussion.image') + '__](' + answer.image.url + ')\n' : '' ) + lang.get('discussion.votes', answer.votes.toLocaleString(lang.get('dateformat')), answer.votes, ( ( answer.votes / discussion.poll.totalVotes ) * 100 ).toFixed(1).toLocaleString(lang.get('dateformat'))), true ) );
  247. break;
  248. case 'QUIZ':
  249. description = escapeFormatting(discussion._embedded.quizzes[0].title);
  250. embed.setThumbnail( discussion._embedded.quizzes[0].image );
  251. break;
  252. default:
  253. if ( discussion.jsonModel ) {
  254. try {
  255. description = discussion_formatting(JSON.parse(discussion.jsonModel)).replace( /(?:\*\*\*\*|(?<!\\)\_\_)/g, '' ).replace( /{@wiki}/g, wiki );
  256. if ( discussion._embedded.contentImages.length ) {
  257. if ( description.trim().endsWith( '{@0}' ) ) {
  258. embed.setImage( discussion._embedded.contentImages[0].url );
  259. description = description.replace( '{@0}', '' ).trim();
  260. }
  261. else {
  262. description = description.replace( /\{\@(\d+)\}/g, (match, n) => {
  263. if ( n >= discussion._embedded.contentImages.length ) return '';
  264. else return '[__' + lang.get('discussion.image') + '__](' + discussion._embedded.contentImages[n].url + ')';
  265. } );
  266. embed.setThumbnail( discussion._embedded.contentImages[0].url );
  267. }
  268. }
  269. else embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  270. }
  271. catch ( jsonerror ) {
  272. console.log( '- Error while getting the formatting: ' + jsonerror );
  273. description = escapeFormatting(discussion.rawContent);
  274. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  275. }
  276. }
  277. else if ( discussion.renderedContent ) {
  278. description = htmlToDiscord(discussion.renderedContent, pagelink);
  279. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  280. }
  281. else {
  282. description = escapeFormatting(discussion.rawContent);
  283. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  284. }
  285. }
  286. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  287. embed.setDescription( description );
  288. if ( discussion.tags?.length ) {
  289. embed.addField( lang.get('discussion.tags'), Util.splitMessage( discussion.tags.map( tag => '[' + escapeFormatting(tag.articleTitle) + '](' + wiki.toLink(tag.articleTitle, '', '', true) + ')' ).join(', '), {char:', ',maxLength:1000} )[0], false );
  290. }
  291. msg.sendChannel( spoiler + text + spoiler, {embed} );
  292. }
  293. /**
  294. * Format discussion content
  295. * @param {Object} jsonModel - The content of the discussion post.
  296. * @returns {String}
  297. */
  298. function discussion_formatting(jsonModel) {
  299. var description = '';
  300. switch ( jsonModel.type ) {
  301. case 'doc':
  302. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  303. break;
  304. case 'paragraph':
  305. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  306. description += '\n';
  307. break;
  308. case 'openGraph':
  309. if ( !jsonModel.attrs.wasAddedWithInlineLink ) description += jsonModel.attrs.url + '\n';
  310. break;
  311. case 'text':
  312. var prepend = '';
  313. var append = '';
  314. if ( jsonModel.marks ) {
  315. jsonModel.marks.forEach( mark => {
  316. switch ( mark.type ) {
  317. case 'mention':
  318. prepend += '[';
  319. append = ']({@wiki}f/u/' + mark.attrs.userId + ')' + append;
  320. break;
  321. case 'link':
  322. prepend += '[';
  323. append = '](' + mark.attrs.href + ')' + append;
  324. break;
  325. case 'strong':
  326. prepend += '**';
  327. append = '**' + append;
  328. break;
  329. case 'em':
  330. prepend += '_';
  331. append = '_' + append;
  332. break;
  333. }
  334. } );
  335. }
  336. description += prepend + escapeFormatting(jsonModel.text) + append;
  337. break;
  338. case 'image':
  339. if ( jsonModel.attrs.id !== null ) description += '{@' + jsonModel.attrs.id + '}\n';
  340. break;
  341. case 'code_block':
  342. description += '```\n';
  343. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  344. description += '\n```\n';
  345. break;
  346. case 'bulletList':
  347. jsonModel.content.forEach( listItem => {
  348. description += '\t• ';
  349. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  350. } );
  351. break;
  352. case 'orderedList':
  353. var n = 1;
  354. jsonModel.content.forEach( listItem => {
  355. description += '\t' + n + '. ';
  356. n++;
  357. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  358. } );
  359. break;
  360. }
  361. return description;
  362. }
  363. module.exports = fandom_discussion;