youtube embed

This commit is contained in:
Asim Aslam
2021-12-10 11:07:11 +00:00
parent d5fa802db2
commit 13dd1af1d4
4 changed files with 283 additions and 52 deletions

View File

@@ -2,6 +2,8 @@ package handler
import (
"context"
"fmt"
"net/url"
"strings"
"github.com/micro/micro/v3/service/errors"
@@ -15,6 +17,10 @@ type Youtube struct {
Client *youtube.Service
}
var (
iframe = `<iframe width="560" height="315" src="%s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`
)
func New(apiKey string) *Youtube {
ctx := context.TODO()
yt, _ := youtube.NewService(ctx, option.WithAPIKey(apiKey))
@@ -24,6 +30,44 @@ func New(apiKey string) *Youtube {
}
}
func (y *Youtube) Embed(ctx context.Context, req *pb.EmbedRequest, rsp *pb.EmbedResponse) error {
if len(req.Url) == 0 {
return errors.BadRequest("youtube.embed", "missing url")
}
if strings.HasPrefix(req.Url, "https://youtu.be/") {
id := strings.TrimPrefix(req.Url, "https://youtu.be/")
rsp.Link = "https://www.youtube.com/embed/" + id
rsp.Script = fmt.Sprintf(iframe, rsp.Link)
rsp.ShortUrl = req.Url
return nil
}
if !strings.HasPrefix(req.Url, "https://www.youtube.com/watch") {
return errors.BadRequest("youtube.embed", "invalid url")
}
uri, err := url.Parse(req.Url)
if err != nil {
return errors.BadRequest("youtube.embed", "invalid url")
}
vals := uri.Query()
id := vals.Get("v")
if len(id) == 0 {
return errors.BadRequest("youtube.embed", "invalid url")
}
rsp.Link = "https://www.youtube.com/embed/" + id
rsp.Script = fmt.Sprintf(iframe, rsp.Link)
rsp.ShortUrl = "https://youtu.be/" + id
return nil
}
func (y *Youtube) Search(ctx context.Context, req *pb.SearchRequest, rsp *pb.SearchResponse) error {
if len(req.Query) == 0 {
return errors.BadRequest("youtube.search", "missing query")