-
Notifications
You must be signed in to change notification settings - Fork 11
/
title.go
397 lines (365 loc) · 9.78 KB
/
title.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package imdb
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
)
// A Title represents an IMDb title (movie, series, etc.).
type Title struct {
ID string `json:",omitempty"`
URL string `json:",omitempty"`
Name string `json:",omitempty"`
Type string `json:",omitempty"`
Year int `json:",omitempty"`
Rating string `json:",omitempty"`
RatingCount int `json:",omitempty"`
Duration string `json:",omitempty"`
Directors []Name `json:",omitempty"`
Writers []Name `json:",omitempty"`
Actors []Name `json:",omitempty"`
Genres []string `json:",omitempty"`
Languages []string `json:",omitempty"`
Nationalities []string `json:",omitempty"`
Description string `json:",omitempty"`
Poster Media `json:",omitempty"`
AKA []string `json:",omitempty"`
}
// String formats a Title on one line.
func (t *Title) String() string {
name := t.Name
if t.Year > 0 {
name = fmt.Sprintf("%s (%d)", name, t.Year)
}
infos := []string{name}
if len(t.Genres) > 0 {
genres := t.Genres
if len(t.Genres) > 3 {
genres = genres[:3]
}
infos = append(infos, strings.Join(genres, ", "))
}
if len(t.Directors) > 0 {
var directors []string
for _, d := range t.Directors {
directors = append(directors, d.FullName)
}
if len(directors) > 2 {
directors = directors[:2]
}
infos = append(infos, strings.Join(directors, ", "))
}
if len(t.Actors) > 0 {
var actors []string
for _, a := range t.Actors {
actors = append(actors, a.FullName)
}
if len(actors) > 3 {
actors = actors[:3]
}
infos = append(infos, strings.Join(actors, ", "))
}
if t.Duration != "" {
infos = append(infos, t.Duration)
}
if t.Rating != "" {
infos = append(infos, t.Rating)
}
infos = append(infos, t.URL)
return strings.Join(infos, " - ")
}
var ttRE = regexp.MustCompile(`^tt\d+$`)
const titleURL = "https://www.imdb.com/title/%s"
// NewTitle gets, parses and returns a Title by its ID.
func NewTitle(c *http.Client, id string) (*Title, error) {
if !ttRE.MatchString(id) {
return nil, ErrInvalidID
}
resp, err := c.Get(fmt.Sprintf(titleURL, id))
if err != nil {
return nil, err
}
defer resp.Body.Close()
page, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
t := Title{}
if err := t.Parse(page); err != nil {
return nil, err
}
resp, err = c.Get(t.URL + "/releaseinfo")
if err != nil {
return nil, err
}
defer resp.Body.Close()
rls, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err := t.ParseRls(rls); err != nil {
return nil, err
}
return &t, nil
}
// Regular expressions to parse a Title.
var (
schemaRE = regexp.MustCompile(`(?s)<script type="application/ld\+json">(.*?)</script>`)
titleYearRE = regexp.MustCompile(`<a href="/year/(\d+)/`)
titleYear2RE = regexp.MustCompile(`(?s)<h4[^>]*>\s*Release Date:\s*</h4>\s*(\d+)\s+`)
titleYear3RE = regexp.MustCompile(`(?s)<title[^>]*>[^<]*TV Episode (\d{4})[^<]*</title>`)
titleDurationRE = regexp.MustCompile(`<time datetime="(?:PT)?([0-9HM]+)"`)
titleDuration2RE = regexp.MustCompile(`(?s)<span[^>]*>Runtime</span><div[^>]*><ul[^>]*><li[^>]*><span[^>]*>(\d+m)in</span>`)
titleLanguagesRE = regexp.MustCompile(`(?s)<[^>]+>Language:?</[^>]+>(.*?)</div>`)
titleLanguageRE = regexp.MustCompile(`<a[^>]*>([^<]+)</a>`)
titleNationalitiesRE = regexp.MustCompile(`href="/search/title/?\?country_of_origin[^"]*"[^>]*>([^<]+)`)
titleDescriptionRE = regexp.MustCompile(`<meta property="og:description" content="(?:(?:Created|Directed) by .*?\w\w\.\s*)*(?:With .*?\w\w\.\s*)?([^"]*)`)
titlePosterRE = regexp.MustCompile(`(?s)<div class="poster">\s*<a href="/title/tt\d+/mediaviewer/(rm\d+)[^"]*"[^>]*>\s*<img.*?src="([^"]+)"`)
titlePoster2RE = regexp.MustCompile(`(?s)"primaryImage":{"id":"([^"]*)","__typename":"Image"}`)
)
type schemaJSON struct {
Type string `json:"@type"`
Url string
Name string
Image string
Genre genreJSON
Actor personsJSON
Director personsJSON
Creator personsJSON
Description string
DatePublished string
AggregateRating struct {
RatingValue json.RawMessage
RatingCount int
}
Duration string
}
// Some types are either single or list, so we need to handle that.
type genreJSON []string
func (s *genreJSON) UnmarshalJSON(data []byte) error {
var v string
if err := json.Unmarshal(data, &v); err == nil {
*s = []string{v}
return nil
}
var w []string
if err := json.Unmarshal(data, &w); err != nil {
return err
}
*s = w
return nil
}
type personsJSON []personJSON
func (s *personsJSON) UnmarshalJSON(data []byte) error {
var v personJSON
if err := json.Unmarshal(data, &v); err == nil {
*s = []personJSON{v}
return nil
}
var w []personJSON
if err := json.Unmarshal(data, &w); err != nil {
return err
}
*s = w
return nil
}
type personJSON struct {
Type string `json:"@type"`
Url string
Name string
}
// Parse parses a Title from its page.
func (t *Title) Parse(page []byte) error {
s := schemaRE.FindSubmatch(page)
if s == nil {
return NewErrParse("schema")
}
var v schemaJSON
if err := json.Unmarshal(s[1], &v); err != nil {
return NewErrParse(err.Error() + "; schema was: " + string(s[1]))
}
p := strings.Split(v.Url, "/")
if len(p) != 4 {
return NewErrParse("id")
}
t.ID = p[2]
t.URL = fmt.Sprintf(titleURL, t.ID)
t.Name = decode(v.Name)
t.Type = v.Type
titleYear := titleYearRE.FindSubmatch(page)
titleYear2 := titleYear2RE.FindSubmatch(page)
titleYear3 := titleYear3RE.FindSubmatch(page)
if len(v.DatePublished) >= 4 {
year, err := strconv.Atoi(v.DatePublished[:4])
if err != nil {
return NewErrParse(fmt.Sprintf("date: %v", err))
}
t.Year = year
} else if titleYear != nil {
t.Year, _ = strconv.Atoi(string(titleYear[1])) // regexp matches digits
} else if titleYear2 != nil {
t.Year, _ = strconv.Atoi(string(titleYear2[1])) // regexp matches digits
} else if titleYear3 != nil {
t.Year, _ = strconv.Atoi(string(titleYear3[1])) // regexp matches digits
} else {
// sometimes there's just no year, e.g. https://www.imdb.com/title/tt12592252/
}
var rating string
if err := json.Unmarshal(v.AggregateRating.RatingValue, &rating); err == nil {
t.Rating = rating
}
var ratingf float64
if err := json.Unmarshal(v.AggregateRating.RatingValue, &ratingf); err == nil && ratingf > 0 {
t.Rating = fmt.Sprintf("%.1f", ratingf)
}
t.RatingCount = v.AggregateRating.RatingCount
if v.Duration != "" {
t.Duration = strings.ToLower(strings.TrimLeft(v.Duration, "PT"))
} else {
s := titleDurationRE.FindSubmatch(page)
if s != nil {
t.Duration = strings.ToLower(string(s[1]))
} else {
s := titleDuration2RE.FindSubmatch(page)
if s != nil {
t.Duration = string(s[1])
}
}
}
t.Directors = nil
for _, e := range v.Director {
if e.Type != "Person" {
continue
}
p := strings.Split(e.Url, "/")
if len(p) != 4 {
return NewErrParse("director id")
}
id := p[2]
if nameSlice(t.Directors).Has(id) {
continue
}
t.Directors = append(t.Directors, Name{
ID: id,
URL: fmt.Sprintf(nameURL, id),
FullName: e.Name,
})
}
t.Writers = nil
for _, e := range v.Creator {
if e.Type != "Person" {
continue
}
p := strings.Split(e.Url, "/")
if len(p) != 4 {
return NewErrParse("writer id")
}
id := p[2]
if nameSlice(t.Writers).Has(id) {
continue
}
t.Writers = append(t.Writers, Name{
ID: id,
URL: fmt.Sprintf(nameURL, id),
FullName: e.Name,
})
}
t.Actors = nil
for _, e := range v.Actor {
if e.Type != "Person" {
continue
}
p := strings.Split(e.Url, "/")
if len(p) != 4 {
return NewErrParse("actor id")
}
id := p[2]
if nameSlice(t.Actors).Has(id) {
continue
}
t.Actors = append(t.Actors, Name{
ID: id,
URL: fmt.Sprintf(nameURL, id),
FullName: e.Name,
})
}
t.Genres = v.Genre
s = titleLanguagesRE.FindSubmatch(page)
if s != nil {
s := titleLanguageRE.FindAllSubmatch(s[1], -1)
if s == nil {
return NewErrParse("languages")
}
t.Languages = nil
for _, m := range s {
language := decode(string(m[1]))
if stringSlice(t.Languages).Has(language) {
continue
}
t.Languages = append(t.Languages, language)
}
}
as := titleNationalitiesRE.FindAllSubmatch(page, -1)
if as != nil {
t.Nationalities = nil
for _, m := range as {
nationality := decode(string(m[1]))
if stringSlice(t.Nationalities).Has(nationality) {
continue
}
t.Nationalities = append(t.Nationalities, nationality)
}
}
t.Description = v.Description
s = titlePosterRE.FindSubmatch(page)
if s != nil {
id := string(s[1])
t.Poster = Media{
ID: id,
TitleID: t.ID,
URL: fmt.Sprintf(mediaURL, t.ID, id),
ContentURL: string(s[2]),
}
} else {
s = titlePoster2RE.FindSubmatch(page)
if s != nil {
id := string(s[1])
re, err := regexp.Compile(`(?s)"primaryImage":{"id":"` + id + `","width":\d+,"height":\d+,"url":"([^"]+)"`)
if err != nil {
return NewErrParse("poster RE")
}
s = re.FindSubmatch(page)
if s != nil {
t.Poster = Media{
ID: id,
TitleID: t.ID,
URL: fmt.Sprintf(mediaURL, t.ID, id),
ContentURL: string(s[1]),
}
}
}
}
return nil
}
// Regular expressions to parse a Title release info.
var (
titleAKARE = regexp.MustCompile(`<td class="aka-item__title">([^<]+)</td>`)
)
// ParseRls parses a Title release info from its page.
func (t *Title) ParseRls(page []byte) error {
t.AKA = nil
s := titleAKARE.FindAllSubmatch(page, -1)
for _, m := range s {
aka := decode(string(m[1]))
if stringSlice(t.AKA).Has(aka) {
continue
}
t.AKA = append(t.AKA, aka)
}
sort.StringSlice(t.AKA).Sort()
return nil
}