Skip to content

Commit

Permalink
Issue a new auth token
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiofalci committed Apr 26, 2018
1 parent 71dfd91 commit 6cd23b3
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 16 deletions.
29 changes: 19 additions & 10 deletions sconsify.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"runtime"
"strconv"
"github.com/fabiofalci/sconsify/ui"
"github.com/fabiofalci/sconsify/webapi"
)

var version string
Expand Down Expand Up @@ -46,6 +47,7 @@ func main() {
providedNoUiRepeatOn := flag.Bool("noui-repeat-on", true, "Play your playlist and repeat it after the last track.")
providedNoUiShuffle := flag.Bool("noui-shuffle", true, "Shuffle tracks or follow playlist order.")
providedWebApiCacheToken := flag.Bool("web-api-cache-token", true, "Cache the web-api token as plain text in ~/.sconsify until its expiration.")
providedIssueWebApiToken := flag.Bool("issue-web-api-token", false, "Issue a new web-api token.")
providedWebApiCacheContent := flag.Bool("web-api-cache-content", true, "Cache some of the web-api content as plain text in ~/.sconsify.")
providedDebug := flag.Bool("debug", false, "Enable debug mode.")
askingVersion := flag.Bool("version", false, "Print version.")
Expand Down Expand Up @@ -74,6 +76,23 @@ func main() {
}

fmt.Println("Sconsify - your awesome Spotify music service in a text-mode interface.")

initConf := &spotify.SpotifyInitConf{
WebApiAuth: *providedWebApi,
PlaylistFilter: *providedPlaylists,
PreferredBitrate: *providedPreferredBitrate,
CacheWebApiToken: *providedWebApiCacheToken,
CacheWebApiContent: *providedWebApiCacheContent,
SpotifyClientId: spotifyClientId,
AuthRedirectUrl: authRedirectUrl,
OpenBrowserCommand: *providedOpenBrowser,
}

if *providedIssueWebApiToken {
webapi.Auth(initConf.SpotifyClientId, initConf.AuthRedirectUrl, initConf.CacheWebApiToken, initConf.OpenBrowserCommand)
return
}

username, pass := credentials(providedUsername)
events := sconsify.InitialiseEvents()
publisher := &sconsify.Publisher{}
Expand All @@ -86,16 +105,6 @@ func main() {
go ui.ToStatusFile(*providedStatusFile, statusFileTemplate)
}

initConf := &spotify.SpotifyInitConf{
WebApiAuth: *providedWebApi,
PlaylistFilter: *providedPlaylists,
PreferredBitrate: *providedPreferredBitrate,
CacheWebApiToken: *providedWebApiCacheToken,
CacheWebApiContent: *providedWebApiCacheContent,
SpotifyClientId: spotifyClientId,
AuthRedirectUrl: authRedirectUrl,
OpenBrowserCommand: *providedOpenBrowser,
}
go spotify.Initialise(initConf, username, pass, events, publisher)

if *providedServer {
Expand Down
15 changes: 15 additions & 0 deletions sconsify/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Events struct {
trackPaused chan *Track

newTrackLoaded chan time.Duration
tokenExpired chan bool
}

var (
Expand Down Expand Up @@ -61,6 +62,7 @@ func InitialiseEvents() *Events {
trackPaused: make(chan *Track),

newTrackLoaded: make(chan time.Duration, 2),
tokenExpired: make(chan bool),
}

subscribers = append(subscribers, events)
Expand Down Expand Up @@ -229,3 +231,16 @@ func (publisher *Publisher) NewTrackLoaded(duration time.Duration) {
func (events *Events) NewTrackLoadedUpdate() <-chan time.Duration {
return events.newTrackLoaded
}

func (publisher *Publisher) TokenExpired() {
for _, subscriber := range subscribers {
select {
case subscriber.tokenExpired <- true:
default:
}
}
}

func (events *Events) TokenExpiredUpdates() <-chan bool {
return events.tokenExpired
}
2 changes: 2 additions & 0 deletions sconsify/mainloop.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ func StartMainLoop(events *Events, publisher *Publisher, ui UserInterface, askFo
return nil
case duration := <-events.NewTrackLoadedUpdate():
ui.NewTrackLoaded(duration)
case <-events.TokenExpiredUpdates():
ui.TokenExpired()
}
}

Expand Down
1 change: 1 addition & 0 deletions sconsify/ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ type UserInterface interface {
ArtistAlbums(folder *Playlist)
Shutdown()
NewTrackLoaded(duration time.Duration)
TokenExpired()
}
13 changes: 12 additions & 1 deletion spotify/spotify_actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
webspotify "github.com/zmb3/spotify"
"strings"
"time"
"github.com/fabiofalci/sconsify/webapi"
)

func (spotify *Spotify) shutdownSpotify() {
Expand Down Expand Up @@ -73,7 +74,17 @@ func (spotify *Spotify) search(query string) {

playlist := sconsify.InitSearchPlaylist(name, name, func(playlist *sconsify.Playlist) {
options := createWebSpotifyOptions(50, playlist.Tracks())
// search is an auth endpoint now, when the token expires, it won't work

if webapi.HasTokenExpired() {
webapi.LoadTokenFromFile()
if webapi.HasTokenExpired() {
spotify.publisher.TokenExpired()
} else {
client := webapi.NewClient()
spotify.client = &client
}
}

if searchResult, err := spotify.client.SearchOpt(query, webspotify.SearchTypeTrack, options); err == nil {
numberOfTracks := len(searchResult.Tracks.Tracks)
infrastructure.Debugf("Search '%v' returned %v track(s)", query, numberOfTracks)
Expand Down
4 changes: 4 additions & 0 deletions ui/noui/noui.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ func (noui *NoUi) NewTrackLoaded(duration time.Duration) {

}

func (noui *NoUi) TokenExpired() {

}

func (p *SilentPrinter) Print(message string) {
}

Expand Down
7 changes: 7 additions & 0 deletions ui/simple/cui.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ func (cui *ConsoleUserInterface) NewTrackLoaded(duration time.Duration) {
}
}

func (cui *ConsoleUserInterface) TokenExpired() {
gui.g.Update(func(g *gocui.Gui) error {
gui.flash("Token has expired. To issue a new one: sconsify -issue-web-api-token")
return nil
})
}

func (gui *Gui) countdown() {

var timeLeft time.Duration
Expand Down
1 change: 1 addition & 0 deletions ui/status_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ func ToStatusFile(file string, text string) {
case <-toFileEvents.PlaylistsUpdates():
case <-toFileEvents.ArtistAlbumsUpdates():
case <-toFileEvents.NewTrackLoadedUpdate():
case <-toFileEvents.TokenExpiredUpdates():
case <-toFileEvents.ShutdownSpotifyUpdates():
case <-toFileEvents.SearchUpdates():
case <-toFileEvents.PlayUpdates():
Expand Down
28 changes: 23 additions & 5 deletions webapi/web_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,26 @@ import (
"os/exec"
)


var token *oauth2.Token
var auth spotify.Authenticator

func Auth(spotifyClientId string, authRedirectUrl string, cacheWebApiToken bool, openBrowserCommand string) (*spotify.Client, error) {
if spotifyClientId == "" {
fmt.Print("Spotify Client ID not set")
return nil, nil
}

auth := spotify.NewAuthenticator(authRedirectUrl,
auth = spotify.NewAuthenticator(authRedirectUrl,
spotify.ScopeUserLibraryRead,
spotify.ScopeUserFollowRead,
spotify.ScopePlaylistReadCollaborative,
spotify.ScopePlaylistReadPrivate)

auth.SetAuthInfo(spotifyClientId, "")

token := loadToken()
if token == nil || hasExpired(token.Expiry) {
LoadTokenFromFile()
if token == nil || HasTokenExpired() {
url := auth.AuthURL("")
url = strings.Replace(url, "response_type=code", "response_type=token", -1)

Expand Down Expand Up @@ -65,17 +69,31 @@ func Auth(spotifyClientId string, authRedirectUrl string, cacheWebApiToken bool,
if cacheWebApiToken {
persistToken(token)
}
} else {
fmt.Println("Token still valid")
}

client := auth.NewClient(token)
client := NewClient()
return &client, nil
}

func NewClient() spotify.Client {
return auth.NewClient(token)
}

func HasTokenExpired() bool {
return hasExpired(token.Expiry)
}

func hasExpired(expiry time.Time) bool {
return expiry.Before(time.Now())
}

func loadToken() *oauth2.Token {
func LoadTokenFromFile() {
token = loadTokenFromFile()
}

func loadTokenFromFile() *oauth2.Token {
if fileLocation := infrastructure.GetWebApiTokenLocation(); fileLocation != "" {
if b, err := ioutil.ReadFile(fileLocation); err == nil {
var token *oauth2.Token
Expand Down

0 comments on commit 6cd23b3

Please sign in to comment.