-
Notifications
You must be signed in to change notification settings - Fork 2
/
youtube.go
49 lines (46 loc) · 1.29 KB
/
youtube.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
package unfurlist
import (
"context"
"net/http"
"net/url"
"strings"
"time"
"github.com/artyom/oembed"
)
// youtubeFetcher that retrieves metadata directly from
// https://www.youtube.com/oembed endpoint.
//
// This is only needed because sometimes youtube may return captcha-walled
// response that does not include oembed endpoint address as part of such html
// page.
func youtubeFetcher(ctx context.Context, client *http.Client, u *url.URL) (*Metadata, bool) {
switch {
case u.Host == "youtu.be" && len(u.Path) > 2:
case u.Host == "www.youtube.com" && u.Path == "/watch" && strings.HasPrefix(u.RawQuery, "v="):
default:
return nil, false
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
const endpointPrefix = `https://www.youtube.com/oembed?format=json&url=`
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpointPrefix+url.QueryEscape(u.String()), nil)
if err != nil {
return nil, false
}
resp, err := client.Do(req)
if err != nil {
return nil, false
}
defer resp.Body.Close()
meta, err := oembed.FromResponse(resp)
if err != nil {
return nil, false
}
return &Metadata{
Title: meta.Title,
Type: string(meta.Type),
Image: meta.Thumbnail,
ImageWidth: meta.ThumbnailWidth,
ImageHeight: meta.ThumbnailHeight,
}, true
}