From a2ef5d3b79d4b1ffe0b7159da0b50aa05e8c2da3 Mon Sep 17 00:00:00 2001
From: rick <rick@gnous.eu>
Date: Sat, 4 Sep 2021 19:05:09 +0200
Subject: [PATCH] update(spotify): get token to use API

---
 server.go         | 13 +++++++++----
 static/gethash.js | 13 +++++++++++++
 struct.go         |  6 ++++++
 3 files changed, 28 insertions(+), 4 deletions(-)
 create mode 100644 static/gethash.js

diff --git a/server.go b/server.go
index c32e9a2..55a8527 100644
--- a/server.go
+++ b/server.go
@@ -14,6 +14,7 @@ import (
 
 var MyClient = &http.Client{}
 var MyResp = &RespBandcamp{}
+var SpotifyAPI = &TokenUser{}
 
 func loginSpotify(w http.ResponseWriter, r *http.Request) {
     if err := r.ParseForm(); err != nil {
@@ -71,7 +72,7 @@ func getAllTracksPlaylist(id string, offset int) (SpotifyPlaylist, error) {
     }
     req.Header.Add("Accept", "application/json")
     req.Header.Add("Content-Type", "application/json")
-    req.Header.Add("Authorization", SpotifyAPI)
+    req.Header.Add("Authorization", SpotifyAPI.TokenType + " " + SpotifyAPI.Token)
     res, err := MyClient.Do(req)
 
     if err != nil {
@@ -226,8 +227,12 @@ func getNew(w http.ResponseWriter, r *http.Request) {
     MyResp.Notfound = nil
 }
 
-func mytest(w http.ResponseWriter, r *http.Request) {
-    fmt.Fprintf(w, r.RequestURI)
+func mytoken(w http.ResponseWriter, r *http.Request) {
+    defer r.Body.Close()
+    err := json.NewDecoder(r.Body).Decode(&SpotifyAPI)
+    if err != nil {
+        fmt.Printf("error:", err)
+    }
 }
 
 func main() {
@@ -237,7 +242,7 @@ func main() {
     http.HandleFunc("/back", formHandler)
     http.HandleFunc("/refresh", getNew)
     http.HandleFunc("/spotify", loginSpotify)
-    http.HandleFunc("/mytest", mytest)
+    http.HandleFunc("/mytoken", mytoken)
 
     fmt.Printf("Starting the server…\n")
     if err := http.ListenAndServe(":8080", nil); err != nil {
diff --git a/static/gethash.js b/static/gethash.js
new file mode 100644
index 0000000..62fa7a0
--- /dev/null
+++ b/static/gethash.js
@@ -0,0 +1,13 @@
+const hash = window.location.hash.substring(1).split('&')
+var datas = {}
+for (let elem of hash) {
+  elem = elem.split('=')
+  datas[elem[0]] = elem[1]
+}
+fetch('/mytoken', {
+  method: 'POST',
+  headers: {
+    'Content-Type': 'application/json'
+  },
+  body: JSON.stringify(datas)
+}).then(() => {window.location.replace("/")})
diff --git a/struct.go b/struct.go
index 91edb10..248b004 100644
--- a/struct.go
+++ b/struct.go
@@ -2,6 +2,12 @@ package main
 
 import "time"
 
+type TokenUser struct {
+    Token string `json:"access_token"`
+    TokenType string `json:"token_type"`
+    ExpiresIn string `json:"expires_in"`
+}
+
 type BandcampAlbum struct {
     find bool
     url string