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

Commit

Permalink
fixing db (id)
Browse files Browse the repository at this point in the history
  • Loading branch information
keshon committed Apr 11, 2024
1 parent 0e57c38 commit 95905a9
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 30 deletions.
16 changes: 16 additions & 0 deletions internal/db/track.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,19 @@ func GetAllTracks() ([]Track, error) {
}
return tracks, nil
}

func GetTrackByFilepath(filepath string) (*Track, error) {
var track Track
if err := DB.Where("filepath = ?", filepath).First(&track).Error; err != nil {
return nil, err
}
return &track, nil
}

func GetTrackByURL(url string) (*Track, error) {
var track Track
if err := DB.Where("url = ?", url).First(&track).Error; err != nil {
return nil, err
}
return &track, nil
}
37 changes: 27 additions & 10 deletions mod-music/discord/curl.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import (

"github.com/bwmarrin/discordgo"
"github.com/gookit/slog"
"github.com/keshon/melodix-player/internal/db"
"github.com/keshon/melodix-player/mod-music/player"
"github.com/keshon/melodix-player/mod-music/sources"
"github.com/keshon/melodix-player/mod-music/utils"
)

const (
Expand All @@ -29,22 +30,13 @@ 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
Expand Down Expand Up @@ -90,6 +82,31 @@ func (d *Discord) handleCacheUrlCommand(s *discordgo.Session, m *discordgo.Messa
slog.Error("Error removing temporary video file:", err)
}

// Check if cached file exists in database
existingTrack, err := db.GetTrackBySongID(song.SongID)
if err == nil {
existingTrack.Filepath = audioFilePath
existingTrack.Source = player.SourceLocalFile.String()
err := db.UpdateTrack(existingTrack)
if err != nil {
slog.Error("Error updating track in database:", err)
return
}
} else {
newTrack := &db.Track{
SongID: song.SongID,
Title: song.Title,
URL: song.URL,
Source: player.SourceLocalFile.String(),
Filepath: audioFilePath,
}
err = db.CreateTrack(newTrack)
if err != nil {
slog.Error("Error creating track in database:", err)
return
}
}

// Get the audio file size and format
audioFileInfo, err := os.Stat(audioFilePath)
if err != nil {
Expand Down
46 changes: 36 additions & 10 deletions mod-music/discord/play.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import (
"fmt"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"

embed "github.com/Clinet/discordgo-embed"
"github.com/bwmarrin/discordgo"
"github.com/gookit/slog"
"github.com/keshon/melodix-player/internal/db"
"github.com/keshon/melodix-player/internal/version"
"github.com/keshon/melodix-player/mod-music/history"
"github.com/keshon/melodix-player/mod-music/player"
Expand Down Expand Up @@ -124,34 +126,51 @@ func getSongsFromSources(originType string, songsOrigins []string, guildID strin

switch originType {
case "local_file":
slog.Error(originType)
songPath := "cache/" + guildID + "/" + songOrigin
slog.Info("Local file: ", songOrigin)

songPath := filepath.Join("cache", guildID, songOrigin)

if _, err := os.Stat(songPath); os.IsNotExist(err) {
slog.Error("No such file or directory: %v", err)
continue
}

song := player.Song{
Title: songOrigin,
Filepath: songPath,
Source: player.SourceLocalFile,
var song *player.Song
existingTrack, err := db.GetTrackByFilepath(songPath)
if err == nil {
song = &player.Song{
SongID: existingTrack.SongID,
Title: existingTrack.Title,
Filepath: existingTrack.Filepath,
}
} else {
song = &player.Song{
Title: songOrigin,
Filepath: songPath,
}
}

songs = append(songs, &song)
song.Source = player.SourceLocalFile

songs = append(songs, song)
case "history_id":
slog.Info("History ID: ", songOrigin)

id, err := strconv.Atoi(songOrigin)
if err != nil {
slog.Error("Cannot convert string id to int id")
continue
}
h := history.NewHistory()
track, err := h.GetTrackFromHistory(guildID, uint(id))
slog.Error(track)
if err != nil {
slog.Error("Error getting track from history with ID %v", id)
continue
}

var song []*player.Song

if track.Source == "YouTube" {
slog.Info("Track is from YouTube")
song, err = youtube.GetAllSongsFromURL(track.URL)
Expand All @@ -172,25 +191,32 @@ func getSongsFromSources(originType string, songsOrigins []string, guildID strin
slog.Info("Track is from LocalFile")
song = []*player.Song{{
Title: track.Title,
URL: track.URL,
Filepath: track.Filepath,
Source: player.SourceLocalFile,
}}
}

songs = append(songs, song...)
case "youtube_title":
slog.Info("Youtube title: ", songOrigin)

songs, err = youtube.FetchSongsByTitle(songOrigin)
if err != nil {
slog.Warnf("Error fetching songs by title: %v", err)
continue
}
case "youtube_url":
slog.Info("Youtube URL: ", songOrigin)

songs, err = youtube.FetchSongsByURLs([]string{songOrigin})
if err != nil {
slog.Warnf("Error fetching songs by URL: %v", err)
continue
}
case "stream_url":
slog.Info("Stream URL: ", songOrigin)

songs, err = stream.FetchStreamsByURLs([]string{songOrigin})
if err != nil {
slog.Warnf("Error fetching stream by URL: %v", err)
Expand Down Expand Up @@ -292,10 +318,10 @@ func showStatusMessage(d *Discord, s *discordgo.Session, channelID, prevMessageI

// Display current song information
if currentSong := d.Player.GetCurrentSong(); currentSong != nil {
if currentSong.URL != "" {
content += fmt.Sprintf("\n*[%v](%v)*\n\n", currentSong.Title, currentSong.URL)
if len(currentSong.URL) > 0 {
content += fmt.Sprintf("\n**`%v`**\n[%v](%v)\n\n", strings.ToLower(currentSong.Source.String()), currentSong.Title, currentSong.URL)
} else {
content += fmt.Sprintf("\n%v\n\n", currentSong.Title)
content += fmt.Sprintf("\n**`%v`**\n%v\n\n", strings.ToLower(currentSong.Source.String()), currentSong.Title)
}
embedMsg.SetThumbnail(currentSong.Thumbnail.URL)
} else {
Expand Down
9 changes: 6 additions & 3 deletions mod-music/player/play.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,12 @@ func (p *Player) Play(startAt int, song *Song) error {
p.SetCurrentStatus(StatusPlaying)

// Create song ID
songID := GetMD5Hash(p.GetCurrentSong().Title)
if p.GetCurrentSong().ID != "" {
songID = p.GetCurrentSong().ID
var songID string
slog.Fatal(p.GetCurrentSong().SongID)
if len(p.GetCurrentSong().SongID) > 0 {
songID = p.GetCurrentSong().SongID
} else {
songID = GetMD5Hash(p.GetCurrentSong().Title)
}

// Add song to history
Expand Down
2 changes: 1 addition & 1 deletion mod-music/player/player.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ type Song struct {
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
SongID string // Unique ID for the song
Source SongSource // Source type of the song
}

Expand Down
4 changes: 2 additions & 2 deletions mod-music/player/skip.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ func (p *Player) Skip() error {

if len(p.GetSongQueue()) == 0 {
slog.Warn("is actually stopping...")
h.AddPlaybackCountStats(p.GetVoiceConnection().GuildID, p.GetCurrentSong().ID)
h.AddPlaybackCountStats(p.GetVoiceConnection().GuildID, p.GetCurrentSong().SongID)
p.Stop()
} else {
if len(p.SkipInterrupt) == 0 {
slog.Warn("is actually skipping to", p.GetSongQueue()[0].Title)
h.AddPlaybackCountStats(p.GetVoiceConnection().GuildID, p.GetCurrentSong().ID)
h.AddPlaybackCountStats(p.GetVoiceConnection().GuildID, p.GetCurrentSong().SongID)
p.SkipInterrupt <- true
time.Sleep(250 * time.Millisecond)
p.Play(0, nil)
Expand Down
2 changes: 1 addition & 1 deletion mod-music/sources/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func (s *Stream) FetchStreamsByURLs(urls []string) ([]*player.Song, error) {
Filepath: u.String(),
Thumbnail: player.Thumbnail{},
Duration: -1,
ID: fmt.Sprintf("%d", hash),
SongID: fmt.Sprintf("%d", hash),
Source: player.SourceStream,
}
songs = append(songs, song)
Expand Down
6 changes: 3 additions & 3 deletions mod-music/sources/youtube.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (y *Youtube) GetSongFromVideoURL(url string) (*player.Song, error) {
Filepath: song.Formats.WithAudioChannels()[0].URL,
Duration: song.Duration,
Thumbnail: thumbnail,
ID: song.ID,
SongID: song.ID,
Source: player.SourceYouTube,
}, nil
}
Expand Down Expand Up @@ -95,8 +95,8 @@ func (y *Youtube) GetAllSongsFromURL(url string) ([]*player.Song, error) {
// Sort the songs based on the order of playlistVideos.Videos
sort.SliceStable(songs, func(i, j int) bool {
// Get the index of each song's video ID in the playlist
indexI := videoIndex[songs[i].ID]
indexJ := videoIndex[songs[j].ID]
indexI := videoIndex[songs[i].SongID]
indexJ := videoIndex[songs[j].SongID]

// Compare the indices to determine the order
return indexI < indexJ
Expand Down

0 comments on commit 95905a9

Please sign in to comment.