-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
164 lines (140 loc) · 3.69 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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
"time"
)
type NasaAPOD struct {
Date string `json:"date"`
Title string `json:"title"`
URL string `json:"hdurl"`
}
const apiURL = "https://api.nasa.gov/planetary/apod"
func main() {
apiKey := os.Getenv("NASA_API_KEY")
if apiKey == "" {
apiKey = getOrCreateAPIKey()
}
start, end, downloadOnly := parseArgumentsForDateRange()
fmt.Println("Fetching APODs...")
apods, err := getAPODsForDateRange(apiKey, start, end)
if err != nil {
fmt.Println("Error retrieving data:", err)
return
}
if len(apods) == 0 {
fmt.Println("No APODs found in the given date range")
return
}
for _, apod := range apods {
printPrettyFormattedAPOD(apod)
if downloadOnly {
downloadImage(apod.URL, sanitizeFilename(apod.Title))
} else {
openBrowser(apod.URL)
}
}
}
func parseArgumentsForDateRange() (start, end string, downloadOnly bool) {
flag.StringVar(&start, "start", "", "start date (YYYY-MM-DD)")
flag.StringVar(&end, "end", "", "end date (YYYY-MM-DD)")
flag.BoolVar(&downloadOnly, "download-only", false, "Only download images without opening in browser")
flag.Parse()
return
}
/*
This function is used to retrieve Astronomy Picture of the Day (APOD) data for a given date range from the NASA API.
It takes in three parameters: apiKey, start, and end, which represent the API key and the date range to retrieve.
If either start or end is empty, the function will retrieve the APODs for the last week.
*/
func getAPODsForDateRange(apiKey, start, end string) ([]NasaAPOD, error) {
url := constructURL(apiKey, start, end)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var apods []NasaAPOD
err = json.NewDecoder(resp.Body).Decode(&apods)
if err != nil {
return nil, err
}
return apods, nil
}
func printPrettyFormattedAPOD(apod NasaAPOD) {
date, err := time.Parse("2006-01-02", apod.Date)
if err != nil {
fmt.Println("Error parsing date:", err)
return
}
fmt.Printf("%s\n%s\n%s\n\n", apod.Title, date.Format("January 2, 2006"), apod.URL)
}
func constructURL(apiKey, start, end string) string {
if start == "" || end == "" {
endDate := time.Now()
startDate := endDate.AddDate(0, 0, -7)
return fmt.Sprintf(
"%s?api_key=%s&start_date=%s&end_date=%s",
apiURL, apiKey,
startDate.Format("2006-01-02"),
endDate.Format("2006-01-02"))
}
return fmt.Sprintf(
"%s?api_key=%s&start_date=%s&end_date=%s",
apiURL, apiKey,
start, end)
}
func downloadImage(url, filename string) {
dir := "./images/"
// Make sure the directory exists
if _, err := os.Stat(dir); os.IsNotExist(err) {
os.Mkdir(dir, 0755)
}
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error downloading image:", err)
return
}
defer resp.Body.Close()
file, err := os.Create(dir + sanitizeFilename(filename) + ".jpg")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
fmt.Println("Error saving image:", err)
}
}
func sanitizeFilename(filename string) string {
return strings.Map(func(r rune) rune {
if r == ' ' || r == '_' || r == '-' || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') {
return r
}
return -1
}, filename)
}
func openBrowser(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
fmt.Println("Error opening browser", url, ":", err)
}
}