-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcommunautofinder.go
161 lines (120 loc) · 5.35 KB
/
communautofinder.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
package communautofinder
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
const fetchDelayInMin = 1 // delay between two API call
const dateFormat = "2006-01-02T15:04:05" // time format accepted by communauto API
// As soon as at least one car is found return the number of cars found
func SearchStationCar(cityId CityId, currentCoordinate Coordinate, marginInKm float64, startDate time.Time, endDate time.Time, vehiculeType VehiculeType) int {
responseChannel := make(chan int, 1)
ctx, cancel := context.WithCancel(context.Background())
nbCarFound := searchCar(SearchingStation, cityId, currentCoordinate, marginInKm, startDate, endDate, vehiculeType, responseChannel, ctx, cancel)
cancel()
return nbCarFound
}
// As soon as at least one car is found return the number of cars found
func SearchFlexCar(cityId CityId, currentCoordinate Coordinate, marginInKm float64) int {
responseChannel := make(chan int, 1)
ctx, cancel := context.WithCancel(context.Background())
nbCarFound := searchCar(SearchingFlex, cityId, currentCoordinate, marginInKm, time.Time{}, time.Time{}, AllTypes, responseChannel, ctx, cancel)
cancel()
return nbCarFound
}
// This function is designed to be called as a goroutine. As soon as at least one car is found return the number of cars found. Or can be cancelled by the context
func SearchStationCarForGoRoutine(cityId CityId, currentCoordinate Coordinate, marginInKm float64, startDate time.Time, endDate time.Time, vehiculeType VehiculeType, responseChannel chan<- int, ctx context.Context, cancelCtxFunc context.CancelFunc) int {
defer func() {
if r := recover(); r != nil {
responseChannel <- -1
log.Printf("Pannic append : %s", r)
}
}()
return searchCar(SearchingStation, cityId, currentCoordinate, marginInKm, startDate, endDate, vehiculeType, responseChannel, ctx, cancelCtxFunc)
}
// This function is designed to be called as a goroutine. As soon as at least one car is found return the number of cars found. Or can be cancelled by the context
func SearchFlexCarForGoRoutine(cityId CityId, currentCoordinate Coordinate, marginInKm float64, responseChannel chan<- int, ctx context.Context, cancelCtxFunc context.CancelFunc) int {
defer func() {
if r := recover(); r != nil {
responseChannel <- -1
log.Printf("Pannic append : %s", r)
}
}()
return searchCar(SearchingFlex, cityId, currentCoordinate, marginInKm, time.Time{}, time.Time{}, AllTypes, responseChannel, ctx, cancelCtxFunc)
}
// Loop until a result is found. Return the number of cars found or can be cancelled by the context
func searchCar(searchingType SearchType, cityId CityId, currentCoordinate Coordinate, marginInKm float64, startDate time.Time, endDate time.Time, vehiculeType VehiculeType, responseChannel chan<- int, ctx context.Context, cancelCtxFunc context.CancelFunc) int {
minCoordinate, maxCoordinate := currentCoordinate.ExpandCoordinate(marginInKm)
var urlCalled string
if searchingType == SearchingFlex {
urlCalled = fmt.Sprintf("https://restapifrontoffice.reservauto.net/api/v2/Vehicle/FreeFloatingAvailability?CityId=%d&MaxLatitude=%f&MinLatitude=%f&MaxLongitude=%f&MinLongitude=%f", cityId, maxCoordinate.latitude, minCoordinate.latitude, maxCoordinate.longitude, minCoordinate.longitude)
} else if searchingType == SearchingStation {
startDateFormat := startDate.Format(dateFormat)
endDataFormat := endDate.Format(dateFormat)
urlCalled = fmt.Sprintf("https://restapifrontoffice.reservauto.net/api/v2/StationAvailability?CityId=%d&MaxLatitude=%f&MinLatitude=%f&MaxLongitude=%f&MinLongitude=%f&StartDate=%s&EndDate=%s", cityId, maxCoordinate.latitude, minCoordinate.latitude, maxCoordinate.longitude, minCoordinate.longitude, url.QueryEscape(startDateFormat), url.QueryEscape(endDataFormat))
if vehiculeType != AllTypes {
urlCalled += fmt.Sprintf("&VehicleTypes=%d", vehiculeType)
}
}
msSecondeToSleep := 0
for {
select {
case <-ctx.Done():
responseChannel <- -1
return -1
default:
if msSecondeToSleep > 0 {
time.Sleep(time.Millisecond)
msSecondeToSleep--
} else {
nbCarFound := 0
var err error
if searchingType == SearchingFlex {
var flexAvailable flexCarResponse
err = apiCall(urlCalled, &flexAvailable)
nbCarFound = flexAvailable.TotalNbVehicles
} else if searchingType == SearchingStation {
var stationsAvailable stationsResponse
err = apiCall(urlCalled, &stationsAvailable)
for _, station := range stationsAvailable.Stations {
if station.SatisfiesFilters && station.RecommendedVehicleId != nil {
nbCarFound++
}
}
}
if err != nil {
cancelCtxFunc()
}
if nbCarFound > 0 {
responseChannel <- nbCarFound
return nbCarFound
}
msSecondeToSleep = fetchDelayInMin * 60 * 1000 // Wait only 1ms each time to don't block the for loop and be able to catch the cancel signal
}
}
}
}
// Make an api call at url passed and return the result in response object
func apiCall(url string, response interface{}) error {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
errDecode := json.NewDecoder(resp.Body).Decode(response)
if errDecode != nil {
log.Fatal(errDecode)
}
} else {
errString := fmt.Sprintf("Error %d in API call", resp.StatusCode)
err = errors.New(errString)
log.Print(err)
}
return err
}