-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.go
198 lines (161 loc) · 4.31 KB
/
server.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
package superscribe
import (
"context"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/carpenterscode/superscribe/receipt"
)
type server struct {
Match ExpiringSubscriptions
Listener *MultiEventListener
Fetch SubscriptionFetch
Updater SubscriptionUpdater
mux *http.ServeMux
secret string
server *http.Server
Ticker *time.Ticker
}
func (s server) Start() {
go func() {
now := time.Now()
log.Println("Scan at", now)
s.reviewSubscriptions(s.Match(now))
for tick := range s.Ticker.C {
log.Println("Scan at", tick)
s.reviewSubscriptions(s.Match(tick))
}
}()
go func() {
if err := s.server.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
}
func (s server) Stop() {
s.Ticker.Stop()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := s.server.Shutdown(ctx); err != nil {
log.Printf("Shutdown error %v\n", err)
panic(err)
}
}
func notificationHandler(w http.ResponseWriter, r *http.Request, listener EventListener,
fetch SubscriptionFetch, updater SubscriptionUpdater) {
data, bodyErr := ioutil.ReadAll(r.Body)
if bodyErr != nil {
log.Println("Should have read notification", bodyErr, r)
w.WriteHeader(http.StatusBadRequest)
return
}
var body Notification
if err := json.Unmarshal(data, &body); err != nil {
log.Println("Should have unmarshaled notification", err, r)
w.WriteHeader(http.StatusInternalServerError)
return
}
n := notification{body}
if n.Environment() == Sandbox {
log.Println("Received Sandbox notification")
w.WriteHeader(http.StatusForbidden)
return
}
if err := updater.UpdateWithNotification(n); err != nil {
log.Println(n.OriginalTransactionID(), err)
w.WriteHeader(http.StatusInternalServerError)
return
}
sub, fetchErr := fetch(n.OriginalTransactionID())
if fetchErr != nil {
log.Println(fetchErr, n.OriginalTransactionID())
w.WriteHeader(http.StatusNotFound)
return
}
evt := Event{}
evt.SetNote(n)
evt.SetRevenue(sub.Currency(), sub.Price())
evt.SetUser(sub)
var err error
switch n.Type() {
case Cancel:
err = listener.Refunded(evt)
case Renewal, InteractiveRenewal:
err = listener.Paid(evt)
case InitialBuy:
if n.IsTrialPeriod() {
err = listener.StartedTrial(evt)
} else {
err = listener.Paid(evt)
}
case DidChangeRenewalPref:
err = listener.ChangedAutoRenewProduct(evt)
case DidChangeRenewalStatus:
err = listener.ChangedAutoRenewStatus(evt)
}
if err != nil {
log.Println("Notification handler returns 500", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (s server) reviewSubscriptions(receipts []string) {
for _, receiptData := range receipts {
resp, err := receipt.Validate(s.secret, receiptData)
if err != nil {
log.Println(err, receiptData)
continue
}
if err := s.Updater.UpdateWithReceipt(resp); err != nil {
log.Println(resp.OriginalTransactionID(), err)
continue
}
sub, fetchErr := s.Fetch(resp.OriginalTransactionID())
if fetchErr != nil {
log.Println(fetchErr, resp.OriginalTransactionID())
continue
}
// Check if expiration was pushed back before marking as paid
if !sub.ExpiresAt().Before(resp.ExpiresAt()) {
log.Println("Expiring has not renewed", sub.UserID())
continue
}
evt := Event{}
evt.SetReceiptInfo(resp)
evt.SetRevenue(sub.Currency(), sub.Price())
evt.SetUser(sub)
if err := s.Listener.Paid(evt); err != nil {
log.Println("Expiring Paid event error", err)
}
}
}
func (s server) AddListener(l EventListener) {
s.Listener.Add(l)
}
func (s server) Addr() string {
return s.server.Addr
}
func (s server) HandleFunc(pattern string, handlerFunc http.HandlerFunc) {
s.mux.HandleFunc(pattern, handlerFunc)
}
func NewServer(addr, secret string, matcher ExpiringSubscriptions,
fetch SubscriptionFetch, updater SubscriptionUpdater, interval time.Duration) *server {
mux := http.NewServeMux()
srv := server{
Match: matcher,
Listener: NewMultiEventListener(),
Fetch: fetch,
Updater: updater,
mux: mux,
secret: secret,
server: &http.Server{Addr: addr, Handler: mux},
Ticker: time.NewTicker(interval),
}
mux.HandleFunc("/superscribe", func(w http.ResponseWriter, r *http.Request) {
notificationHandler(w, r, srv.Listener, fetch, updater)
})
return &srv
}