/
handlers.go
214 lines (176 loc) · 6.07 KB
/
handlers.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
package api
import (
"encoding/json"
"expvar"
"log"
"net/http"
"sort"
"strconv"
"sync"
"google.golang.org/api/youtube/v3"
"github.com/gorilla/mux"
"github.com/youcodeio/proxy/database"
"github.com/youcodeio/proxy/utils"
)
// Two metrics, these are exposed by "magic" :)
// Number of calls to our server.
var lastSearch = expvar.NewString("youcodeio.last.search")
var numCalls = expvar.NewInt("youcodeio.counter.api.calls")
// NewRouter return a new mux Router
// https://groups.google.com/forum/#!msg/golang-nuts/Xs-Ho1feGyg/xg5amXHsM_oJ
func NewRouter(db *database.YouCodeDB) *mux.Router {
r := mux.NewRouter().StrictSlash(true)
r.Handle("/channels", GetChannels(db))
r.Handle("/channels/{channel}/lastVideos", GetChannelLatestVideos())
r.Handle("/channels/{channel}/info", GetChannelInfo())
r.Handle("/search", GetQuery(db))
r.Handle("/debug/vars", http.DefaultServeMux)
return r
}
// GetChannels returns the list of channels used by YouCode
func GetChannels(db *database.YouCodeDB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
numCalls.Add(1)
channels := db.GetChannels()
json, err := json.Marshal(channels)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
})
}
//GetChannelLatestVideos returns the latest videos from a channel
func GetChannelLatestVideos() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
numCalls.Add(1)
var videoSize int64
var err error
size := r.URL.Query().Get("size")
if len(size) == 0 {
videoSize = 2
} else {
videoSize, err = strconv.ParseInt(size, 10, 64)
if err != nil {
http.Error(w, "size is not a number", http.StatusBadRequest)
return
}
}
vars := mux.Vars(r)
id := vars["channel"]
if len(id) == 0 {
http.Error(w, "Not enough args", http.StatusBadRequest)
return
}
resultsChannel := make(chan []*youtube.SearchResult, videoSize)
var wg sync.WaitGroup
var results []youtube.SearchResult
wg.Add(1)
go database.SearchOnChannel("", id, resultsChannel, &wg, videoSize)
wg.Wait()
close(resultsChannel)
log.Println("Size of resultsChannels", len(resultsChannel))
for _, result := range <-resultsChannel {
// log.Println("Pushing ", *result.Id)
results = append(results, *result)
}
log.Println("Sorting results...")
// Sorting
sort.Sort(utils.Channels(results))
log.Println("Done")
json, err := json.Marshal(results)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
})
}
// GetQuery return the result of a query on all the channels available
func GetQuery(db *database.YouCodeDB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
numCalls.Add(1)
query := r.URL.Query().Get("query")
tuto := r.URL.Query().Get("istuts")
if len(query) == 0 {
http.Error(w, "Not enough args", http.StatusBadRequest)
return
}
lastSearch.Set(query)
channels := db.GetChannels()
resultsChannel := make(chan []*youtube.SearchResult, database.DefaultMaxResults*int64(len(channels)))
var wg sync.WaitGroup
var results []youtube.SearchResult
for _, channel := range channels {
if len(tuto) == 0 || strconv.FormatBool(channel.IsTuts) == tuto {
log.Println("Querying", query, "on", channel.Name)
wg.Add(1)
go database.SearchOnChannel(query, channel.Ytid, resultsChannel, &wg, database.DefaultMaxResults)
}
}
wg.Wait()
close(resultsChannel)
log.Println("Size of resultsChannels", len(resultsChannel))
for index := 0; index < len(channels); index++ {
// Because we closed the channel above,
// the iteration terminates after receiving the events
for _, result := range <-resultsChannel {
// log.Println("Pushing ", *result.Id)
results = append(results, *result)
}
}
log.Println("Sorting results...")
// Sorting
sort.Sort(utils.Channels(results))
log.Println("Done")
json, err := json.Marshal(results)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
})
}
func GetChannelInfo() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
vars := mux.Vars(r)
id := vars["channel"]
resultChannel := make(chan *youtube.ChannelListResponse)
log.Println("Querying channel", id, "for info")
go database.ChannelInfo(id, resultChannel)
json, err := json.Marshal(<-resultChannel)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(json)
})
}