discussion.js 17 KB

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