-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
104 lines (79 loc) · 2.29 KB
/
service.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
package main
import (
"github.com/cameliot/alpaca"
"fmt"
)
type SamplerSvc struct {
repo *Repository
playCmd string
}
func NewSamplerSvc(playCmd string, repository *Repository) *SamplerSvc {
svc := &SamplerSvc{
repo: repository,
playCmd: playCmd,
}
return svc
}
func (self *SamplerSvc) handleGroupsListRequest() alpaca.Action {
groups := self.repo.Groups()
return GroupsListSuccess(groups)
}
func (self *SamplerSvc) handleSamplesListRequest(request *SamplesListPayload) alpaca.Action {
samples := self.repo.Samples(request.Group)
return SamplesListSuccess(request.Group, samples)
}
func (self *SamplerSvc) handleSampleStartRequest(dispatch alpaca.Dispatch, request *SampleIdPayload) alpaca.Action {
sample := self.repo.GetSampleById(request.SampleId)
if sample == nil {
return SampleStartError(request.SampleId, 404, fmt.Errorf("Sample not found"))
}
// Start playback
done, err := sample.Start(self.playCmd)
if err != nil {
return SampleStartError(request.SampleId, 501, err)
}
go func() {
// Wait until done, dispatch finished callback
<-done
dispatch(SampleStopSuccess(sample.Id))
}()
return SampleStartSuccess(sample.Id)
}
func (self *SamplerSvc) handleSampleStopRequest(request *SampleIdPayload) alpaca.Action {
if request.SampleId == 0 {
for _, sample := range self.repo.AllSamples() {
sample.Stop() // Just stop do not care
}
return SampleStopSuccess(0)
}
sample := self.repo.GetSampleById(request.SampleId)
if sample == nil {
return SampleStopError(0, 404, fmt.Errorf("Sample not found"))
}
sample.Stop()
return SampleStopSuccess(sample.Id)
}
func (self *SamplerSvc) Handle(actions alpaca.Actions, dispatch alpaca.Dispatch) {
for action := range actions {
switch action.Type {
case GROUPS_LIST_REQUEST:
dispatch(self.handleGroupsListRequest())
break
case SAMPLES_LIST_REQUEST:
var request SamplesListPayload
action.DecodePayload(&request)
dispatch(self.handleSamplesListRequest(&request))
break
case SAMPLE_START_REQUEST:
var request SampleIdPayload
action.DecodePayload(&request)
dispatch(self.handleSampleStartRequest(dispatch, &request))
break
case SAMPLE_STOP_REQUEST:
var request SampleIdPayload
action.DecodePayload(&request)
dispatch(self.handleSampleStopRequest(&request))
break
}
}
}