feat: update multiple tomtom keys and switch tomtom key and add comming soon button
This commit is contained in:
@@ -10,7 +10,6 @@ import (
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -266,44 +265,37 @@ func CalculateETA(distanceKm float64) int {
|
||||
// CalculateETAWithTomTom calcule l'ETA via TomTom API (précis avec trafic réel)
|
||||
// Retourne (etaMinutes, distanceKm, error)
|
||||
func CalculateETAWithTomTom(from, to Coordinates) (int, float64, error) {
|
||||
apiKey := os.Getenv("TOMTOM_API_KEY")
|
||||
if apiKey == "" {
|
||||
// Fallback sur calcul local si pas de clé API
|
||||
distance := CalculateDistance(from, to)
|
||||
return CalculateETA(distance), distance, nil
|
||||
}
|
||||
|
||||
// API TomTom Routing: Calculate Route avec trafic
|
||||
u := &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "api.tomtom.com",
|
||||
Path: fmt.Sprintf("/routing/1/calculateRoute/%f,%f:%f,%f/json", from.Latitude, from.Longitude, to.Latitude, to.Longitude),
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Set("key", apiKey)
|
||||
q.Set("traffic", "true")
|
||||
q.Set("travelMode", "car")
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
|
||||
if err != nil {
|
||||
if len(tomTomKeys.keys) == 0 {
|
||||
distance := CalculateDistance(from, to)
|
||||
return CalculateETA(distance), distance, nil
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 8 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
|
||||
buildReq := func(key string) (*http.Request, error) {
|
||||
u := &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "api.tomtom.com",
|
||||
Path: fmt.Sprintf("/routing/1/calculateRoute/%f,%f:%f,%f/json", from.Latitude, from.Longitude, to.Latitude, to.Longitude),
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Set("key", key)
|
||||
q.Set("traffic", "true")
|
||||
q.Set("travelMode", "car")
|
||||
u.RawQuery = q.Encode()
|
||||
return http.NewRequest(http.MethodGet, u.String(), nil)
|
||||
}
|
||||
|
||||
resp, err := tomTomKeys.Do(client, buildReq)
|
||||
if err != nil {
|
||||
// Fallback sur calcul local en cas d'erreur réseau
|
||||
distance := CalculateDistance(from, to)
|
||||
eta := CalculateETA(distance)
|
||||
fmt.Printf("⚠️ TomTom timeout, fallback: %.2f km -> %d min\n", distance, eta)
|
||||
fmt.Printf("⚠️ TomTom indisponible, fallback: %.2f km -> %d min (%v)\n", distance, eta, err)
|
||||
return eta, distance, nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// Fallback sur calcul local en cas d'erreur API
|
||||
distance := CalculateDistance(from, to)
|
||||
eta := CalculateETA(distance)
|
||||
fmt.Printf("⚠️ TomTom API error %d, fallback: %.2f km -> %d min\n", resp.StatusCode, distance, eta)
|
||||
@@ -328,18 +320,14 @@ func CalculateETAWithTomTom(from, to Coordinates) (int, float64, error) {
|
||||
}
|
||||
|
||||
summary := routeResponse.Routes[0].Summary
|
||||
|
||||
// Calculer ETA en minutes (arrondi supérieur)
|
||||
etaMinutes := (summary.TravelTimeInSeconds + 59) / 60
|
||||
distanceKm := float64(summary.LengthInMeters) / 1000.0
|
||||
|
||||
// Appliquer minimum
|
||||
if etaMinutes < MinETA {
|
||||
etaMinutes = MinETA
|
||||
}
|
||||
|
||||
fmt.Printf("🛣️ TomTom: %.2f km -> %d min (trafic réel)\n", distanceKm, etaMinutes)
|
||||
|
||||
return etaMinutes, distanceKm, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -12,36 +12,29 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetETAWithTraffic(from, to Coordinates) (etaMinutes int, distanceKm float64, err error) {
|
||||
apiKey := os.Getenv("TOMTOM_API_KEY")
|
||||
if apiKey == "" {
|
||||
return 0, 0, fmt.Errorf("TOMTOM_API_KEY non configurée")
|
||||
}
|
||||
|
||||
u := &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "api.tomtom.com",
|
||||
Path: fmt.Sprintf("/routing/1/calculateRoute/%f,%f:%f,%f/json", from.Latitude, from.Longitude, to.Latitude, to.Longitude),
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Set("key", apiKey)
|
||||
q.Set("traffic", "true")
|
||||
q.Set("travelMode", "car")
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("erreur construction requête TomTom: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
|
||||
buildReq := func(key string) (*http.Request, error) {
|
||||
u := &url.URL{
|
||||
Scheme: "https",
|
||||
Host: "api.tomtom.com",
|
||||
Path: fmt.Sprintf("/routing/1/calculateRoute/%f,%f:%f,%f/json", from.Latitude, from.Longitude, to.Latitude, to.Longitude),
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Set("key", key)
|
||||
q.Set("traffic", "true")
|
||||
q.Set("travelMode", "car")
|
||||
u.RawQuery = q.Encode()
|
||||
return http.NewRequest(http.MethodGet, u.String(), nil)
|
||||
}
|
||||
|
||||
resp, err := tomTomKeys.Do(client, buildReq)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("erreur requête TomTom: %w", err)
|
||||
return 0, 0, fmt.Errorf("erreur TomTom: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
@@ -65,12 +58,9 @@ func GetETAWithTraffic(from, to Coordinates) (etaMinutes int, distanceKm float64
|
||||
}
|
||||
|
||||
summary := routeResponse.Routes[0].Summary
|
||||
|
||||
// Calculer ETA en minutes (arrondi supérieur)
|
||||
etaMinutes = (summary.TravelTimeInSeconds + 59) / 60
|
||||
distanceKm = float64(summary.LengthInMeters) / 1000.0
|
||||
|
||||
log.Printf("🛣️ TomTom Routing: %.2f km → %d min (trafic inclus)", distanceKm, etaMinutes)
|
||||
|
||||
return etaMinutes, distanceKm, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type tomTomKeyManager struct {
|
||||
keys []string
|
||||
current atomic.Int32
|
||||
}
|
||||
|
||||
var tomTomKeys = initTomTomKeyManager()
|
||||
|
||||
func initTomTomKeyManager() *tomTomKeyManager {
|
||||
m := &tomTomKeyManager{}
|
||||
seen := map[string]bool{}
|
||||
|
||||
candidates := []string{
|
||||
os.Getenv("TOMTOM_API_KEY"),
|
||||
os.Getenv("TOMTOM_API_KEY_1"),
|
||||
os.Getenv("TOMTOM_API_KEY_2"),
|
||||
os.Getenv("TOMTOM_API_KEY_3"),
|
||||
}
|
||||
for _, k := range candidates {
|
||||
if k != "" && !seen[k] {
|
||||
seen[k] = true
|
||||
m.keys = append(m.keys, k)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("🔑 [TOMTOM] %d clé(s) API configurée(s)", len(m.keys))
|
||||
return m
|
||||
}
|
||||
|
||||
// currentKey retourne la clé active et son index.
|
||||
func (m *tomTomKeyManager) currentKey() (string, int) {
|
||||
n := len(m.keys)
|
||||
if n == 0 {
|
||||
return "", -1
|
||||
}
|
||||
idx := int(m.current.Load()) % n
|
||||
return m.keys[idx], idx
|
||||
}
|
||||
|
||||
// rotate passe à la clé suivante.
|
||||
func (m *tomTomKeyManager) rotate(fromIdx int) {
|
||||
n := len(m.keys)
|
||||
if n <= 1 {
|
||||
return
|
||||
}
|
||||
next := int32((fromIdx + 1) % n)
|
||||
m.current.CompareAndSwap(int32(fromIdx), next)
|
||||
log.Printf("🔄 [TOMTOM] Rotation clé %d → clé %d (quota atteint)", fromIdx+1, next+1)
|
||||
}
|
||||
|
||||
// Do exécute la requête en rotant automatiquement sur 403/429.
|
||||
// buildReq doit construire une nouvelle *http.Request pour la clé donnée.
|
||||
func (m *tomTomKeyManager) Do(client *http.Client, buildReq func(key string) (*http.Request, error)) (*http.Response, error) {
|
||||
n := len(m.keys)
|
||||
if n == 0 {
|
||||
return nil, fmt.Errorf("aucune clé TomTom configurée (TOMTOM_API_KEY / TOMTOM_API_KEY_1..3)")
|
||||
}
|
||||
|
||||
_, startIdx := m.currentKey()
|
||||
|
||||
for attempt := 0; attempt < n; attempt++ {
|
||||
idx := (startIdx + attempt) % n
|
||||
key := m.keys[idx]
|
||||
|
||||
req, err := buildReq(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
m.rotate(idx)
|
||||
continue
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("toutes les clés TomTom ont atteint leur quota (%d clé(s) testée(s))", n)
|
||||
}
|
||||
Reference in New Issue
Block a user