-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebcams.go
188 lines (155 loc) · 4.75 KB
/
webcams.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"sort"
"strconv"
"sync"
)
const BASE_URL = "https://developer.nps.gov/api/v1/"
// Structs for JSON data
type Crop struct {
AspectRatio float64 `json:"aspectRatio"`
URL string `json:"url"`
}
type Image struct {
URL string `json:"url"`
Credit string `json:"credit"`
AltText string `json:"altText"`
Title string `json:"title"`
Description string `json:"description"`
Caption string `json:"caption"`
Crops []Crop `json:"crops"`
}
type RelatedPark struct {
States string `json:"states"`
ParkCode string `json:"parkCode"`
Designation string `json:"designation"`
FullName string `json:"fullName"`
URL string `json:"url"`
Name string `json:"name"`
}
type WebcamData struct {
URL string `json:"url"`
Title string `json:"title"`
GeometryPoiID string `json:"geometryPoiId"`
ID string `json:"id"`
Description string `json:"description"`
Images []Image `json:"images"`
RelatedParks []RelatedPark `json:"relatedParks"`
Status string `json:"status"`
StatusMessage string `json:"statusMessage"`
IsStreaming bool `json:"isStreaming"`
Tags []string `json:"tags"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
type WebcamResponse struct {
Total string `json:"total"`
Data []WebcamData `json:"data"`
Limit string `json:"limit"`
Start string `json:"start"`
}
type WebcamDataSlice []WebcamData
// Implement sort.Interface for WebcamDataSlice
func (w WebcamDataSlice) Len() int {
return len(w)
}
func (w WebcamDataSlice) Less(i, j int) bool {
return w[i].Title < w[j].Title // Sort by title
}
func (w WebcamDataSlice) Swap(i, j int) {
w[i], w[j] = w[j], w[i]
}
var (
allWebcams WebcamDataSlice
mutex sync.Mutex
)
// Get API key from environment variable
func GetApiKey() string {
key := os.Getenv("NPS_API_KEY")
if key == "" {
log.Fatal("API key not found. Please set NPS_API_KEY environment variable. Here to register: https://www.nps.gov/subjects/developer/get-started.htm")
}
return key
}
// Fetch all webcams data from the API
func FetchAllWebcams() error {
mutex.Lock()
defer mutex.Unlock()
// Get the total number of webcams from the initial request
initialResponse, err := GetWebcams(1, 0)
if err != nil {
return fmt.Errorf("failed to fetch initial webcams: %w", err)
}
total, err := strconv.Atoi(initialResponse.Total)
if err != nil {
return fmt.Errorf("error converting total to integer: %w", err)
}
start := 0
limit := 50
for start < total {
webcams, err := GetWebcams(limit, start)
if err != nil {
return fmt.Errorf("failed to fetch webcams: %w", err)
}
allWebcams = append(allWebcams, webcams.Data...)
log.Printf("Total webcams stored: %d", len(allWebcams))
start += limit
}
sort.Sort(allWebcams) // Sort the webcams by title
log.Printf("Total webcams stored: %d", len(allWebcams))
return nil
}
// Get webcams data from the API with pagination
func GetWebcams(limit, start int) (WebcamResponse, error) {
url := fmt.Sprintf("%swebcams?limit=%d&start=%d", BASE_URL, limit, start)
log.Printf("Fetching data from the API. Url: %s", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return WebcamResponse{}, fmt.Errorf("error creating request: %w", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Api-Key", GetApiKey())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return WebcamResponse{}, fmt.Errorf("error fetching data from the API: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return WebcamResponse{}, fmt.Errorf("error fetching data from the API. Status code: %d", resp.StatusCode)
}
var webcams WebcamResponse
if err := json.NewDecoder(resp.Body).Decode(&webcams); err != nil {
return WebcamResponse{}, fmt.Errorf("error decoding JSON response: %w", err)
}
log.Printf("Total found: %s", webcams.Total)
return webcams, nil
}
// Get webcams data from memory with pagination
func GetWebcamsFromMemory(limit, start int) []WebcamData {
mutex.Lock()
defer mutex.Unlock()
end := start + limit
if end > len(allWebcams) {
end = len(allWebcams)
}
return allWebcams[start:end]
}
// Group webcams by park
func GroupWebcamsByPark() map[string][]WebcamData {
mutex.Lock()
defer mutex.Unlock()
groupedWebcams := make(map[string][]WebcamData)
for _, webcam := range allWebcams {
for _, park := range webcam.RelatedParks {
groupedWebcams[park.FullName+" - "+park.States] = append(groupedWebcams[park.FullName], webcam)
}
}
log.Printf("grouped entries: %d", len(groupedWebcams))
return groupedWebcams
}