discussion.js 17 KB

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