/
apiShows.go
81 lines (66 loc) · 2.47 KB
/
apiShows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
. "github.com/42minutes/42minutes-server-api/models"
"github.com/codegangsta/martini-contrib/encoder"
_ "github.com/garfunkel/go-tvdb"
"github.com/go-martini/martini"
)
func ApiShowsGetAll(r *http.Request, enc encoder.Encoder, store Store, user User) (int, []byte) {
db := GetDbSession()
var shows []*Show
if r.URL.Query().Get("name") == "" {
_, err := db.Select(&shows, "SELECT shows.* FROM shows LEFT JOIN users_shows ON shows.id = users_shows.show_id WHERE users_shows.user_id = ? AND (users_shows.favorite = true OR users_shows.library = true) ORDER BY shows.title asc", user.ID)
if err != nil {
return http.StatusNotFound, encoder.Must(enc.Encode(NewError(ErrCodeNotExist, fmt.Sprintf("TODO error"))))
}
} else {
name := r.URL.Query().Get("name")
fmt.Println("Looking for show...", name)
shows, _ = ShowFindAllByName(name, 5)
if len(shows) == 0 {
return http.StatusNotFound, encoder.Must(enc.Encode(NewError(ErrCodeNotExist, fmt.Sprintf("could not find Show with name '%s'", name))))
}
}
for show_i, _ := range shows {
shows[show_i].Personalize(user.ID)
}
return http.StatusOK, encoder.Must(enc.Encode(shows))
}
func ApiShowsGetOne(r *http.Request, enc encoder.Encoder, store Store, parms martini.Params, user User) (int, []byte) {
id, err := strconv.Atoi(parms["id"])
if err != nil {
return http.StatusBadRequest, encoder.Must(enc.Encode(err))
}
show, err := store.GetShowOrRetrieve(id)
if err != nil {
return http.StatusBadRequest, encoder.Must(enc.Encode(err))
}
show.Personalize(user.ID)
return http.StatusOK, encoder.Must(enc.Encode(show))
}
func ApiShowsPutOne(r *http.Request, enc encoder.Encoder, store Store, parms martini.Params, user User) (int, []byte) {
id, err := strconv.Atoi(parms["id"])
if err != nil {
return http.StatusBadRequest, encoder.Must(enc.Encode(err))
}
show, err := store.GetShowOrRetrieve(id)
if err != nil {
return http.StatusBadRequest, encoder.Must(enc.Encode(err))
}
var showPost Show
body, _ := ioutil.ReadAll(r.Body)
r.Body.Close()
err = json.Unmarshal(body, &showPost)
if err != nil {
return http.StatusNotFound, encoder.Must(enc.Encode(NewError(ErrCodeNotExist, "Could not decode body")))
}
userShow := UserShow{UserID: user.ID, ShowID: show.ID, Favorite: showPost.Favorite, Library: showPost.Library}
err = store.UserShowUpsert(&userShow)
show.Personalize(user.ID)
return http.StatusOK, encoder.Must(enc.Encode(show))
}