Sélectionner une révision Git
youtube.go
youtube.go 1,16 Kio
package site
import (
"errors"
"fmt"
"net/http"
"regexp"
"google.golang.org/api/googleapi/transport"
"google.golang.org/api/youtube/v3"
)
type Youtube struct {
service *youtube.Service
}
func NewYoutube(key string) (Reader, error) {
client := &http.Client{
Transport: &transport.APIKey{Key: key},
}
service, err := youtube.New(client)
return &Youtube{service: service}, err
}
func (yt Youtube) Read(url string) (*Content, error) {
re := regexp.MustCompile(`(?:^|[^!])https?://(?:www.youtube.com/watch\?[a-zA-Z0-9_=&-]*v=|youtu.be/)([a-zA-Z0-9_-]+)`)
match := re.FindStringSubmatch(url)
if len(match) == 0 {
return nil, nil
}
response, err := yt.service.Videos.List("snippet,contentDetails").Id(match[1]).Do()
if err != nil {
return nil, err
}
video := response.Items[0]
duration, err := ParseISO8601Duration(video.ContentDetails.Duration)
if err != nil {
return nil, errors.New(fmt.Sprintf("Invalid duration: %s", err))
}
return &Content{
Author: video.Snippet.ChannelTitle,
Duration: duration,
Title: video.Snippet.Title,
Source: "youtube",
SourceId: video.Id,
Url: "https://www.youtube.com/watch?v=" + video.Id,
}, nil
}