-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
130 lines (103 loc) · 3.48 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
import (
_ "github.com/joho/godotenv/autoload"
"github.com/oliverbenns/spotification/browser"
"github.com/oliverbenns/spotification/musiclib"
"github.com/zmb3/spotify"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
)
var redirectUrl = "http://localhost:3000/callback"
var state = ""
type App struct {
Auth spotify.Authenticator
Client spotify.Client
MusicLibPath string
Playlist *spotify.FullPlaylist
RemoteTrackIds []spotify.ID
Tracks []musiclib.Track
}
func main() {
relativePath := os.Args[1]
path, _ := filepath.Abs(relativePath)
app := App{
Auth: spotify.NewAuthenticator(redirectUrl, spotify.ScopeUserLibraryModify, spotify.ScopeUserLibraryRead, spotify.ScopePlaylistModifyPrivate),
MusicLibPath: path,
}
url := app.Auth.AuthURL(state)
browser.Open(url)
mux := http.NewServeMux()
mux.HandleFunc("/callback", app.CallbackHandler)
err := http.ListenAndServe("localhost:3000", mux)
if err != nil {
panic(err)
}
}
func (app *App) CallbackHandler(w http.ResponseWriter, r *http.Request) {
token, err := app.Auth.Token(state, r)
if err != nil {
log.Print(err)
http.Error(w, "Couldn't get token", http.StatusNotFound)
return
}
app.Client = app.Auth.NewClient(token)
app.Client.AutoRetry = true
musiclib.GetTracks(app.MusicLibPath, &app.Tracks)
app.CreateSpotifyPlaylist()
app.FindSpotifyTracks()
app.AddSpotifyTracks()
log.Print("Total mp3 tracks: " + strconv.Itoa(len(app.Tracks)))
log.Print("Added Spotify tracks: " + strconv.Itoa(len(app.RemoteTrackIds)))
}
func (app *App) CreateSpotifyPlaylist() {
user, _ := app.Client.CurrentUser()
playlistName := "Spotification " + time.Now().Format(time.RFC3339)
app.Playlist, _ = app.Client.CreatePlaylistForUser(user.ID, playlistName, "Playlist created by https://github.com/oliverbenns/spotification", false)
}
func (app *App) FindSpotifyTracks() {
for _, track := range app.Tracks {
// @NOTE: Flags like "artist:" don't work unless the artist is the _exact_ name.
query := StripSpecialCharacters(track.Name + " " + track.Artist)
searchResult, err := app.Client.Search(query, spotify.SearchTypeTrack)
if err != nil {
log.Print(err)
}
trackPrettyPrint := track.Artist + " - " + track.Name
if len(searchResult.Tracks.Tracks) == 0 {
log.Println("❌ " + trackPrettyPrint)
} else {
log.Println("✅ " + trackPrettyPrint)
app.RemoteTrackIds = append(app.RemoteTrackIds, searchResult.Tracks.Tracks[0].ID)
}
}
}
// @NOTE: Add the tracks in bulk to reduce # of queries which helps reduce api rate limit hits.
func (app *App) AddSpotifyTracks() {
totalCount := len(app.RemoteTrackIds)
index := 0
for index < totalCount {
var increment int
if totalCount-index >= 100 {
increment = 100
} else {
increment = totalCount % 100
}
ids := app.RemoteTrackIds[index : index+increment]
_, err := app.Client.AddTracksToPlaylist(app.Playlist.ID, ids...)
if err != nil {
log.Panic("Error adding ids to playlist", err)
}
index += increment
}
}
// @NOTE: The Spotify API does not respect special characters even though they are correct! E.g. Tomáš Dvořák does not work, but Tomas Dvorak does!
// It also seems Spotify try to remove some special characters wherever possible, e.g. `Will Sparks - Ah Yeah!` is actually correct, but Spotify catalogues it without the exclamation.
func StripSpecialCharacters(value string) string {
reg, _ := regexp.Compile("[^a-zA-Z0-9 -.]+")
return reg.ReplaceAllString(value, "")
}