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