Skip to content

Commit

Permalink
Fix a lot of error handling issues and other code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
BharatKalluri authored Nov 23, 2019
2 parents 602dfce + a4f8614 commit 8177de3
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 23 deletions.
33 changes: 28 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"fmt"
"os"
"strings"

spotifydl "github.com/BharatKalluri/spotifydl/src"
"github.com/spf13/cobra"
Expand All @@ -11,17 +12,38 @@ import (
func main() {
var playlistid string
var albumid string
var spotifyURL string

var rootCmd = &cobra.Command{
Use: "spotifydl",
Short: "spotifydl is a awesome music downloader",
Long: `Spotifydl lets you download albums and playlists and tags them for you
Long: `Spotifydl lets you download albums and playlists and tags them for you.
Pass Either album ID or Playlist ID to start downloading`,
Run: func(cmd *cobra.Command, args []string) {
if len(playlistid) > 0 && len(albumid) > 0 {
fmt.Println("Either album ID or playlist ID")
cmd.Help()
} else if len(albumid) > 0 {

if len(spotifyURL) > 0 {
splitURL := strings.Split(spotifyURL, "/")

if len(splitURL) < 2 {
fmt.Println("Please enter the url copied from the spotify client")
os.Exit(1)
}

spotifyID := splitURL[len(splitURL)-1]
if strings.Contains(spotifyID, "?") {
fmt.Println("Please remove the part of the url after the question mark (?) and try again")
fmt.Println("For example, https://open.spotify.com/playlist/randomID?si=otherRandomID should just be https://open.spotify.com/playlist/randomID ")
os.Exit(1)
}

if strings.Contains(spotifyURL, "album") {
albumid = spotifyID
} else if strings.Contains(spotifyURL, "playlist") {
playlistid = spotifyID
}
}

if len(albumid) > 0 {
// Download album with the given album ID
spotifydl.DownloadAlbum(albumid)
} else if len(playlistid) > 0 {
Expand All @@ -36,6 +58,7 @@ Pass Either album ID or Playlist ID to start downloading`,

rootCmd.Flags().StringVarP(&playlistid, "playlistid", "p", "", "Album ID found on spotify")
rootCmd.Flags().StringVarP(&albumid, "albumid", "a", "", "Album ID found on spotify")
rootCmd.Flags().StringVarP(&spotifyURL, "spotifyurl", "u", "", "URL copied on spotify")

if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
Expand Down
6 changes: 5 additions & 1 deletion src/downloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package spotifydl

import (
"fmt"
"os"
"os/exec"

"github.com/zmb3/spotify"
Expand All @@ -17,7 +18,10 @@ func Downloader(url string, track spotify.FullTrack) {
"-o", track.Name+".%(ext)s", "--audio-quality", "0", url)
_, err := ytdlCmd.Output()
if err != nil {
panic(err)
fmt.Println("=> An error occured while trying to download using youtube-dl")
fmt.Println("Make sure you have youtube-dl and ffmpeg installed on this system. This was the command we tried to run:")
fmt.Println(ytdlCmd.String())
os.Exit(1)
}

// Tag the file with metadata
Expand Down
15 changes: 11 additions & 4 deletions src/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package spotifydl

import (
"fmt"
"os"

"github.com/zmb3/spotify"
)
Expand All @@ -13,8 +14,11 @@ func DownloadPlaylist(pid string) {
UserClient: user,
}
playlistID := spotify.ID(pid)
// TODO: Exit gracefully if the playlist is not found
trackListJSON, _ := cli.UserClient.GetPlaylistTracks(playlistID)
trackListJSON, err := cli.UserClient.GetPlaylistTracks(playlistID)
if err != nil {
fmt.Println("Playlist not found!")
os.Exit(1)
}
for _, val := range trackListJSON.Tracks {
cli.TrackList = append(cli.TrackList, val.Track)
}
Expand All @@ -28,8 +32,11 @@ func DownloadAlbum(aid string) {
UserClient: user,
}
albumid := spotify.ID(aid)
// TODO: Exit gracefully if album is not found
album, _ := user.GetAlbum(albumid)
album, err := user.GetAlbum(albumid)
if err != nil {
fmt.Println("Album not found!")
os.Exit(1)
}
for _, val := range album.Tracks.Tracks {
cli.TrackList = append(cli.TrackList, spotify.FullTrack{
SimpleTrack: val,
Expand Down
11 changes: 8 additions & 3 deletions src/utils/generic_utils.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
package utils

import (
"fmt"
"io/ioutil"
"net/http"
)

// DownloadFile will get a url and return bytes
func DownloadFile(url string) []byte {
func DownloadFile(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
buffer, _ := ioutil.ReadAll(resp.Body)
return buffer
buffer, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to download album art!")
return nil, err
}
return buffer, nil
}
25 changes: 15 additions & 10 deletions src/utils/tagger.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ func TagFileWithSpotifyMetadata(fileName string, trackData spotify.FullTrack) {
artistTag := strings.Join(trackArtist[:], ",")
dateObject, _ := time.Parse("2006-01-02", trackData.Album.ReleaseDate)
yearTag := dateObject.Year()
// TODO: Check images is not null
albumArtURL := trackData.Album.Images[0].URL
albumArt := DownloadFile(albumArtURL)
albumArtImages := trackData.Album.Images

mp3File, err := id3v2.Open(fileName, id3v2.Options{Parse: true})
if err != nil {
Expand All @@ -35,14 +33,21 @@ func TagFileWithSpotifyMetadata(fileName string, trackData spotify.FullTrack) {
mp3File.SetArtist(artistTag)
mp3File.SetAlbum(albumTag)
mp3File.SetYear(strconv.Itoa(yearTag))
pic := id3v2.PictureFrame{
Encoding: id3v2.EncodingUTF8,
MimeType: "image/jpeg",
PictureType: id3v2.PTFrontCover,
Description: "Front cover",
Picture: albumArt,

if len(albumArtImages) > 0 {
albumArtURL := albumArtImages[0].URL
albumArt, albumArtDownloadErr := DownloadFile(albumArtURL)
if albumArtDownloadErr != nil {
pic := id3v2.PictureFrame{
Encoding: id3v2.EncodingUTF8,
MimeType: "image/jpeg",
PictureType: id3v2.PTFrontCover,
Description: "Front cover",
Picture: albumArt,
}
mp3File.AddAttachedPicture(pic)
}
}
mp3File.AddAttachedPicture(pic)

if err = mp3File.Save(); err != nil {
log.Fatal("Error while saving a tag: ", err)
Expand Down

0 comments on commit 8177de3

Please sign in to comment.