-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
226 lines (178 loc) · 4.96 KB
/
main.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
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"sync"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/gocolly/colly"
"github.com/gocolly/colly/extensions"
)
type Movie struct {
Title string `json:"title"`
Link string `json:"movielink"`
ImageLink string `json:"imagelink"`
}
func fetchRandomPage(link string) string {
c := colly.NewCollector(
colly.AllowedDomains("letterboxd.com"),
colly.Async(true),
)
c.OnError(func(e *colly.Response, err error) {
log.Println("Something went wrong: ", err)
})
// Determines if a link to a list or a username.
link = formatInput(link)
c.Limit(&colly.LimitRule{DomainGlob: "*", Parallelism: 4})
extensions.RandomUserAgent(c)
c.OnRequest(func(r *colly.Request) {
log.Println("Visiting:", r.URL.String())
})
var page string
c.OnHTML(".pagination .paginate-pages", func(e *colly.HTMLElement) {
pages := e.ChildAttrs(".paginate-page a", "href")
splitLink := strings.Split(pages[len(pages)-1], "page/")
numPages, _ := strconv.Atoi(strings.Trim(splitLink[1], "/"))
randPage := rand.Intn(numPages) + 1
page = e.Request.AbsoluteURL(fmt.Sprintf("%s%s%d%s", splitLink[0], "page/", randPage, "/"))
})
c.Visit(link)
c.Wait()
return page
}
func fetchList(link string, everyPage bool) []string {
var movies []string
c := colly.NewCollector(
colly.AllowedDomains("letterboxd.com"),
colly.Async(true),
)
c.OnError(func(e *colly.Response, err error) {
log.Println("Something went wrong: ", err)
})
if everyPage {
// Determines if a link to a list or a username.
link = formatInput(link)
} else {
link = fetchRandomPage(link)
}
c.Limit(&colly.LimitRule{DomainGlob: "*", Parallelism: 4})
extensions.RandomUserAgent(c)
c.OnRequest(func(r *colly.Request) {
log.Println("Visiting:", r.URL.String())
})
if everyPage {
// Fetch next page of watchlist
c.OnHTML(".pagination", func(e *colly.HTMLElement) {
nextPage := e.ChildAttr(".paginate-nextprev a.next", "href")
c.Visit(e.Request.AbsoluteURL(nextPage))
})
}
// Find all movies in watchlist
c.OnHTML(".poster-list li", func(e *colly.HTMLElement) {
film := e.ChildAttr("div", "data-target-link")
movie := Movie{}
movie.Link = "https://letterboxd.com" + film
movies = append(movies, movie.Link)
})
c.Visit(link)
c.Wait()
return movies
}
func formatInput(s string) string {
if strings.HasPrefix(s, "http") {
return s
}
return fmt.Sprintf("https://letterboxd.com/%s/watchlist/page/1/", s)
}
func chooseMovie(movies []string) Movie {
randMovie := rand.Intn(len(movies))
movie := Movie{}
movie.Link = movies[randMovie]
return movie
}
func fetchMovieInfo(movieLink string) (string, string) {
var movieImgLink, movieTitle string
c := colly.NewCollector(
colly.AllowedDomains("letterboxd.com"),
colly.Async(true),
)
c.OnError(func(e *colly.Response, err error) {
log.Println("Something went wrong: ", err)
})
c.OnRequest(func(r *colly.Request) {
log.Println("Visiting:", r.URL.String())
})
// Fetch movie poster title & link
c.OnHTML("div.film-poster", func(e *colly.HTMLElement) {
movieTitle = e.Attr("data-film-name")
movieImgLink = e.ChildAttr("img", "src")
})
movieLink = "https://letterboxd.com/ajax/poster/" + strings.TrimPrefix(movieLink, "https://letterboxd.com/") + "std/230x345/"
c.Visit(movieLink)
c.Wait()
return movieImgLink, movieTitle
}
func intersectLists(watchlist []string, numUsers int) []string {
intersection := make([]string, 0)
hash := make(map[string]int)
for _, movie := range watchlist {
hash[movie]++
}
for movie, count := range hash {
if count == numUsers {
intersection = append(intersection, movie)
}
}
return intersection
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
var wg sync.WaitGroup
router := gin.Default()
router.Use(cors.Default())
router.GET("/api", func(c *gin.Context) {
usernames := c.QueryArray("src")
intersection := c.Query("i")
var movieList []string
if len(usernames) > 1 && intersection == "true" {
var allMovies []string
// Fetch all user's watchlists
for _, username := range usernames {
wg.Add(1)
go func(username string) {
defer wg.Done()
movies := fetchList(username, true)
allMovies = append(allMovies, movies...)
}(username)
}
wg.Wait()
// Create intersected watchlist
movieList = intersectLists(allMovies, len(usernames))
} else { // Union
// Pick a random user
user := usernames[rand.Intn(len(usernames))]
// Fetch single user's watchlist, equivalent to union since randomness
movieList = fetchList(user, false)
}
// Return movie
if len(movieList) != 0 {
randomMovie := chooseMovie(movieList)
randomMovie.ImageLink, randomMovie.Title = fetchMovieInfo(randomMovie.Link)
c.JSON(http.StatusOK, randomMovie)
} else {
c.Status(http.StatusNotFound)
}
})
err := router.Run(":" + port)
if err != nil {
log.Fatal("Server crashed unexpectedly ", err)
}
}