forked from jda/srtm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imagico.go
184 lines (177 loc) · 4.25 KB
/
imagico.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
package srtm
import (
"archive/zip"
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/rs/zerolog/log"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
func client() *http.Client {
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
Timeout: time.Second * 10,
}
}
func parse(r io.Reader) ([]string, error) {
var v []interface{}
if err := json.NewDecoder(r).Decode(&v); err != nil {
log.Error().Caller().Err(err).Msg("decode json")
return nil, err
}
if len(v) == 0 {
return nil, fmt.Errorf("No tiles found (%+v)", v)
}
urls := make([]string, 0, len(v))
for _, f := range v {
fields, ok := f.(map[string]interface{})
if !ok {
continue
}
field, ok := fields["link"]
if !ok {
continue
}
link, ok := field.(string)
if !ok {
continue
}
urls = append(urls, link)
}
return urls, nil
}
func search(ll LatLng) ([]string, error) {
r, err := client().Get(fmt.Sprintf("http://www.imagico.de/map/dem_json.php?date=&lon=%0.7f&lat=%0.7f&lonE=%0.7f&latE=%0.7f&vf=1", ll.Longitude, ll.Latitude, ll.Longitude, ll.Latitude))
if err != nil {
log.Error().Caller().Err(err).Msg("GET")
return nil, err
}
if r.StatusCode != http.StatusOK {
err = fmt.Errorf("status code for request '%s' is not Ok (%d)", r.Request.RequestURI, r.StatusCode)
log.Error().Caller().Err(err).Msg("GET")
return nil, err
}
defer r.Body.Close()
return parse(r.Body)
}
func moveHgt(sourcePath, destPath string) error {
inputFile, err := os.Open(sourcePath)
if err != nil {
return fmt.Errorf("Couldn't open source file: %s", err)
}
outputFile, err := os.Create(destPath)
if err != nil {
inputFile.Close()
return fmt.Errorf("Couldn't open dest file: %s", err)
}
defer outputFile.Close()
_, err = io.Copy(outputFile, inputFile)
inputFile.Close()
if err != nil {
return fmt.Errorf("Writing to output file failed: %s", err)
}
err = os.Remove(sourcePath)
if err != nil {
return fmt.Errorf("Failed removing original file: %s", err)
}
return nil
}
func downloadByURL(tileDir, url string) (extracted []string) {
defer runtime.GC()
targetDir := path.Join(os.TempDir(), "srtm-" + strconv.Itoa(rand.Int()))
err := os.Mkdir(targetDir, 0755)
if err != nil {
log.Error().Caller().Err(err).Msg("")
return extracted
}
defer os.RemoveAll(targetDir)
response, err := http.Get(url)
if err != nil {
log.Error().Caller().Err(err).Msg("")
return extracted
}
defer response.Body.Close()
b, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Error().Caller().Err(err).Msg("")
return extracted
}
zipReader, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
log.Error().Caller().Err(err).Msg("")
return extracted
}
for _, file := range zipReader.File {
zippedFile, err := file.Open()
if err != nil {
log.Error().Caller().Err(err).Msg("unzip")
}
extractedFilePath := filepath.Join(
targetDir,
file.Name,
)
if file.FileInfo().IsDir() {
os.MkdirAll(extractedFilePath, file.Mode())
} else {
outputFile, err := os.OpenFile(
extractedFilePath,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
file.Mode(),
)
if err != nil {
log.Error().Caller().Err(err).Msg("open file")
}
_, err = io.Copy(outputFile, zippedFile)
if err != nil {
log.Error().Caller().Err(err).Msg("copy")
}
outputFile.Close()
if err == nil {
_, file := path.Split(extractedFilePath)
hgt := path.Join(tileDir, file)
extracted = append(extracted, hgt)
if err := moveHgt(extractedFilePath, hgt); err != nil {
log.Error().Caller().Err(err).Msg("move")
}
}
}
zippedFile.Close()
}
return extracted
}
func download(tileDir string, ll LatLng) (string, os.FileInfo, error) {
key := tileKey(ll)
urls, err := search(ll)
if err != nil {
return "", nil, err
}
extracted := make([]string, 0)
for _, url := range urls {
extracted = append(extracted, downloadByURL(tileDir, url)...)
}
for _, hgt := range extracted {
if strings.Contains(hgt, key) {
info, err := os.Stat(hgt)
if err != nil {
return "", nil, nil
}
return hgt, info, nil
}
}
return "", nil, fmt.Errorf("tile file for key = %s is not exists (urls %+v -> %+v)", key, urls, extracted)
}