-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlers.go
executable file
·6060 lines (5451 loc) · 222 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
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
// Various handlers for the various routes of Indigo.
package main
import (
// Internals
"bufio"
"bytes"
"crypto/md5"
"crypto/tls"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net"
"net/http"
"net/smtp"
"net/url"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"os"
// Externals
//"github.com/badoux/checkmail"
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
sessions "github.com/kataras/go-sessions/v3"
"github.com/lucasb-eyer/go-colorful"
"golang.org/x/crypto/bcrypt"
)
// function handler with CurrentUser
type UserResponseWriter struct {
http.ResponseWriter
CurrentUser user
}
// websocket doesn't work without this
func (u *UserResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return u.ResponseWriter.(http.Hijacker).Hijack()
}
// just for good measure
func (u *UserResponseWriter) Flush() {
u.ResponseWriter.(http.Flusher).Flush()
}
func (u *UserResponseWriter) CloseNotify() <-chan bool {
return u.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
func (u *UserResponseWriter) Push(target string, opts *http.PushOptions) error {
return u.ResponseWriter.(http.Pusher).Push(target, opts)
}
// redirect to login if the user is not logged in
func requireLogin(handler func(http.ResponseWriter, *http.Request, user)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
CurrentUser, success := doSession(w, r)
if !success {
return
}
if len(CurrentUser.Username) == 0 {
redirectTo := "/login"
// only add callback if it's not on root otherwise that would be annoying
if r.URL.Path != "/" {
redirectTo = redirectTo + "?callback=" + url.QueryEscape(r.URL.Path)
}
http.Redirect(w, r, redirectTo, 302)
return
}
userResponseWriter := &UserResponseWriter{w, CurrentUser}
handler(userResponseWriter, r, CurrentUser)
}
}
// use the login if it's there
func useLogin(handler func(http.ResponseWriter, *http.Request, user)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
CurrentUser, success := doSession(w, r)
if !success {
return
}
userResponseWriter := &UserResponseWriter{w, CurrentUser}
handler(userResponseWriter, r, CurrentUser)
}
}
// Accept a friend request.
func acceptFriendRequest(w http.ResponseWriter, r *http.Request, CurrentUser user) {
vars := mux.Vars(r)
username := vars["username"]
var user_id int
var requested int
err := db.QueryRow("SELECT id FROM users WHERE username = ?", username).Scan(&user_id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if user_id == 0 {
http.Error(w, "That user does not exist.", http.StatusBadRequest)
return
}
err = db.QueryRow("SELECT COUNT(*) FROM friend_requests WHERE request_by = ? AND request_to = ?", user_id, CurrentUser.ID).Scan(&requested)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if requested == 0 {
http.Error(w, "This user has not sent you a friend request.", http.StatusBadRequest)
return
}
stmt, err := db.Prepare("INSERT INTO friendships (source, target) VALUES (?, ?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&user_id, &CurrentUser.ID)
stmt.Close()
var conversation_id int
err = db.QueryRow("SELECT id FROM conversations WHERE (source = ? AND target = ?) OR (source = ? AND target = ?)", user_id, CurrentUser.ID, CurrentUser.ID, user_id).Scan(&conversation_id)
if conversation_id == 0 {
stmt, err = db.Prepare("INSERT INTO conversations (source, target) SELECT ?, ? FROM dual WHERE NOT EXISTS (SELECT 1 FROM conversations WHERE (source = ? AND target = ?) OR (source = ? AND target = ?))")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&user_id, &CurrentUser.ID, &user_id, &CurrentUser.ID, &CurrentUser.ID, &user_id)
stmt.Close()
} else {
stmt, err = db.Prepare("UPDATE conversations SET is_rm = 0 WHERE id = ?")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&conversation_id)
stmt.Close()
}
stmt, err = db.Prepare("DELETE FROM friend_requests WHERE request_by = ? AND request_to = ?")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&user_id, &CurrentUser.ID)
stmt.Close()
}
// Give a favorite to a community.
func addCommunityFavorite(w http.ResponseWriter, r *http.Request, CurrentUser user) {
vars := mux.Vars(r)
community_id := vars["id"]
var communityExists int
err := db.QueryRow("SELECT COUNT(*) FROM communities WHERE id = ? AND rm = 0", community_id).Scan(&communityExists)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if communityExists == 0 {
handle404(w, r, CurrentUser)
return
}
stmt, err := db.Prepare("INSERT INTO community_favorites (community, favorite_by) VALUES (?, ?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&community_id, &CurrentUser.ID)
stmt.Close()
}
// Ban a user.
func adminBanUser(w http.ResponseWriter, r *http.Request, CurrentUser user) {
if CurrentUser.Level < admin.Manage.MinimumLevel {
http.Redirect(w, r, "/", 302)
return
}
length := r.FormValue("length")
cidr := r.FormValue("cidr")
if cidr != "1" && cidr != "2" {
cidr = "0"
}
username := r.FormValue("username")
userID := -1
var ip string
db.QueryRow("SELECT id, ip FROM users WHERE username = ? LIMIT 1", username).Scan(&userID, &ip)
if userID == -1 {
http.Error(w, "The user does not exist.", http.StatusBadRequest)
return
}
if len(ip) > 0 && (cidr == "1" || cidr == "2") {
ip = getCIDR(ip, cidr)
}
fmt.Println(length)
_, err = db.Exec("REPLACE INTO bans (user, ip, cidr, until, ban_by) VALUES (?, ?, ?, NOW() + INTERVAL ? DAY, ?)", userID, ip, cidr, length, CurrentUser.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var msg wsMessage
msg.Type = "refresh"
for client := range clients {
if clients[client].UserID == userID {
err := writeWs(clients[client], client, msg)
if err != nil {
client.Close()
delete(clients, client)
}
}
}
w.Write([]byte("Success!"))
// audit log
// type 2 - ban user
db.Exec("INSERT INTO audit_log_entries(type, context, created_by) values(2, ?, ?)", userID, CurrentUser.ID)
}
// Unban a user.
func adminUnbanUser(w http.ResponseWriter, r *http.Request, CurrentUser user) {
if CurrentUser.Level < admin.Manage.MinimumLevel {
http.Redirect(w, r, "/", 302)
return
}
username := r.FormValue("username")
userID := -1
var ip string
db.QueryRow("SELECT id, ip FROM users WHERE username = ? LIMIT 1", username).Scan(&userID, &ip)
if userID == -1 {
http.Error(w, "The user does not exist.", http.StatusBadRequest)
return
}
cidr := getCIDR(ip, "1")
cidr2 := getCIDR(ip, "2")
db.Exec("DELETE FROM bans WHERE user = ? OR (cidr = 0 AND ip = ?) OR (cidr = 1 AND ip = ?) OR (cidr = 2 AND ip = ?)", userID, ip, cidr, cidr2)
w.Write([]byte("Success!"))
// audit log
// type 3 - unban user
db.Exec("INSERT INTO audit_log_entries(type, context, created_by) values(3, ?, ?)", userID, CurrentUser.ID)
}
// audit log
func showAdminAuditLog(w http.ResponseWriter, r *http.Request, CurrentUser user) {
if CurrentUser.Level < admin.Manage.MinimumLevel {
http.Redirect(w, r, "/", 302)
return
}
offset, _ := strconv.Atoi(r.FormValue("offset"))
offsetTime, err := strconv.ParseInt(r.FormValue("offset_time"), 10, 64)
if err != nil {
offsetTime = time.Now().Unix()
}
typee := r.FormValue("type")
username := r.FormValue("username")
var rows *sql.Rows
//var err error
if typee != "" {
if username != "" {
var userIdThing int
db.QueryRow("SELECT id FROM users WHERE username = ? LIMIT 1", username).Scan(&userIdThing)
rows, err = db.Query("SELECT id, type, context, created_at, created_by FROM audit_log_entries WHERE type = ? AND created_by = ? AND UNIX_TIMESTAMP(created_at) <= ? ORDER BY created_at DESC LIMIT 50 OFFSET ?", typee, userIdThing, offsetTime, offset)
} else {
rows, err = db.Query("SELECT id, type, context, created_at, created_by FROM audit_log_entries WHERE type = ? AND UNIX_TIMESTAMP(created_at) <= ? ORDER BY created_at DESC LIMIT 50 OFFSET ?", typee, offsetTime, offset)
}
} else {
if username != "" {
var userIdThing int
db.QueryRow("SELECT id FROM users WHERE username = ? LIMIT 1", username).Scan(&userIdThing)
rows, err = db.Query("SELECT id, type, context, created_at, created_by FROM audit_log_entries WHERE created_by = ? AND UNIX_TIMESTAMP(created_at) <= ? ORDER BY created_at DESC LIMIT 50 OFFSET ?", userIdThing, offsetTime, offset)
} else {
rows, err = db.Query("SELECT id, type, context, created_at, created_by FROM audit_log_entries WHERE UNIX_TIMESTAMP(created_at) <= ? ORDER BY created_at DESC LIMIT 50 OFFSET ?", offsetTime, offset)
}
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var auditLogEntries []auditLogEntry
for rows.Next() {
var row = auditLogEntry{}
var targetUser user
err = rows.Scan(&row.ID, &row.Type, &row.Context, &row.CreatedAt, &row.CreatedBy)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if row.Type == 2 || row.Type == 3 {
// ONLY get user
db.QueryRow("SELECT username, avatar, has_mh FROM users WHERE id = ? LIMIT 1", row.Context).Scan(&targetUser.Username, &targetUser.Avatar, &targetUser.HasMii)
} else {
// post and then user
var targetUserId int
var postBody string
if row.Type == 0 {
db.QueryRow("SELECT body, created_by FROM posts WHERE id = ? LIMIT 1", row.Context).Scan(&postBody, &targetUserId)
} else if row.Type == 1 {
db.QueryRow("SELECT body, created_by FROM comments WHERE id = ? LIMIT 1", row.Context).Scan(&postBody, &targetUserId)
} else if row.Type == 4 {
db.QueryRow("SELECT token, user FROM password_resets WHERE id = ? LIMIT 1", row.Context).Scan(&postBody, &targetUserId)
if targetUserId == 1 {
targetUserId = row.CreatedBy
targetUser.ID = row.CreatedBy
targetUser.Username = postBody
}
}
if postBody != "" {
row.PostSummary = " ("
if len(postBody) > 50 {
row.PostSummary += postBody[0:50] + "..."
} else {
row.PostSummary += postBody
}
row.PostSummary += ")"
}
db.QueryRow("SELECT avatar, has_mh FROM users WHERE id = ? LIMIT 1", targetUserId).Scan(&targetUser.Avatar, &targetUser.HasMii)
}
row.TargetUserAvatar = getAvatar(targetUser.Avatar, targetUser.HasMii, 0)
switch row.Type {
case 0:
row.TypeText = "post delete"
row.TypeURI = "/posts/" + strconv.Itoa(row.Context)
case 1:
row.TypeText = "comment delete"
row.TypeURI = "/comments/" + strconv.Itoa(row.Context)
case 2:
row.TypeText = "ban"
row.TypeURI = "/users/" + targetUser.Username
case 3:
row.TypeText = "unban"
row.TypeURI = "/users/" + targetUser.Username
case 4:
row.TypeText = "invite"
if targetUser.ID == row.CreatedBy {
row.TypeURI = "/invite/" + targetUser.Username
} else {
row.TypeURI = "/users/" + targetUser.Username
}
}
db.QueryRow("SELECT username, nickname, avatar, has_mh FROM users WHERE id = ? LIMIT 1", row.CreatedBy).Scan(&row.CreatorUsername, &row.CreatorNickname, &row.CreatorAvatar, &row.CreatorHasMii)
row.CreatorFinalAva = getAvatar(row.CreatorAvatar, row.CreatorHasMii, 3)
auditLogEntries = append(auditLogEntries, row)
}
rows.Close()
var data = map[string]interface{}{
"AuditLogEntries": auditLogEntries,
"Offset": offset,
"OffsetTime": offsetTime,
"Type": typee,
"User": username,
}
err = templates.ExecuteTemplate(w, "audit_logs.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Block a user.
func blockUser(w http.ResponseWriter, r *http.Request, CurrentUser user) {
vars := mux.Vars(r)
username := vars["username"]
if username != CurrentUser.Username {
var user_id int
var usern string
var level int
db.QueryRow("SELECT id, username, level FROM users WHERE username = ?", username).Scan(&user_id, &usern, &level)
if len(usern) == 0 {
handle404(w, r, CurrentUser)
return
}
if level > 0 {
http.Error(w, "You can't block admins.", http.StatusBadRequest)
return
}
stmt, err := db.Prepare("INSERT blocks SET source = ?, target = ?")
if err == nil {
// If there's no errors, we can go ahead and execute the statement.
_, err := stmt.Exec(&CurrentUser.ID, &user_id)
stmt.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt, err = db.Prepare("DELETE FROM friendships WHERE (source = ? AND target = ?) OR (source = ? AND target = ?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&user_id, &CurrentUser.ID, &CurrentUser.ID, &user_id)
stmt.Close()
stmt, err = db.Prepare("UPDATE conversations SET is_rm = 1 WHERE (source = ? AND target = ?) OR (source = ? AND target = ?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&user_id, &CurrentUser.ID, &CurrentUser.ID, &user_id)
stmt.Close()
stmt, err = db.Prepare("DELETE FROM follows WHERE (follow_to = ? AND follow_by = ?) OR (follow_to = ? AND follow_by = ?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&user_id, &CurrentUser.ID, &CurrentUser.ID, &user_id)
stmt.Close()
var msg wsMessage
msg.Type = "block"
msg.Content = CurrentUser.Username
for client := range clients {
if clients[client].UserID == user_id {
err := writeWs(clients[client], client, msg)
if err != nil {
client.Close()
delete(clients, client)
}
}
}
}
}
}
// Cancel a friend request.
func cancelFriendRequest(w http.ResponseWriter, r *http.Request, CurrentUser user) {
vars := mux.Vars(r)
username := vars["username"]
var user_id int
err := db.QueryRow("SELECT id FROM users WHERE username = ?", username).Scan(&user_id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if user_id == 0 {
http.Error(w, "That user does not exist.", http.StatusBadRequest)
return
}
stmt, err := db.Prepare("DELETE FROM friend_requests WHERE request_by = ? AND request_to = ?")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&CurrentUser.ID, &user_id)
stmt.Close()
}
// the handler for comment creation
func createComment(w http.ResponseWriter, r *http.Request, CurrentUser user) {
vars := mux.Vars(r)
post_id := vars["id"]
user_id := CurrentUser.ID
post_type := r.FormValue("post_type")
body := r.FormValue("body")
painting := r.FormValue("painting")
if post_type == "1" {
body = painting
}
image := r.FormValue("image")
attachment_type := r.FormValue("attachment_type")
url := r.FormValue("url")
url_type := 0
is_spoiler := r.FormValue("is_spoiler")
feeling := r.FormValue("feeling_id")
// Check if a comment has been made recently.
var post_by int
var recent_comment int
db.QueryRow("SELECT created_by FROM posts WHERE id = ?", post_id).Scan(&post_by)
if CurrentUser.ID != post_by {
db.QueryRow("SELECT COUNT(*) FROM comments WHERE created_by = ? AND created_at > DATE_SUB(NOW(), INTERVAL 10 SECOND)", CurrentUser.ID).Scan(&recent_comment)
if recent_comment > 0 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
// Feel free to un-hardcode this if you want.
w.Write([]byte("{\"success\":0,\"errors\":[{\"message\":\"You're making comments too fast, wait a few seconds and try again.\",\"error_code\":0}],\"code\":400}"))
return
}
}
if utf8.RuneCountInString(body) > 2000 {
http.Error(w, "Your comment is too long. (2000 characters maximum)", http.StatusBadRequest)
return
}
if len(body) == 0 && len(image) == 0 {
http.Error(w, "Your comment is empty.", http.StatusBadRequest)
return
}
if len(image) > 0 {
imageURL := ""
db.QueryRow("SELECT value FROM images WHERE id = ?", image).Scan(&imageURL)
if len(imageURL) == 0 {
http.Error(w, "Invalid image.", http.StatusBadRequest)
return
}
image = imageURL
}
if len(attachment_type) == 0 {
attachment_type = "0"
}
if len(is_spoiler) == 0 {
is_spoiler = "0"
}
if len(body) > 0 {
matched := youtube.FindAllStringSubmatch(body, 1)
if len(matched) > 0 {
url = matched[0][1]
url_type = 1
} else {
matched = spotify.FindAllStringSubmatch(body, 1)
if len(matched) > 0 {
url = matched[0][1]
url_type = 2
} else {
matched = soundcloud.FindAllStringSubmatch(body, 1)
if len(matched) > 0 {
url = "https://" + matched[0][0]
url_type = 3
}
}
}
}
if len(post_type) == 0 {
post_type = "0"
} else if post_type == "1" {
if len(painting) == 0 {
http.Error(w, "You must add a drawing.", http.StatusBadRequest)
return
}
db.QueryRow("SELECT value FROM images WHERE id = ?", painting).Scan(&body)
if body == painting {
http.Error(w, "Invalid drawing.", http.StatusBadRequest)
return
}
} else if post_type != "0" {
http.Error(w, "Invalid post type.", http.StatusBadRequest)
return
}
postedBy := 0
db.QueryRow("SELECT created_by FROM posts WHERE posts.id = ?", post_id).Scan(&postedBy)
if postedBy == 0 {
http.Error(w, "That post does not exist.", http.StatusBadRequest)
return
}
if checkIfEitherBlocked(postedBy, CurrentUser.ID) && CurrentUser.Level == 0 {
http.Error(w, "You're not allowed to do that.", http.StatusForbidden)
return
}
stmt, err := db.Prepare("INSERT comments SET created_by = ?, post = ?, body = ?, image = ?, attachment_type = ?, url = ?, url_type = ?, is_spoiler = ?, post_type = ?, feeling = ?")
if err == nil {
// If there's no errors, we can go ahead and execute the statement.
_, err := stmt.Exec(CurrentUser.ID, post_id, body, image, attachment_type, url, url_type, is_spoiler, post_type, feeling)
stmt.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var comments = comment{}
var timestamp time.Time
var role int
db.QueryRow("SELECT comments.id, created_by, created_at, feeling, body, image, attachment_type, is_spoiler, post_type, url, url_type, username, nickname, avatar, has_mh, online, hide_online, color, role FROM comments LEFT JOIN users ON users.id = created_by WHERE created_by = ? ORDER BY created_at DESC LIMIT 1", CurrentUser.ID).Scan(&comments.ID, &comments.CreatedBy, ×tamp, &comments.Feeling, &comments.BodyText, &comments.Image, &comments.AttachmentType, &comments.IsSpoiler, &comments.PostType, &comments.URL, &comments.URLType, &comments.CommenterUsername, &comments.CommenterNickname, &comments.CommenterIcon, &comments.CommenterHasMii, &comments.CommenterOnline, &comments.CommenterHideOnline, &comments.CommenterColor, &role)
comments.CommenterIcon = getAvatar(comments.CommenterIcon, comments.CommenterHasMii, comments.Feeling)
if role > 0 {
comments.CommenterRoleImage = getRoleImage(role)
}
comments.CreatedAt = humanTiming(timestamp, CurrentUser.Timezone)
comments.CreatedAtUnix = timestamp.Unix()
comments.Body = parseBody(comments.BodyText, false, true)
comments.ByMii = true
var data = map[string]interface{}{
"CanYeah": false,
"Comment": comments,
}
data["ByMe"] = CurrentUser.ID == post_by
if data["ByMe"] == true {
notif_getcomments, _ := db.Query("SELECT created_by FROM comments WHERE post = ? AND created_by != ? AND is_rm = 0 GROUP BY created_by", &post_id, &user_id)
var notif_comment_by int
for notif_getcomments.Next() {
notif_getcomments.Scan(¬if_comment_by)
createNotif(notif_comment_by, 3, post_id, CurrentUser.ID)
}
notif_getcomments.Close()
} else {
createNotif(post_by, 2, post_id, CurrentUser.ID)
}
err = templates.ExecuteTemplate(w, "create_comment.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
var commentTpl bytes.Buffer
var commentPreviewTpl bytes.Buffer
comments.ByMii = false
data["CanYeah"] = true
templates.ExecuteTemplate(&commentTpl, "create_comment.html", data)
var commentCount int
db.QueryRow("SELECT COUNT(*) FROM comments WHERE post = ?", post_id).Scan(&commentCount)
data = map[string]interface{}{
"CommentPreview": comments,
"CommentCount": commentCount,
}
templates.ExecuteTemplate(&commentPreviewTpl, "render_comment_preview.html", data)
var msg wsMessage
var community_id string
db.QueryRow("SELECT community_id FROM posts WHERE id = ?", post_id).Scan(&community_id)
for client := range clients {
if (!checkIfEitherBlocked(clients[client].UserID, comments.CreatedBy) || clients[client].Level > 0) && !inForbiddenKeywords(body, clients[client].UserID) {
if clients[client].OnPage == "/posts/"+post_id && clients[client].UserID != comments.CreatedBy {
msg.Type = "comment"
msg.Content = commentTpl.String()
err := writeWs(clients[client], client, msg)
if err != nil {
client.Close()
delete(clients, client)
}
} else if clients[client].OnPage == "/communities/"+community_id && is_spoiler == "0" {
msg.Type = "commentPreview"
msg.ID = post_id
msg.Content = commentPreviewTpl.String()
err := writeWs(clients[client], client, msg)
if err != nil {
client.Close()
delete(clients, client)
}
}
}
}
}
}
// Give a Yeah to a comment.
func createCommentYeah(w http.ResponseWriter, r *http.Request, CurrentUser user) {
vars := mux.Vars(r)
comment_id := vars["id"]
user_id := CurrentUser.ID
var comment_by int
var post_id string
var yeah_exists int
var feeling int
db.QueryRow("SELECT created_by, post, feeling FROM comments WHERE id = ?", comment_id).Scan(&comment_by, &post_id, &feeling)
// Check if the comment exists first.
if comment_by != 0 {
db.QueryRow("SELECT id FROM yeahs WHERE yeah_post = ? AND yeah_by = ? AND on_comment = 1", comment_id, user_id).Scan(&yeah_exists)
if yeah_exists != 0 {
return
}
if checkIfCanYeah(CurrentUser, comment_by) {
stmt, err := db.Prepare("INSERT yeahs SET yeah_post = ?, yeah_by = ?, on_comment = 1")
if err == nil {
// If there's no errors, we can go ahead and execute the statement.
_, err := stmt.Exec(&comment_id, &user_id)
stmt.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
createNotif(comment_by, 1, comment_id, user_id)
var msg wsMessage
var yeahs = yeah{}
var role int
db.QueryRow("SELECT yeahs.id, username, avatar, has_mh, role FROM yeahs LEFT JOIN users ON users.id = yeah_by WHERE yeah_by = ? ORDER BY yeahs.id DESC LIMIT 1", user_id).Scan(&yeahs.ID, &yeahs.Username, &yeahs.Avatar, &yeahs.HasMii, &role)
yeahs.Avatar = getAvatar(yeahs.Avatar, yeahs.HasMii, feeling)
if role > 0 {
yeahs.Role = getRoleImage(role)
}
msg.Type = "commentYeah"
msg.ID = comment_id
var yeahIconTpl bytes.Buffer
templates.ExecuteTemplate(&yeahIconTpl, "yeah_icon.html", yeahs)
msg.Content = yeahIconTpl.String()
for client := range clients {
if (clients[client].OnPage == "/posts/"+post_id || clients[client].OnPage == "/comments/"+comment_id) && clients[client].UserID != user_id {
err := writeWs(clients[client], client, msg)
if err != nil {
client.Close()
delete(clients, client)
}
}
}
}
}
}
}
}
// Follow a user.
func createFollow(w http.ResponseWriter, r *http.Request, CurrentUser user) {
vars := mux.Vars(r)
username := vars["username"]
current_username := CurrentUser.Username
if username != current_username {
var user_id int
var usern string
db.QueryRow("SELECT id, username FROM users WHERE username = ?", username).Scan(&user_id, &usern)
if len(usern) == 0 {
handle404(w, r, CurrentUser)
return
}
if checkIfEitherBlocked(user_id, CurrentUser.ID) && CurrentUser.Level == 0 {
http.Error(w, "You're not allowed to do that.", http.StatusBadRequest)
return
}
stmt, err := db.Prepare("INSERT follows SET follow_to = ?, follow_by = ?")
if err == nil {
// If there's no errors, we can go ahead and execute the statement.
_, err := stmt.Exec(&user_id, &CurrentUser.ID)
stmt.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
createNotif(user_id, 4, "", CurrentUser.ID)
// This is necessary for the Miiverse client-side scripts.
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, "{\"following_count\":1}")
var msg wsMessage
msg.Type = "follow"
for client := range clients {
if strings.HasPrefix(clients[client].OnPage, "/users/"+username) {
err := writeWs(clients[client], client, msg)
if err != nil {
client.Close()
delete(clients, client)
}
}
}
}
}
}
// Create a group chat.
func createGroupChat(w http.ResponseWriter, r *http.Request, CurrentUser user) {
var users []int
for i := 1; i <= 10; i++ {
username := r.FormValue("user" + strconv.Itoa(i))
if len(username) > 0 {
var id int
var group_permissions int
db.QueryRow("SELECT id, group_permissions FROM users WHERE username = ?", username).Scan(&id, &group_permissions)
if id == 0 {
http.Error(w, "The user "+username+" does not exist.", http.StatusBadRequest)
return
}
if group_permissions == 1 {
var followCount int
db.QueryRow("SELECT COUNT(*) FROM follows WHERE follow_to = ? AND follow_by = ?", CurrentUser.ID, id).Scan(&followCount)
if followCount == 0 {
http.Error(w, "The user "+username+" does not allow you to add them to chat groups.", http.StatusBadRequest)
return
}
}
var friendCount int
db.QueryRow("SELECT COUNT(*) FROM friendships WHERE (source = ? AND target = ?) OR (source = ? AND target = ?)", id, CurrentUser.ID, CurrentUser.ID, id).Scan(&friendCount)
if friendCount == 0 {
http.Error(w, "The user "+username+" is not on your friend list.", http.StatusBadRequest)
return
}
users = append(users, id)
}
}
users = append(users, CurrentUser.ID)
stmt, err := db.Prepare("INSERT INTO conversations (source, target) VALUES (?, 0)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&CurrentUser.ID)
stmt.Close()
var conversationID int
db.QueryRow("SELECT id FROM conversations WHERE source = ? AND target = 0 ORDER BY id DESC", CurrentUser.ID).Scan(&conversationID)
for _, user := range users {
stmt, err = db.Prepare("INSERT INTO group_members (user, conversation) VALUES (?, ?)")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stmt.Exec(&user, &conversationID)
stmt.Close()
}
http.Redirect(w, r, "/conversations/"+strconv.Itoa(conversationID), 302)
}
// Create a post.
func createPost(w http.ResponseWriter, r *http.Request, CurrentUser user) {
user_id := CurrentUser.ID
community_id := r.FormValue("community")
post_type := r.FormValue("post_type")
body := r.FormValue("body")
painting := r.FormValue("painting")
if post_type == "1" {
body = painting
}
image := r.FormValue("image")
attachment_type := r.FormValue("attachment_type")
url := ""
url_type := 0
is_spoiler := r.FormValue("is_spoiler")
feeling := r.FormValue("feeling_id")
privacy := r.FormValue("privacy")
repost := r.FormValue("repost")
// Check if a post has been made recently.
var recent_post int
db.QueryRow("SELECT id FROM posts WHERE created_by = ? AND created_at > DATE_SUB(NOW(), INTERVAL 10 SECOND)", user_id).Scan(&recent_post)
if recent_post != 0 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
// Feel free to un-hardcode this if you want.
w.Write([]byte("{\"success\":0,\"errors\":[{\"message\":\"You're making posts too fast, wait a few seconds and try again.\",\"error_code\":0}],\"code\":400}"))
return
}
if len(community_id) == 0 {
http.Error(w, "You must specify a community.", http.StatusBadRequest)
return
}
var communityCount int
err = db.QueryRow("SELECT COUNT(*) FROM communities WHERE id = ? AND (rm = 0 OR id = 0) AND permissions <= ? LIMIT 1", community_id, CurrentUser.Level).Scan(&communityCount)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if communityCount == 0 {
http.Error(w, "The community could not be found.", http.StatusBadRequest)
return
}
if utf8.RuneCountInString(body) > 2000 {
http.Error(w, "Your post is too long. (2000 characters maximum)", http.StatusBadRequest)
return
}
if len(body) == 0 && len(image) == 0 && len(repost) == 0 {
http.Error(w, "Your post is empty.", http.StatusBadRequest)
return
}
if len(image) > 0 {
imageURL := ""
db.QueryRow("SELECT value FROM images WHERE id = ?", image).Scan(&imageURL)
if len(imageURL) == 0 {
http.Error(w, "Invalid image.", http.StatusBadRequest)
return
}
image = imageURL
}
if len(attachment_type) == 0 {
attachment_type = "0"
}
if is_spoiler != "1" {
is_spoiler = "0"
}
if len(privacy) != 1 {
privacy = "0"
}
if len(repost) == 0 {
repost = "0"
} else {
var count int
err = db.QueryRow("SELECT COUNT(*) FROM posts LEFT JOIN users ON users.id = created_by WHERE posts.id = ? AND is_rm = 0 AND is_rm_by_admin = 0 AND users.id NOT IN (SELECT if(source = ?, target, source) FROM blocks WHERE (source = ? AND target = users.id) OR (source = users.id AND target = ?)) AND IF(created_by = ?, true, LOWER(body) NOT REGEXP LOWER(?)) AND (privacy = 0 OR (privacy IN (1, 2, 3, 4) AND (SELECT COUNT(*) FROM friendships WHERE source = ? AND target = created_by OR source = created_by AND target = ? LIMIT 1) = 1) OR (privacy IN (1, 3, 5, 6) AND (SELECT COUNT(*) FROM follows WHERE follow_to = created_by AND follow_by = ? LIMIT 1) = 1) OR (privacy IN (1, 2, 5, 7) AND (SELECT COUNT(*) FROM follows WHERE follow_to = ? AND follow_by = created_by) = 1) OR (privacy = 8 AND ? > 0) OR created_by = ?) LIMIT 1", repost, CurrentUser.ID, CurrentUser.ID, CurrentUser.ID, CurrentUser.ID, escapeForbiddenKeywords(CurrentUser.ForbiddenKeywords), CurrentUser.ID, CurrentUser.ID, CurrentUser.ID, CurrentUser.ID, CurrentUser.Level, CurrentUser.ID).Scan(&count)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if count != 1 {
http.Error(w, "The post could not be found.", http.StatusBadRequest)
return
}
}
if len(post_type) == 0 {
post_type = "0"
} else if post_type == "1" {
if len(painting) == 0 {
http.Error(w, "You must add a drawing.", http.StatusBadRequest)
return
}
db.QueryRow("SELECT value FROM images WHERE id = ?", painting).Scan(&body)
if body == painting {
http.Error(w, "Invalid drawing.", http.StatusBadRequest)
return
}
} else if post_type == "2" {
if len(r.FormValue("option-a")) == 0 || len(r.FormValue("option-b")) == 0 {
http.Error(w, "Polls must have at least two options.", http.StatusBadRequest)
return
}
} else if post_type != "0" {
http.Error(w, "Invalid post type.", http.StatusBadRequest)
return
}
if len(body) > 0 {
matched := youtube.FindAllStringSubmatch(body, 1)
if len(matched) > 0 {
url = matched[0][1]
url_type = 1
} else {
matched = spotify.FindAllStringSubmatch(body, 1)
if len(matched) > 0 {
url = matched[0][1]
url_type = 2
} else {
matched = soundcloud.FindAllStringSubmatch(body, 1)
if len(matched) > 0 {
url = "https://" + matched[0][0]
url_type = 3
}
}
}
}
stmt, err := db.Prepare("INSERT posts SET created_by = ?, community_id = ?, body = ?, image = ?, attachment_type = ?, url = ?, url_type = ?, is_spoiler = ?, feeling = ?, privacy = ?, repost = ?, post_type = ?, migrated_id = '', migrated_community = 0")
if err == nil {
// If there's no errors, we can go ahead and execute the statement.
_, err = stmt.Exec(&user_id, &community_id, &body, &image, &attachment_type, &url, &url_type, &is_spoiler, &feeling, &privacy, &repost, &post_type)
stmt.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var posts = post{}
var timestamp time.Time
var role int
err = db.QueryRow("SELECT posts.id, created_by, created_at, feeling, body, image, attachment_type, is_spoiler, post_type, url, url_type, pinned, privacy, repost, communities.id, title, icon, username, nickname, avatar, has_mh, hide_online, color, role FROM posts LEFT JOIN communities ON communities.id = community_id LEFT JOIN users ON users.id = created_by WHERE created_by = ? ORDER BY created_at DESC LIMIT 1", user_id).Scan(&posts.ID, &posts.CreatedBy, ×tamp, &posts.Feeling, &posts.BodyText, &posts.Image, &posts.AttachmentType, &posts.IsSpoiler, &posts.PostType, &posts.URL, &posts.URLType, &posts.Pinned, &posts.Privacy, &posts.RepostID, &posts.CommunityID, &posts.CommunityName, &posts.CommunityIcon, &posts.PosterUsername, &posts.PosterNickname, &posts.PosterIcon, &posts.PosterHasMii, &posts.PosterHideOnline, &posts.PosterColor, &role)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if posts.PostType == 2 {
_, err = db.Exec("INSERT INTO options (post, name) VALUES (?, ?), (?, ?)", posts.ID, r.FormValue("option-a"), posts.ID, r.FormValue("option-b"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(r.FormValue("option-c")) > 0 {
_, err = db.Exec("INSERT INTO options (post, name) VALUES (?, ?)", posts.ID, r.FormValue("option-c"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)