1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | axios = require('axios')
|
20 |
|
21 | getRequestConfig = (endpoint, params) ->
|
22 | searchUrl = 'https://frinkiac.com/api/search'
|
23 | captionUrl = 'https://frinkiac.com/api/caption'
|
24 | url = if endpoint is 'search' then searchUrl else captionUrl
|
25 | return {
|
26 | method: 'get'
|
27 | url: url
|
28 | params: params
|
29 | }
|
30 |
|
31 | encode = (str) ->
|
32 | encodeURIComponent(str).replace /[!'()*]/g, (c) ->
|
33 | '%' + c.charCodeAt(0).toString(16)
|
34 |
|
35 | getImageUrl = (episode, timestamp, caption) ->
|
36 | "https://frinkiac.com/meme/#{episode}/#{timestamp}.jpg?lines=#{encode(caption)}"
|
37 |
|
38 | getLongestWordLength = (words) ->
|
39 | longestWordLength = 0
|
40 | words.forEach (word) ->
|
41 | longestWordLength = word.length if word.length > longestWordLength
|
42 | longestWordLength
|
43 |
|
44 | getNumberOfWordsBeforeBreaking = (words) ->
|
45 | longestWordLength = getLongestWordLength(words)
|
46 | if longestWordLength <= 5
|
47 | wordsBeforeBreaking = 5
|
48 | else if 5 < longestWordLength <= 8
|
49 | wordsBeforeBreaking = 4
|
50 | else
|
51 | wordsBeforeBreaking = 3
|
52 | wordsBeforeBreaking
|
53 |
|
54 | addLineBreaks = (str) ->
|
55 | newString = ''
|
56 | words = str.split(' ')
|
57 | wordsBeforeBreaking = getNumberOfWordsBeforeBreaking(words)
|
58 | words.forEach (word, i) ->
|
59 | i++
|
60 | delimiter = if i % wordsBeforeBreaking then ' ' else '\n'
|
61 | newString += word + delimiter
|
62 | newString
|
63 |
|
64 | trimWhitespace = (string) ->
|
65 | string.replace /^\s*|\s*$/g, ''
|
66 |
|
67 | formatCaption = (caption) ->
|
68 | addLineBreaks(trimWhitespace(caption))
|
69 |
|
70 | combineCaptions = (captions) ->
|
71 | if captions.length <= 4
|
72 | newCaption = ''
|
73 | captions.forEach (caption, i) ->
|
74 | newCaption += formatCaption(caption.Content)
|
75 | unless i == (captions.length - 1)
|
76 | newCaption += '\n'
|
77 | newCaption
|
78 | else
|
79 | captions[0].Content
|
80 |
|
81 | module.exports = (robot) ->
|
82 | robot.respond /(simpsons search|frinkiac) (.*)/i, (msg) ->
|
83 | query = msg.match[2].split('|')
|
84 | customCaption = query[1]
|
85 |
|
86 | axios(getRequestConfig('search', {q: query[0]}))
|
87 | .then (response) ->
|
88 | if (response.data.length)
|
89 | episode = response.data[0].Episode
|
90 | timestamp = response.data[0].Timestamp
|
91 |
|
92 | if customCaption
|
93 | msg.send getImageUrl(episode, timestamp, formatCaption(customCaption))
|
94 |
|
95 | else
|
96 | axios(getRequestConfig('caption', {e: episode, t: timestamp}))
|
97 | .then (response) ->
|
98 | msg.send getImageUrl(episode, timestamp, combineCaptions(response.data.Subtitles))
|
99 |
|
100 | else
|
101 | console.log("D'oh! I couldn't find anything for `#{query[0]}`.");
|
102 |
|
103 | .catch (error) ->
|
104 | console.error(error);
|