forked from rslashplace2/rslashplace2.github.io
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
3133 lines (2925 loc) · 121 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en" ontouchstart="if (maincontent.contains(event.target)) event.preventDefault()" ontouchend="event.preventDefault()">
<head>
<meta charset="UTF-8">
<script>
const CHAT_COLOURS = ["lightblue", "navy", "green", "purple", "grey", "brown", "orangered", "gold"]
const VERIFIED_APP_HASH = "90e58b1f2c5fb98f74962806b85c2d7d3f7b18be8abe7a04f21e939868625357"
const UNMUTED_SVG = '<path d="M10.543.5a1.12 1.12 0 00-1.182.117L3.789 4.875h-1.8A1.127 1.127 0 00.868 6v8a1.127 1.127 0 001.125 1.125h1.8l5.572 4.258a1.117 1.117 0 00.681.232 1.128 1.128 0 001.127-1.126V1.511A1.119 1.119 0 0010.543.5zm-.624 17.736l-5.708-4.361H2.118v-7.75h2.093l5.708-4.361zM13 3.375v1.25a5.375 5.375 0 010 10.75v1.25a6.625 6.625 0 000-13.25z"></path><path d="M16.125 10A3.129 3.129 0 0013 6.875v1.25a1.875 1.875 0 010 3.75v1.25A3.129 3.129 0 0016.125 10z"></path>'
const MUTED_SVG = '<path d="M19.442 7.442l-.884-.884L16.5 8.616l-2.058-2.058-.884.884L15.616 9.5l-2.058 2.058.884.884 2.058-2.058 2.058 2.058.884-.884L17.384 9.5l2.058-2.058zM10.543.5a1.12 1.12 0 00-1.182.117L3.789 4.875h-1.8A1.127 1.127 0 00.868 6v8a1.127 1.127 0 001.125 1.125h1.8l5.572 4.258a1.117 1.117 0 00.681.232 1.128 1.128 0 001.127-1.126V1.511A1.119 1.119 0 0010.543.5zm-.624 17.736l-5.708-4.361H2.118v-7.75h2.093l5.708-4.361z"></path>'
const BADGES = [ "badges/based.svg", "badges/trouble_maker.svg", "badges/veteran.svg", "badges/admin.svg", "badges/moderator.svg", "badges/noob.svg", "badges/script_kiddie.svg", "badges/ethical_botter.svg", "badges/gay.svg", "badges/discord_member.svg", "badges/100_pixels_placed", "badges/1000_pixels_placed", "badges/5000_pixels_placed", "badges/2000_pixels_placed", "badges/100000_pixels_placed", "badges/1000000_pixels_placed" ]
const DEFAULT_PALETTE_KEYS = "123456789abcdefghijklmnopqrstuvwxyz"
const AUDIOS = {
invalid: new Audio("./sounds/invalid.mp3"),
highlight: new Audio("./sounds/highlight.mp3"),
selectColour: new Audio("./sounds/select-colour.mp3"),
closePalette: new Audio("./sounds/close-palette.mp3"),
cooldownStart: new Audio("./sounds/cooldown-start.mp3"),
cooldownEnd: new Audio("./sounds/cooldown-end.mp3"),
bell: new Audio("./sounds/bell.mp3"),
celebration: new Audio("./sounds/celebration.mp3")
}
const EMOJIS = {
rofl: "🤣",
joy: "😂",
cool: "😎",
sunglasses: "😎",
heart: "❤️",
moyai: "🗿",
bruh: "🗿",
turkey: "🇹🇷",
skull: "💀",
sus: "ඞ",
iran: "🇮🇷",
uk: "🇬🇧",
usa: "🇺🇸",
america: "🇺🇸",
eyes: "👀",
fire: "🔥",
thumbsup: "👍",
thumbsdown: "👎",
clown: "🤡",
facepalm: "🤦♂️",
ok: "👌",
poop: "💩",
rocket: "🚀",
tada: "🎉",
celebration: "🎉",
moneybag: "💰",
crown: "👑",
muscle: "💪",
beer: "🍺",
pizza: "🍕",
cookie: "🍪",
balloon: "🎈",
gift: "🎁",
star: "⭐️",
love: "😍",
crying: "😢",
angry: "😠",
sleepy: "😴",
nerd: "🤓",
laughing: "😆",
vomiting: "🤮",
unicorn: "🦄",
alien: "👽",
ghost: "👻",
skullcrossbones: "☠️",
explosion: "💥",
shush: "🤫",
deaf: "🧏",
mew:"🤫🧏",
pray: "🙏",
thinking: "🤔"
}
const EMOJIS_CUSTOM = {
amogus: '<img src="custom_emojis/amogus.png" height="24">',
biaoqing: '<img src="custom_emojis/biaoqing.png" height="24">',
deepfriedh: '<img src="custom_emojis/deepfriedh.png" height="24">',
edp445: '<img src="custom_emojis/edp445.png" height="24">',
fan: '<img src="custom_emojis/fan.png" height="24">',
heavy: '<img src="custom_emojis/heavy.png" height="24">',
herkul: '<img src="custom_emojis/herkul.png" height="24">',
kaanozdil: '<img src="custom_emojis/kaanozdil.png" height="24">',
lowtiergod: '<img src="custom_emojis/lowtiergod.png" height="24">',
manly: '<img src="custom_emojis/manly.png" height="24">',
plsaddred: '<img src="custom_emojis/plsaddred.png" height="24">',
rplace: '<img src="custom_emojis/rplace.png" height="24">',
rplacediscord: '<img src="custom_emojis/rplacediscord.png" height="24">',
sonic: '<img src="custom_emojis/sonic.png" height="24">',
transparent: '<img src="custom_emojis/transparent.png" height="24">',
trollface: '<img src="custom_emojis/trollface.png" height="24">',
// Special 'commands'
help: "<kbd>Chat commands: :vip, :name, :getid</kbd>",
name: "<kbd>Change your username</kbd>",
vip: "<kbd>Apply a VIP cooldown code</kbd>",
lookup: "<kbd>Get the IDs of all players with the given name</kbd>",
getid: "<kbd>View your own User Id, or provide a name to view a list of online player User Ids</kbd>",
whoplaced: "<kbd>View details of who placed the current pixel being hoveredd</kbd>"
}
// Flag emojis all sourced from openmoji.org, https://www.langoly.com/most-spoken-languages/
const LANG_INFOS = new Map([
["en", { name: "English", flag: "https://openmoji.org/data/color/svg/1F1EC-1F1E7.svg" }],
["zh", { name: "中文", flag: "https://openmoji.org/data/color/svg/1F1E8-1F1F3.svg" }],
["hi", { name: "हिन्दी", flag: "https://openmoji.org/data/color/svg/1F1EE-1F1F3.svg" }],
["es", { name: "Español", flag: "https://openmoji.org/data/color/svg/1F1EA-1F1F8.svg" }],
["fr", { name: "Français", flag: "https://openmoji.org/data/color/svg/1F1EB-1F1F7.svg" }],
["ar", { name: "عربي", flag: "https://openmoji.org/data/color/svg/1F1F8-1F1E6.svg", rtl: true }],
["bn", { name: "বাংলা", flag: "https://openmoji.org/data/color/svg/1F1EE-1F1F3.svg" }],
["ru", { name: "pусский", flag: "https://openmoji.org/data/color/svg/1F1F7-1F1FA.svg" }],
["pt", { name: "Português", flag: "https://openmoji.org/data/color/svg/1F1E7-1F1F7.svg" }],
["ur", { name: "اردو", flag: "https://openmoji.org/data/color/svg/1F1F5-1F1F0.svg", rtl: true }],
["de", { name: "Deutsch", flag: "https://openmoji.org/data/color/svg/1F1E9-1F1EA.svg" }],
["jp", { name: "日本語", flag: "https://openmoji.org/data/color/svg/1F1EF-1F1F5.svg" }],
["tr", { name: "Türkçe", flag: "https://openmoji.org/data/color/svg/1F1F9-1F1F7.svg" }],
["vi", { name: "Tiếng Việt", flag: "https://openmoji.org/data/color/svg/1F1FB-1F1F3.svg" }],
["ko", { name: "한국인", flag: "https://openmoji.org/data/color/svg/1F1F0-1F1F7.svg" }],
["it", { name: "Italiana", flag: "https://openmoji.org/data/color/svg/1F1EE-1F1F9.svg" }],
["fa", { name: "فارسی", flag: "https://openmoji.org/data/color/svg/1F1EE-1F1F7.svg", rtl: true }],
["sr", { name: "Српски", flag: "https://openmoji.org/data/color/svg/1F1E6-1F1F1.svg"}],
["az", { name: "Azərbaycan", flag: "https://openmoji.org/data/color/svg/1F1E6-1F1FF.svg", rtl: true }],
])
const DEFAULT_THEMES = new Map([
[ "r/place 2022", { id: "r/place 2022", css: "rplace-2022.css", cssVersion: "11", pixelselect: "svg/pixel-select-2022.svg" }],
[ "r/place 2023", { id: "r/place 2023", css: "rplace-2023.css", cssVersion: "11", pixelselect: "svg/pixel-select-2023.svg" }],
])
const ADS = [
{ url: "https://youtu.be/R3UBtMloTdI", banners: { en: "images/august21-ad.png" } },
{ url: "https://t.me/rplacelive", banners: { en: "images/telegram-ad.png" } },
{ url: "https://discord.gg/4XnZ9WGux2", banners: { en: "images/discord-ad.png" } },
{ url: "https://arbitrum.life", banners: { en: "https://avatars.githubusercontent.com/u/131141781" } },
]
const PUNISHMENT_STATE = {
mute: 0,
ban: 1,
appealRejected: 2,
}
const MAX_CHANNEL_MESSAGES = 100
</script>
<script>
if(!("subtle" in (window.crypto || {}))) location.protocol = "https:"
const automated = navigator.webdriver
// csrfstate not used at the moment, may be later to encode some extra info for client
let params = new URLSearchParams(location.search)
let csrfState = params.get("state"),
redditOauthCode = params.get("code")
boardParam = params.get("board"),
serverParam = params.get("server")
if (boardParam && serverParam) {
if (localStorage.server != serverParam || localStorage.board != boardParam) {
localStorage.server = serverParam
localStorage.board = boardParam
history.pushState(null, '', location.origin)
window.location.reload()
}
}
// Register PWA Service worker
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("./sw.js?v=2.0")
}
const intIdPositions = new Map() // position : intId
const intIdNames = new Map() // intId : name
let account = null
let intId = null
let chatName = null
let fetchLinkKey = null // function injected by wscapsule
let setName = null // function injected by wscapsule
let requestPixelPlacers = null // function injected by wscapsule
let requestLoadChannelPrevious = null // function injected by wscapsule
let canvasLocked = false // Server will tell us this
let includesPlacer = false // Server will tell us this
const wscapsule = ((send, addEventListener, call) => {
let focused = true
call(addEventListener, window, "blur", () => focused = false)
call(addEventListener, window, "focus", () => focused = true)
let authSocket = {} //new WebSocket("wss://server.poemanthology.org/auth")
// HACK: Until enough clients are using the new server
if (localStorage.server?.startsWith("wss://server.rplace.tk")) {
delete localStorage.server
}
let svUri = localStorage.server || DEFAULT_SERVER
if (localStorage.vip) {
if (!svUri.endsWith("/")) svUri += "/"
svUri += localStorage.vip
}
let ws = new WebSocket(svUri)
delete WebSocket
function chatReport(messageId, senderId) {
const reason = prompt("Enter the reason for why you are reporting this message (max 280 chars)\n\n" +
`Additional info:\nMessage ID: ${messageId}\nSender ID: ${senderId}\n`)
if (!reason || !reason.trim()) {
return
}
const reportBuffer = encoder.encode("XXXXX" + reason)
reportBuffer[0] = 14
reportBuffer[1] = messageId >> 24
reportBuffer[2] = messageId >> 16
reportBuffer[3] = messageId >> 8
reportBuffer[4] = messageId & 255
call(send, ws, reportBuffer)
alert("Report sent!\nIn the meantime you can block this user by 'right clicking / press hold on the message' > 'block'")
}
function createLiveChatMessage(messageId, txt, senderId, name, sendDate, repliesTo = null) {
let newMessage = document.createElement("div")
newMessage.messageId = messageId
newMessage.name = name
newMessage.originalContent = txt
// Sanitise regex
txt = sanitise(txt)
// Simple markdown parse regexes
txt = markdownParse(txt)
// Custom emoji regex
txt = txt.replaceAll(/:([a-z-_]{0,16}):/g, (full, source) => {
// If this emoji is the only thing in the message we can make it big!
if (txt.match(source).length == 1 && !txt.replace(full, "").trim()) {
return `<img src="custom_emojis/${source}.png" alt=":${source}:" title=":${source}:" width="48" height="48">`
}
// Else smaller and inline with the rest of the message
return `<img src="custom_emojis/${source}.png" alt=":${source}:" title=":${source}:" width="16" height="16">`
})
// Coordinate to clickable link regex
txt = txt.replaceAll(/([0-9]+),\s*([0-9]+)/g, (element) => {
let px = parseInt(element.split(",")[0].trim())
let py = parseInt(element.split(",")[1].trim())
if (px != NaN && py != NaN) {
return `<a href="#" onclick="event.preventDefault();x=${px};y=${py};pos();">${px},${py}</a>`
}
})
let namePart = document.createElement("span")
if (messageId === 0) {
namePart.classList.add("rainbow-glow")
}
else {
namePart.style.color = CHAT_COLOURS[hash("" + senderId) & 7]
}
namePart.title = (new Date(sendDate * 1000)).toLocaleString()
namePart.textContent = `[${name || ("#" + senderId)}] `
let txtPart = document.createElement("span")
txtPart.innerHTML = txt
if (repliesTo != null) {
let replyingMessage = null
for (let message of cMessages[currentChannel]) {
if (message.messageId == repliesTo) {
replyingMessage = message
break
}
}
if (replyingMessage == null) {
replyingMessage = {
name: "[?????]",
originalContent: translate("messageCouldntBeLoaded"),
fake: true
}
}
let repliesPart = document.createElement("p")
if (!replyingMessage.fake) {
repliesPart.onclick = function() {
let height = 0
for (let message of cMessages[currentChannel]) {
if (message == replyingMessage) break
height += message.offsetHeight
}
replyingMessage.setAttribute("highlight", "true")
setTimeout(() => {
replyingMessage.removeAttribute("highlight")
}, 500)
chatMessages.scroll({ top: height, left: 0, behavior: "smooth" })
}
}
repliesPart.innerText = `↪️ ${replyingMessage.name} ${replyingMessage.originalContent}`
newMessage.appendChild(repliesPart)
}
newMessage.appendChild(namePart)
newMessage.appendChild(txtPart)
if (messageId > 0) { // Disable interactivity for system messages
namePart.onclick = (e) => chatMentionUser(senderId)
newMessage.oncontextmenu = (e) => onChatContext(e, senderId, messageId)
let actionsPart = document.createElement("div")
let replyBtn = document.createElement("img")
replyBtn.onclick = function(e) { chatReply(messageId, senderId) }
replyBtn.title = translate("replyTo")
replyBtn.tabIndex = "0"
replyBtn.src = "svg/reply-action.svg"
actionsPart.appendChild(replyBtn)
let reportBtn = document.createElement("img")
reportBtn.onclick = function(e) { chatReport(messageId, senderId) }
reportBtn.title = translate("report")
replyBtn.tabIndex = "0"
reportBtn.src = "svg/report-action.svg"
actionsPart.appendChild(reportBtn)
if (localStorage.vip?.startsWith("!")) {
let moderateBtn = document.createElement("img")
moderateBtn.onclick = function(e) { chatModerate("delete", senderId, messageId, newMessage) }
replyBtn.title = "Moderation options"
replyBtn.tabIndex = "0"
moderateBtn.src = "svg/moderate-action.svg"
actionsPart.appendChild(moderateBtn)
}
newMessage.appendChild(actionsPart)
}
return newMessage
}
authSocket.binaryType = "arraybuffer"
authSocket.onopen = function() {
// Then we know we have been redirected from a reddit oauth, and will now authenticate with auth server
if (redditOauthCode) {
let cb = encoder.encode("X" + redditOauthCode)
cb[0] = 9 // ClientPackets.RedditCreateAccount
call(send, authSocket, cb)
}
else if (localStorage.refreshToken) {
let ab = encoder.encode("X" + localStorage.refreshToken)
ab[0] = 10 // ClientPackets.RedditAuthenticate
call(send, authSocket, ab)
}
else if (localStorage.accountToken) {
let ab = encoder.encode("X" + localStorage.accountToken)
ab[0] = 5 // ClientPackets.Authenticate
call(send, authSocket, ab)
}
}
authSocket.onmessage = async function({data}) {
data = new DataView(data)
switch (data.getUint8(0)) {
case 0: { // ServerPackets.Fail
console.error(decoder.decode(data.buffer.slice(1)))
break
}
case 1: {
loginPanel.style.display = "flex"
account = JSON.parse(decoder.decode(data.buffer.slice(1)))
profileName2.textContent = profileName.textContent = account.Username
// We use discord ID so that we can directly link their discord profile. Thanks https://discord.name/ for the api :).
if (account.DiscordSnowflake) {
let discordUser = await (await fetch("https://discord-lookup-api.herokuapp.com/user/" + account.DiscordSnowflake)).json()
if (discordUser && discordUser.success) {
profileDiscordIcon.src = discordUser.data.avatar || "images/discord.png"
profileDiscord.textContent = discordUser.data.username
profileDiscord.href = "https://discord.com/users/" + account.DiscordSnowflake
}
}
if (account.TwitterHandle) {
profileTwitter.textContent = account.TwitterHandle
profileTwitter.href = "https://twitter.com/" + account.TwitterHandle
}
// We can also scrape their snoo/user icon using reddit. Thanks reddit!
if (account.RedditHandle) {
profileReddit.textContent = account.RedditHandle
profileReddit.href = "https://www.reddit.com/user/" + account.RedditHandle.replaceAll("/u/", "")
let redditUser = await (await fetch("https://www.reddit.com/user/"+ account.RedditHandle +"/about.json")).json()
if (redditUser && !redditUser.error) {
profileRedditIcon.src = redditUser.data.snoovatar_img || redditUser.data.icon_img || "images/reddit.png"
}
}
profilePixels.textContent = account.PixelsPlaced
profileJoin.textContent = new Date(account.JoinDate).toLocaleString()
for (let i of account.Badges) {
let badgeImg = document.createElement("img")
badgeImg.src = BADGES[i]
badgeImg.style.width = "16px"
badgeImg.title = BADGES[i][7].toUpperCase() + BADGES[i].replace("_", "").slice(8, BADGES[i].length - 4)
profileBadges.appendChild(badgeImg)
}
accountTier.textContent = account.AccountTier
accountName.textContent = account.Username
let censoredSection = account.Email.slice(4, account.Email.indexOf("@"))
accountEmail.textContent = account.Email.replace(censoredSection, "*".repeat(censoredSection.length))
break
}
case 5: { // ServerPackets.AccountToken
localStorage.accountToken = decoder.decode(data.buffer.slice(1))
console.log("Account authentication success")
call(send, authSocket, new Uint8Array([4])) // ClientPackets.AccountInfo
break
}
case 7: { // ServerPackets.RedditRefreshToken
localStorage.refreshToken = decoder.decode(data.buffer.slice(1))
console.log("Reddit OAuth success")
call(send, authSocket, new Uint8Array([4])) // ClientPackets.AccountInfo
// Clean up our params to avoid reauthenticating on reload
let params = new URLSearchParams(location.search)
params.delete("code")
history.pushState(null, "", location.origin + "/" + params.toString())
break
}
}
}
authSocket.onclose = console.error
ws.onopen = function(e) {
initialConnect = true
if (automated) {
console.error("Unsupported environment. Connection can not be guarenteed")
function reportUsage() {
const activityBuffer = encoder.encode(`\x1eWindow outer width: ${window.outerWidth}\nWindow inner width: ${window.innerWidth}\n` +
`Window outer height: ${window.outerHeight}\nWindow inner height: ${window.innerHeight}\nLast mouse move: ${new Date(lastMouseMove).toISOString()}\n` +
`Mouse X (mx): ${mx}\nMouse Y (my): ${my}\nLocal storage: ${JSON.stringify(localStorage, null, 4)}`)
call(send, ws, activityBuffer)
}
setInterval(reportUsage, 3e5) // 5 mins
reportUsage()
}
}
ws.onmessage = async function({data}) {
delete sessionStorage.err
data = new DataView(await data.arrayBuffer())
switch (data.getUint8(0)) {
case 0: {
let pi = 1
const paletteLength = data.getUint8(pi++)
PALETTE = [...new Uint32Array(data.buffer.slice(pi, pi += paletteLength * 4))]
PALETTE_USABLE_REGION.start = data.getUint8(pi++)
PALETTE_USABLE_REGION.end = data.getUint8(pi++)
generatePalette()
const binds = (localStorage.paletteKeys || DEFAULT_PALETTE_KEYS)
generateIndicators(binds)
// Board might have already been drawn with old palette so we need to draw it again
if (boardAlreadyRendered === true) {
renderAll()
}
break
}
case 1: {
CD = data.getUint32(1) * 1000 // Current cooldown
COOLDOWN = data.getUint32(5)
// New server packs canvas width and height in code 1, making it 17
if (data.byteLength == 17) {
let width = data.getUint32(9)
let height = data.getUint32(13)
setSize(width, height)
runLengthDecodeBoard(await preloadedBoard, width * height)
hideLoadingScreen()
}
break
}
case 2: {
// Old server "changes" packet - preloadedBoard = http board, data = changes
runLengthChanges(data, await preloadedBoard)
hideLoadingScreen()
break
}
case 3: { // Online
online = data.getUint16(1)
onlineCounter.textContent = online
sendPostsFrameMessage("onlineCounter", online)
break
}
case 5: { // Pixel with included placer
let i = 1
while (i < data.byteLength) {
let position = data.getUint32(i); i += 4
seti(position, data.getUint8(i)); i += 1
intIdPositions.set(position, data.getUint32(i)); i += 4
}
break
}
case 6: { // Pixel without included placer
let i = 0
while (i < data.byteLength - 2) {
seti(data.getUint32(i += 1), data.getUint8(i += 4))
}
break
}
case 7: { // Rejected pixel
CD = data.getUint32(1) * 1000
seti(data.getUint32(5), data.getUint8(9))
break
}
case 8: { // Canvas restriction
canvasLocked = !!data.getUint8(1)
canvasLock.style.display = canvasLocked ? "flex" : "none"
const reason = decoder.decode(data.buffer.slice(2))
if (reason) { // TODO: Maybe find a more pretty elegant solution
alert(reason)
}
break
}
case 9: { // Placer info region
let i = data.getUint32(1)
const regionWidth = data.getUint8(5)
const regionHeight = data.getUint8(6)
let dataI = 7
while (dataI < data.byteLength) {
for (let xi = i; xi < i + regionWidth; xi++) {
const placerIntId = data.getUint32(dataI)
if (placerIntId !== 0xFFFFFFFF) {
intIdPositions.set(xi, placerIntId)
}
dataI += 4
}
i += WIDTH
}
break
}
case 11: { // Player int ID // TODO: Integrate into packet 1
intId = data.getUint32(1)
break
}
case 12: { // Name info
for (let i = 1; i < data.byteLength;) {
let pIntId = data.getUint32(i); i += 4
let pNameLen = data.getUint8(i); i++
let pName = decoder.decode(data.buffer.slice(i, (i += pNameLen)))
intIdNames.set(pIntId, pName)
// Occurs either if server has sent us name it has remembered from a previous session,
// or we have just sent server packet 12 name update, and it is sending us back our name
if (pIntId == intId) {
chatName = pName
namePanel.style.visibility = "hidden"
}
}
break
}
case 13: { // Live chat history
let i = 1
let fromMessageId = data.getUint32(i); i += 4
let count = data.getUint8(i) & 127
let before = data.getUint8(i) >> 7; i++
let channelLen = data.getUint8(i++)
let channel = decoder.decode(data.buffer.slice(i, (i += channelLen)))
if (channel !== currentChannel) return
while (i < data.byteLength) {
let offset = i
const messageLength = data.getUint16(offset); offset += 2
const messageId = data.getUint32(offset); offset += 4
const txtLength = data.getUint16(offset); offset += 2
let txt = decoder.decode(data.buffer.slice(offset, (offset += txtLength)))
const intId = data.getUint32(offset); offset += 4 // sender int ID
const name = intIdNames.get(intId)
let sendDate = data.getUint32(offset); offset += 4
let reactionsL = data.getUint8(offset); offset++ // TODO: Reactions
// let reactions = .. TODO: we worry about this later
let channelL = data.getUint8(offset); offset++
let channel = decoder.decode(data.buffer.slice(offset, (offset += channelL)))
let repliesTo = null
if (messageLength - (offset - i) == 4) {
repliesTo = data.getUint32(offset); offset += 4
}
// TODO: We will worry about after when we get dynamic message loading
const newMessage = createLiveChatMessage(messageId, txt, intId, name, sendDate, repliesTo)
if (before) {
let scrollBefore = chatMessages.scrollTop
chatMessages.prepend(newMessage)
chatMessages.scrollTop = scrollBefore + newMessage.offsetHeight
}
i = offset
}
// chatPrevious button height (looks more seamless if the last of the
// loaded previous messages can be seen in place of the previous button
chatMessages.scrollTop -= 18
// Prevent site from spam loading chat messages when already at scroll top until it
// received the last lot
chatPreviousLoadDebounce = false
break
}
case 14: { // Moderation
let i = 1
const state = data.getUint8(i++)
const startDate = data.getUint32(i) * 1000; i += 4
const endDate = data.getUint32(i) * 1000; i += 4
const reasonLen = data.getUint8(i++)
const reason = decoder.decode(data.buffer.slice(i, i + reasonLen)); i += reasonLen
const appealLen = data.getUint8(i++)
const appeal = decoder.decode(data.buffer.slice(i, i + appealLen)); i += appealLen
// TODO: Localise
if (state === PUNISHMENT_STATE.mute) {
messageInput.disabled = true
punishmentNote.innerHTML = "You have been <stronng>muted</stronng>, you can not send messages in live chat."
}
else if (state === PUNISHMENT_STATE.ban) {
messageInput.disabled = true
canvasLock.style.display = "flex"
canvasLocked = true
punishmentNote.innerHTML = "You have been <strong>banned</strong> from placing on the canvas or sending messages in live chat."
}
punishmentUserId.textContent = `Your User ID: #${intId}`
punishmentStartDate.textContent = `Started on: ${new Date(startDate).toLocaleString()}`
punishmentEndDate.textContent = `Ending on: ${new Date(endDate).toLocaleString()}`
punishmentReason.textContent = `Reason: ${reason}`
punishmentAppeal.textContent = `Appeal status: ${(appeal && appeal !== "null") ? appeal : 'Unappealable'}`
punishmentMenu.setAttribute("opened", "true")
break
}
case 15: { // Chat
let repliesTo = null
let offset = 1
const msgType = data.getUint8(offset); offset++
const messageId = data.getUint32(offset); offset += 4
const txtLength = data.getUint16(offset); offset += 2
let txt = decoder.decode(data.buffer.slice(offset, (offset += txtLength)))
const senderIntId = data.getUint32(offset); offset += 4 // sender int ID
const name = intIdNames.get(senderIntId)
if (msgType == 0) { // live
let sendDate = data.getUint32(offset); offset += 4
let reactionsL = data.getUint8(offset); offset++ // TODO: Reactions
// let reactions = .. TODO: we worry about this later
let channelL = data.getUint8(offset); offset++
let channel = decoder.decode(data.buffer.slice(offset, (offset += channelL)))
if (data.byteLength - offset >= 4) {
repliesTo = data.getUint32(offset)
}
if (!(channel in cMessages)) return
const newMessage = createLiveChatMessage(messageId, txt, senderIntId, name, sendDate, repliesTo)
if (senderIntId !== 0 && blockedUsers.includes(senderIntId)) {
newMessage.style.color = "transparent"
newMessage.style.textShadow = "0px 0px 6px black"
}
if (txt.includes("@" + chatName) || txt.includes("@#" + intId) || txt.includes("@everyone")) {
newMessage.setAttribute("mention", "true")
if (currentChannel == channel) AUDIOS.closePalette.run()
}
const atScrollBottom = chatMessages.scrollTop + chatMessages.offsetHeight + 16 >= chatMessages.scrollHeight
// Insert the message into the channel
cMessages[channel].push(newMessage)
if (cMessages[channel].length > MAX_CHANNEL_MESSAGES) {
cMessages[channel].shift()
}
if (channel == currentChannel) {
if (chatMessages.children.length > MAX_CHANNEL_MESSAGES) chatMessages.children[0].remove()
chatMessages.insertAdjacentElement("beforeEnd", newMessage)
}
// If at scroll bottom (we scroll down when new chat messages come)
if (atScrollBottom) {
chatMessages.scrollTo(0, chatMessages.scrollHeight)
}
}
else { // place
if (!placeChat) return
let msgPos = data.getUint32(offset)
txt = txt.substring(0, 56)
const placeMessage = document.createElement("placechat")
placeMessage.innerHTML = `<span title="${(new Date()).toLocaleString()}" style="color: ${CHAT_COLOURS[hash("" + senderIntId) & 7]};">[${name}]</span><span>${txt}</span>`
placeMessage.style.left = (msgPos % WIDTH) + "px"
placeMessage.style.top = (Math.floor(msgPos / WIDTH) + 0.5) + "px"
canvparent2.appendChild(placeMessage)
//Remove message after given time.
setTimeout(() => {
canvparent2.removeChild(placeMessage)
}, localStorage.placeChatTime || 7e3)
}
break
}
case 16: { // Captcha success
captchaPopup.style.display = "none"
break
}
case 17: {// Live chat delete
const messageId = data.getUint32(1)
for (let channel of Object.values(cMessages)) {
for (let messageEl of channel) {
if (messageEl.messageId !== messageId) continue
channel.splice(channel.indexOf(messageEl), 1)
messageEl.remove()
}
}
break
}
case 18: { // Text capcha
let textsSize = data.getUint8(1)
let texts = decoder.decode(new Uint8Array(data.buffer).slice(2, textsSize + 2)).split("\n")
let imageData = new Uint8Array(data.buffer).slice(2 + textsSize)
captchaOptions.innerHTML = ""
for (let text of texts) {
let button = document.createElement("button")
button.textContent = text
captchaOptions.appendChild(button)
button.addEventListener("click", (event) => {
call(send, ws, encoder.encode("\x10" + event.target.textContent))
captchaOptions.style.pointerEvents = "none"
})
}
captchaPopup.style.display = "flex"
captchaOptions.style.pointerEvents = "all"
const imageBlob = new Blob([imageData], { type: "image/png" })
if (webGLSupported) {
updateImgCaptchaCanvas(imageBlob)
}
else {
updateImgCaptchaCanvasFallback(imageBlob)
}
break
}
case 19: { // Math captcha
console.error("Math captcha not yet supported. Ignoring.")
break
}
case 20: { // Emoji captcha
let emojisSize = data.getUint8(1)
let emojis = decoder.decode(new Uint8Array(data.buffer).slice(2, emojisSize + 2)).split("\n")
let imageData = new Uint8Array(data.buffer).slice(2 + emojisSize)
captchaOptions.innerHTML = ""
let captchaSubmitted = false
for (let emoji of emojis) {
let buttonParent = document.createElement("button")
buttonParent.classList.add("captcha-options-button")
buttonParent.setAttribute("value", emoji)
let emojiImg = document.createElement("img")
emojiImg.src = `./tweemoji/${emoji.codePointAt(0).toString(16)}.png`
emojiImg.alt = emoji
emojiImg.title = emoji
emojiImg.fetchPriority = "high"
emojiImg.addEventListener("load", (event) => {
buttonParent.classList.add("loaded")
})
buttonParent.appendChild(emojiImg)
captchaOptions.appendChild(buttonParent)
function submitCaptcha(event) {
if (captchaSubmitted || !emoji) {
return console.error("Could not send captcha response. No emoji?")
}
captchaSubmitted = true
call(send, ws, encoder.encode("\x10" + emoji))
captchaOptions.style.pointerEvents = "none"
clearCaptchaCanvas()
}
buttonParent.addEventListener("click", submitCaptcha)
emojiImg.addEventListener("click", submitCaptcha)
buttonParent.addEventListener("touchend", submitCaptcha)
emojiImg.addEventListener("touchend", submitCaptcha)
}
captchaPopup.style.display = "flex"
captchaOptions.style.pointerEvents = "all"
const imageBlob = new Blob([imageData], { type: "image/png" })
if (webGLSupported) {
updateImgCaptchaCanvas(imageBlob)
}
else {
updateImgCaptchaCanvasFallback(imageBlob)
}
break
}
case 21: {
let a=data.getUint32(1),b=5+a,c=data.buffer.slice(5,5+a),f=new Uint8Array(9),u=new DataView(f.buffer)
;window.challengeData=new Uint8Array(data.buffer.slice(b));let d=await Object.getPrototypeOf(async function(){}).constructor(atob(decoder.decode(c)))()
;delete window.challengeData;u.setUint8(0,21);u.setBigInt64(1,d);call(send,ws,u.buffer);
break
}
case 23: { // Turnstile
const siteKey = decoder.decode(data.buffer.slice(1))
const siteVariant = document.documentElement.dataset.variant
const turnstileTheme = siteVariant === "dark" ? "dark" : "light"
turnstileMenu.setAttribute("opened", true)
turnstile.ready(function () {
turnstile.render("#turnstileContainer", {
sitekey: siteKey,
theme: turnstileTheme,
language: lang,
callback: function(token) {
call(send, ws, encoder.encode("\x17" + token))
},
})
})
break
}
case 24: { // Turnstile success
turnstileMenu.removeAttribute("opened")
break
}
case 110: {
const requestsLength = linkKeyRequests.length
if (!requestsLength) {
console.error("Could not resolve link key, no existing link key requests could be found")
break
}
const instanceId = data.getUint32(1)
const linkKey = decoder.decode(data.buffer.slice(5))
linkKeyRequests[requestsLength - 1].resolve({ linkKey, instanceId })
break
}
}
}
ws.onclose = function(e) {
//Something went wrong...
CD = null
console.error(e)
if (e.code == 1006 && !sessionStorage.err) {
sessionStorage.err = "1"
window.location.reload(true)
}
loadingScreen.children[0].src = "images/rplace-offline.png"
showLoadingScreen()
}
let linkKeyRequests = []
async function _fetchLinkKey() {
linkKeyRequest = new PublicPromise()
linkKeyRequests.push(linkKeyRequest)
call(send, ws, new Uint8Array([110]))
const linkInfo = await linkKeyRequest.promise
return linkInfo
}
fetchLinkKey = _fetchLinkKey
window["fetchLinkKey"] = _fetchLinkKey
function _setName(uname) {
if (uname.length > 16) return
uname ||= "anon"
const nameBuf = encoder.encode("\x0C" + uname)
call(send, ws, nameBuf)
}
setName = _setName
// Requests all the pixel placers for a given region from the server to be loaded into
function _requestPixelPlacers(x, y, width, height) {
if (ws.readyState !== ws.OPEN) {
return
}
const placerInfoBuf = new DataView(new Uint8Array(7).buffer)
placerInfoBuf.setUint8(0, 9)
placerInfoBuf.setUint32(1, x + y * WIDTH)
placerInfoBuf.setUint8(5, width)
placerInfoBuf.setUint8(6, height)
call(send, ws, placerInfoBuf)
}
requestPixelPlacers = _requestPixelPlacers
function put() {
// If CD is null but we have already made that initial connection, we have likely ghost disconnected from the WS
if (!focused || !initialConnect || (CD === null && initialConnect) || CD > Date.now()) {
return
}
pok.classList.remove("enabled")
set(Math.floor(x), Math.floor(y), PEN)
canvselect.style.background = ""
canvselect.children[0].style.display = "block"
canvselect.style.outline = ""
canvselect.style.boxShadow = ""
palette.style.transform = "translateY(100%)"
AUDIOS.cooldownStart.run()
CD = Date.now() + (localStorage.vip ? (localStorage.vip[0] == '!' ? 0 : COOLDOWN / 2) : COOLDOWN)
const pixelView = new DataView(new Uint8Array(6).buffer)
pixelView.setUint8(0, 4)
pixelView.setUint32(1, Math.floor(x) + Math.floor(y) * WIDTH)
pixelView.setUint8(5, PEN)
if (!mobile) {
colours.children[PEN].classList.remove("sel")
PEN = -1
}
localStorage.placed = (localStorage.placed >>> 0) + 1
call(send, ws, pixelView)
}
let pok = document.getElementById("pok")
function onOkClicked(e) {
if (!e.isTrusted) return
if (pok.classList.contains("enabled")) put()
hideIndicators()
}
call(addEventListener, pok, "click", onOkClicked)
function sendLiveChatMsg(message) {
if (message.startsWith(":name")) {
namePanel.style.visibility = "visible"
nameInput.value = message.slice(5).trim()
return
}
else if (message.startsWith(":vip")) {
let key = message.slice(4).trim()
localStorage.vip = key
window.location.reload(true)
return
}
else if (localStorage.vip && message.includes(localStorage.vip)) {
alert("Can't send VIP key in chat. Use ':vip yourvipkeyhere' to apply a VIP key")
return
}
else if (message.startsWith(":getid")) {
let targetName = message.slice(6).trim().toLowerCase()
if (!targetName) {
alert("Your User ID is: #" + intId)
}
else {
let foundUsers = `Found Users with name '${targetName}:'\n`
for (let pair of intIdNames) {
if (pair[1] === targetName) {
foundUsers += `${pair[1]}, #${pair[0]}\n`
}
}
alert(foundUsers)
}
return
}
else if (message.startsWith(":whoplaced")) {
let id = intIdPositions.get(Math.floor(x) + Math.floor(y) * WIDTH)
if (id === undefined) {
alert("Could not find details of who placed pixel at current location...")
return
}
let name = intIdNames.get(id)
alert(`Details of who placed at ${Math.floor(x)}, ${Math.floor(y)
}:\nName: ${name || 'anon'
}\nUser ID: #${id}`)
return
}
else if (message.startsWith(":help")) {
return
}
const encodedChannel = encoder.encode(currentChannel)
const encodedMsg = encoder.encode(message)
let msgArray = new Uint8Array(1 + 1 + 2 + encodedMsg.byteLength + 1
+ encodedChannel.byteLength + (currentReply ? 4 : 0))
let msgView = new DataView(msgArray.buffer)
let offset = 0;
msgView.setUint8(offset++, 15)
msgView.setUint8(offset++, 0) // type
msgView.setUint16(offset, encodedMsg.byteLength) // msg length
offset += 2
msgArray.set(encodedMsg, offset)
offset += encodedMsg.byteLength
msgView.setUint8(offset, encodedChannel.byteLength)
offset += 1
msgArray.set(encodedChannel, offset)
offset += encodedChannel.byteLength
if (currentReply != null) {
msgView.setUint32(offset, currentReply)
}
chatCancelReplies()
call(send, ws, msgView)
}
function sendPlaceMsg(message) { // message put on the canvas
const encodedMsg = encoder.encode(message)
let msgArray = new Uint8Array(1 + 1 + 2 + encodedMsg.byteLength + 4)
let msgView = new DataView(msgArray.buffer)
let offset = 0
msgView.setUint8(offset++, 15)
msgView.setUint8(offset++, 1) // type
msgView.setUint16(offset, encodedMsg.byteLength)
offset += 2
msgArray.set(encodedMsg, offset)
offset += encodedMsg.byteLength
msgView.setUint32(offset, Math.floor(y) * WIDTH + Math.floor(x))
call(send, ws, msgView)
}
messageTypePanel.children[0].onclick = e => {
sendPlaceMsg(messageInput.value)
messageInput.value = ""
}