1
0

discussion.js 18 KB

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