This repository has been archived on 2019-06-23. You can view files and clone it, but cannot push or open issues or pull requests.
mumbledj/service_youtube.go

246 lines
7.5 KiB
Go
Raw Normal View History

/*
* MumbleDJ
* By Matthieu Grieger
* service_youtube.go
* Copyright (c) 2014, 2015 Matthieu Grieger (MIT License)
*/
2015-07-30 18:28:01 +02:00
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/jmoiron/jsonq"
2015-07-27 23:29:50 +02:00
"github.com/layeh/gumble/gumble"
)
2015-07-28 13:35:52 +02:00
// Regular expressions for youtube urls
2015-07-28 01:11:35 +02:00
var youtubePlaylistPattern = `https?:\/\/www\.youtube\.com\/playlist\?list=([\w-]+)`
var youtubeVideoPatterns = []string{
`https?:\/\/www\.youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`,
`https?:\/\/youtube\.com\/watch\?v=([\w-]+)(\&t=\d*m?\d*s?)?`,
`https?:\/\/youtu.be\/([\w-]+)(\?t=\d*m?\d*s?)?`,
`https?:\/\/youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`,
`https?:\/\/www.youtube.com\/v\/([\w-]+)(\?t=\d*m?\d*s?)?`,
}
2015-07-30 14:48:53 +02:00
// ------
// TYPES
// ------
// YouTube implements the Service interface
type YouTube struct{}
2015-07-27 23:13:40 +02:00
// ---------------
// YOUTUBE SERVICE
// ---------------
// Name of the service
2015-07-30 14:48:53 +02:00
func (yt YouTube) ServiceName() string {
2015-07-27 23:13:40 +02:00
return "Youtube"
}
// Checks to see if service will accept URL
2015-07-30 14:48:53 +02:00
func (yt YouTube) URLRegex(url string) bool {
2015-07-28 01:11:35 +02:00
return RegexpFromURL(url, append(youtubeVideoPatterns, []string{youtubePlaylistPattern}...)) != nil
}
2015-07-27 23:13:40 +02:00
// Creates the requested song/playlist and adds to the queue
2015-07-30 14:48:53 +02:00
func (yt YouTube) NewRequest(user *gumble.User, url string) (string, error) {
2015-07-28 01:13:13 +02:00
var shortURL, startOffset = "", ""
2015-07-28 00:30:59 +02:00
if re, err := regexp.Compile(youtubePlaylistPattern); err == nil {
if re.MatchString(url) {
2015-07-28 00:35:19 +02:00
if dj.HasPermission(user.Name, dj.conf.Permissions.AdminAddPlaylists) {
2015-07-28 00:36:50 +02:00
shortURL = re.FindStringSubmatch(url)[1]
2015-07-30 14:48:53 +02:00
playlist, err := yt.NewPlaylist(user.Name, shortURL)
2015-07-28 22:38:35 +02:00
return playlist.Title(), err
2015-07-28 00:30:59 +02:00
} else {
2015-07-28 22:43:02 +02:00
return "", errors.New("NO_PLAYLIST_PERMISSION")
2015-07-28 00:30:59 +02:00
}
} else {
2015-07-28 01:11:35 +02:00
re = RegexpFromURL(url, youtubeVideoPatterns)
2015-07-28 00:36:50 +02:00
matches := re.FindAllStringSubmatch(url, -1)
2015-07-28 00:30:59 +02:00
shortURL = matches[0][1]
if len(matches[0]) == 3 {
startOffset = matches[0][2]
}
2015-07-30 14:48:53 +02:00
song, err := yt.NewSong(user.Name, shortURL, startOffset, nil)
2015-08-10 20:29:58 +02:00
if err == nil {
return song.Title(), nil
} else {
Verbose("youtube.NewRequest: " + err.Error())
2015-08-10 20:31:12 +02:00
return "", err
2015-08-10 20:29:58 +02:00
}
2015-07-28 00:30:59 +02:00
}
2015-07-28 00:37:52 +02:00
} else {
2015-07-28 22:43:02 +02:00
return "", err
2015-07-28 00:30:59 +02:00
}
2015-07-27 23:13:40 +02:00
}
2015-07-30 14:48:53 +02:00
// NewSong gathers the metadata for a song extracted from a YouTube video, and returns
// the song.
2015-08-10 17:04:31 +02:00
func (yt YouTube) NewSong(user, id, offset string, playlist Playlist) (Song, error) {
2015-04-16 08:44:35 +02:00
var apiResponse *jsonq.JsonQuery
var err error
url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s",
id, os.Getenv("YOUTUBE_API_KEY"))
2015-08-02 19:55:51 +02:00
if apiResponse, err = PerformGetRequest(url); err != nil {
2015-07-28 13:35:52 +02:00
return nil, errors.New(INVALID_API_KEY)
}
var offsetDays, offsetHours, offsetMinutes, offsetSeconds int64
if offset != "" {
offsetExp := regexp.MustCompile(`t\=(?P<days>\d+d)?(?P<hours>\d+h)?(?P<minutes>\d+m)?(?P<seconds>\d+s)?`)
offsetMatch := offsetExp.FindStringSubmatch(offset)
offsetResult := make(map[string]string)
for i, name := range offsetExp.SubexpNames() {
if i < len(offsetMatch) {
offsetResult[name] = offsetMatch[i]
}
}
if offsetResult["days"] != "" {
offsetDays, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["days"], "d"), 10, 32)
}
if offsetResult["hours"] != "" {
offsetHours, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["hours"], "h"), 10, 32)
}
if offsetResult["minutes"] != "" {
offsetMinutes, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["minutes"], "m"), 10, 32)
}
if offsetResult["seconds"] != "" {
offsetSeconds, _ = strconv.ParseInt(strings.TrimSuffix(offsetResult["seconds"], "s"), 10, 32)
}
}
title, _ := apiResponse.String("items", "0", "snippet", "title")
thumbnail, _ := apiResponse.String("items", "0", "snippet", "thumbnails", "high", "url")
duration, _ := apiResponse.String("items", "0", "contentDetails", "duration")
var days, hours, minutes, seconds int64
timestampExp := regexp.MustCompile(`P(?P<days>\d+D)?T(?P<hours>\d+H)?(?P<minutes>\d+M)?(?P<seconds>\d+S)?`)
timestampMatch := timestampExp.FindStringSubmatch(duration)
timestampResult := make(map[string]string)
for i, name := range timestampExp.SubexpNames() {
if i < len(timestampMatch) {
timestampResult[name] = timestampMatch[i]
}
}
if timestampResult["days"] != "" {
days, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["days"], "D"), 10, 32)
}
if timestampResult["hours"] != "" {
hours, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["hours"], "H"), 10, 32)
}
if timestampResult["minutes"] != "" {
minutes, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["minutes"], "M"), 10, 32)
}
if timestampResult["seconds"] != "" {
seconds, _ = strconv.ParseInt(strings.TrimSuffix(timestampResult["seconds"], "S"), 10, 32)
2015-04-18 01:30:13 +02:00
}
totalSeconds := int((days * 86400) + (hours * 3600) + (minutes * 60) + seconds)
2015-05-13 07:55:06 +02:00
var durationString string
if hours != 0 {
if days != 0 {
durationString = fmt.Sprintf("%d:%02d:%02d:%02d", days, hours, minutes, seconds)
} else {
durationString = fmt.Sprintf("%d:%02d:%02d", hours, minutes, seconds)
}
} else {
durationString = fmt.Sprintf("%d:%02d", minutes, seconds)
}
if dj.conf.General.MaxSongDuration == 0 || totalSeconds <= dj.conf.General.MaxSongDuration {
2015-08-10 17:00:47 +02:00
song := &YouTubeDLSong{
submitter: user,
title: title,
id: id,
offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds),
duration: durationString,
thumbnail: thumbnail,
skippers: make([]string, 0),
2015-07-28 14:29:14 +02:00
playlist: playlist,
dontSkip: false,
}
dj.queue.AddSong(song)
2015-07-30 19:10:06 +02:00
Verbose(song.Submitter() + " added track " + song.Title())
return song, nil
}
2015-07-28 13:35:52 +02:00
return nil, errors.New(VIDEO_TOO_LONG_MSG)
}
2015-07-30 14:48:53 +02:00
// NewPlaylist gathers the metadata for a YouTube playlist and returns it.
2015-08-10 17:04:31 +02:00
func (yt YouTube) NewPlaylist(user, id string) (Playlist, error) {
2015-07-30 14:48:53 +02:00
var apiResponse *jsonq.JsonQuery
var err error
// Retrieve title of playlist
url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=%s&key=%s",
id, os.Getenv("YOUTUBE_API_KEY"))
2015-08-02 19:55:51 +02:00
if apiResponse, err = PerformGetRequest(url); err != nil {
2015-07-30 14:48:53 +02:00
return nil, err
}
title, _ := apiResponse.String("items", "0", "snippet", "title")
2015-08-10 17:00:47 +02:00
playlist := &YouTubeDLPlaylist{
2015-07-30 14:48:53 +02:00
id: id,
title: title,
}
// Retrieve items in playlist
url = fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=%s&key=%s",
id, os.Getenv("YOUTUBE_API_KEY"))
2015-08-02 19:55:51 +02:00
if apiResponse, err = PerformGetRequest(url); err != nil {
2015-07-30 14:48:53 +02:00
return nil, err
}
numVideos, _ := apiResponse.Int("pageInfo", "totalResults")
if numVideos > 50 {
numVideos = 50
}
for i := 0; i < numVideos; i++ {
index := strconv.Itoa(i)
videoID, _ := apiResponse.String("items", index, "snippet", "resourceId", "videoId")
yt.NewSong(user, videoID, "", playlist)
}
return playlist, nil
}
// PerformGetRequest does all the grunt work for a YouTube HTTPS GET request.
2015-08-02 19:55:51 +02:00
func PerformGetRequest(url string) (*jsonq.JsonQuery, error) {
jsonString := ""
if response, err := http.Get(url); err == nil {
defer response.Body.Close()
if response.StatusCode == 200 {
if body, err := ioutil.ReadAll(response.Body); err == nil {
jsonString = string(body)
}
} else {
if response.StatusCode == 403 {
return nil, errors.New("Invalid API key supplied.")
}
2015-08-02 19:55:51 +02:00
return nil, errors.New("Invalid ID supplied.")
}
} else {
return nil, errors.New("An error occurred while receiving HTTP GET response.")
}
jsonData := map[string]interface{}{}
decoder := json.NewDecoder(strings.NewReader(jsonString))
decoder.Decode(&jsonData)
jq := jsonq.NewQuery(jsonData)
return jq, nil
}