-
Notifications
You must be signed in to change notification settings - Fork 0
/
pelotonsession.go
90 lines (74 loc) · 2.34 KB
/
pelotonsession.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
82
83
84
85
86
87
88
89
90
package main
import "fmt"
import "log"
import "github.com/levigross/grequests"
/*
"C:\git\bin\go-bindata.exe" -o data.go data/...
"C:\git\bin\go-bindata.exe" -debug -o data.go data/...
*/
type GetClassDetailsJSON struct {
Title string `json:"title"`
JoinTokens GetClassRideJoinTokensJSON `json:"join_tokens"`
}
type GetClassRideJoinTokensJSON struct {
OnDemand string `json:"on_demand"`
}
type PelotonSession struct {
DefaultBaseUrl string
DefaultHeaders map[string]string
Session *grequests.Session
}
func NewPelotonSession(username string, password string) *PelotonSession {
ps := PelotonSession{
DefaultBaseUrl: "https://api.onepeloton.com",
DefaultHeaders: map[string]string{
"Content-Type": "application/json",
"User-Agent": "peloton-scheduler",
},
Session: grequests.NewSession(nil),
}
authUrl := fmt.Sprintf("%s/%s", ps.DefaultBaseUrl, "auth/login")
log.Printf("Authenticating to %s", authUrl)
resp, _ := ps.Session.Post(
authUrl,
&grequests.RequestOptions{
JSON: map[string]string{
"username_or_email": username,
"password": password,
},
Headers: ps.DefaultHeaders,
},
)
if resp.Error != nil {
log.Printf("Unable to make request", resp.Error)
}
if resp.Ok {
log.Printf("Successfully created Peloton Session")
} else {
if resp.StatusCode == 401 {
log.Printf("Invalid username or password: %d - %s", resp.StatusCode, "")
} else {
log.Printf("Unable to login and create a Peloton session: %d - %s", resp.StatusCode, "")
}
}
return &ps
}
func (ps *PelotonSession) GetClass(classId string) (GetClassDetailsJSON, error) {
ro := &grequests.RequestOptions{UserAgent: "web", DisableCompression: false}
resp, _ := ps.Session.Get(fmt.Sprintf("%s/api/ride/%s", ps.DefaultBaseUrl, classId), ro)
if !resp.Ok {
if resp.StatusCode == 401 {
return GetClassDetailsJSON{}, fmt.Errorf("Invalid username or password: %d - %s", resp.StatusCode, "")
} else {
return GetClassDetailsJSON{}, fmt.Errorf("Unable to login and create a Peloton session: %d - %s", resp.StatusCode, resp.String())
}
}
// log.Printf("Found join token: %s", resp.String())
classjson := &GetClassDetailsJSON{}
err := resp.JSON(classjson)
if err != nil {
return GetClassDetailsJSON{}, err
}
//log.Printf("%s: %s", classjson.Title, classjson.JoinTokens.OnDemand)
return *classjson, nil
}