| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "git.jacobcasper.com/brackets/env" |
| 5 | _ "github.com/mattn/go-sqlite3" |
| 6 | "github.com/zmb3/spotify" |
| 7 | "log" |
| 8 | "net/http" |
| 9 | ) |
| 10 | |
| 11 | type handler func(http.ResponseWriter, *http.Request) |
| 12 | |
| 13 | func main() { |
| 14 | env, err := env.New() |
| 15 | if err != nil { |
| 16 | log.Fatal("Could not set up Env: ", err.Error()) |
| 17 | } |
| 18 | |
| 19 | http.HandleFunc( |
| 20 | "/artist/add", |
| 21 | artistAddHandler(env), |
| 22 | ) |
| 23 | |
| 24 | log.Fatal(http.ListenAndServe(":8080", nil)) |
| 25 | } |
| 26 | |
| 27 | func artistAddHandler(env *env.Env) handler { |
| 28 | return func(w http.ResponseWriter, r *http.Request) { |
| 29 | if r.Method != "POST" { |
| 30 | http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) |
| 31 | return |
| 32 | } |
| 33 | |
| 34 | r.ParseForm() |
| 35 | artistId := r.PostForm.Get("id") |
| 36 | |
| 37 | if artistId == "" { |
| 38 | http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) |
| 39 | return |
| 40 | } |
| 41 | |
| 42 | artist, err := env.C.GetArtist(spotify.ID(artistId)) |
| 43 | if err != nil { |
| 44 | log.Printf("Failed to retrieve artist %s: %s", artistId, err.Error()) |
| 45 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 46 | return |
| 47 | } |
| 48 | |
| 49 | env.Db.Mu.Lock() |
| 50 | defer env.Db.Mu.Unlock() |
| 51 | env.Db.Db.Exec("INSERT INTO ARTIST (ID, NAME) VALUES (?, ?)", artist.ID, artist.Name) |
| 52 | |
| 53 | for _, genre := range artist.Genres { |
| 54 | result, err := env.Db.Db.Exec("REPLACE INTO GENRE (NAME) VALUES (?)", genre) |
| 55 | if err != nil { |
| 56 | log.Printf("Failed to insert genre %s: %s", genre, err.Error()) |
| 57 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | genreId, err := result.LastInsertId() |
| 62 | if err != nil { |
| 63 | log.Print("Failed to retrieve last insert id: ", err.Error()) |
| 64 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| 65 | return |
| 66 | } |
| 67 | |
| 68 | env.Db.Db.Exec("INSERT INTO ARTIST_GENRE_XREF (ARTIST_ID, GENRE_ID) VALUES (?, ?)", artist.ID, genreId) |
| 69 | } |
| 70 | w.WriteHeader(http.StatusCreated) |
| 71 | } |
| 72 | } |