forked from atlasdatatech/tiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
382 lines (345 loc) · 9.84 KB
/
task.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package main
import (
"bytes"
"compress/gzip"
"database/sql"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/paulmach/orb"
"github.com/paulmach/orb/maptile"
"github.com/paulmach/orb/maptile/tilecover"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/teris-io/shortid"
pb "gopkg.in/cheggaaa/pb.v1"
)
// MBTileVersion mbtiles版本号
const MBTileVersion = "1.2"
// Task 下载任务
type Task struct {
ID string
Name string
Description string
File string
Min int
Max int
Layers []Layer
TileMap TileMap
Total int64
Current int64
Bar *pb.ProgressBar
db *sql.DB
workerCount int
savePipeSize int
timeDelay int
bufSize int
tileWG sync.WaitGroup
abort, pause, play chan struct{}
workers chan maptile.Tile
savingpipe chan Tile
tileSet Set
outformat string
}
// NewTask 创建下载任务
func NewTask(layers []Layer, m TileMap) *Task {
if len(layers) == 0 {
return nil
}
id, _ := shortid.Generate()
task := Task{
ID: id,
Name: m.Name,
Layers: layers,
Min: m.Min,
Max: m.Max,
TileMap: m,
}
for i := 0; i < len(layers); i++ {
if layers[i].URL == "" {
layers[i].URL = m.URL
}
layers[i].Count = tilecover.CollectionCount(layers[i].Collection, maptile.Zoom(layers[i].Zoom))
log.Printf("zoom: %d, tiles: %d \n", layers[i].Zoom, layers[i].Count)
task.Total += layers[i].Count
}
task.abort = make(chan struct{})
task.pause = make(chan struct{})
task.play = make(chan struct{})
task.workerCount = viper.GetInt("task.workers")
task.savePipeSize = viper.GetInt("task.savepipe")
task.timeDelay = viper.GetInt("task.timedelay")
task.workers = make(chan maptile.Tile, task.workerCount)
task.savingpipe = make(chan Tile, task.savePipeSize)
task.bufSize = viper.GetInt("task.mergebuf")
task.tileSet = Set{M: make(maptile.Set)}
task.outformat = viper.GetString("output.format")
return &task
}
// Bound 范围
func (task *Task) Bound() orb.Bound {
bound := orb.Bound{Min: orb.Point{1, 1}, Max: orb.Point{-1, -1}}
for _, layer := range task.Layers {
for _, g := range layer.Collection {
bound = bound.Union(g.Bound())
}
}
return bound
}
// Center 中心点
func (task *Task) Center() orb.Point {
layer := task.Layers[len(task.Layers)-1]
bound := orb.Bound{Min: orb.Point{1, 1}, Max: orb.Point{-1, -1}}
for _, g := range layer.Collection {
bound = bound.Union(g.Bound())
}
return bound.Center()
}
// MetaItems 输出
func (task *Task) MetaItems() map[string]string {
b := task.Bound()
c := task.Center()
data := map[string]string{
"id": task.ID,
"name": task.Name,
"description": task.Description,
"attribution": `<a href="http://www.atlasdata.cn/" target="_blank">© MapCloud</a>`,
"basename": task.TileMap.Name,
"format": task.TileMap.Format,
"type": task.TileMap.Schema,
"pixel_scale": strconv.Itoa(TileSize),
"version": MBTileVersion,
"bounds": fmt.Sprintf(`%f,%f,%f,%f`, b.Left(), b.Bottom(), b.Right(), b.Top()),
"center": fmt.Sprintf(`%f,%f,%d`, c.X(), c.Y(), (task.Min+task.Max)/2),
"minzoom": strconv.Itoa(task.Min),
"maxzoom": strconv.Itoa(task.Max),
"json": task.TileMap.JSON,
}
return data
}
// SetupMBTileTables 初始化配置MBTile库
func (task *Task) SetupMBTileTables() error {
if task.File == "" {
outdir := viper.GetString("output.directory")
os.MkdirAll(outdir, os.ModePerm)
task.File = filepath.Join(outdir, fmt.Sprintf("%s-z%d-%d.%s.mbtiles", task.Name, task.Min, task.Max, task.ID))
}
os.Remove(task.File)
db, err := sql.Open("sqlite3", task.File)
if err != nil {
return err
}
err = optimizeConnection(db)
if err != nil {
return err
}
_, err = db.Exec("create table if not exists tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob);")
if err != nil {
return err
}
_, err = db.Exec("create table if not exists metadata (name text, value text);")
if err != nil {
return err
}
_, err = db.Exec("create unique index name on metadata (name);")
if err != nil {
return err
}
_, err = db.Exec("create unique index tile_index on tiles(zoom_level, tile_column, tile_row);")
if err != nil {
return err
}
// Load metadata.
for name, value := range task.MetaItems() {
_, err := db.Exec("insert into metadata (name, value) values (?, ?)", name, value)
if err != nil {
return err
}
}
task.db = db //保存任务的库连接
return nil
}
func (task *Task) abortFun() {
// os.Stdin.Read(make([]byte, 1)) // read a single byte
// <-time.After(8 * time.Second)
task.abort <- struct{}{}
}
func (task *Task) pauseFun() {
// os.Stdin.Read(make([]byte, 1)) // read a single byte
// <-time.After(3 * time.Second)
task.pause <- struct{}{}
}
func (task *Task) playFun() {
// os.Stdin.Read(make([]byte, 1)) // read a single byte
// <-time.After(5 * time.Second)
task.play <- struct{}{}
}
// SavePipe 保存瓦片管道
func (task *Task) savePipe() {
for tile := range task.savingpipe {
err := saveToMBTile(tile, task.db)
if err != nil {
if strings.HasPrefix(err.Error(), "UNIQUE constraint failed") {
log.Warnf("save %v tile to mbtiles db error ~ %s", tile.T, err)
} else {
log.Errorf("save %v tile to mbtiles db error ~ %s", tile.T, err)
}
}
}
}
// SaveTile 保存瓦片
func (task *Task) saveTile(tile Tile) error {
// defer task.wg.Done()
err := saveToFiles(tile, task)
if err != nil {
log.Errorf("create %v tile file error ~ %s", tile.T, err)
}
return nil
}
// tileFetcher 瓦片加载器
func (task *Task) tileFetcher(mt maptile.Tile, url string) {
start := time.Now()
defer task.tileWG.Done() //结束该瓦片请求
defer func() {
<-task.workers //workers完成并清退
}()
prep := func(t maptile.Tile, url string) string {
url = strings.Replace(url, "{x}", strconv.Itoa(int(t.X)), -1)
url = strings.Replace(url, "{y}", strconv.Itoa(int(t.Y)), -1)
maxY := int(math.Pow(2, float64(t.Z))) - 1
url = strings.Replace(url, "{-y}", strconv.Itoa(maxY-int(t.Y)), -1)
url = strings.Replace(url, "{z}", strconv.Itoa(int(t.Z)), -1)
return url
}
tile := prep(mt, url)
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// 自定义重定向的行为
return http.ErrUseLastResponse // 使用最后一个响应
},
}
req, err := http.NewRequest("GET", tile, nil)
if err != nil {
fmt.Println("创建请求失败:", err)
return
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
req.Header.Set("Referer", "https://map.tianditu.gov.cn")
// req.Header.Set("Referer", "https://jiangsu.tianditu.gov.cn")
resp, err := client.Do(req)
if err != nil {
fmt.Println("发送请求失败:", err)
return
}
defer resp.Body.Close()
// resp, err := http.Get(tile)
// if err != nil {
// log.Errorf("fetch :%s error, details: %s ~", tile, err)
// return
// }
// defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Errorf("fetch %v tile error, status code: %d ~", tile, resp.StatusCode)
return
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("read %v tile error ~ %s", mt, err)
return
}
if len(body) == 0 {
log.Warnf("nil tile %v ~", mt)
return //zero byte tiles n
}
// tiledata
td := Tile{
T: mt,
C: body,
}
if task.TileMap.Format == PBF {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err = zw.Write(body)
if err != nil {
log.Fatal(err)
}
if err := zw.Close(); err != nil {
log.Fatal(err)
}
td.C = buf.Bytes()
}
//enable savingpipe
if task.outformat == "mbtiles" {
task.savingpipe <- td
} else {
// task.wg.Add(1)
task.saveTile(td)
}
cost := time.Since(start).Milliseconds()
log.Infof("tile(z:%d, x:%d, y:%d), %dms , %.2f kb, %s ...\n", mt.Z, mt.X, mt.Y, cost, float32(len(body))/1024.0, tile)
}
// DownloadZoom 下载指定层级
func (task *Task) downloadLayer(layer Layer) {
bar := pb.New64(layer.Count).Prefix(fmt.Sprintf("Zoom %d : ", layer.Zoom)).Postfix("\n")
// bar.SetRefreshRate(time.Second)
bar.Start()
// bar.SetMaxWidth(300)
var tilelist = make(chan maptile.Tile, task.bufSize)
go tilecover.CollectionChannel(layer.Collection, maptile.Zoom(layer.Zoom), tilelist)
for tile := range tilelist {
// log.Infof(`fetching tile %v ~`, tile)
select {
case task.workers <- tile:
//设置请求发送间隔时间
time.Sleep(time.Duration(task.timeDelay) * time.Millisecond)
bar.Increment()
task.Bar.Increment()
task.tileWG.Add(1)
go task.tileFetcher(tile, layer.URL)
case <-task.abort:
log.Infof("Task %s got canceled.", task.ID)
close(tilelist)
case <-task.pause:
log.Infof("Task %s suspended.", task.ID)
select {
case <-task.play:
log.Infof("Task %s go on.", task.ID)
case <-task.abort:
log.Infof("Task %s got canceled.", task.ID)
close(tilelist)
}
}
}
//等待该层结束
task.tileWG.Wait()
bar.FinishPrint(fmt.Sprintf("Task %s Zoom %d finished ~", task.ID, layer.Zoom))
}
// Download 开启下载任务
func (task *Task) Download() {
//g orb.Geometry, minz int, maxz int
task.Bar = pb.New64(task.Total).Prefix("Task : ").Postfix("\n")
// task.Bar.SetRefreshRate(10 * time.Second)
// task.Bar.Format("<.- >")
task.Bar.Start()
if task.outformat == "mbtiles" {
task.SetupMBTileTables()
} else {
if task.File == "" {
outdir := viper.GetString("output.directory")
task.File = filepath.Join(outdir, fmt.Sprintf("%s-z%d-%d.%s", task.Name, task.Min, task.Max, task.ID))
}
os.MkdirAll(task.File, os.ModePerm)
}
go task.savePipe()
for _, layer := range task.Layers {
task.downloadLayer(layer)
}
task.Bar.FinishPrint(fmt.Sprintf("Task %s finished ~", task.ID))
}