forked from catatsuy/private-isu
/
app.go
1585 lines (1337 loc) · 37.6 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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
crand "crypto/rand"
"crypto/sha512"
"encoding/hex"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"regexp"
// "runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/coocood/freecache"
"github.com/go-chi/chi/v5"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
"github.com/sugawarayuuta/sonnet"
// profiler
_ "net/http/pprof"
)
var (
db *sqlx.DB
deletedUserIDs []int
cache *freecache.Cache
)
const (
postsPerPage = 20
ISO8601Format = "2006-01-02T15:04:05-07:00"
UploadLimit = 10 * 1024 * 1024 // 10mb
)
type User struct {
ID int `db:"id"`
AccountName string `db:"account_name"`
Passhash string `db:"passhash"`
Authority int `db:"authority"`
DelFlg int `db:"del_flg"`
CreatedAt time.Time `db:"created_at"`
}
type Post struct {
ID int `db:"id"`
UserID int `db:"user_id"`
Imgdata []byte `db:"imgdata"`
Body string `db:"body"`
Mime string `db:"mime"`
CreatedAt time.Time `db:"created_at"`
CommentCount int
Comments []Comment
User User `db:"users"`
CSRFToken string
Rendered RenderedPost
}
type RenderedPost struct {
ID []byte
CreatedAt []byte
UserAccountName []byte
ImageURL []byte
Body []byte
CommentCount []byte
}
type Comment struct {
ID int `db:"id"`
PostID int `db:"post_id"`
UserID int `db:"user_id"`
Comment string `db:"comment"`
CreatedAt time.Time `db:"created_at"`
User User `db:"users"`
Rendered RenderedComment
}
type RenderedComment struct {
UserAccountName []byte
Comment []byte
}
func init() {
cache = freecache.NewCache(50 * 1024 * 1024)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func dbInitialize() {
sqls := []string{
"DELETE FROM users WHERE id > 1000",
"DELETE FROM posts WHERE id > 10000",
"DELETE FROM comments WHERE id > 100000",
// initialize posts.comment_count
"UPDATE posts SET comment_count = (SELECT COUNT(*) FROM comments WHERE comments.post_id = posts.id)",
}
for _, sql := range sqls {
db.Exec(sql)
}
query := "SELECT id FROM users WHERE id % 50 = 0"
err := db.Select(&deletedUserIDs, query)
if err != nil {
log.Print(err)
return
}
}
func tryLogin(accountName, password string) *User {
u := User{}
query := "SELECT * FROM users WHERE account_name = ? AND id NOT IN (?)"
query, args, err := sqlx.In(query, accountName, deletedUserIDs)
if err != nil {
log.Print(err)
return nil
}
query = db.Rebind(query)
err = db.Get(&u, query, args...)
if err != nil {
return nil
}
if calculatePasshash(u.AccountName, password) == u.Passhash {
return &u
} else {
return nil
}
}
func validateUser(accountName, password string) bool {
return regexp.MustCompile(`\A[0-9a-zA-Z_]{3,}\z`).MatchString(accountName) &&
regexp.MustCompile(`\A[0-9a-zA-Z_]{6,}\z`).MatchString(password)
}
func digest(src string) string {
h := sha512.New()
h.Write([]byte(src))
return fmt.Sprintf("%x", h.Sum(nil))
}
func calculateSalt(accountName string) string {
return digest(accountName)
}
func calculatePasshash(accountName, password string) string {
return digest(password + ":" + calculateSalt(accountName))
}
// ref: https://github.com/methane/pixiv-private-isucon-2016/tree/master
type Session struct {
Key string
UserID int
AccountName string
Authority int
CSRFToken string
Flash string
}
type SessionStore struct {
sync.Mutex
store map[string]*Session
}
var sessionStore = SessionStore{
store: make(map[string]*Session),
}
const sessionName = "isucon_go_session"
func (store *SessionStore) Get(r *http.Request) *Session {
cookie, _ := r.Cookie(sessionName)
if cookie == nil {
return &Session{}
}
key := cookie.Value
store.Lock()
s := store.store[key]
store.Unlock()
if s == nil {
s = &Session{}
}
return s
}
func (store *SessionStore) Set(w http.ResponseWriter, sess *Session) {
key := sess.Key
if key == "" {
b := make([]byte, 8)
crand.Read(b)
key = hex.EncodeToString(b)
sess.Key = key
}
cookie := sessions.NewCookie(sessionName, key, &sessions.Options{})
http.SetCookie(w, cookie)
store.Lock()
store.store[key] = sess
store.Unlock()
}
func getSession(r *http.Request) *Session {
return sessionStore.Get(r)
}
func getSessionUser(r *http.Request) User {
sess := getSession(r)
return User{
ID: sess.UserID,
AccountName: sess.AccountName,
Authority: sess.Authority,
}
}
func getFlash(w http.ResponseWriter, r *http.Request) string {
sess := getSession(r)
flash := sess.Flash
sess.Flash = ""
sessionStore.Set(w, sess)
return flash
}
func setFlash(w http.ResponseWriter, r *http.Request, flash string) {
sess := getSession(r)
sess.Flash = flash
sessionStore.Set(w, sess)
}
var (
commentM sync.Mutex
commentStore map[int][]Comment = make(map[int][]Comment)
)
func getCommentsLocked(postID int) []Comment {
if cs, ok := commentStore[postID]; ok {
return cs
}
var cs []Comment
query := `
SELECT comments.post_id, comments.comment, users.account_name AS "users.account_name"
FROM comments
JOIN users ON comments.user_id = users.id
WHERE post_id = ?
ORDER BY comments.created_at
`
err := db.Select(&cs, query, postID)
if err != nil {
log.Print(err)
return cs
}
for i := 0; i < len(cs); i++ {
cs[i].Rendered = RenderedComment{
UserAccountName: []byte(cs[i].User.AccountName),
Comment: []byte(cs[i].Comment),
}
}
commentStore[postID] = cs
return cs
}
func getComments(postID int) []Comment {
commentM.Lock()
defer commentM.Unlock()
return getCommentsLocked(postID)
}
func appendComment(c Comment) {
commentM.Lock()
cs := getCommentsLocked(c.PostID)
c.Rendered = RenderedComment{
UserAccountName: []byte(c.User.AccountName),
Comment: []byte(c.Comment),
}
commentStore[c.PostID] = append(cs, c)
commentM.Unlock()
postM.Lock()
getIndexPostsLocked(true, true)
postM.Unlock()
}
func makePosts(results []Post, csrfToken string, allComments bool) ([]Post, error) {
posts := make([]Post, 0, len(results))
for _, p := range results {
comments := getComments(p.ID)
p.CommentCount = len(comments)
if !allComments && len(comments) > 3 {
comments = comments[len(comments)-3:]
}
p.Comments = comments
p.CSRFToken = csrfToken
posts = append(posts, p)
}
return posts, nil
}
func imageURL(p Post) string {
ext := ""
if p.Mime == "image/jpeg" {
ext = ".jpg"
} else if p.Mime == "image/png" {
ext = ".png"
} else if p.Mime == "image/gif" {
ext = ".gif"
}
return "/image/" + strconv.Itoa(p.ID) + ext
}
func isLogin(u User) bool {
return u.ID != 0
}
func getCSRFToken(r *http.Request) string {
session := getSession(r)
return session.CSRFToken
}
func secureRandomStr(b int) string {
k := make([]byte, b)
if _, err := crand.Read(k); err != nil {
panic(err)
}
return fmt.Sprintf("%x", k)
}
func getTemplPath(filename string) string {
return path.Join("templates", filename)
}
func getInitialize(w http.ResponseWriter, r *http.Request) {
dbInitialize()
w.WriteHeader(http.StatusOK)
}
func getLogin(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
if isLogin(me) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
flash := getFlash(w, r)
templateLayout(
w,
me,
func(w io.Writer) {
templateLogin(w, flash)
},
)
}
var templateLoginByteArray = [...][]byte{
[]byte(`<div class="header"> <h1>ログイン</h1> </div>`),
[]byte(`<div id="notice-message" class="alert alert-danger">`),
[]byte(`</div>`),
[]byte(`<div class="submit"> <form method="post" action="/login"> <div class="form-account-name"> <span>アカウント名</span> <input type="text" name="account_name"> </div> <div class="form-password"> <span>パスワード</span> <input type="password" name="password"> </div> <div class="form-submit"> <input type="submit" name="submit" value="submit"> </div> </form> </div> <div class="isu-register"> <a href="/register">ユーザー登録</a> </div>`),
}
func templateLogin(w io.Writer, flash string) {
w.Write(templateLoginByteArray[0])
if len(flash) > 0 {
w.Write(templateLoginByteArray[1])
w.Write([]byte(flash))
w.Write(templateLoginByteArray[2])
}
w.Write(templateLoginByteArray[3])
}
func postLogin(w http.ResponseWriter, r *http.Request) {
if isLogin(getSessionUser(r)) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
u := tryLogin(r.FormValue("account_name"), r.FormValue("password"))
time.Sleep(time.Millisecond * 200)
if u != nil {
session := Session{
UserID: u.ID,
AccountName: u.AccountName,
Authority: u.Authority,
CSRFToken: secureRandomStr(16),
}
sessionStore.Set(w, &session)
http.Redirect(w, r, "/", http.StatusFound)
} else {
setFlash(w, r, "アカウント名かパスワードが間違っています")
http.Redirect(w, r, "/login", http.StatusFound)
}
}
func getRegister(w http.ResponseWriter, r *http.Request) {
if isLogin(getSessionUser(r)) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
template.Must(template.ParseFiles(
getTemplPath("layout.html"),
getTemplPath("register.html")),
).Execute(w, struct {
Me User
Flash string
}{User{}, getFlash(w, r)})
}
func postRegister(w http.ResponseWriter, r *http.Request) {
if isLogin(getSessionUser(r)) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
accountName, password := r.FormValue("account_name"), r.FormValue("password")
validated := validateUser(accountName, password)
if !validated {
setFlash(w, r, "アカウント名は3文字以上、パスワードは6文字以上である必要があります")
http.Redirect(w, r, "/register", http.StatusFound)
return
}
exists := 0
// ユーザーが存在しない場合はエラーになるのでエラーチェックはしない
db.Get(&exists, "SELECT 1 FROM users WHERE account_name = ?", accountName)
if exists == 1 {
setFlash(w, r, "アカウント名がすでに使われています")
http.Redirect(w, r, "/register", http.StatusFound)
return
}
query := "INSERT INTO users (account_name, passhash) VALUES (?,?)"
result, err := db.Exec(query, accountName, calculatePasshash(accountName, password))
if err != nil {
log.Print(err)
return
}
uid, err := result.LastInsertId()
if err != nil {
log.Print(err)
return
}
session := Session{
UserID: int(uid),
AccountName: accountName,
Authority: 0,
CSRFToken: secureRandomStr(16),
}
sessionStore.Set(w, &session)
http.Redirect(w, r, "/", http.StatusFound)
}
func getLogout(w http.ResponseWriter, r *http.Request) {
session := getSession(r)
session.UserID = 0
session.AccountName = ""
session.Authority = 0
session.CSRFToken = ""
sessionStore.Set(w, session)
http.Redirect(w, r, "/", http.StatusFound)
}
var (
postM sync.Mutex
postStore []Post = make([]Post, 0, cachedPostsCount+1)
)
const cachedPostsCount = postsPerPage * 100
func getIndexPostsLocked(forceUpdate bool, skipQuery bool) []Post {
// 初期データの時点でpostsPerPage以上あるのは確定
if len(postStore) >= cachedPostsCount && !forceUpdate {
return postStore
}
ps := make([]Post, 0, cachedPostsCount)
if skipQuery {
ps = postStore
} else {
query := `
SELECT posts.id, posts.body, posts.mime, posts.created_at,
users.account_name AS "users.account_name", users.authority AS "users.authority"
FROM posts
JOIN users ON posts.user_id = users.id
WHERE users.id NOT IN (?)
ORDER BY posts.created_at DESC
LIMIT ?
`
query, args, err := sqlx.In(query, deletedUserIDs, cachedPostsCount)
if err != nil {
log.Print(err)
return []Post{}
}
query = db.Rebind(query)
err = db.Select(&ps, query, args...)
if err != nil {
log.Print(err)
return []Post{}
}
}
results, err := makePosts(ps, "", false)
if err != nil {
log.Print(err)
return []Post{}
}
for i := 0; i < len(results); i++ {
results[i].Rendered = RenderedPost{
ID: []byte(strconv.Itoa(results[i].ID)),
CreatedAt: []byte(results[i].CreatedAt.Format(ISO8601Format)),
UserAccountName: []byte(results[i].User.AccountName),
ImageURL: []byte(imageURL(results[i])),
Body: []byte(results[i].Body),
CommentCount: []byte(strconv.Itoa(results[i].CommentCount)),
}
}
postStore = results
return results
}
func getIndexPosts() []Post {
postM.Lock()
defer postM.Unlock()
return getIndexPostsLocked(false, false)
}
func appendPost(p Post) {
postM.Lock()
defer postM.Unlock()
ps := getIndexPostsLocked(false, false)
p.Rendered = RenderedPost{
ID: []byte(strconv.Itoa(p.ID)),
CreatedAt: []byte(p.CreatedAt.Format(ISO8601Format)),
UserAccountName: []byte(p.User.AccountName),
ImageURL: []byte(imageURL(p)),
Body: []byte(p.Body),
CommentCount: []byte(strconv.Itoa(p.CommentCount)),
}
postStore = append([]Post{p}, ps...)
postStore = postStore[:cachedPostsCount]
}
func getIndex(w http.ResponseWriter, r *http.Request) {
me := getSessionUser(r)
results := getIndexPosts()
csrfToken := getCSRFToken(r)
posts := make([]Post, 0, postsPerPage)
for _, p := range results {
p.CSRFToken = csrfToken
posts = append(posts, p)
if len(posts) >= postsPerPage {
break
}
}
flash := getFlash(w, r)
templateLayout(
w,
me,
func(w io.Writer) {
templateIndex(w, posts, csrfToken, flash)
},
)
}
var templateLayoutByteArray = [...][]byte{
[]byte(`<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Iscogram</title> <link href="/css/style.css" media="screen" rel="stylesheet" type="text/css"> </head> <body> <div class="container"> <div class="header"> <div class="isu-title"> <h1><a href="/">Iscogram</a></h1> </div> <div class="isu-header-menu">`),
[]byte(`<div><a href="/login">ログイン</a></div>`),
[]byte(`<div><a href="/@`),
[]byte(`"><span class="isu-account-name">`),
[]byte(`</span>さん</a></div>`),
[]byte(`<div><a href="/admin/banned">管理者用ページ</a></div>`),
[]byte(`<div><a href="/logout">ログアウト</a></div>`),
[]byte(`</div> </div>`),
[]byte(`</div> <script src="/js/timeago.min.js"></script> <script src="/js/main.js"></script> </body> </html>`),
}
func templateLayout(w io.Writer, me User, content func(w io.Writer)) {
w.Write(templateLayoutByteArray[0])
if me.ID == 0 {
w.Write(templateLayoutByteArray[1])
} else {
var accountName = []byte(me.AccountName)
w.Write(templateLayoutByteArray[2])
w.Write(accountName)
w.Write(templateLayoutByteArray[3])
w.Write(accountName)
w.Write(templateLayoutByteArray[4])
if me.Authority == 1 {
w.Write(templateLayoutByteArray[5])
}
w.Write(templateLayoutByteArray[6])
}
w.Write(templateLayoutByteArray[7])
content(w)
w.Write(templateLayoutByteArray[8])
}
var templateIndexByteArray = [...][]byte{
[]byte(`<div class="isu-submit"> <form method="post" action="/" enctype="multipart/form-data"> <div class="isu-form"> <input type="file" name="file" value="file"> </div> <div class="isu-form"> <textarea name="body"></textarea> </div> <div class="form-submit">
<input type="hidden" name="csrf_token" value="`),
[]byte(`"> <input type="submit" name="submit" value="submit"> </div>`),
[]byte(`<div id="notice-message" class="alert alert-danger">`),
[]byte(`</div>`),
[]byte(`</form></div>`),
[]byte(`<div id="isu-post-more"><button id="isu-post-more-btn">もっと見る</button><img class="isu-loading-icon" src="/img/ajax-loader.gif"></div>`),
}
func templateIndex(w io.Writer, posts []Post, csrfToken string, flash string) {
w.Write(templateIndexByteArray[0])
w.Write([]byte(csrfToken))
w.Write(templateIndexByteArray[1])
if len(flash) > 0 {
w.Write(templateIndexByteArray[2])
w.Write([]byte(flash))
w.Write(templateIndexByteArray[3])
}
w.Write(templateIndexByteArray[4])
templatePosts(w, posts)
w.Write(templateIndexByteArray[5])
}
var templatePostsByteArray = [...][]byte{
[]byte(`<div class="isu-posts">`),
[]byte(`</div>`),
}
func templatePosts(w io.Writer, posts []Post) {
w.Write(templatePostsByteArray[0])
for _, p := range posts {
templatePost(w, p)
}
w.Write(templatePostsByteArray[1])
}
var templatePostByteArray = [...][]byte{
[]byte(`<div class="isu-post" id="pid_`),
[]byte(`" data-created-at="`),
[]byte(`"><div class="isu-post-header"><a href="/@`),
[]byte(`" class="isu-post-account-name">`),
[]byte(`</a><a href="/posts/`),
[]byte(`" class="isu-post-permalink"><time class="timeago" datetime="`),
[]byte(`"></time></a></div><div class="isu-post-image"><img src="`),
[]byte(`" class="isu-image"></div><div class="isu-post-text"><a href="/@`),
[]byte(`" class="isu-post-account-name">`),
[]byte(`</a>`),
[]byte(`</div><div class="isu-post-comment"><div class="isu-post-comment-count">comments: <b>`),
[]byte(`</b></div>`),
[]byte(`<div class="isu-comment"><a href="/@`),
[]byte(`" class="isu-comment-account-name">`),
[]byte(`</a><span class="isu-comment-text">`),
[]byte(`</span></div>`),
[]byte(`<div class="isu-comment-form"><form method="post" action="/comment"> <input type="text" name="comment"><input type="hidden" name="post_id" value="`),
[]byte(`"><input type="hidden" name="csrf_token" value="`),
[]byte(`"><input type="submit" name="submit" value="submit"> </form> </div> </div> </div>`),
}
func templatePost(w io.Writer, post Post) {
rendered := post.Rendered
if len(rendered.ID) > 0 {
w.Write(templatePostByteArray[0])
w.Write(rendered.ID)
w.Write(templatePostByteArray[1])
w.Write(rendered.CreatedAt)
w.Write(templatePostByteArray[2])
w.Write(rendered.UserAccountName)
w.Write(templatePostByteArray[3])
w.Write(rendered.UserAccountName)
w.Write(templatePostByteArray[4])
w.Write(rendered.ID)
w.Write(templatePostByteArray[5])
w.Write(rendered.CreatedAt)
w.Write(templatePostByteArray[6])
w.Write(rendered.ImageURL)
w.Write(templatePostByteArray[7])
w.Write(rendered.UserAccountName)
w.Write(templatePostByteArray[8])
w.Write(rendered.UserAccountName)
w.Write(templatePostByteArray[9])
w.Write(rendered.Body)
w.Write(templatePostByteArray[10])
w.Write(rendered.CommentCount)
w.Write(templatePostByteArray[11])
// w.Write([]byte(
// fmt.Sprintf(`
// <div class="isu-post" id="pid_%d" data-created-at="%s">
// <div class="isu-post-header">
// <a href="/@%s" class="isu-post-account-name">%s</a>
// <a href="/posts/%d" class="isu-post-permalink">
// <time class="timeago" datetime="%s"></time>
// </a>
// </div>
// <div class="isu-post-image">
// <img src="%s" class="isu-image">
// </div>
// <div class="isu-post-text">
// <a href="/@%s" class="isu-post-account-name">%s</a>
// %s
// </div>
// <div class="isu-post-comment">
// <div class="isu-post-comment-count">
// comments: <b>%d</b>
// </div>
// `,
// post.ID,
// createdAt,
// post.User.AccountName,
// post.User.AccountName,
// post.ID,
// createdAt,
// imageURL(post),
// post.User.AccountName,
// post.User.AccountName,
// post.Body,
// post.CommentCount,
// ),
// ))
for _, comment := range post.Comments {
w.Write(templatePostByteArray[12])
w.Write(comment.Rendered.UserAccountName)
w.Write(templatePostByteArray[13])
w.Write(comment.Rendered.UserAccountName)
w.Write(templatePostByteArray[14])
w.Write(comment.Rendered.Comment)
w.Write(templatePostByteArray[15])
// w.Write([]byte(fmt.Sprintf(`
// <div class="isu-comment">
// <a href="/@%s" class="isu-comment-account-name">%s</a>
// <span class="isu-comment-text">%s</span>
// </div>
// `,
// c.User.AccountName,
// c.User.AccountName,
// c.Comment,
// )))
}
w.Write(templatePostByteArray[16])
w.Write(rendered.ID)
w.Write(templatePostByteArray[17])
w.Write([]byte(post.CSRFToken))
w.Write(templatePostByteArray[18])
// w.Write([]byte(fmt.Sprintf(
// `<div class="isu-comment-form"> <form method="post" action="/comment"> <input type="text" name="comment">
// <input type="hidden" name="post_id" value="%d">
// <input type="hidden" name="csrf_token" value="%s">
// <input type="submit" name="submit" value="submit"> </form> </div> </div> </div>
// `,
// post.ID,
// post.CSRFToken,
// )))
} else {
createdAt := []byte(post.CreatedAt.Format(ISO8601Format))
postID := []byte(strconv.Itoa(post.ID))
userAccountName := []byte(post.User.AccountName)
w.Write(templatePostByteArray[0])
w.Write(postID)
w.Write(templatePostByteArray[1])
w.Write(createdAt)
w.Write(templatePostByteArray[2])
w.Write(userAccountName)
w.Write(templatePostByteArray[3])
w.Write(userAccountName)
w.Write(templatePostByteArray[4])
w.Write(postID)
w.Write(templatePostByteArray[5])
w.Write(createdAt)
w.Write(templatePostByteArray[6])
w.Write([]byte(imageURL(post)))
w.Write(templatePostByteArray[7])
w.Write(userAccountName)
w.Write(templatePostByteArray[8])
w.Write(userAccountName)
w.Write(templatePostByteArray[9])
w.Write([]byte(post.Body))
w.Write(templatePostByteArray[10])
w.Write([]byte(strconv.Itoa(post.CommentCount)))
w.Write(templatePostByteArray[11])
// w.Write([]byte(
// fmt.Sprintf(`
// <div class="isu-post" id="pid_%d" data-created-at="%s">
// <div class="isu-post-header">
// <a href="/@%s" class="isu-post-account-name">%s</a>
// <a href="/posts/%d" class="isu-post-permalink">
// <time class="timeago" datetime="%s"></time>
// </a>
// </div>
// <div class="isu-post-image">
// <img src="%s" class="isu-image">
// </div>
// <div class="isu-post-text">
// <a href="/@%s" class="isu-post-account-name">%s</a>
// %s
// </div>
// <div class="isu-post-comment">
// <div class="isu-post-comment-count">
// comments: <b>%d</b>
// </div>
// `,
// post.ID,
// createdAt,
// post.User.AccountName,
// post.User.AccountName,
// post.ID,
// createdAt,
// imageURL(post),
// post.User.AccountName,
// post.User.AccountName,
// post.Body,
// post.CommentCount,
// ),
// ))
for _, c := range post.Comments {
userAccountName := []byte(c.User.AccountName)
w.Write(templatePostByteArray[12])
w.Write(userAccountName)
w.Write(templatePostByteArray[13])
w.Write(userAccountName)
w.Write(templatePostByteArray[14])
w.Write([]byte(c.Comment))
w.Write(templatePostByteArray[15])
// w.Write([]byte(fmt.Sprintf(`
// <div class="isu-comment">
// <a href="/@%s" class="isu-comment-account-name">%s</a>
// <span class="isu-comment-text">%s</span>
// </div>
// `,
// c.User.AccountName,
// c.User.AccountName,
// c.Comment,
// )))
}
w.Write(templatePostByteArray[16])
w.Write(postID)
w.Write(templatePostByteArray[17])
w.Write([]byte(post.CSRFToken))
w.Write(templatePostByteArray[18])
// w.Write([]byte(fmt.Sprintf(
// `<div class="isu-comment-form"> <form method="post" action="/comment"> <input type="text" name="comment">
// <input type="hidden" name="post_id" value="%d">
// <input type="hidden" name="csrf_token" value="%s">
// <input type="submit" name="submit" value="submit"> </form> </div> </div> </div>
// `,
// post.ID,
// post.CSRFToken,
// )))
}
}
func getAccountName(w http.ResponseWriter, r *http.Request) {
accountName := chi.URLParam(r, "accountName")
user := User{}
query := "SELECT * FROM users WHERE account_name = ? AND id NOT IN (?)"
query, args, err := sqlx.In(query, accountName, deletedUserIDs)
if err != nil {
log.Print(err)
return
}
query = db.Rebind(query)
err = db.Get(&user, query, args...)
if err != nil {
log.Print(err)
return
}
if user.ID == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
results := []Post{}
query = `
SELECT posts.id, posts.user_id, posts.body, posts.mime, posts.created_at,
users.id AS "users.id", users.account_name AS "users.account_name", users.authority AS "users.authority", users.created_at AS "users.created_at"
FROM posts
JOIN users ON posts.user_id = users.id
WHERE user_id = ? AND users.id NOT IN (?)
ORDER BY posts.created_at DESC
LIMIT ?
`
query, args, err = sqlx.In(query, user.ID, deletedUserIDs, postsPerPage)
if err != nil {
log.Print(err)
return
}
query = db.Rebind(query)
err = db.Select(&results, query, args...)
if err != nil {
log.Print(err)
return
}
posts, err := makePosts(results, getCSRFToken(r), false)
if err != nil {
log.Print(err)
return
}
commentCount := 0
err = db.Get(&commentCount, "SELECT COUNT(*) AS count FROM comments WHERE user_id = ?", user.ID)
if err != nil {
log.Print(err)
return
}
postIDs := []int{}
err = db.Select(&postIDs, "SELECT id FROM posts WHERE user_id = ?", user.ID)
if err != nil {
log.Print(err)
return
}
postCount := len(postIDs)
commentedCount := 0
query = `
SELECT COUNT(*)
FROM comments
JOIN posts ON comments.post_id = posts.id
WHERE posts.user_id = ?
`
err = db.Get(&commentedCount, query, user.ID)
if err != nil {
log.Print(err)