Commit | Line | Data |
---|---|---|
2400eea4 JC |
1 | package artist |
2 | ||
3 | import ( | |
4 | "git.jacobcasper.com/brackets/env" | |
5 | "git.jacobcasper.com/brackets/routes" | |
6 | "github.com/zmb3/spotify" | |
7 | "log" | |
8 | "net/http" | |
9 | ) | |
10 | ||
11 | func Add(env *env.Env) routes.Handler { | |
12 | return func(w http.ResponseWriter, r *http.Request) { | |
13 | if r.Method != "POST" { | |
14 | http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) | |
15 | return | |
16 | } | |
17 | ||
18 | r.ParseForm() | |
19 | artistId := r.PostForm.Get("id") | |
20 | ||
21 | if artistId == "" { | |
22 | http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) | |
23 | return | |
24 | } | |
25 | ||
26 | artist, err := env.C.GetArtist(spotify.ID(artistId)) | |
27 | if err != nil { | |
28 | log.Printf("Failed to retrieve artist %s: %s", artistId, err.Error()) | |
29 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
30 | return | |
31 | } | |
32 | ||
33 | env.Db.Mu.Lock() | |
34 | defer env.Db.Mu.Unlock() | |
35 | env.Db.Db.Exec("INSERT INTO ARTIST (ID, NAME) VALUES (?, ?)", artist.ID, artist.Name) | |
36 | ||
37 | for _, genre := range artist.Genres { | |
38 | result, err := env.Db.Db.Exec("REPLACE INTO GENRE (NAME) VALUES (?)", genre) | |
39 | if err != nil { | |
40 | log.Printf("Failed to insert genre %s: %s", genre, err.Error()) | |
41 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
42 | return | |
43 | } | |
44 | ||
45 | genreId, err := result.LastInsertId() | |
46 | if err != nil { | |
47 | log.Print("Failed to retrieve last insert id: ", err.Error()) | |
48 | http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | |
49 | return | |
50 | } | |
51 | ||
52 | env.Db.Db.Exec("INSERT INTO ARTIST_GENRE_XREF (ARTIST_ID, GENRE_ID) VALUES (?, ?)", artist.ID, genreId) | |
53 | } | |
54 | w.WriteHeader(http.StatusCreated) | |
55 | } | |
56 | } |