-
Notifications
You must be signed in to change notification settings - Fork 19
/
cache.go
113 lines (100 loc) · 2.31 KB
/
cache.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
package terrarium
import (
"fmt"
"image"
"image/png"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
type Cache struct {
URLTemplate string
Directory string
MaxDownloads int
sem chan int
wg *sync.WaitGroup
}
func NewCache(urlTemplate, directory string, maxDownloads int) *Cache {
sem := make(chan int, maxDownloads)
wg := &sync.WaitGroup{}
return &Cache{urlTemplate, directory, maxDownloads, sem, wg}
}
func (cache *Cache) EnsureTile(z, x, y int) {
path := cache.tilePath(z, x, y)
if _, err := os.Stat(path); err == nil {
return
}
cache.wg.Add(1)
go cache.tileWorker(z, x, y)
}
func (cache *Cache) Wait() {
cache.wg.Wait()
}
func (cache *Cache) GetTile(z, x, y int) (*Tile, error) {
im, err := cache.getTileImage(z, x, y)
if err != nil {
return nil, err
}
return newTile(z, x, y, im), nil
}
func (cache *Cache) GetStitchedTile(z, x, y int) (*Tile, error) {
im, err := stitchTile(cache, z, x, y)
if err != nil {
return nil, err
}
return newTile(z, x, y, im), nil
}
func (cache *Cache) getTileImage(z, x, y int) (image.Image, error) {
path := cache.tilePath(z, x, y)
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return png.Decode(file)
}
func (cache *Cache) tileURL(z, x, y int) string {
url := cache.URLTemplate
url = strings.Replace(url, "{z}", strconv.Itoa(z), -1)
url = strings.Replace(url, "{x}", strconv.Itoa(x), -1)
url = strings.Replace(url, "{y}", strconv.Itoa(y), -1)
return url
}
func (cache *Cache) tilePath(z, x, y int) string {
path := fmt.Sprintf("%d/%d/%d.png", z, x, y)
path = filepath.Join(cache.Directory, path)
return path
}
func (cache *Cache) tileDir(z, x, y int) string {
path := cache.tilePath(z, x, y)
dir, _ := filepath.Split(path)
return dir
}
func (cache *Cache) tileWorker(z, x, y int) {
defer cache.wg.Done()
cache.sem <- 1
err := cache.downloadTile(z, x, y)
<-cache.sem
if err != nil {
panic(err)
}
}
func (cache *Cache) downloadTile(z, x, y int) error {
os.MkdirAll(cache.tileDir(z, x, y), os.ModePerm)
path := cache.tilePath(z, x, y)
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
url := cache.tileURL(z, x, y)
response, err := http.Get(url)
defer response.Body.Close()
_, err = io.Copy(file, response.Body)
fmt.Println(path)
return err
}