forked from zorchenhimer/MovieNight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemotes.go
256 lines (211 loc) · 6.24 KB
/
emotes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/zorchenhimer/MovieNight/common"
)
const emoteDir = "/static/emotes/"
type TwitchUser struct {
ID string
Login string
}
type EmoteInfo struct {
ID int
Code string
}
func loadEmotes() error {
newEmotes, err := processEmoteDir(common.RunPath() + emoteDir)
if err != nil {
return err
}
common.Emotes = newEmotes
return nil
}
func processEmoteDir(path string) (common.EmotesMap, error) {
dirInfo, err := ioutil.ReadDir(path)
if err != nil {
return nil, errors.Wrap(err, "could not open emoteDir:")
}
subDirs := []string{}
for _, item := range dirInfo {
// Get first level subdirs (eg, "twitch", "discord", etc)
if item.IsDir() {
subDirs = append(subDirs, item.Name())
continue
}
}
em := common.NewEmotesMap()
// Find top level emotes
em, err = findEmotes(path, em)
if err != nil {
return nil, errors.Wrap(err, "could not findEmotes() in top level directory:")
}
// Get second level subdirs (eg, "twitch", "zorchenhimer", etc)
for _, dir := range subDirs {
subd, err := ioutil.ReadDir(filepath.Join(path, dir))
if err != nil {
fmt.Printf("Error reading dir %q: %v\n", subd, err)
continue
}
for _, d := range subd {
if d.IsDir() {
// emotes = append(emotes, findEmotes(filepath.Join(path, dir, d.Name()))...)
p := filepath.Join(path, dir, d.Name())
em, err = findEmotes(p, em)
if err != nil {
fmt.Printf("Error finding emotes in %q: %v\n", p, err)
}
}
}
}
common.LogInfof("processEmoteDir: %d\n", len(em))
return em, nil
}
func substr(input string, start int, length int) string {
asRunes := []rune(input)
if start >= len(asRunes) {
return ""
}
if start+length > len(asRunes) {
length = len(asRunes) - start
}
return string(asRunes[start : start+length])
}
func findEmotes(dir string, em common.EmotesMap) (common.EmotesMap, error) {
var runPathLength = len(common.RunPath() + "/static/")
common.LogDebugf("finding emotes in %q\n", dir)
emotePNGs, err := filepath.Glob(filepath.Join(dir, "*.png"))
if err != nil {
return em, fmt.Errorf("unable to glob emote directory: %s\n", err)
}
common.LogInfof("Found %d emotePNGs\n", len(emotePNGs))
emoteGIFs, err := filepath.Glob(filepath.Join(dir, "*.gif"))
if err != nil {
return em, errors.Wrap(err, "unable to glob emote directory:")
}
common.LogInfof("Found %d emoteGIFs\n", len(emoteGIFs))
for _, file := range emotePNGs {
png := strings.ReplaceAll(common.Substr(file, runPathLength, len(file)), "\\", "/")
//common.LogDebugf("Emote PNG: %s", png)
em = em.Add(png)
}
for _, file := range emoteGIFs {
gif := strings.ReplaceAll(common.Substr(file, runPathLength, len(file)), "\\", "/")
//common.LogDebugf("Emote GIF: %s", gif)
em = em.Add(gif)
}
return em, nil
}
func getEmotes(names []string) error {
users := getUserIDs(names)
users = append(users, TwitchUser{ID: "0", Login: "twitch"})
for _, user := range users {
emotes, cheers, err := getChannelEmotes(user.ID)
if err != nil {
return errors.Wrapf(err, "could not get emote data for \"%s\"", user.ID)
}
emoteUserDir := filepath.Join(common.RunPath()+emoteDir, "twitch", user.Login)
if _, err := os.Stat(emoteUserDir); os.IsNotExist(err) {
os.MkdirAll(emoteUserDir, os.ModePerm)
}
for _, emote := range emotes {
if !strings.ContainsAny(emote.Code, `:;\[]|?&`) {
filePath := filepath.Join(emoteUserDir, emote.Code+".png")
file, err := os.Create(filePath)
if err != nil {
return errors.Wrapf(err, "could not create emote file in path \"%s\":", filePath)
}
err = downloadEmote(emote.ID, file)
if err != nil {
return errors.Wrapf(err, "could not download emote %s:", emote.Code)
}
}
}
for amount, sizes := range cheers {
name := fmt.Sprintf("%sCheer%s.gif", user.Login, amount)
filePath := filepath.Join(emoteUserDir, name)
file, err := os.Create(filePath)
if err != nil {
return errors.Wrapf(err, "could not create emote file in path \"%s\":", filePath)
}
err = downloadCheerEmote(sizes["4"], file)
if err != nil {
return errors.Wrapf(err, "could not download emote %s:", name)
}
}
}
return nil
}
func getUserIDs(names []string) []TwitchUser {
logins := strings.Join(names, "&login=")
request, err := http.NewRequest("GET", fmt.Sprintf("https://api.twitch.tv/helix/users?login=%s", logins), nil)
if err != nil {
log.Fatalln("Error generating new request:", err)
}
request.Header.Set("Client-ID", settings.TwitchClientID)
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", settings.TwitchClientSecret))
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
log.Fatalln("Error sending request:", err)
}
decoder := json.NewDecoder(resp.Body)
type userResponse struct {
Data []TwitchUser
}
var data userResponse
err = decoder.Decode(&data)
if err != nil {
log.Fatalln("Error decoding data:", err)
}
return data.Data
}
func getChannelEmotes(ID string) ([]EmoteInfo, map[string]map[string]string, error) {
resp, err := http.Get("https://api.twitchemotes.com/api/v4/channels/" + ID)
if err != nil {
return nil, nil, errors.Wrap(err, "could not get emotes")
}
decoder := json.NewDecoder(resp.Body)
type EmoteResponse struct {
Emotes []EmoteInfo
Cheermotes map[string]map[string]string
}
var data EmoteResponse
err = decoder.Decode(&data)
if err != nil {
return nil, nil, errors.Wrap(err, "could not decode emotes")
}
return data.Emotes, data.Cheermotes, nil
}
func downloadEmote(ID int, file *os.File) error {
resp, err := http.Get(fmt.Sprintf("https://static-cdn.jtvnw.net/emoticons/v1/%d/3.0", ID))
if err != nil {
return errors.Errorf("could not download emote file %s: %v", file.Name(), err)
}
defer resp.Body.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
return errors.Errorf("could not save emote: %v", err)
}
return nil
}
func downloadCheerEmote(url string, file *os.File) error {
resp, err := http.Get(url)
if err != nil {
return errors.Errorf("could not download cheer file %s: %v", file.Name(), err)
}
defer resp.Body.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
return errors.Errorf("could not save cheer: %v", err)
}
return nil
}