-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
330 lines (277 loc) · 8.08 KB
/
client.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/http/cookiejar"
"net/url"
"time"
)
type RestClient struct {
Client *http.Client
Config Config
SessionID string
UserId int
CustomerId int
CookieJar *cookiejar.Jar
Bookings []Bookings
}
func NewClient(Config Config) (*RestClient, error) {
c := &RestClient{}
err := ValidateConfig(Config)
if err != nil {
return &RestClient{}, fmt.Errorf("validating config: %w", err)
}
c.Config = Config
jar, err := cookiejar.New(nil)
if err != nil {
return nil, fmt.Errorf("initializing cookie jar: %v", err)
}
c.CookieJar = jar
c.Client = &http.Client{
Jar: jar,
}
cookie := &http.Cookie{
Name: "JSESSIONID",
Value: c.Config.SessionCredentials.SessionID,
Path: "/",
}
cookieUrl, err := url.Parse("https://rest.tastenext.de")
if err != nil {
return &RestClient{}, fmt.Errorf("perse cookie url: %w", err)
}
c.CookieJar.SetCookies(cookieUrl, []*http.Cookie{cookie})
// Check if the old SessionId works
c.SessionID = c.Config.SessionCredentials.SessionID
currentUserResponse, err := c.getCurrentUser()
// If not, login again and get a new one
if err != nil {
err := c.login()
if err != nil {
return nil, fmt.Errorf("failed to log in")
}
// Does it work now?
currentUserResponse, err = c.getCurrentUser()
if err != nil {
return nil, fmt.Errorf("failed to refresh token")
}
}
c.UserId = currentUserResponse.User.ID
userResponse, err := c.GetUser()
if err != nil {
return &RestClient{}, fmt.Errorf("unable to load user")
}
c.CustomerId = userResponse.User.Customer.ID
c.Bookings = userResponse.User.Customer.Bookings
return c, nil
}
// Private
func (c *RestClient) sendRequest(method, urlStr string, body io.Reader, result interface{}) error {
if c.Client == nil {
return fmt.Errorf("client not initialized. Please login first")
}
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return fmt.Errorf("error creating request: %v", err)
}
resp, err := c.Client.Do(req)
if err != nil {
return fmt.Errorf("error performing request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("server returns status code %d", resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading response body: %v", err)
}
err = json.Unmarshal(respBody, result)
if err != nil {
return fmt.Errorf("error unmarshaling JSON: %v", err)
}
return nil
}
func (c *RestClient) login() error {
// Prepare the multipart form data
var b bytes.Buffer
writer := multipart.NewWriter(&b)
writer.WriteField("username", c.Config.LoginCredentials.User)
writer.WriteField("password", c.Config.LoginCredentials.Password)
writer.WriteField("remember-me", "true")
writer.Close()
// Create a new POST request
req, err := http.NewRequest("POST", "https://rest.tastenext.de/public/login/process", &b)
if err != nil {
return fmt.Errorf("error creating request: %v", err)
}
// Set Content-Type for the request
req.Header.Set("Content-Type", writer.FormDataContentType())
// Perform the request
resp, err := c.Client.Do(req)
if err != nil {
return fmt.Errorf("error performing request: %v", err)
}
defer resp.Body.Close()
// Get sessionId from cookie
foundCookie := false
for _, cookie := range c.CookieJar.Cookies(req.URL) {
if cookie.Name == "JSESSIONID" {
c.SessionID = cookie.Value
foundCookie = true
break
}
}
if !foundCookie {
return fmt.Errorf("error getting session cookie")
}
return nil
}
func (c *RestClient) getCurrentUser() (CurrentUserResponse, error) {
var currentUserResp CurrentUserResponse
err := c.sendRequest("GET", "https://rest.tastenext.de/backend/user/current-user", nil, ¤tUserResp)
if err != nil {
return CurrentUserResponse{}, fmt.Errorf("error creating request: %v", err)
}
return currentUserResp, nil
}
func (c *RestClient) GetUser() (UserResponse, error) {
var userResp UserResponse
urlWithUserID := fmt.Sprintf("https://rest.tastenext.de/backend/user/%d", c.UserId)
err := c.sendRequest("GET", urlWithUserID, nil, &userResp)
if err != nil {
log.Fatal("Error sending request")
}
return userResp, nil
}
// We can only get one whole week from the API
func (c *RestClient) GetMenuWeek(Year int, Week int) (UpcomingDishMap, error) {
var retVal = UpcomingDishMap{}
customer := c.CustomerId
menuUrl := fmt.Sprintf(
"https://rest.tastenext.de/frontend/menu/get-personal-menu-week/calendar-week/%d/year/%d/customer/%d/menu-block/14",
Week,
Year,
customer,
)
var menuResp MenuResponse
err := c.sendRequest("GET", menuUrl, nil, &menuResp)
if err != nil {
log.Fatal("Error getting menus")
}
// extract fields
for _, mblw := range menuResp.MenuBlockWeekWrapper.MenuBlockWeek.MenuBlockLineWeeks {
for _, dish := range mblw.Entries {
edate, err := GetEmissionDateAsTime(dish.EmissionDate)
if err != nil {
log.Fatal("Error getting emission date")
}
// Check for dummy values. They appear if there is no menu for that day.
isDummy := dish.Dish.Name == "---"
// Flag already booked dishes
isBooked := false
for _, booking := range menuResp.Bookings {
if booking.MenuBlockLineEntry.ID == dish.ID {
isBooked = true
}
}
// Append upcoming dishes
personalOrderCount, _ := c.GetOrderCount(dish.Dish.ID)
upcomingDish := UpcomingDish{
OrderId: dish.ID,
Dish: dish.Dish,
Orders: dish.NumberOfBookings,
PersonalOrders: personalOrderCount,
Date: edate,
Dummy: isDummy,
Booked: isBooked,
}
dateKey := edate.Format("06-01-02")
retVal[dateKey] = append(retVal[dateKey], upcomingDish)
}
}
return retVal, nil
}
// Get menu for the next n calender weeks
func (c *RestClient) GetMenuWeeks(weeks int) (UpcomingDishMap, error) {
var retVal = UpcomingDishMap{}
nextWeeks := GetNextCalenderWeeks(weeks)
for _, week := range nextWeeks {
menuWeek, err := c.GetMenuWeek(week.Year, week.CalendarWeek)
if err != nil {
fmt.Errorf("Error getting weeks")
}
retVal.Merge(menuWeek)
}
return retVal, nil
}
// Get Menu for one Day
func (c *RestClient) GetMenuDay(Day time.Time) (UpcomingDishMap, error) {
var retVal = UpcomingDishMap{}
menuWeek, err := c.GetMenuWeek(Day.ISOWeek())
if err != nil {
return retVal, fmt.Errorf("error: %w", err)
}
dateKey := Day.Format("06-01-02")
retVal[dateKey] = menuWeek[dateKey]
if len(retVal) == 0 {
return retVal, fmt.Errorf("no dishes found for this day")
}
return retVal, nil
}
// OrderDish places or cancels an order.
func (c *RestClient) OrderDish(DishOrderId int, CancelOrder bool) error {
// Is the dish already ordered?
userResp, err := c.GetUser()
if err != nil {
return fmt.Errorf(err.Error())
}
var alreadyOrdered = false
for _, booking := range userResp.User.Customer.Bookings {
if booking.MenuBlockLineEntry.ID == DishOrderId {
alreadyOrdered = true
break
}
}
// Check if there is something to do, return if not
if (alreadyOrdered && !CancelOrder) || (!alreadyOrdered && CancelOrder) {
return nil
}
// Toggle booking
bookingUrl := fmt.Sprintf(
"https://rest.tastenext.de/frontend/menu/order/menu-block-line-entry/%d/customer/%d",
DishOrderId,
c.CustomerId)
var menuResp MenuResponse
err = c.sendRequest("GET", bookingUrl, nil, &menuResp)
if err != nil {
return errors.New("failed sending order request")
}
switch menuResp.Message {
case "app.messages.changed-booking-status.too-late":
return fmt.Errorf("to late to place order")
case "app.messages.changed-booking-status.insufficient-money":
return fmt.Errorf("not enough account balance to place order")
case "app.messages.changed-booking-status.successful":
return nil
default:
return fmt.Errorf("failed to place or remove order: %v", menuResp.Message)
}
}
// How often a dish was ordered in the past
func (c RestClient) GetOrderCount(DishId int) (count int, dish Dish) {
count = 0
dish = Dish{}
for _, booking := range c.Bookings {
if DishId == booking.MenuBlockLineEntry.Dish.ID {
count++
dish = booking.MenuBlockLineEntry.Dish
}
}
return count, dish
}