Skip to content
This repository has been archived by the owner on Nov 14, 2024. It is now read-only.

Commit

Permalink
fix: song fields naming
Browse files Browse the repository at this point in the history
  • Loading branch information
keshon committed Apr 10, 2024
1 parent 1a626c0 commit 0e57c38
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 77 deletions.
14 changes: 7 additions & 7 deletions internal/db/track.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package db

type Track struct {
ID uint `gorm:"primaryKey;autoIncrement"`
SongID string
Title string
HumanURL string
DownloadPath string
Source string
Histories []History `gorm:"foreignKey:TrackID"`
ID uint `gorm:"primaryKey;autoIncrement"`
SongID string
Title string
URL string
Filepath string
Source string
Histories []History `gorm:"foreignKey:TrackID"`
}

func CreateTrack(track *Track) error {
Expand Down
12 changes: 11 additions & 1 deletion mod-music/discord/curl.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/bwmarrin/discordgo"
"github.com/gookit/slog"
"github.com/keshon/melodix-player/mod-music/sources"
"github.com/keshon/melodix-player/mod-music/utils"
)

const (
Expand All @@ -28,21 +29,30 @@ func (d *Discord) handleCacheUrlCommand(s *discordgo.Session, m *discordgo.Messa
return
}

if !utils.IsYouTubeURL(param) {
s.ChannelMessageSend(m.ChannelID, "Only YouTube URL supported")
}

yt := sources.NewYoutube()
song, err := yt.GetSongFromVideoURL(param)
if err != nil {
s.ChannelMessageSend(m.ChannelID, err.Error())
return
}

if song.Duration > 360*time.Minute {
s.ChannelMessageSend(m.ChannelID, "Song too long")
return
}

s.ChannelMessageSend(m.ChannelID, "Starting download "+song.Title)

// Generate unique filename
filename := generateFilename()

// Download the video
videoFilePath := filepath.Join(uploadsFolder, filename+".mp4")
err = downloadURLToFile(videoFilePath, song.DownloadPath)
err = downloadURLToFile(videoFilePath, song.Filepath)
if err != nil {
slog.Error("Error downloading audio:", err)
return
Expand Down
6 changes: 3 additions & 3 deletions mod-music/discord/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ func (d *Discord) handleHistoryCommand(s *discordgo.Session, m *discordgo.Messag
duration := utils.FormatDuration(elem.History.Duration)
fieldContent := fmt.Sprintf("```id %d```\t```x%d```\t```%v```\t```%v```", elem.History.TrackID, elem.History.PlayCount, duration, strings.ToLower(elem.Track.Source))

if remainingSpace := maxLimit - len(embedMsg.Fields) - len(fieldContent) - len(elem.Track.Title) - len(elem.Track.HumanURL); remainingSpace < 0 {
if remainingSpace := maxLimit - len(embedMsg.Fields) - len(fieldContent) - len(elem.Track.Title) - len(elem.Track.URL); remainingSpace < 0 {
break
}

if elem.Track.HumanURL != "" {
embedMsg.AddField(fieldContent, fmt.Sprintf("[%v](%v)\n\n", elem.Track.Title, elem.Track.HumanURL))
if elem.Track.URL != "" {
embedMsg.AddField(fieldContent, fmt.Sprintf("[%v](%v)\n\n", elem.Track.Title, elem.Track.URL))
} else {
embedMsg.AddField(fieldContent, fmt.Sprintf("%v\n\n", elem.Track.Title))
}
Expand Down
27 changes: 14 additions & 13 deletions mod-music/discord/play.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/keshon/melodix-player/mod-music/history"
"github.com/keshon/melodix-player/mod-music/player"
"github.com/keshon/melodix-player/mod-music/sources"
"github.com/keshon/melodix-player/mod-music/utils"
)

// handlePlayCommand handles the play command for Discord.
Expand Down Expand Up @@ -132,9 +133,9 @@ func getSongsFromSources(originType string, songsOrigins []string, guildID strin
}

song := player.Song{
Title: songOrigin,
DownloadPath: songPath,
Source: player.SourceLocalFile,
Title: songOrigin,
Filepath: songPath,
Source: player.SourceLocalFile,
}

songs = append(songs, &song)
Expand All @@ -153,15 +154,15 @@ func getSongsFromSources(originType string, songsOrigins []string, guildID strin
var song []*player.Song
if track.Source == "YouTube" {
slog.Info("Track is from YouTube")
song, err = youtube.GetAllSongsFromURL(track.HumanURL)
song, err = youtube.GetAllSongsFromURL(track.URL)
if err != nil {
slog.Error("error fetching new songs from URL: %v", err)
continue
}
}
if track.Source == "Stream" {
slog.Info("Track is from Stream")
song, err = stream.FetchStreamsByURLs([]string{track.HumanURL})
song, err = stream.FetchStreamsByURLs([]string{track.URL})
if err != nil {
slog.Error("error fetching new songs from URL: %v", err)
continue
Expand All @@ -170,9 +171,9 @@ func getSongsFromSources(originType string, songsOrigins []string, guildID strin
if track.Source == "LocalFile" {
slog.Info("Track is from LocalFile")
song = []*player.Song{{
Title: track.Title,
DownloadPath: track.DownloadPath,
Source: player.SourceLocalFile,
Title: track.Title,
Filepath: track.Filepath,
Source: player.SourceLocalFile,
}}
}

Expand Down Expand Up @@ -291,8 +292,8 @@ func showStatusMessage(d *Discord, s *discordgo.Session, channelID, prevMessageI

// Display current song information
if currentSong := d.Player.GetCurrentSong(); currentSong != nil {
if currentSong.UserURL != "" {
content += fmt.Sprintf("\n*[%v](%v)*\n\n", currentSong.Title, currentSong.UserURL)
if currentSong.URL != "" {
content += fmt.Sprintf("\n*[%v](%v)*\n\n", currentSong.Title, currentSong.URL)
} else {
content += fmt.Sprintf("\n%v\n\n", currentSong.Title)
}
Expand Down Expand Up @@ -337,8 +338,8 @@ func showStatusMessage(d *Discord, s *discordgo.Session, channelID, prevMessageI
}

// Display playlist entry
if elem.UserURL != "" {
content = fmt.Sprintf("%v\n` %v ` [%v](%v)", content, counter, elem.Title, elem.UserURL)
if elem.URL != "" {
content = fmt.Sprintf("%v\n` %v ` [%v](%v)", content, counter, elem.Title, elem.URL)
} else {
content = fmt.Sprintf("%v\n` %v ` %v", content, counter, elem.Title)
}
Expand All @@ -365,7 +366,7 @@ func parseOriginParameter(param string) (string, []string) {
u, err := url.Parse(param)
if err == nil && (u.Scheme == "http" || u.Scheme == "https") {
paramSlice := strings.Fields(param)
if u.Host == "www.youtube.com" || u.Host == "youtube.com" || u.Host == "youtu.be" {
if utils.IsYouTubeURL(u.Host) {
return "youtube_url", paramSlice
}
return "stream_url", paramSlice
Expand Down
34 changes: 17 additions & 17 deletions mod-music/history/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import (
)

type Song struct {
Title string // Title of the song
HumanURL string // URL provided by the user
DownloadPath string // Path/URL for downloading the song
Thumbnail Thumbnail // Thumbnail image for the song
Duration time.Duration // Duration of the song
SongID string // Unique ID for the song
Source string // Source type of the song
Title string // Title of the song
URL string // URL provided by the user
Filepath string // Path/URL for downloading the song
Thumbnail Thumbnail // Thumbnail image for the song
Duration time.Duration // Duration of the song
SongID string // Unique ID for the song
Source string // Source type of the song
}

type Thumbnail struct {
Expand Down Expand Up @@ -50,11 +50,11 @@ func (h *History) AddTrackToHistory(guildID string, song *Song) error {
existingTrack, err := db.GetTrackBySongID(song.SongID)
if err != nil {
newTrack := &db.Track{
SongID: song.SongID,
Title: song.Title,
HumanURL: song.HumanURL,
Source: song.Source,
DownloadPath: song.DownloadPath,
SongID: song.SongID,
Title: song.Title,
URL: song.URL,
Source: song.Source,
Filepath: song.Filepath,
}

if err := db.CreateTrack(newTrack); err != nil {
Expand All @@ -66,11 +66,11 @@ func (h *History) AddTrackToHistory(guildID string, song *Song) error {

if existingTrack == nil {
newTrack := &db.Track{
SongID: song.SongID,
Title: song.Title,
HumanURL: song.HumanURL,
Source: song.Source,
DownloadPath: song.DownloadPath,
SongID: song.SongID,
Title: song.Title,
URL: song.URL,
Source: song.Source,
Filepath: song.Filepath,
}
track = newTrack
} else {
Expand Down
18 changes: 9 additions & 9 deletions mod-music/player/play.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (p *Player) Play(startAt int, song *Song) error {
return fmt.Errorf("failed to create encode options: %w", err)
}

encoding, err := dca.EncodeFile(p.GetCurrentSong().DownloadPath, options)
encoding, err := dca.EncodeFile(p.GetCurrentSong().Filepath, options)
if err != nil {
return fmt.Errorf("failed to encode file: %w", err)
}
Expand Down Expand Up @@ -104,13 +104,13 @@ func (p *Player) Play(startAt int, song *Song) error {

// Add song to history
historySong := &history.Song{
Title: p.GetCurrentSong().Title,
HumanURL: p.GetCurrentSong().UserURL,
DownloadPath: p.GetCurrentSong().DownloadPath,
Duration: p.GetCurrentSong().Duration,
SongID: songID,
Thumbnail: history.Thumbnail(p.GetCurrentSong().Thumbnail),
Source: p.GetCurrentSong().Source.String(),
Title: p.GetCurrentSong().Title,
URL: p.GetCurrentSong().URL,
Filepath: p.GetCurrentSong().Filepath,
Duration: p.GetCurrentSong().Duration,
SongID: songID,
Thumbnail: history.Thumbnail(p.GetCurrentSong().Thumbnail),
Source: p.GetCurrentSong().Source.String(),
}
p.GetHistory().AddTrackToHistory(p.GetVoiceConnection().GuildID, historySong)

Expand Down Expand Up @@ -368,7 +368,7 @@ func (p *Player) calculateSongMetrics(encodingSession *dca.EncodeSession, stream
streamingPosition := streamingSession.PlaybackPosition()
delay := encodingDuration - streamingPosition

parsedURL, err := url.Parse(song.DownloadPath)
parsedURL, err := url.Parse(song.Filepath)
if err != nil {
return 0, 0, fmt.Errorf("failed to parse URL: %v", err)
}
Expand Down
14 changes: 7 additions & 7 deletions mod-music/player/player.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ type Player struct {
}

type Song struct {
Title string // Title of the song
UserURL string // URL provided by the user
DownloadPath string // Path/URL for downloading the song
Thumbnail Thumbnail // Thumbnail image for the song
Duration time.Duration // Duration of the song
ID string // Unique ID for the song
Source SongSource // Source type of the song
Title string // Title of the song
URL string // URL provided by the user
Filepath string // Path/URL for downloading the song
Thumbnail Thumbnail // Thumbnail image for the song
Duration time.Duration // Duration of the song
ID string // Unique ID for the song
Source SongSource // Source type of the song
}

type Thumbnail struct {
Expand Down
14 changes: 7 additions & 7 deletions mod-music/sources/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ func (s *Stream) FetchStreamsByURLs(urls []string) ([]*player.Song, error) {

if isValidStream(contentType) {
song = &player.Song{
Title: u.Host,
UserURL: u.String(),
DownloadPath: u.String(),
Thumbnail: player.Thumbnail{},
Duration: -1,
ID: fmt.Sprintf("%d", hash),
Source: player.SourceStream,
Title: u.Host,
URL: u.String(),
Filepath: u.String(),
Thumbnail: player.Thumbnail{},
Duration: -1,
ID: fmt.Sprintf("%d", hash),
Source: player.SourceStream,
}
songs = append(songs, song)
} else {
Expand Down
21 changes: 8 additions & 13 deletions mod-music/sources/youtube.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ func (y *Youtube) GetSongFromVideoURL(url string) (*player.Song, error) {
}

return &player.Song{
Title: song.Title,
UserURL: url,
DownloadPath: song.Formats.WithAudioChannels()[0].URL,
Duration: song.Duration,
Thumbnail: thumbnail,
ID: song.ID,
Source: player.SourceYouTube,
Title: song.Title,
URL: url,
Filepath: song.Formats.WithAudioChannels()[0].URL,
Duration: song.Duration,
Thumbnail: thumbnail,
ID: song.ID,
Source: player.SourceYouTube,
}, nil
}

Expand Down Expand Up @@ -173,7 +173,7 @@ func (y *Youtube) FetchSongsByIDs(guildID string, ids []int) ([]*player.Song, er
return nil, fmt.Errorf("error getting track from history with ID %v", id)
}

song, err := y.GetAllSongsFromURL(track.HumanURL)
song, err := y.GetAllSongsFromURL(track.URL)
if err != nil {
return nil, fmt.Errorf("error fetching new songs from URL: %v", err)
}
Expand Down Expand Up @@ -249,8 +249,3 @@ func (y *Youtube) FetchSongByURLs(url string) ([]*player.Song, error) {

return songs, nil
}

func (y *Youtube) IsYouTubeURL(url string) bool {
pattern := regexp.MustCompile(`^(https?://)?(www\.)?(youtube\.com|youtu\.be)/.*$`)
return pattern.MatchString(strings.ToLower(url))
}
6 changes: 6 additions & 0 deletions mod-music/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode"
Expand Down Expand Up @@ -257,3 +258,8 @@ func findUserVoiceState(userID string, voiceStates []*discordgo.VoiceState) (fou
}
return
}

func IsYouTubeURL(url string) bool {
pattern := regexp.MustCompile(`^(https?://)?(www\.)?(youtube\.com|youtu\.be)/.*$`)
return pattern.MatchString(strings.ToLower(url))
}

0 comments on commit 0e57c38

Please sign in to comment.