discussion.js 17 KB

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