-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstammtisch.go
128 lines (105 loc) · 1.92 KB
/
stammtisch.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
package main
import (
"bytes"
"fmt"
"launchpad.net/goyaml"
"log"
"os/exec"
"sync"
"time"
)
var (
gitRepo = "/srv/git/website.git"
uniLocation = Location{
Address: "Im Neuenheimer Feld 368, 69120 Heidelberg",
Lat: 49.41759,
Lon: 8.66834,
}
)
type LocationPoller struct {
loc Location
mtx *sync.RWMutex
tick *time.Ticker
done chan struct{}
}
func NewLocationPoller(interval time.Duration) *LocationPoller {
p := &LocationPoller{}
p.mtx = &sync.RWMutex{}
p.tick = time.NewTicker(interval)
p.done = make(chan struct{})
p.Poll()
go func() {
for {
select {
case <-p.tick.C:
p.Poll()
case <-p.done:
return
}
}
}()
return p
}
func (p *LocationPoller) Poll() {
var loc *Location
defer func() {
if loc == nil {
loc = &uniLocation
}
p.mtx.Lock()
p.loc = *loc
p.mtx.Unlock()
}()
site, err := p.GetStammtisch()
if err != nil {
log.Println(err)
return
}
if site == "" {
return
}
loc, err = p.GetLocation(site)
if err != nil {
log.Println(err)
return
}
}
func (p *LocationPoller) Get() Location {
var loc Location
p.mtx.RLock()
loc = p.loc
p.mtx.RUnlock()
return loc
}
func (p *LocationPoller) Stop() {
p.mtx.Lock()
defer p.mtx.Unlock()
p.tick.Stop()
close(p.done)
}
func (p *LocationPoller) GetLocation(site string) (loc *Location, err error) {
buf := new(bytes.Buffer)
cmd := exec.Command("/usr/bin/git", "cat-file", "-p", fmt.Sprintf("master:stammtisch_%s.md", site))
cmd.Dir = gitRepo
cmd.Stdout = buf
err = cmd.Run()
if err != nil {
return nil, err
}
loc = &Location{}
err = goyaml.Unmarshal(buf.Bytes(), loc)
if err != nil {
return nil, err
}
return loc, nil
}
func (p *LocationPoller) GetStammtisch() (site string, err error) {
buf := new(bytes.Buffer)
cmd := exec.Command("/usr/bin/termine", "location")
cmd.Stdout = buf
err = cmd.Run()
if err != nil {
return "", err
}
return string(bytes.TrimSpace(buf.Bytes())), nil
}