/
app.go
760 lines (658 loc) · 16.5 KB
/
app.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
package main
import (
crand "crypto/rand"
"crypto/sha1"
"database/sql"
"encoding/binary"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/go-sql-driver/mysql"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
"github.com/labstack/echo"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/middleware"
)
const (
avatarMaxBytes = 1 * 1024 * 1024
)
var (
db *sqlx.DB
ErrBadReqeust = echo.NewHTTPError(http.StatusBadRequest)
)
type Renderer struct {
templates *template.Template
}
func (r *Renderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return r.templates.ExecuteTemplate(w, name, data)
}
func init() {
seedBuf := make([]byte, 8)
crand.Read(seedBuf)
rand.Seed(int64(binary.LittleEndian.Uint64(seedBuf)))
db_host := os.Getenv("ISUBATA_DB_HOST")
if db_host == "" {
db_host = "127.0.0.1"
}
db_port := os.Getenv("ISUBATA_DB_PORT")
if db_port == "" {
db_port = "3306"
}
db_user := os.Getenv("ISUBATA_DB_USER")
if db_user == "" {
db_user = "root"
}
db_password := os.Getenv("ISUBATA_DB_PASSWORD")
if db_password != "" {
db_password = ":" + db_password
}
dsn := fmt.Sprintf("%s%s@tcp(%s:%s)/isubata?parseTime=true&loc=Local&charset=utf8mb4",
db_user, db_password, db_host, db_port)
log.Printf("Connecting to db: %q", dsn)
db, _ = sqlx.Connect("mysql", dsn)
for {
err := db.Ping()
if err == nil {
break
}
log.Println(err)
time.Sleep(time.Second * 3)
}
db.SetMaxOpenConns(20)
db.SetConnMaxLifetime(5 * time.Minute)
log.Printf("Succeeded to connect db.")
}
type User struct {
ID int64 `json:"-" db:"id"`
Name string `json:"name" db:"name"`
Salt string `json:"-" db:"salt"`
Password string `json:"-" db:"password"`
DisplayName string `json:"display_name" db:"display_name"`
AvatarIcon string `json:"avatar_icon" db:"avatar_icon"`
CreatedAt time.Time `json:"-" db:"created_at"`
}
func getUser(userID int64) (*User, error) {
u := User{}
if err := db.Get(&u, "SELECT * FROM user WHERE id = ?", userID); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &u, nil
}
func addMessage(channelID, userID int64, content string) (int64, error) {
res, err := db.Exec(
"INSERT INTO message (channel_id, user_id, content, created_at) VALUES (?, ?, ?, NOW())",
channelID, userID, content)
if err != nil {
return 0, err
}
return res.LastInsertId()
}
type Message struct {
ID int64 `db:"id"`
ChannelID int64 `db:"channel_id"`
UserID int64 `db:"user_id"`
Content string `db:"content"`
CreatedAt time.Time `db:"created_at"`
}
func queryMessages(chanID, lastID int64) ([]Message, error) {
msgs := []Message{}
err := db.Select(&msgs, "SELECT * FROM message WHERE id > ? AND channel_id = ? ORDER BY id DESC LIMIT 100",
lastID, chanID)
return msgs, err
}
func sessUserID(c echo.Context) int64 {
sess, _ := session.Get("session", c)
var userID int64
if x, ok := sess.Values["user_id"]; ok {
userID, _ = x.(int64)
}
return userID
}
func sessSetUserID(c echo.Context, id int64) {
sess, _ := session.Get("session", c)
sess.Options = &sessions.Options{
HttpOnly: true,
MaxAge: 360000,
}
sess.Values["user_id"] = id
sess.Save(c.Request(), c.Response())
}
func ensureLogin(c echo.Context) (*User, error) {
var user *User
var err error
userID := sessUserID(c)
if userID == 0 {
goto redirect
}
user, err = getUser(userID)
if err != nil {
return nil, err
}
if user == nil {
sess, _ := session.Get("session", c)
delete(sess.Values, "user_id")
sess.Save(c.Request(), c.Response())
goto redirect
}
return user, nil
redirect:
c.Redirect(http.StatusSeeOther, "/login")
return nil, nil
}
const LettersAndDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func randomString(n int) string {
b := make([]byte, n)
z := len(LettersAndDigits)
for i := 0; i < n; i++ {
b[i] = LettersAndDigits[rand.Intn(z)]
}
return string(b)
}
func register(name, password string) (int64, error) {
salt := randomString(20)
digest := fmt.Sprintf("%x", sha1.Sum([]byte(salt+password)))
res, err := db.Exec(
"INSERT INTO user (name, salt, password, display_name, avatar_icon, created_at)"+
" VALUES (?, ?, ?, ?, ?, NOW())",
name, salt, digest, name, "default.png")
if err != nil {
return 0, err
}
return res.LastInsertId()
}
// request handlers
func getInitialize(c echo.Context) error {
db.MustExec("DELETE FROM user WHERE id > 1000")
db.MustExec("DELETE FROM image WHERE id > 1001")
db.MustExec("DELETE FROM channel WHERE id > 10")
db.MustExec("DELETE FROM message WHERE id > 10000")
db.MustExec("DELETE FROM haveread")
return c.String(204, "")
}
func getIndex(c echo.Context) error {
userID := sessUserID(c)
if userID != 0 {
return c.Redirect(http.StatusSeeOther, "/channel/1")
}
return c.Render(http.StatusOK, "index", map[string]interface{}{
"ChannelID": nil,
})
}
type ChannelInfo struct {
ID int64 `db:"id"`
Name string `db:"name"`
Description string `db:"description"`
UpdatedAt time.Time `db:"updated_at"`
CreatedAt time.Time `db:"created_at"`
}
func getChannel(c echo.Context) error {
user, err := ensureLogin(c)
if user == nil {
return err
}
cID, err := strconv.Atoi(c.Param("channel_id"))
if err != nil {
return err
}
channels := []ChannelInfo{}
err = db.Select(&channels, "SELECT * FROM channel ORDER BY id")
if err != nil {
return err
}
var desc string
for _, ch := range channels {
if ch.ID == int64(cID) {
desc = ch.Description
break
}
}
return c.Render(http.StatusOK, "channel", map[string]interface{}{
"ChannelID": cID,
"Channels": channels,
"User": user,
"Description": desc,
})
}
func getRegister(c echo.Context) error {
return c.Render(http.StatusOK, "register", map[string]interface{}{
"ChannelID": 0,
"Channels": []ChannelInfo{},
"User": nil,
})
}
func postRegister(c echo.Context) error {
name := c.FormValue("name")
pw := c.FormValue("password")
if name == "" || pw == "" {
return ErrBadReqeust
}
userID, err := register(name, pw)
if err != nil {
if merr, ok := err.(*mysql.MySQLError); ok {
if merr.Number == 1062 { // Duplicate entry xxxx for key zzzz
return c.NoContent(http.StatusConflict)
}
}
return err
}
sessSetUserID(c, userID)
return c.Redirect(http.StatusSeeOther, "/")
}
func getLogin(c echo.Context) error {
return c.Render(http.StatusOK, "login", map[string]interface{}{
"ChannelID": 0,
"Channels": []ChannelInfo{},
"User": nil,
})
}
func postLogin(c echo.Context) error {
name := c.FormValue("name")
pw := c.FormValue("password")
if name == "" || pw == "" {
return ErrBadReqeust
}
var user User
err := db.Get(&user, "SELECT * FROM user WHERE name = ?", name)
if err == sql.ErrNoRows {
return echo.ErrForbidden
} else if err != nil {
return err
}
digest := fmt.Sprintf("%x", sha1.Sum([]byte(user.Salt+pw)))
if digest != user.Password {
return echo.ErrForbidden
}
sessSetUserID(c, user.ID)
return c.Redirect(http.StatusSeeOther, "/")
}
func getLogout(c echo.Context) error {
sess, _ := session.Get("session", c)
delete(sess.Values, "user_id")
sess.Save(c.Request(), c.Response())
return c.Redirect(http.StatusSeeOther, "/")
}
func postMessage(c echo.Context) error {
user, err := ensureLogin(c)
if user == nil {
return err
}
message := c.FormValue("message")
if message == "" {
return echo.ErrForbidden
}
var chanID int64
if x, err := strconv.Atoi(c.FormValue("channel_id")); err != nil {
return echo.ErrForbidden
} else {
chanID = int64(x)
}
if _, err := addMessage(chanID, user.ID, message); err != nil {
return err
}
return c.NoContent(204)
}
func jsonifyMessage(m Message) (map[string]interface{}, error) {
u := User{}
err := db.Get(&u, "SELECT name, display_name, avatar_icon FROM user WHERE id = ?",
m.UserID)
if err != nil {
return nil, err
}
r := make(map[string]interface{})
r["id"] = m.ID
r["user"] = u
r["date"] = m.CreatedAt.Format("2006/01/02 15:04:05")
r["content"] = m.Content
return r, nil
}
func getMessage(c echo.Context) error {
userID := sessUserID(c)
if userID == 0 {
return c.NoContent(http.StatusForbidden)
}
chanID, err := strconv.ParseInt(c.QueryParam("channel_id"), 10, 64)
if err != nil {
return err
}
lastID, err := strconv.ParseInt(c.QueryParam("last_message_id"), 10, 64)
if err != nil {
return err
}
messages, err := queryMessages(chanID, lastID)
if err != nil {
return err
}
response := make([]map[string]interface{}, 0)
for i := len(messages) - 1; i >= 0; i-- {
m := messages[i]
r, err := jsonifyMessage(m)
if err != nil {
return err
}
response = append(response, r)
}
if len(messages) > 0 {
_, err := db.Exec("INSERT INTO haveread (user_id, channel_id, message_id, updated_at, created_at)"+
" VALUES (?, ?, ?, NOW(), NOW())"+
" ON DUPLICATE KEY UPDATE message_id = ?, updated_at = NOW()",
userID, chanID, messages[0].ID, messages[0].ID)
if err != nil {
return err
}
}
return c.JSON(http.StatusOK, response)
}
func queryChannels() ([]int64, error) {
res := []int64{}
err := db.Select(&res, "SELECT id FROM channel")
return res, err
}
func queryHaveRead(userID, chID int64) (int64, error) {
type HaveRead struct {
UserID int64 `db:"user_id"`
ChannelID int64 `db:"channel_id"`
MessageID int64 `db:"message_id"`
UpdatedAt time.Time `db:"updated_at"`
CreatedAt time.Time `db:"created_at"`
}
h := HaveRead{}
err := db.Get(&h, "SELECT * FROM haveread WHERE user_id = ? AND channel_id = ?",
userID, chID)
if err == sql.ErrNoRows {
return 0, nil
} else if err != nil {
return 0, err
}
return h.MessageID, nil
}
func fetchUnread(c echo.Context) error {
userID := sessUserID(c)
if userID == 0 {
return c.NoContent(http.StatusForbidden)
}
time.Sleep(time.Second)
channels, err := queryChannels()
if err != nil {
return err
}
resp := []map[string]interface{}{}
for _, chID := range channels {
lastID, err := queryHaveRead(userID, chID)
if err != nil {
return err
}
var cnt int64
if lastID > 0 {
err = db.Get(&cnt,
"SELECT COUNT(*) as cnt FROM message WHERE channel_id = ? AND ? < id",
chID, lastID)
} else {
err = db.Get(&cnt,
"SELECT COUNT(*) as cnt FROM message WHERE channel_id = ?",
chID)
}
if err != nil {
return err
}
r := map[string]interface{}{
"channel_id": chID,
"unread": cnt}
resp = append(resp, r)
}
return c.JSON(http.StatusOK, resp)
}
func getHistory(c echo.Context) error {
chID, err := strconv.ParseInt(c.Param("channel_id"), 10, 64)
if err != nil || chID <= 0 {
return ErrBadReqeust
}
user, err := ensureLogin(c)
if user == nil {
return err
}
var page int64
pageStr := c.QueryParam("page")
if pageStr == "" {
page = 1
} else {
page, err = strconv.ParseInt(pageStr, 10, 64)
if err != nil || page < 1 {
return ErrBadReqeust
}
}
const N = 20
var cnt int64
err = db.Get(&cnt, "SELECT COUNT(*) as cnt FROM message WHERE channel_id = ?", chID)
if err != nil {
return err
}
maxPage := int64(cnt+N-1) / N
if maxPage == 0 {
maxPage = 1
}
if page > maxPage {
return ErrBadReqeust
}
messages := []Message{}
err = db.Select(&messages,
"SELECT * FROM message WHERE channel_id = ? ORDER BY id DESC LIMIT ? OFFSET ?",
chID, N, (page-1)*N)
if err != nil {
return err
}
mjson := make([]map[string]interface{}, 0)
for i := len(messages) - 1; i >= 0; i-- {
r, err := jsonifyMessage(messages[i])
if err != nil {
return err
}
mjson = append(mjson, r)
}
channels := []ChannelInfo{}
err = db.Select(&channels, "SELECT * FROM channel ORDER BY id")
if err != nil {
return err
}
return c.Render(http.StatusOK, "history", map[string]interface{}{
"ChannelID": chID,
"Channels": channels,
"Messages": mjson,
"MaxPage": maxPage,
"Page": page,
"User": user,
})
}
func getProfile(c echo.Context) error {
self, err := ensureLogin(c)
if self == nil {
return err
}
channels := []ChannelInfo{}
err = db.Select(&channels, "SELECT * FROM channel ORDER BY id")
if err != nil {
return err
}
userName := c.Param("user_name")
var other User
err = db.Get(&other, "SELECT * FROM user WHERE name = ?", userName)
if err == sql.ErrNoRows {
return echo.ErrNotFound
}
if err != nil {
return err
}
return c.Render(http.StatusOK, "profile", map[string]interface{}{
"ChannelID": 0,
"Channels": channels,
"User": self,
"Other": other,
"SelfProfile": self.ID == other.ID,
})
}
func getAddChannel(c echo.Context) error {
self, err := ensureLogin(c)
if self == nil {
return err
}
channels := []ChannelInfo{}
err = db.Select(&channels, "SELECT * FROM channel ORDER BY id")
if err != nil {
return err
}
return c.Render(http.StatusOK, "add_channel", map[string]interface{}{
"ChannelID": 0,
"Channels": channels,
"User": self,
})
}
func postAddChannel(c echo.Context) error {
self, err := ensureLogin(c)
if self == nil {
return err
}
name := c.FormValue("name")
desc := c.FormValue("description")
if name == "" || desc == "" {
return ErrBadReqeust
}
res, err := db.Exec(
"INSERT INTO channel (name, description, updated_at, created_at) VALUES (?, ?, NOW(), NOW())",
name, desc)
if err != nil {
return err
}
lastID, _ := res.LastInsertId()
return c.Redirect(http.StatusSeeOther,
fmt.Sprintf("/channel/%v", lastID))
}
func postProfile(c echo.Context) error {
self, err := ensureLogin(c)
if self == nil {
return err
}
avatarName := ""
var avatarData []byte
if fh, err := c.FormFile("avatar_icon"); err == http.ErrMissingFile {
// no file upload
} else if err != nil {
return err
} else {
dotPos := strings.LastIndexByte(fh.Filename, '.')
if dotPos < 0 {
return ErrBadReqeust
}
ext := fh.Filename[dotPos:]
switch ext {
case ".jpg", ".jpeg", ".png", ".gif":
break
default:
return ErrBadReqeust
}
file, err := fh.Open()
if err != nil {
return err
}
avatarData, _ = ioutil.ReadAll(file)
file.Close()
if len(avatarData) > avatarMaxBytes {
return ErrBadReqeust
}
avatarName = fmt.Sprintf("%x%s", sha1.Sum(avatarData), ext)
}
if avatarName != "" && len(avatarData) > 0 {
_, err := db.Exec("INSERT INTO image (name, data) VALUES (?, ?)", avatarName, avatarData)
if err != nil {
return err
}
_, err = db.Exec("UPDATE user SET avatar_icon = ? WHERE id = ?", avatarName, self.ID)
if err != nil {
return err
}
}
if name := c.FormValue("display_name"); name != "" {
_, err := db.Exec("UPDATE user SET display_name = ? WHERE id = ?", name, self.ID)
if err != nil {
return err
}
}
return c.Redirect(http.StatusSeeOther, "/")
}
func getIcon(c echo.Context) error {
var name string
var data []byte
err := db.QueryRow("SELECT name, data FROM image WHERE name = ?",
c.Param("file_name")).Scan(&name, &data)
if err == sql.ErrNoRows {
return echo.ErrNotFound
}
if err != nil {
return err
}
mime := ""
switch true {
case strings.HasSuffix(name, ".jpg"), strings.HasSuffix(name, ".jpeg"):
mime = "image/jpeg"
case strings.HasSuffix(name, ".png"):
mime = "image/png"
case strings.HasSuffix(name, ".gif"):
mime = "image/gif"
default:
return echo.ErrNotFound
}
return c.Blob(http.StatusOK, mime, data)
}
func tAdd(a, b int64) int64 {
return a + b
}
func tRange(a, b int64) []int64 {
r := make([]int64, b-a+1)
for i := int64(0); i <= (b - a); i++ {
r[i] = a + i
}
return r
}
func main() {
e := echo.New()
funcs := template.FuncMap{
"add": tAdd,
"xrange": tRange,
}
e.Renderer = &Renderer{
templates: template.Must(template.New("").Funcs(funcs).ParseGlob("views/*.html")),
}
e.Use(session.Middleware(sessions.NewCookieStore([]byte("secretonymoris"))))
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "request:\"${method} ${uri}\" status:${status} latency:${latency} (${latency_human}) bytes:${bytes_out}\n",
}))
e.Use(middleware.Static("../public"))
e.GET("/initialize", getInitialize)
e.GET("/", getIndex)
e.GET("/register", getRegister)
e.POST("/register", postRegister)
e.GET("/login", getLogin)
e.POST("/login", postLogin)
e.GET("/logout", getLogout)
e.GET("/channel/:channel_id", getChannel)
e.GET("/message", getMessage)
e.POST("/message", postMessage)
e.GET("/fetch", fetchUnread)
e.GET("/history/:channel_id", getHistory)
e.GET("/profile/:user_name", getProfile)
e.POST("/profile", postProfile)
e.GET("add_channel", getAddChannel)
e.POST("add_channel", postAddChannel)
e.GET("/icons/:file_name", getIcon)
e.Start(":5000")
}