discussion.js 17 KB

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