Finished YouTube API

This commit is contained in:
Matthieu Grieger 2015-04-09 13:20:40 -07:00
parent 14bb9df146
commit 985f48572f
5 changed files with 276 additions and 103 deletions

View file

@ -7,7 +7,7 @@
package services
// Generic Song interface. Each service will implement these
// Song interface. Each service will implement these
// functions in their Song types.
type Song interface {
Download()
@ -18,7 +18,7 @@ type Song interface {
SkipReached()
}
// Generic playlist interface. Each service will implement these
// Playlist interface. Each service will implement these
// functions in their Playlist types.
type Playlist interface {
AddSkip()

View file

@ -10,73 +10,14 @@ package youtube
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/jmoiron/jsonq"
)
// Video holds the metadata for a YouTube video.
type Video struct {
id string
title string
duration string
secondsDuration string
thumbnail string
}
// Playlist holds the metadata for a YouTube playlist.
type Playlist struct {
id string
title string
videoIds []string
}
// GetYouTubeVideo retrieves the metadata for a new YouTube video, and creates and returns a
// Video type.
func GetYouTubeVideo(id string) (*YouTubeVideo, error) {
url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s",
id, os.Getenv("YOUTUBE_API_KEY"))
if response, err := PerformGetRequest(url); err != nil {
return nil, err
}
title, _ := response.String("items", "0", "snippet", "title")
thumbnail, _ := response.String("items", "0", "snippet", "thumbnails", "high", "url")
duration, _ := response.String("items", "0", "contentDetails", "duration")
minutes := int(duration[2:strings.Index(duration, "M")])
seconds := int(duration[strings.Index(duration, "M")+1 : len(duration)-1])
totalSeconds := (minutes * 60) + seconds
durationString := fmt.Sprintf("%d:%d", minutes, seconds)
video := &YoutubeVideo{
id: id,
title: title,
duration: durationString,
secondsDuration: totalSeconds,
thumbnail: thumbnail,
}
return video, nil
}
// GetYouTubePlaylist retrieves the metadata for a new YouTube playlist, and creates and returns
// a Playlist type.
func GetYouTubePlaylist(id string) (*YouTubePlaylist, error) {
url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=%s&key=%s",
id, os.Getenv("YOUTUBE_API_KEY"))
if response, err := PerformGetRequest(url); err != nil {
return nil, err
}
title, _ := response.String("items", "0")
}
// PerformGetRequest does all the grunt work for a Youtube HTTPS GET request.
// PerformGetRequest does all the grunt work for a YouTube HTTPS GET request.
func PerformGetRequest(url string) (*jsonq.JsonQuery, error) {
jsonString := ""

View file

@ -6,3 +6,117 @@
*/
package youtube
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
)
// Playlist holds the metadata for a YouTube playlist.
type Playlist struct {
id string
title string
}
// NewPlaylist gathers the metadata for a YouTube playlist and returns it.
func NewPlaylist(user, id string) (*Playlist, 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"))
if response, err := PerformGetRequest(url); err != nil {
return nil, err
}
title, _ := response.String("items", "0")
playlist := &Playlist{
id: id,
title: title,
}
// Retrieve items in playlist
url = fmt.Sprintf("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=%s&key=%s",
id, os.Getenv("YOUTUBE_API_KEY"))
if response, err = PerformGetRequest(url); err != nil {
return nil, err
}
numVideos := response.Int("pageInfo", "totalResults")
if numVideos > 25 {
numVideos = 25
}
for i := 0; i < numVideos; i++ {
index := strconv.Itoa(i)
videoTitle, _ := response.String("items", index, "snippet", "title")
videoID, _ := response.String("items", index, "snippet", "resourceId", "videoId")
videoThumbnail, _ := response.String("items", index, "snippet", "thumbnails", "high", "url")
// A completely separate API call just to get the duration of a video in a
// playlist? WHY GOOGLE, WHY?!
url = fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=%s&key=%s",
videoID, os.Getenv("YOUTUBE_API_KEY"))
if response, err = PerformGetRequest(url); err != nil {
return nil, err
}
videoDuration, _ := response.String("items", "0", "contentDetails", "duration")
minutes := int(videoDuration[2:strings.Index(videoDuration, "M")])
seconds := int(videoDuration[strings.Index(videoDuration, "M")+1 : len(videoDuration)-1])
totalSeconds := (minutes * 60) + seconds
durationString := fmt.Sprintf("%d:%d", minutes, seconds)
if dj.conf.General.MaxSongDuration == 0 || totalSeconds <= dj.conf.General.MaxSongDuration {
playlistSong := &Song{
submitter: user,
title: videoTitle,
id: videoID,
duration: durationString,
thumbnail: videoThumbnail,
skippers: make([]string, 0),
playlist: playlist,
dontSkip: false,
}
dj.queue.AddSong(playlistSong)
}
}
return playlist, nil
}
// AddSkip adds a skip to the playlist's skippers slice.
func (p *Playlist) AddSkip(username string) error {
for _, user := range dj.playlistSkips[p.id] {
if username == user {
return errors.New("This user has already skipped the current song.")
}
}
dj.playlistSkips[p.id] = append(dj.playlistSkips[p.id], username)
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 *Playlist) RemoveSkip(username string) error {
for i, user := range dj.playlistSkips[p.id] {
if username == user {
dj.playlistSkips[p.id] = append(dj.playlistSkips[p.id][:i], dj.playlistSkips[p.id][i+1:]...)
return nil
}
}
return errors.New("This user has not skipped the song.")
}
// DeleteSkippers removes the skippers entry in dj.playlistSkips.
func (p *Playlist) DeleteSkippers() {
delete(dj.playlistSkips, p.id)
}
// 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 *Playlist) SkipReached(channelUsers int) bool {
if float32(len(dj.playlistSkips[p.id]))/float32(channelUsers) >= dj.conf.General.PlaylistSkipRatio {
return true
}
return false
}

