-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
208 lines (173 loc) · 4.51 KB
/
main.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
package main
import (
"context"
"fmt"
"math/rand"
"net/http"
"os"
"regexp"
"time"
"github.com/jhillyerd/enmime"
"go.mercari.io/datastore"
"go.mercari.io/datastore/aedatastore"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
gaemail "google.golang.org/appengine/mail"
)
func main() {
to := os.Getenv("WI2_GUESTCODE_SERVER_TO")
if to == "" {
panic("WI2_GUESTCODE_SERVER_TO is not set")
}
a := &app{
to: to,
}
a.handle(http.DefaultServeMux)
appengine.Main()
}
type codeEntity struct {
Code string `datastore:"code"`
Used bool `datastore:"used"`
Created time.Time `datastore:"created"`
}
type app struct {
to string
}
func (a *app) handle(mux *http.ServeMux) {
// Request code
mux.HandleFunc("/code", func(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
client, err := aedatastore.FromContext(ctx)
if err != nil {
log.Errorf(ctx, "%v", err)
return
}
defer client.Close()
var code *codeEntity
if _, err := client.RunInTransaction(ctx, func(tx datastore.Transaction) error {
var codes []*codeEntity
keys, err := client.GetAll(ctx, client.NewQuery("code").Transaction(tx).Ancestor(dcsKey(client)).Filter("used =", false).Order("-created").Limit(1), &codes)
if err != nil {
return err
}
if len(codes) == 0 || codes[0].Used {
log.Infof(ctx, "could not get code")
w.Write([]byte("wait please"))
return nil
}
log.Infof(ctx, "%#+v", codes)
code = codes[0]
key := keys[0]
code.Used = true
if _, err := tx.Put(key, code); err != nil {
return err
}
log.Infof(ctx, "updated")
return nil
}); err != nil {
log.Errorf(ctx, "%v", err)
return
}
if code != nil {
w.Write([]byte(code.Code))
}
})
// Check code availability cron
mux.HandleFunc("/check", func(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
client, err := aedatastore.FromContext(ctx)
if err != nil {
log.Errorf(ctx, "%v", err)
return
}
defer client.Close()
var codes []*codeEntity
if _, err := client.GetAll(ctx, client.NewQuery("code").Ancestor(dcsKey(client)).Filter("used =", false).Order("-created").Limit(1), &codes); err != nil {
log.Errorf(ctx, "%v", err)
}
log.Infof(ctx, "%#+v", codes)
if len(codes) > 0 && !codes[0].Used {
log.Infof(ctx, "code available")
return
}
if err := a.sendMail(ctx); err != nil {
log.Errorf(ctx, "%v", err)
return
}
w.Write([]byte("sent"))
})
// Receive mail
mux.HandleFunc("/_ah/mail/", func(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
client, err := aedatastore.FromContext(ctx)
if err != nil {
log.Errorf(ctx, "%v", err)
return
}
defer client.Close()
env, err := enmime.ReadEnvelope(r.Body)
if err != nil {
log.Errorf(ctx, "%v", err)
return
}
log.Infof(ctx, "Received mail: %v", env.Text)
code := regexp.MustCompile(`DCS[\w\d]+`).FindString(env.Text)
if code == "" {
log.Infof(ctx, "No code in the reply. Retrying to send mail.")
if err := a.sendMail(ctx); err != nil {
log.Errorf(ctx, "%v", err)
return
}
} else {
count, err := client.Count(ctx, client.NewQuery("code").Filter("code =", code).Ancestor(dcsKey(client)).Limit(1))
if err != nil {
log.Errorf(ctx, "error on counting the code: %v", err)
return
}
if count == 1 {
log.Errorf(ctx, "Received old code. Retrying to send mail.")
if err := a.sendMail(ctx); err != nil {
log.Errorf(ctx, "%v", err)
}
return
}
k := client.IncompleteKey("code", dcsKey(client))
if _, err := client.Put(ctx, k, &codeEntity{
Code: code,
Used: false,
Created: time.Now(),
}); err != nil {
log.Errorf(ctx, "%v", err)
return
}
log.Infof(ctx, "put new record")
}
})
}
func (a *app) sendMail(ctx context.Context) error {
if err := gaemail.Send(ctx, a.composeMessage(ctx)); err != nil {
return err
}
return nil
}
func (a *app) composeMessage(ctx context.Context) *gaemail.Message {
return &gaemail.Message{
Sender: fmt.Sprintf("<%s@%s.appspotmail.com>", randstr(), appengine.AppID(ctx)),
To: []string{a.to},
Subject: "",
Body: "",
}
}
func randstr() string {
letters := []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
str := make([]byte, 0, 8)
rand.Seed(time.Now().Unix())
for i := 0; i < 8; i++ {
li := rand.Intn(len(letters))
str = append(str, letters[li])
}
return string(str)
}
func dcsKey(client datastore.Client) datastore.Key {
return client.NameKey("code", "dcs", nil)
}