-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
659 lines (571 loc) · 18.6 KB
/
main.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/gocolly/colly"
"github.com/google/uuid"
"github.com/joho/godotenv"
"logit/utils"
)
var (
baseAuthorizeUrl = "https://www.fitbit.com/oauth2/authorize"
fitbitApiUrl = "https://api.fitbit.com"
scopes = []string{
"profile",
"nutrition",
}
expiry = 604800
)
var sessionStore = map[string]utils.AuthResponse{}
var uagents = []string{}
func init() {
// load uagents
utils.LoadUagents(&uagents)
// load environment variables
godotenv.Load()
// check debug
debug, _ := strconv.ParseBool(os.Getenv("DEBUG"))
// disable console color
if !debug {
gin.DisableConsoleColor()
gin.SetMode(gin.ReleaseMode)
// create a log file
f, _ := os.Create("gin.log")
// Essentially, makes gin route all console output
// to a file
gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
log.SetOutput(gin.DefaultWriter)
}
}
func main() {
// initialize router
r := gin.Default()
r.Static("/static", "./static")
r.LoadHTMLGlob("static/templates/*")
frontendUrl := os.Getenv("FRONTEND_URL")
r.Use(cors.New(cors.Config{
AllowOrigins: []string{frontendUrl, "https://logit-xyz.netlify.app"},
AllowMethods: []string{"*"},
AllowHeaders: []string{"*"},
AllowCredentials: true,
}))
r.GET("/health", func(c *gin.Context) {
c.String(200, "ok")
})
// gets an auth token from fitbit to make all subsequent requests
r.GET("/auth", func(ctx *gin.Context) {
// form the full authorization url
authorizeUrlFormat := "%s?response_type=code&client_id=%s&redirect_uri=%s&scope=%s&expires_in=%d"
encodedScopes := strings.Join(scopes, " ")
authorizeUrl := fmt.Sprintf(authorizeUrlFormat,
baseAuthorizeUrl, os.Getenv("CLIENT_ID"),
url.QueryEscape(os.Getenv("REDIRECT_URL")),
encodedScopes, expiry,
)
// return a redirect response
ctx.Redirect(http.StatusTemporaryRedirect, authorizeUrl)
})
// callback gets access tokens and return
r.GET("/auth_callback", func(ctx *gin.Context) {
authToken := os.Getenv("TOKEN")
// get the authorization code
code := ctx.Query("code")
// make an http client
client := &http.Client{
Timeout: time.Second * 10,
}
// construct request
data := url.Values{}
data.Set("clientId", os.Getenv("CLIENT_ID"))
data.Set("grant_type", "authorization_code")
data.Set("redirect_uri", os.Getenv("REDIRECT_URL"))
data.Set("code", code)
tokenEndpoint := fmt.Sprintf("%s/oauth2/token", fitbitApiUrl)
req, _ := http.NewRequest(http.MethodPost, tokenEndpoint, strings.NewReader(data.Encode()))
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", authToken))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// send request
resp, err := client.Do(req)
if err != nil {
log.Printf("error: %+v", err)
ctx.HTML(500, "error.html", gin.H{
"title": "Unsuccessful",
"header": "Oh no! Your login failed",
"body": "Unfortunately, your login request was unsuccessful. You will be redirected back to the app.",
"redirectUrl": frontendUrl,
})
}
// read response
responseBody, _ := io.ReadAll(resp.Body)
defer resp.Body.Close()
var authConf utils.AuthResponse
json.Unmarshal(responseBody, &authConf)
// generate session id
sessionId := md5.Sum([]byte(authConf.UserId))
sessionIdStr := fmt.Sprintf("%x", sessionId)
sessionStore[sessionIdStr] = authConf
redirectUrl := fmt.Sprintf(
"%s?sess=%s",
frontendUrl,
sessionIdStr,
)
// redirect
ctx.HTML(200, "success.html", gin.H{
"title": "Success",
"header": "Congrats! You're all set",
"body": "Your login request was successful! You should be redirected back to the app shortly.",
"redirectUrl": redirectUrl,
})
})
// calculates nutrition
r.GET("/calculate", func(ctx *gin.Context) {
// spoof user agent
uagent := utils.Spoof(uagents)
fmt.Printf("user agent: %s", uagent)
var rawRecipe *map[string]interface{}
var recipeId string = ""
// create a collector
c := colly.NewCollector(
colly.UserAgent(uagent),
)
c.Limit(&colly.LimitRule{
RandomDelay: 1 * time.Second,
})
// when it makes the request
c.OnRequest(func(r *colly.Request) {
r.Headers.Set("Referer", "https://www.google.com")
log.Printf("Visiting %s", r.URL)
})
// when it finishes scrapes
c.OnScraped(func(r *colly.Response) {
log.Printf("Finished scraping %s", r.Request.URL)
})
c.OnError(func(r *colly.Response, err error) {
log.Printf("response: %s", r.Body)
log.Printf("scraping error: %+v", err)
})
// grab the application/ld+json script data
c.OnHTML("script[type='application/ld+json']", func(h *colly.HTMLElement) {
// parse html into interface
var ldJSON interface{}
json.Unmarshal([]byte(h.Text), &ldJSON)
// this if for logging purposes
// in case something fails, I can always refer to the recipe
// id and get a stack trace of what happened
id := uuid.New().String()
log.Printf("Created log for recipe %s\n", id)
f, _ := os.Create(fmt.Sprintf("./logs/%s.json", id))
f.Write([]byte(h.Text))
f.Close()
// use type switching in order to do logic based
// on the type of the underlying interface
switch json := ldJSON.(type) {
case []map[string]interface{}:
// it's a list of schemas
// find the @type == recipe
for _, schema := range json {
if schemaType, exists := schema["@type"]; exists {
switch schemaType := schemaType.(type) {
case string:
schemaType = strings.ToLower(schemaType)
if schemaType == "recipe" {
rawRecipe = &schema
recipeId = id
}
case []interface{}:
for _, val := range schemaType {
if val, ok := val.(string); ok {
val = strings.ToLower(val)
if val == "recipe" {
rawRecipe = &schema
recipeId = id
}
}
}
default:
log.Printf("error: encountered unexpected type %T", schemaType)
}
}
}
case []interface{}:
// it's a list of schemas
// find the @type == recipe
for _, schema := range json {
if schema, ok := schema.(map[string]interface{}); ok {
if schemaType, exists := schema["@type"]; exists {
switch schemaType := schemaType.(type) {
case string:
schemaType = strings.ToLower(schemaType)
if schemaType == "recipe" {
rawRecipe = &schema
recipeId = id
}
case []interface{}:
for _, val := range schemaType {
if val, ok := val.(string); ok {
val = strings.ToLower(val)
if val == "recipe" {
rawRecipe = &schema
recipeId = id
}
}
}
default:
log.Printf("error: encountered unexpected type %T", schemaType)
}
}
}
}
case map[string]interface{}:
// does @graph prop exist?
if nodeArray, exists := json["@graph"]; exists {
// is it a []interface{}
if nodeArray, ok := nodeArray.([]interface{}); ok {
// loop through it
for _, schema := range nodeArray {
// check if schema is map[string]interface{}
if schema, ok := schema.(map[string]interface{}); ok {
// check if @type prop exists
if schemaType, exists := schema["@type"]; exists {
switch schemaType := schemaType.(type) {
case string:
schemaType = strings.ToLower(schemaType)
if schemaType == "recipe" {
rawRecipe = &schema
recipeId = id
}
case []interface{}:
for _, val := range schemaType {
if val, ok := val.(string); ok {
val = strings.ToLower(val)
if val == "recipe" {
rawRecipe = &schema
recipeId = id
}
}
}
default:
log.Printf("error: encountered unexpected type %T", schemaType)
}
}
}
}
}
}
// check if the json is actually the recipe structure
if schemaType, exists := json["@type"]; exists {
switch schemaType := schemaType.(type) {
case string:
schemaType = strings.ToLower(schemaType)
if schemaType == "recipe" {
rawRecipe = &json
recipeId = id
}
case []interface{}:
for _, val := range schemaType {
if val, ok := val.(string); ok {
val = strings.ToLower(val)
if val == "recipe" {
rawRecipe = &json
recipeId = id
}
}
}
default:
log.Printf("error: encountered unexpected type %T", schemaType)
}
}
default:
log.Printf("error: encountered unexpected type %T", json)
}
})
link := ctx.Query("link")
c.Visit(link)
// marshal then remarshal into utils.Recipe
var recipe utils.Recipe
bytes, _ := json.Marshal(rawRecipe)
json.Unmarshal(bytes, &recipe)
// change nutrition data
nutritionData := recipe.Nutrition
if nutritionData, ok := nutritionData.(map[string]interface{}); ok {
// delete the type identifier from schema.org
delete(nutritionData, "@type")
delete(nutritionData, "@context")
// change the rest of the nutrition data into {"val": "", "unit": ""}
for key, val := range nutritionData {
// parse the quantity
exp := regexp.MustCompile(`[0-9]+\.*[0-9]*`)
if val == nil {
delete(nutritionData, key)
}
// TODO: add better type checking for [val]
if val, ok := val.(string); ok {
match := exp.FindIndex([]byte(val))
if len(match) == 2 {
i, j := match[0], match[1]
qty, err := strconv.ParseFloat(val[i:j], 64)
if err != nil {
log.Println("error: failed to parse nutrition quantity values")
log.Printf("check recipe log: %s\n", recipeId)
}
unit, name := utils.GetUnit(key), utils.CreateName(key)
// overrite the map
nutritionData[key] = map[string]interface{}{
"qty": qty,
"unit": unit,
"name": name,
}
}
}
}
}
// change image data
switch img := recipe.Image.(type) {
case []interface{}:
i := rand.Intn(len(img))
switch imgObj := img[i].(type) {
case map[string]interface{}:
if link, exists := imgObj["url"]; exists {
recipe.Image = link
}
case string:
recipe.Image = imgObj
default:
log.Printf("url: encountered type %T", imgObj)
}
case map[string]interface{}:
// grap url and set it
if url, exists := img["url"]; exists {
recipe.Image = url
}
default:
log.Printf("img: encountered type %T", img)
}
// change main entity
if entity, ok := recipe.MainEntity.(map[string]interface{}); ok {
// grap url and set it
if url, exists := entity["@id"]; exists {
recipe.MainEntity = url
}
}
ctx.JSON(http.StatusAccepted, recipe)
})
// calculates nutrition (based on ingredients)
r.GET("/build", func(ctx *gin.Context) {
// get the nutritional information from text
})
// ** REQUESTS REQUIRE AUTH **
// adds food into log
r.POST("/log", func(ctx *gin.Context) {
// get the current session
sess := ctx.Request.Header.Get("Authorization")
// if no session is present, return a Unauthorized code
if sess == "" {
err := fmt.Errorf("not authorized to make this request")
ctx.AbortWithError(http.StatusUnauthorized, err)
}
// read the auth config
var authConf utils.AuthResponse = sessionStore[sess]
// read the request body
var body utils.FoodLogRequest
if err := ctx.ShouldBindJSON(&body); err != nil {
ctx.AbortWithError(500, err)
}
// ** make request to fitbit api **
client := &http.Client{
Timeout: time.Second * 10,
}
// construct query params
// 304 -> 1 serving unit
defaultMeasurementId := 304
params := url.Values{}
params.Set("foodName", body.Name)
params.Set("mealTypeId", fmt.Sprintf("%d", body.Meal))
params.Set("unitId", fmt.Sprintf("%d", defaultMeasurementId))
params.Set("amount", utils.ConvertFloat(body.Amount, 2))
params.Set("date", time.Now().Format("2006-01-02"))
// Set nutrition information
params.Set("calories", utils.ConvertFloat(body.Nutrition.Calories, 0))
params.Set("totalFat", utils.ConvertFloat(body.Nutrition.Fat, 2))
params.Set("transFat", utils.ConvertFloat(body.Nutrition.TransFat, 2))
params.Set("saturatedFat", utils.ConvertFloat(body.Nutrition.SaturatedFat, 2))
params.Set("cholesterol", utils.ConvertFloat(body.Nutrition.Cholesterol, 2))
params.Set("sodium", utils.ConvertFloat(body.Nutrition.Sodium, 2))
params.Set("totalCarbohydrate", utils.ConvertFloat(body.Nutrition.Carbohydrates, 2))
params.Set("dietaryFiber", utils.ConvertFloat(body.Nutrition.Fiber, 2))
params.Set("sugars", utils.ConvertFloat(body.Nutrition.Sugar, 2))
params.Set("protein", utils.ConvertFloat(body.Nutrition.Protein, 2))
logEndpoint := fmt.Sprintf(
"%s/1/user/%s/foods/log.json",
fitbitApiUrl,
authConf.UserId,
)
// create request obj
req, _ := http.NewRequest(http.MethodPost, logEndpoint, nil)
req.URL.RawQuery = params.Encode()
// set headers
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authConf.AccessToken))
req.Header.Set("Accept", "application/json")
// send request
resp, err := client.Do(req)
if err != nil {
ctx.AbortWithError(500, err)
}
if resp.StatusCode == http.StatusCreated {
ctx.JSON(http.StatusCreated, `{"message": "success"}`)
} else {
responseBody, _ := io.ReadAll(resp.Body)
defer resp.Body.Close()
ctx.JSON(resp.StatusCode, string(responseBody))
}
})
// creates a food
r.POST("/create", func(ctx *gin.Context) {
// get the current session
sess := ctx.Request.Header.Get("Authorization")
// if no session is present, return a Unauthorized code
if sess == "" {
err := fmt.Errorf("not authorized to make this request")
ctx.JSON(http.StatusUnauthorized, fmt.Sprintf(`{"message":"%+v"`, err))
}
// read the auth config
var authConf utils.AuthResponse = sessionStore[sess]
// read the request body
var body utils.FoodCreateRequest
if err := ctx.ShouldBindJSON(&body); err != nil {
err := fmt.Errorf("couldn't understand the request")
ctx.JSON(http.StatusBadRequest, fmt.Sprintf(`{"message":"%+v"`, err))
}
// ** make request to fitbit api **
client := &http.Client{
Timeout: time.Second * 10,
}
// construct query params
// 304 -> 1 serving unit
params := url.Values{}
params.Set("name", body.Name)
params.Set("defaultFoodMeasurementUnitId", "304")
params.Set("defaultServingSize", "1")
params.Set("formType", "DRY")
params.Set("description", body.Description)
// Set nutrition information
params.Set("calories", utils.ConvertFloat(body.Nutrition.Calories, 0))
params.Set("totalFat", utils.ConvertFloat(body.Nutrition.Fat, 2))
params.Set("transFat", utils.ConvertFloat(body.Nutrition.TransFat, 2))
params.Set("saturatedFat", utils.ConvertFloat(body.Nutrition.SaturatedFat, 2))
params.Set("cholesterol", utils.ConvertFloat(body.Nutrition.Cholesterol, 2))
params.Set("sodium", utils.ConvertFloat(body.Nutrition.Sodium, 2))
params.Set("totalCarbohydrate", utils.ConvertFloat(body.Nutrition.Carbohydrates, 2))
params.Set("dietaryFiber", utils.ConvertFloat(body.Nutrition.Fiber, 2))
params.Set("sugars", utils.ConvertFloat(body.Nutrition.Sugar, 2))
params.Set("protein", utils.ConvertFloat(body.Nutrition.Protein, 2))
logEndpoint := fmt.Sprintf(
"%s/1/user/%s/foods.json",
fitbitApiUrl,
authConf.UserId,
)
// create request obj
req, _ := http.NewRequest(http.MethodPost, logEndpoint, nil)
req.URL.RawQuery = params.Encode()
// set headers
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authConf.AccessToken))
req.Header.Set("Accept", "application/json")
// send request
resp, err := client.Do(req)
if err != nil {
err := fmt.Errorf("unable to fulfill request")
ctx.JSON(http.StatusInternalServerError, fmt.Sprintf(`{"message":"%+v"`, err))
}
if resp.StatusCode == http.StatusCreated {
ctx.JSON(http.StatusCreated, `{"message": "success"}`)
} else {
responseBody, _ := io.ReadAll(resp.Body)
defer resp.Body.Close()
ctx.JSON(resp.StatusCode, string(responseBody))
}
})
// gets the current active user
r.GET("/me", func(ctx *gin.Context) {
sess := ctx.Request.Header.Get("Authorization")
if authConf, exists := sessionStore[sess]; exists {
client := http.Client{
Timeout: time.Second * 10,
}
profileEndpoint := fmt.Sprintf("%s/1/user/%s/profile.json", fitbitApiUrl, authConf.UserId)
req, _ := http.NewRequest(http.MethodGet, profileEndpoint, nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authConf.AccessToken))
req.Header.Add("Content-Type", "application/json")
// send request
resp, err := client.Do(req)
if err != nil {
ctx.JSON(500, fmt.Sprintf(`{"message": %+v}`, err))
}
// read response
responseBody, _ := io.ReadAll(resp.Body)
defer resp.Body.Close()
var user utils.User
json.Unmarshal(responseBody, &user)
ctx.JSON(200, user.Profile)
} else {
ctx.JSON(401, nil)
}
})
r.GET("/logout", func(ctx *gin.Context) {
authToken := os.Getenv("TOKEN")
sess := ctx.Query("sess")
if authConf, exists := sessionStore[sess]; exists {
client := http.Client{
Timeout: time.Second * 10,
}
// revoke access_token
revokeEndpoint := fmt.Sprintf("%s/oauth2/revoke", fitbitApiUrl)
params := url.Values{}
params.Set("token", authConf.AccessToken)
req, _ := http.NewRequest(http.MethodPost, revokeEndpoint, nil)
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", authToken))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// send request
_, err := client.Do(req)
if err != nil {
log.Printf("error: %+v", err)
ctx.HTML(500, "error.html", gin.H{
"title": "Logout error",
"header": "Oh no! We coudn't log you out",
"body": "We were unable to fulfill your logout request. You can try again once you have been redirected to the app.",
"redirectUrl": frontendUrl,
})
}
// remove the session id from sessionStore
delete(sessionStore, sess)
ctx.HTML(200, "success.html", gin.H{
"title": "Logged out",
"header": "We'll miss you",
"body": "Your logout request was successful! You will be redirected shortly",
"redirectUrl": frontendUrl,
})
} else {
ctx.HTML(401, "error.html", gin.H{
"title": "Logout error",
"header": "Fishy...",
"body": "It doesn't seem that you were logged in. If this is a mistake, please don't hesitate to reach out.",
"redirectUrl": frontendUrl,
})
}
})
// start the server
port := fmt.Sprintf(":%s", os.Getenv("PORT"))
r.Run(port)
}