View file

@ -7,17 +7,168 @@
package youtube
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
// Song holds the metadata for a song extracted from a YouTube video.
type Song struct {
submitter string
title string
id string
duration string
thumbnailUrl string
skippers []string
playlist *Playlist
dontSkip bool
submitter string
title string
id string
duration string
thumbnail string
skippers []string
playlist *Playlist
dontSkip bool
}
// NewSong gathers the metadata for a song extracted from a YouTube video, and returns
// the Song.
func NewSong(user, id string, playlist *Playlist) (*Song, error) {
url := fmt.Sprintf("https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%s&key=%s",
id, os.Getenv("YOUTUBE_API_KEY"))
if response, err := PerformGetRequest(url); err != nil {
return nil, err
}
title, _ := response.String("items", "0", "snippet", "title")
thumbnail, _ := response.String("items", "0", "snippet", "thumbnails", "high", "url")
duration, _ := response.String("items", "0", "contentDetails", "duration")
minutes := int(duration[2:strings.Index(duration, "M")])
seconds := int(duration[strings.Index(duration, "M")+1 : len(duration)-1])
totalSeconds := (minutes * 60) + seconds
durationString := fmt.Sprintf("%d:%d", minutes, seconds)
if dj.conf.General.MaxSongDuration == 0 || totalSeconds <= dj.conf.General.MaxSongDuration {
song := &Song{
submitter: user,
title: title,
id: id,
duration: durationString,
secondsDuration: totalSeconds,
thumbnail: thumbnail,
skippers: make([]string, 0),
playlist: nil,
dontSkip: false,
}
dj.queue.AddSong(song)
return song, nil
}
return nil, errors.New("Song exceeds the maximum allowed duration.")
}
// 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 *Song) Download() error {
if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, s.id)); os.IsNotExist(err) {
cmd := exec.Command("youtube-dl", "--output", fmt.Sprintf(`~/.mumbledj/songs/%s.m4a`, s.id), "--format", "m4a", "--", s.id)
if err := cmd.Run(); err == nil {
if dj.conf.Cache.Enabled {
dj.cache.CheckMaximumDirectorySize()
}
return nil
}
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 *Song) Play() {
if err := dj.audioStream.Play(fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, s.id), dj.queue.OnSongFinished); err != nil {
panic(err)
} else {
if s.playlist == nil {
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>
`
dj.client.Self.Channel.Send(fmt.Sprintf(message, s.thumbnail, s.id, s.title,
s.duration, s.submitter), false)
} 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>
`
dj.client.Self.Channel.Send(fmt.Sprintf(message, s.thumbnail, s.id,
s.title, s.duration, s.submitter, s.playlist.title), false)
}
}
}
// Delete deletes the song from ~/.mumbledj/songs if the cache is disabled.
func (s *Song) Delete() error {
if dj.conf.Cache.Enabled == false {
filePath := fmt.Sprintf("%s/.mumbledj/songs/%s.m4a", dj.homeDir, s.id)
if _, err := os.Stat(filePath); err == nil {
if err := os.Remove(filePath); err == nil {
return nil
}
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 *Song) 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 *Song) 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 *Song) SkipReached(channelUsers int) bool {
if float32(len(s.skippers))/float32(channelUsers) >= dj.conf.General.SkipRatio {
return true
}
return false
}

View file

@ -68,39 +68,6 @@ const CACHE_SIZE_MSG = "The cache is currently %g MB in size."
// Message shown to user when they attempt to issue a cache-related command when caching is not enabled.
const CACHE_NOT_ENABLED_MSG = "The cache is not currently enabled."
// Message shown to a channel when a new song starts playing.
const NOW_PLAYING_HTML = `
<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>
`
// Message shown to channel when a new song in a playlist starts playing.
const NOW_PLAYING_PLAYLIST_HTML = `
<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>
`
// Message shown to channel when a song is added to the queue by a user.
const SONG_ADDED_HTML = `
<b>%s</b> has added "%s" to the queue.