/
handlers.go
349 lines (306 loc) · 7.99 KB
/
handlers.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"fmt"
"encoding/json"
"net/http"
"strings"
"errors"
"log"
"strconv"
"sort"
"github.com/goods/httpbuf"
"github.com/samlecuyer/redactomat"
"code.google.com/p/rsc/imap"
)
type handler func(http.ResponseWriter, *http.Request, *Context) error
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
//create the context
ctx, err := NewContext(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//run the handler and grab the error, and report it
buf := new(httpbuf.Buffer)
err = h(buf, req, ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//save the session
if err = ctx.Session.Save(req, buf); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//apply the buffered response to the writer
buf.Apply(w)
}
func root(w http.ResponseWriter, r *http.Request, ctx *Context) error {
if _, err := ctx.GetClient(); err == nil {
http.Redirect(w, r, "/mail", http.StatusSeeOther)
} else {
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
return nil
}
func Logout(w http.ResponseWriter, r *http.Request, ctx *Context) error {
http.Redirect(w, r, "/", http.StatusSeeOther)
return ctx.Logout()
}
func LoginForm(w http.ResponseWriter, r *http.Request, ctx *Context) error {
return T("login.html").Execute(w, map[string]interface{}{
"ctx": ctx,
})
}
func LoginHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {
host := r.FormValue("host")
name := r.FormValue("username")
pass := r.FormValue("password")
_, err := ctx.PerformLogin(host, name, pass)
w.Header().Add("Location", "/mail")
return err
}
func InboxHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {
client, _ := ctx.GetClient()
return T("inbox.html").Execute(w, map[string]interface{}{
"ctx": ctx,
"bxs": client.Boxes(),
})
}
func max(a, b uint32) uint32 {
if a > b { return a }
return b
}
func minusf(a, b uint32) uint32 {
if a - b > a { return 0 }
return a - b
}
type Message struct {
Uid string
Hdr *imap.MsgHdr
Seen bool
BoxName string
}
// TODO: more than just the last 50 of the inbox
// TODO: offline mode. I think google throttles my requests
// after spending the day killing and restarting the server
// TODO: possibly split the imap client into a separate process
func MessagesHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {
client, err := ctx.GetClient()
if err != nil { return err }
var mailbox *imap.Box
boxName := r.URL.Query().Get("box")
log.Println(r.URL)
if boxName == "" {
mailbox = client.Inbox()
} else {
mailbox = client.Box(boxName)
}
if mailbox == nil {
w.WriteHeader(404)
return nil
}
mailbox.Check()
msgs := mailbox.Msgs()
n := len(msgs)
var headers []*Message
if n > 0 {
mn := max(1, (minusf(uint32(n), 50)))
headers = make([]*Message, uint32(n) - mn)
for i, msg := range msgs[mn:] {
headers[i] = &Message{
fmt.Sprintf("%v",msg.UID),
msg.Hdr,
(msg.Flags & imap.FlagSeen) == imap.FlagSeen,
msg.Box.Name,
}
}
} else {
headers = make([]*Message, 0)
}
b, err := json.Marshal(headers)
if err != nil {
return err
}
w.WriteHeader(200)
w.Write(b)
return nil
}
func handleMixed(msg *imap.MsgPart) (parts []*MessagePart) {
parts = make([]*MessagePart, len(msg.Child))
for i, part := range msg.Child {
parts[i] = &MessagePart{ ID: part.ID, Name: part.Name, Type: part.Type }
switch part.Type {
case "text/plain":
parts[i].Contents = string(part.Text())
case "text/html":
parts[i].Contents, _ = redactomat.RedactString(string(part.Text()))
case "multipart/alternative":
parts[i].Children = handleAlternative(msg)
}
}
return parts
}
func handleAlternative(msg *imap.MsgPart) (parts []*MessagePart) {
parts = make([]*MessagePart, len(msg.Child))
for i, part := range msg.Child {
parts[i] = &MessagePart{ ID: part.ID, Name: part.Name, Type: part.Type }
switch part.Type {
case "text/plain":
parts[i].Contents = string(part.Text())
case "text/html":
parts[i].Contents, _ = redactomat.RedactString(string(part.Text()))
}
}
return parts
}
func handleMail(msg *imap.MsgPart) (parts *MessagePart) {
parts = &MessagePart{ ID: msg.ID, Name: msg.Name, Type: msg.Type }
switch msg.Type {
case "text/plain":
parts.Contents = string(msg.Text())
case "text/html":
parts.Contents, _ = redactomat.RedactString(string(msg.Text()))
case "multipart/alternative":
parts.Children = handleAlternative(msg)
case "multipart/mixed":
parts.Children = handleMixed(msg)
}
return parts
}
type MessagePart struct {
ID, Name, Type string
Contents string
Children []*MessagePart
}
func MessageHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {
client, err := ctx.GetClient()
if err != nil { return err }
uidstr := r.URL.Query().Get(":id")
var mailbox *imap.Box
boxName := r.URL.Query().Get("box")
if boxName == "" {
mailbox = client.Inbox()
} else {
mailbox = client.Box(boxName)
}
if mailbox == nil {
w.WriteHeader(404)
return nil
}
mailbox.Check()
msgs := mailbox.Msgs()
uid, err := strconv.ParseUint(uidstr, 10, 64)
if err != nil {
return err
}
exists := len(msgs)
entryId := sort.Search(exists,
func(i int) bool {
return msgs[i].UID >= uid
})
if entryId < exists && msgs[entryId] != nil {
parts := handleMail(&(msgs[entryId].Root))
b, err := json.Marshal(parts)
if err != nil {
return err
}
w.WriteHeader(200)
w.Write(b)
} else {
w.WriteHeader(404)
}
return nil
}
func ArchiveHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {
client, err := ctx.GetClient()
if err != nil { return err }
uidstr := r.URL.Query().Get(":id")
boxname := r.URL.Query().Get("box")
mailbox := client.Box(boxname)
if mailbox == nil {
w.WriteHeader(404)
return nil
}
mailbox.Check()
msgs := mailbox.Msgs()
uid, err := strconv.ParseUint(uidstr, 10, 64)
if err != nil {
return err
}
exists := len(msgs)
entryId := sort.Search(exists,
func(i int) bool {
return msgs[i].UID >= uid
})
if entryId < exists && msgs[entryId] != nil {
allMail := client.Box("[Gmail]/All Mail")
if allMail == nil {
return errors.New("Could not find all mail")
}
err = allMail.Copy(msgs[entryId:entryId+1])
if err != nil { return err }
err = mailbox.Delete(msgs[entryId:entryId+1])
if err != nil { return err }
w.WriteHeader(200)
} else {
w.WriteHeader(404)
}
return nil
}
func DeleteHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {
client, err := ctx.GetClient()
if err != nil { return err }
uidstr := r.URL.Query().Get(":id")
boxname := r.URL.Query().Get(":box")
mailbox := client.Box(boxname)
if mailbox == nil {
w.WriteHeader(404)
return nil
}
mailbox.Check()
msgs := mailbox.Msgs()
uid, err := strconv.ParseUint(uidstr, 10, 64)
if err != nil {
return err
}
exists := len(msgs)
entryId := sort.Search(exists,
func(i int) bool {
return msgs[i].UID >= uid
})
if entryId < exists && msgs[entryId] != nil {
err = mailbox.Delete(msgs[entryId:entryId+1])
if err != nil { return err }
w.WriteHeader(200)
} else {
w.WriteHeader(404)
}
return nil
}
func AttachmentHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {
client, err := ctx.GetClient()
if err != nil { return err }
mailbox := client.Inbox()
mailbox.Check()
msgs := mailbox.Msgs()
msgIdStr := r.URL.Query().Get(":msg")
attId := r.URL.Query().Get(":id")
uid, err := strconv.ParseUint(msgIdStr, 10, 64)
if err != nil { return err }
entryId := sort.Search(len(msgs), func(i int) bool { return msgs[i].UID >= uid })
root := &(msgs[entryId].Root)
var attachment []byte
var contenttype, dispo string
if strings.Contains(root.Type, "multipart/mixed") {
for _, part := range root.Child {
if part.ID == attId {
attachment = part.Text()
contenttype = part.Type
dispo = fmt.Sprintf("inline; filename=\"%s\"", part.Name)
}
}
}
w.Header().Add("Content-Type", contenttype)
w.Header().Add("Content-Disposition", dispo)
w.WriteHeader(200)
w.Write(attachment)
return nil
}