2015-04-14 08:40:39 +02:00
|
|
|
/*
|
|
|
|
* MumbleDJ
|
|
|
|
* By Matthieu Grieger
|
|
|
|
* service_youtube.go
|
|
|
|
* Copyright (c) 2014, 2015 Matthieu Grieger (MIT License)
|
|
|
|
*/
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2015-05-13 07:47:14 +02:00
|
|
|
"regexp"
|
2015-04-14 08:40:39 +02:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2015-05-10 06:45:00 +02:00
|
|
|
"time"
|
2015-04-14 08:40:39 +02:00
|
|
|
|
|
|
|
"github.com/jmoiron/jsonq"
|
2015-07-27 23:29:50 +02:00
|
|
|
"github.com/layeh/gumble/gumble"
|
2015-05-10 06:45:00 +02:00
|
|
|
"github.com/layeh/gumble/gumble_ffmpeg"
|
2015-04-14 08:40:39 +02:00
|
|
|
)
|
|
|
|
|
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-27 23:13:40 +02:00
|
|
|
// ---------------
|
|
|
|
// YOUTUBE SERVICE
|
|
|
|
// ---------------
|
|
|
|
|
2015-07-27 23:35:27 +02:00
|
|
|
type YouTube struct {
|
2015-07-27 23:34:35 +02:00
|
|
|
}
|
|
|
|
|
2015-07-27 23:13:40 +02:00
|
|
|
// Name of the service
|
2015-07-28 00:00:32 +02:00
|
|
|
func (y YouTube) ServiceName() string {
|
2015-07-27 23:13:40 +02:00
|
|
|
return "Youtube"
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks to see if service will accept URL
|
2015-07-28 00:00:32 +02:00
|
|
|
func (y 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
|
|
|
|
2015-07-28 01:11:35 +02:00
|
|
|
func RegexpFromURL(url string, patterns []string) *regexp.Regexp {
|
|
|
|
for _, pattern := range patterns {
|
2015-07-27 23:13:40 +02:00
|
|
|
if re, err := regexp.Compile(pattern); err == nil {
|
|
|
|
if re.MatchString(url) {
|
2015-07-28 01:11:35 +02:00
|
|
|
return re
|
2015-07-27 23:13:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-07-28 01:11:35 +02:00
|
|
|
return nil
|
2015-07-27 23:13:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Creates the requested song/playlist and adds to the queue
|
2015-07-28 00:01:31 +02:00
|
|
|
func (y YouTube) NewRequest(user *gumble.User, url 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-28 01:11:35 +02:00
|
|
|
_, err := NewYouTubePlaylist(user.Name, shortURL)
|
|
|
|
return err
|
2015-07-28 00:30:59 +02:00
|
|
|
} else {
|
2015-07-28 00:35:19 +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-28 01:13:13 +02:00
|
|
|
_, err := NewYouTubeSong(user.Name, shortURL, startOffset, nil)
|
|
|
|
return err
|
2015-07-28 00:30:59 +02:00
|
|
|
}
|
2015-07-28 00:37:52 +02:00
|
|
|
} else {
|
|
|
|
return err
|
2015-07-28 00:30:59 +02:00
|
|
|
}
|
2015-07-27 23:13:40 +02:00
|
|
|
}
|
|
|
|
|
2015-04-14 08:40:39 +02:00
|
|
|
// ------------
|
|
|
|
// YOUTUBE SONG
|
|
|
|
// ------------
|
|
|
|
|
|
|
|
// YouTubeSong holds the metadata for a song extracted from a YouTube video.
|
|
|
|
type YouTubeSong struct {
|
|
|
|
submitter string
|
|
|
|
title string
|
|
|
|
id string
|
2015-05-10 06:45:00 +02:00
|
|
|
offset int
|
2015-04-14 08:40:39 +02:00
|
|
|
filename string
|
|
|
|
duration string
|
|
|
|
thumbnail string
|
|
|
|
skippers []string
|
2015-04-18 01:30:13 +02:00
|
|
|
playlist Playlist
|
2015-04-14 08:40:39 +02:00
|
|
|
dontSkip bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewYouTubeSong gathers the metadata for a song extracted from a YouTube video, and returns
|
|
|
|
// the song.
|
2015-07-28 14:29:14 +02:00
|
|
|
func NewYouTubeSong(user, id, offset string, playlist *YouTubePlaylist) (*YouTubeSong, error) {
|
2015-04-16 08:44:35 +02:00
|
|
|
var apiResponse *jsonq.JsonQuery
|
|
|
|
var err error
|
2015-04-14 08:40:39 +02:00
|
|
|
url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s",
|
|
|
|
id, os.Getenv("YOUTUBE_API_KEY"))
|
2015-04-16 08:44:35 +02:00
|
|
|
if apiResponse, err = PerformGetRequest(url); err != nil {
|
2015-07-28 13:35:52 +02:00
|
|
|
return nil, errors.New(INVALID_API_KEY)
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
|
|
|
|
2015-05-13 07:47:14 +02:00
|
|
|
var offsetDays, offsetHours, offsetMinutes, offsetSeconds int64
|
2015-05-10 06:45:00 +02:00
|
|
|
if offset != "" {
|
2015-05-13 07:47:14 +02:00
|
|
|
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() {
|
2015-05-19 10:21:33 +02:00
|
|
|
if i < len(offsetMatch) {
|
|
|
|
offsetResult[name] = offsetMatch[i]
|
|
|
|
}
|
2015-05-13 07:47:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
2015-05-10 06:45:00 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-16 08:32:32 +02:00
|
|
|
title, _ := apiResponse.String("items", "0", "snippet", "title")
|
|
|
|
thumbnail, _ := apiResponse.String("items", "0", "snippet", "thumbnails", "high", "url")
|
|
|
|
duration, _ := apiResponse.String("items", "0", "contentDetails", "duration")
|
2015-04-14 08:40:39 +02:00
|
|
|
|
2015-05-13 07:47:14 +02:00
|
|
|
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() {
|
2015-05-19 10:21:33 +02:00
|
|
|
if i < len(timestampMatch) {
|
|
|
|
timestampResult[name] = timestampMatch[i]
|
|
|
|
}
|
2015-05-13 07:47:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|
2015-05-10 06:45:00 +02:00
|
|
|
|
2015-05-13 07:47:14 +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)
|
|
|
|
}
|
2015-04-14 08:40:39 +02:00
|
|
|
|
|
|
|
if dj.conf.General.MaxSongDuration == 0 || totalSeconds <= dj.conf.General.MaxSongDuration {
|
|
|
|
song := &YouTubeSong{
|
2015-04-16 08:32:32 +02:00
|
|
|
submitter: user,
|
|
|
|
title: title,
|
|
|
|
id: id,
|
2015-05-13 07:47:14 +02:00
|
|
|
offset: int((offsetDays * 86400) + (offsetHours * 3600) + (offsetMinutes * 60) + offsetSeconds),
|
2015-04-16 08:32:32 +02:00
|
|
|
filename: id + ".m4a",
|
|
|
|
duration: durationString,
|
|
|
|
thumbnail: thumbnail,
|
|
|
|
skippers: make([]string, 0),
|
2015-07-28 14:29:14 +02:00
|
|
|
playlist: playlist,
|
2015-04-16 08:32:32 +02:00
|
|
|
dontSkip: false,
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
|
|
|
dj.queue.AddSong(song)
|
2015-07-28 13:40:12 +02:00
|
|
|
Verbose(song.Submitter() + " added track " + song.Title() + "\n")
|
2015-07-27 21:44:09 +02:00
|
|
|
|
2015-04-14 08:40:39 +02:00
|
|
|
return song, nil
|
|
|
|
}
|
2015-07-28 13:35:52 +02:00
|
|
|
return nil, errors.New(VIDEO_TOO_LONG_MSG)
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Download downloads the song via youtube-dl if it does not already exist on disk.
|
|
|
|
// All downloaded songs are stored in ~/.mumbledj/songs and should be automatically cleaned.
|
|
|
|
func (s *YouTubeSong) Download() error {
|
2015-07-27 21:44:09 +02:00
|
|
|
|
|
|
|
// Checks to see if song is already downloaded
|
2015-04-18 01:30:13 +02:00
|
|
|
if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, s.Filename())); os.IsNotExist(err) {
|
2015-07-28 13:35:52 +02:00
|
|
|
Verbose("Downloading " + s.Title() + "\n")
|
2015-04-18 01:30:13 +02:00
|
|
|
cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s`, s.Filename()), "--format", "m4a", "--", s.ID())
|
2015-04-14 08:40:39 +02:00
|
|
|
if err := cmd.Run(); err == nil {
|
|
|
|
if dj.conf.Cache.Enabled {
|
|
|
|
dj.cache.CheckMaximumDirectorySize()
|
|
|
|
}
|
2015-07-28 13:35:52 +02:00
|
|
|
Verbose(s.Title() + " downloaded\n")
|
2015-04-14 08:40:39 +02:00
|
|
|
return nil
|
|
|
|
}
|
2015-07-28 13:35:52 +02:00
|
|
|
Verbose(s.Title() + " failed to download\n")
|
2015-04-14 08:40:39 +02:00
|
|
|
return errors.New("Song download failed.")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Play plays the song. Once the song is playing, a notification is displayed in a text message that features the video
|
|
|
|
// thumbnail, URL, title, duration, and submitter.
|
|
|
|
func (s *YouTubeSong) Play() {
|
2015-05-10 06:45:00 +02:00
|
|
|
if s.offset != 0 {
|
|
|
|
offsetDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", s.offset))
|
|
|
|
dj.audioStream.Offset = offsetDuration
|
|
|
|
}
|
|
|
|
dj.audioStream.Source = gumble_ffmpeg.SourceFile(fmt.Sprintf("%s/.mumbledj/songs/%s", dj.homeDir, s.Filename()))
|
|
|
|
if err := dj.audioStream.Play(); err != nil {
|
2015-04-14 08:40:39 +02:00
|
|
|
panic(err)
|
|
|
|
} else {
|
2015-07-28 14:32:09 +02:00
|
|
|
if isNil(s.Playlist()) {
|
2015-04-14 08:40:39 +02:00
|
|
|
message := `
|
|
|
|
<table>
|
|
|
|
<tr>
|
|
|
|
<td align="center"><img src="%s" width=150 /></td>
|
|
|
|
</tr>
|
|
|
|
<tr>
|
|
|
|
<td align="center"><b><a href="http://youtu.be/%s">%s</a> (%s)</b></td>
|
|
|
|
</tr>
|
|
|
|
<tr>
|
|
|
|
<td align="center">Added by %s</td>
|
|
|
|
</tr>
|
|
|
|
</table>
|
|
|
|
`
|
2015-04-18 01:30:13 +02:00
|
|
|
dj.client.Self.Channel.Send(fmt.Sprintf(message, s.Thumbnail(), s.ID(), s.Title(),
|
|
|
|
s.Duration(), s.Submitter()), false)
|
2015-04-14 08:40:39 +02:00
|
|
|
} else {
|
|
|
|
message := `
|
|
|
|
<table>
|
|
|
|
<tr>
|
|
|
|
<td align="center"><img src="%s" width=150 /></td>
|
|
|
|
</tr>
|
|
|
|
<tr>
|
|
|
|
<td align="center"><b><a href="http://youtu.be/%s">%s</a> (%s)</b></td>
|
|
|
|
</tr>
|
|
|
|
<tr>
|
|
|
|
<td align="center">Added by %s</td>
|
|
|
|
</tr>
|
|
|
|
<tr>
|
|
|
|
<td align="center">From playlist "%s"</td>
|
|
|
|
</tr>
|
|
|
|
</table>
|
|
|
|
`
|
2015-04-18 01:30:13 +02:00
|
|
|
dj.client.Self.Channel.Send(fmt.Sprintf(message, s.Thumbnail(), s.ID(),
|
|
|
|
s.Title(), s.Duration(), s.Submitter(), s.Playlist().Title()), false)
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
2015-07-28 13:35:52 +02:00
|
|
|
Verbose("Now playing " + s.Title() + "\n")
|
2015-07-27 21:44:09 +02:00
|
|
|
|
2015-05-10 06:45:00 +02:00
|
|
|
go func() {
|
|
|
|
dj.audioStream.Wait()
|
|
|
|
dj.queue.OnSongFinished()
|
|
|
|
}()
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete deletes the song from ~/.mumbledj/songs if the cache is disabled.
|
|
|
|
func (s *YouTubeSong) Delete() error {
|
|
|
|
if dj.conf.Cache.Enabled == false {
|
2015-04-18 01:30:13 +02:00
|
|
|
filePath := fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, s.ID())
|
2015-04-14 08:40:39 +02:00
|
|
|
if _, err := os.Stat(filePath); err == nil {
|
|
|
|
if err := os.Remove(filePath); err == nil {
|
2015-07-28 13:35:52 +02:00
|
|
|
Verbose("Deleted " + s.Title() + "\n")
|
2015-04-14 08:40:39 +02:00
|
|
|
return nil
|
|
|
|
}
|
2015-07-28 13:35:52 +02:00
|
|
|
Verbose("Failed to delete " + s.Title() + "\n")
|
2015-04-14 08:40:39 +02:00
|
|
|
return errors.New("Error occurred while deleting audio file.")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddSkip adds a skip to the skippers slice. If the user is already in the slice, AddSkip
|
|
|
|
// returns an error and does not add a duplicate skip.
|
|
|
|
func (s *YouTubeSong) AddSkip(username string) error {
|
|
|
|
for _, user := range s.skippers {
|
|
|
|
if username == user {
|
|
|
|
return errors.New("This user has already skipped the current song.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
s.skippers = append(s.skippers, username)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveSkip removes a skip from the skippers slice. If username is not in slice, an error is
|
|
|
|
// returned.
|
|
|
|
func (s *YouTubeSong) RemoveSkip(username string) error {
|
|
|
|
for i, user := range s.skippers {
|
|
|
|
if username == user {
|
|
|
|
s.skippers = append(s.skippers[:i], s.skippers[i+1:]...)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errors.New("This user has not skipped the song.")
|
|
|
|
}
|
|
|
|
|
|
|
|
// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's
|
|
|
|
// channel and the number of usernames in the skippers slice. If the value is greater than or equal
|
|
|
|
// to the skip ratio defined in the config, the function returns true, and returns false otherwise.
|
|
|
|
func (s *YouTubeSong) SkipReached(channelUsers int) bool {
|
|
|
|
if float32(len(s.skippers))/float32(channelUsers) >= dj.conf.General.SkipRatio {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Submitter returns the name of the submitter of the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) Submitter() string {
|
|
|
|
return s.submitter
|
|
|
|
}
|
|
|
|
|
|
|
|
// Title returns the title of the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) Title() string {
|
|
|
|
return s.title
|
|
|
|
}
|
|
|
|
|
|
|
|
// ID returns the id of the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) ID() string {
|
|
|
|
return s.id
|
|
|
|
}
|
|
|
|
|
|
|
|
// Filename returns the filename of the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) Filename() string {
|
|
|
|
return s.filename
|
|
|
|
}
|
|
|
|
|
|
|
|
// Duration returns the duration of the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) Duration() string {
|
|
|
|
return s.duration
|
|
|
|
}
|
|
|
|
|
|
|
|
// Thumbnail returns the thumbnail URL for the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) Thumbnail() string {
|
|
|
|
return s.thumbnail
|
|
|
|
}
|
|
|
|
|
|
|
|
// Playlist returns the playlist type for the YouTubeSong (may be nil).
|
2015-04-16 08:32:32 +02:00
|
|
|
func (s *YouTubeSong) Playlist() Playlist {
|
2015-04-18 01:30:13 +02:00
|
|
|
return s.playlist
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// DontSkip returns the DontSkip boolean value for the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) DontSkip() bool {
|
|
|
|
return s.dontSkip
|
|
|
|
}
|
|
|
|
|
2015-04-16 08:32:32 +02:00
|
|
|
// SetDontSkip sets the DontSkip boolean value for the YouTubeSong.
|
|
|
|
func (s *YouTubeSong) SetDontSkip(value bool) {
|
|
|
|
s.dontSkip = value
|
|
|
|
}
|
|
|
|
|
2015-04-14 08:40:39 +02:00
|
|
|
// ----------------
|
|
|
|
// YOUTUBE PLAYLIST
|
|
|
|
// ----------------
|
|
|
|
|
|
|
|
// YouTubePlaylist holds the metadata for a YouTube playlist.
|
|
|
|
type YouTubePlaylist struct {
|
|
|
|
id string
|
|
|
|
title string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewYouTubePlaylist gathers the metadata for a YouTube playlist and returns it.
|
|
|
|
func NewYouTubePlaylist(user, id string) (*YouTubePlaylist, error) {
|
2015-04-16 08:44:35 +02:00
|
|
|
var apiResponse *jsonq.JsonQuery
|
|
|
|
var err error
|
2015-04-14 08:40:39 +02:00
|
|
|
// 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-04-16 08:44:35 +02:00
|
|
|
if apiResponse, err = PerformGetRequest(url); err != nil {
|
2015-04-14 08:40:39 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2015-04-18 01:30:13 +02:00
|
|
|
title, _ := apiResponse.String("items", "0", "snippet", "title")
|
2015-04-14 08:40:39 +02:00
|
|
|
|
|
|
|
playlist := &YouTubePlaylist{
|
|
|
|
id: id,
|
|
|
|
title: title,
|
|
|
|
}
|
|
|
|
|
2015-07-28 14:56:41 +02:00
|
|
|
// Retrieve items in playlist
|
|
|
|
url = fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=%s&key=%s",
|
2015-04-14 08:40:39 +02:00
|
|
|
id, os.Getenv("YOUTUBE_API_KEY"))
|
2015-04-16 08:32:32 +02:00
|
|
|
if apiResponse, err = PerformGetRequest(url); err != nil {
|
2015-04-14 08:40:39 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2015-04-16 08:44:35 +02:00
|
|
|
numVideos, _ := apiResponse.Int("pageInfo", "totalResults")
|
2015-07-28 14:56:41 +02:00
|
|
|
if numVideos > 25 {
|
|
|
|
numVideos = 25
|
|
|
|
}
|
2015-04-14 08:40:39 +02:00
|
|
|
|
|
|
|
for i := 0; i < numVideos; i++ {
|
|
|
|
index := strconv.Itoa(i)
|
2015-04-16 08:32:32 +02:00
|
|
|
videoID, _ := apiResponse.String("items", index, "snippet", "resourceId", "videoId")
|
2015-07-28 13:35:52 +02:00
|
|
|
NewYouTubeSong(user, videoID, "", playlist)
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
|
|
|
return playlist, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddSkip adds a skip to the playlist's skippers slice.
|
|
|
|
func (p *YouTubePlaylist) AddSkip(username string) error {
|
2015-04-18 01:30:13 +02:00
|
|
|
for _, user := range dj.playlistSkips[p.ID()] {
|
2015-04-14 08:40:39 +02:00
|
|
|
if username == user {
|
|
|
|
return errors.New("This user has already skipped the current song.")
|
|
|
|
}
|
|
|
|
}
|
2015-04-18 01:30:13 +02:00
|
|
|
dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()], username)
|
2015-04-14 08:40:39 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveSkip removes a skip from the playlist's skippers slice. If username is not in the slice
|
|
|
|
// an error is returned.
|
|
|
|
func (p *YouTubePlaylist) RemoveSkip(username string) error {
|
2015-04-18 01:30:13 +02:00
|
|
|
for i, user := range dj.playlistSkips[p.ID()] {
|
2015-04-14 08:40:39 +02:00
|
|
|
if username == user {
|
2015-04-18 01:30:13 +02:00
|
|
|
dj.playlistSkips[p.ID()] = append(dj.playlistSkips[p.ID()][:i], dj.playlistSkips[p.ID()][i+1:]...)
|
2015-04-14 08:40:39 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return errors.New("This user has not skipped the song.")
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteSkippers removes the skippers entry in dj.playlistSkips.
|
|
|
|
func (p *YouTubePlaylist) DeleteSkippers() {
|
2015-04-18 01:30:13 +02:00
|
|
|
delete(dj.playlistSkips, p.ID())
|
2015-04-14 08:40:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// SkipReached calculates the current skip ratio based on the number of users within MumbleDJ's
|
|
|
|
// channel and the number of usernames in the skippers slice. If the value is greater than or equal
|
|
|
|
// to the skip ratio defined in the config, the function returns true, and returns false otherwise.
|
|
|
|
func (p *YouTubePlaylist) SkipReached(channelUsers int) bool {
|
2015-04-18 01:30:13 +02:00
|
|
|
if float32(len(dj.playlistSkips[p.ID()]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio {
|
2015-04-14 08:40:39 +02:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// ID returns the id of the YouTubePlaylist.
|
|
|
|
func (p *YouTubePlaylist) ID() string {
|
|
|
|
return p.id
|
|
|
|
}
|
|
|
|
|
|
|
|
// Title returns the title of the YouTubePlaylist.
|
|
|
|
func (p *YouTubePlaylist) Title() string {
|
|
|
|
return p.title
|
|
|
|
}
|
|
|
|
|
|
|
|
// -----------
|
|
|
|
// YOUTUBE API
|
|
|
|
// -----------
|
|
|
|
|
|
|
|
// PerformGetRequest does all the grunt work for a YouTube HTTPS GET request.
|
|
|
|
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.")
|
|
|
|
}
|
|
|
|
return nil, errors.New("Invalid YouTube 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
|
|
|
|
}
|