-
Notifications
You must be signed in to change notification settings - Fork 1
/
Cloudlink4_Improved.js
2550 lines (2224 loc) · 87.1 KB
/
Cloudlink4_Improved.js
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
// Name: Cloudlink
// ID: cloudlink
// Description: A powerful WebSocket extension for Scratch.
// By: MikeDEV
// License: MIT
/* eslint-disable */
// prettier-ignore
/* generated l10n code */
Scratch.translate.setup({ "fi": { "_(OLD - DO NOT USE IN NEW PROJECTS) my username": "(VANHA - ÄLÄ KÄYTÄ UUSISSA PROJEKTEISSA) oma käyttäjänimi", "_A name": "nimi", "_All data": "kaikki data", "_Another name": "toinen nimi", "_Apple": "omena", "_Banana": "banaani", "_Direct data": "kohdennettu data", "_Global data": "globaali data", "_Global variables": "globaalit muuttujat", "_Hide old blocks": "Piilota vanhat lohkot", "_ID [ID] connected?": "onko tunniste [ID] yhdistetty?", "_Private data": "yksityinen data", "_Private variables": "yksityiset muuttujat", "_Show old blocks": "Näytä vanhat lohkot", "_Status code": "tilakoodi", "_When I receive new [TYPE] data for [VAR]": "kun vastaanotan uuden kohteen [TYPE] datan muuttujalle [VAR]", "_[NUM] from JSON array [ARRAY]": "[NUM] JSON-taulukossa [ARRAY]", "_[PATH] of [JSON_STRING]": "[PATH] JSON-koodissa [JSON_STRING]", "_attach listener [ID] to next packet": "lisää kuuntelija [ID] seuraavaan datapakettiin", "_clear all packets for [TYPE]": "tyhjennä kaikki kohteen [TYPE] datapaketit", "_connect to [IP]": "yhdistä palvelimeen [IP]", "_connect to server [ID]": "yhdistä palvelimeen nro [ID]", "_connected?": "onko yhdistetty?", "_convert [toBeJSONified] to JSON": "muunna [toBeJSONified] JSON-muotoon", "_direct": "kohdennettu", "_direct data": "kohdennettu data", "_disconnect": "katkaise yhteys", "_extension version": "laajennuksen versio", "_failed to connnect?": "epäonnistuiko yhteyden muodostaminen?", "_fetch data from URL [url]": "hae data URL-osoitteesta [url]", "_global data": "globaali data", "_got new [TYPE] data for variable [VAR]?": "onko uusi [TYPE] [VAR] data saapunut?", "_got new [TYPE]?": "onko uusi [TYPE] saapunut?", "_got new packet with listener [ID]?": "onko uusi datapaketti kuuntelijalla [ID] saapunut?", "_id": "tunniste", "_is [JSON_STRING] valid JSON?": "onko [JSON_STRING] kelvollista JSON-koodia?", "_link status": "yhteyden tila", "_link to room(s) [ROOMS]": "yhdistä huoneisiin [ROOMS]", "_linked to rooms?": "onko yhdistetty huoneisiin?", "_lost connection?": "katkesiko yhteys?", "_my IP address": "oma IP-osoite", "_my user object": "oma käyttäjäolio", "_my username": "oma käyttäjänimi", "_packet queue for [TYPE]": "kohteen [TYPE] datapakettijono", "_private data": "yksityinen data", "_reset got new [ID] listener status": "nollaa uusi kuuntelijan [ID] tila", "_reset got new [TYPE] [VAR] status": "nollaa uusi kohteen [TYPE] muuttujan [VAR] tila", "_reset got new [TYPE] status": "nollaa uusi kohteen [TYPE] tila", "_response for listener [ID]": "vastaus kuuntelijalle [ID]", "_select room(s) [ROOMS] for next packet": "valitse huoneet [ROOMS] seuraavalle datapaketille", "_send [DATA]": "lähetä [DATA]", "_send [DATA] to [ID]": "lähetä [DATA] käyttäjälle [ID]", "_send command [CMD] [ID] [DATA]": "lähetä komento [CMD] [ID] [DATA]", "_send command without ID [CMD] [DATA]": "lähetä komento ilman tunnistetta [CMD] [DATA]", "_send request with method [method] for URL [url] with data [data] and headers [headers]": "lähetä pyyntö menetelmällä [method] URL-osoitteeseen [url] datalla [data] ja otsakkeilla [headers]", "_send variable [VAR] to [ID] with data [DATA]": "lähetä muuttuja [VAR] käyttäjälle [ID] datalla [DATA]", "_send variable [VAR] with data [DATA]": "lähetä muuttuja [VAR] datalla [DATA]", "_server MOTD": "palvelimen viesti", "_server list": "palvelinluettelo", "_server version": "palvelimen versio", "_set [NAME] as username": "aseta käyttäjänimeksi [NAME]", "_size of queue for [TYPE]": "kohteen [TYPE] jonon koko", "_status code": "tilakoodi", "_unlink from all rooms": "katkaise yhteys kaikkiin huoneisiin", "_username synced?": "onko käyttäjänimi synkronoitu?", "_usernames": "käyttäjänimet", "_val": "arvo", "_when I receive new [TYPE] message": "kun vastaanotan uuden kohteen [TYPE] viestin", "_when I receive new message with listener [ID]": "kun vastaanotan uuden viestin kuuntelijalla [ID]", "_when connected": "kun yhteys muodostuu", "_when disconnected": "kun yhteys katkeaa" }, "nl": { "_[PATH] of [JSON_STRING]": "[PATH] van [JSON_STRING]", "_id": "ID" }, "ru": { "_[PATH] of [JSON_STRING]": "[PATH] из [JSON_STRING]", "_id": "ID" }, "zh-cn": { "_(OLD - DO NOT USE IN NEW PROJECTS) my username": "(旧版 - 不要在新项目中使用它) 我的用户名", "_A name": "一个名字", "_All data": "所有数据", "_Another name": "另一个名称", "_Apple": "苹果", "_Banana": "香蕉", "_Direct data": "直接数据", "_Global data": "全局数据", "_Global variables": "全局变量", "_Hide old blocks": "隐藏旧积木", "_ID [ID] connected?": "ID[ID]连接?", "_Private data": "私有数据", "_Private variables": "私有变量", "_Show old blocks": "显示旧积木", "_Status code": "状态码", "_When I receive new [TYPE] data for [VAR]": "当我收到新的用于[VAR]的[TYPE]信息", "_[NUM] from JSON array [ARRAY]": "JSON数组[ARRAY]的[NUM]", "_[PATH] of [JSON_STRING]": "[JSON_STRING]中的[PATH]", "_[TYPE] [VAR] data": "[TYPE][VAR]数据", "_attach listener [ID] to next packet": "附加监听器 [ID] 到下一个数据包", "_clear all packets for [TYPE]": "清空[TYPE]的所有数据包", "_connect to [IP]": "连接到[IP]", "_connect to server [ID]": "连接到服务器[ID]", "_connected?": "已连接?", "_convert [toBeJSONified] to JSON": "将[toBeJSONified]转为JSON", "_direct": "直接", "_direct data": "直接数据", "_disconnect": "断开连接", "_extension version": "扩展版本", "_failed to connnect?": "连接失败?", "_fetch data from URL [url]": "从 URL [url]获取数据", "_global data": "全局数据", "_got new [TYPE] data for variable [VAR]?": "收到新的用于变量[VAR]的[TYPE]数据?", "_got new [TYPE]?": "收到新的[TYPE]?", "_got new packet with listener [ID]?": "从监听器[ID]收到新的包?", "_id": "ID", "_is [JSON_STRING] valid JSON?": "[JSON_STRING]是合法JSON?", "_link status": "链接状态", "_link to room(s) [ROOMS]": "连接到房间(列表)[ROOMS]", "_linked to rooms?": "已连接到房间?", "_lost connection?": "连接丢失?", "_my IP address": "我的IP地址", "_my user object": "我的用户对象", "_my username": "我的用户名", "_packet queue for [TYPE]": "[TYPE]的包队列", "_private data": "私有数据", "_reset got new [ID] listener status": "重置收到新的[ID]监听器的状态", "_reset got new [TYPE] [VAR] status": "重置收到新的[TYPE][VAR]状态", "_reset got new [TYPE] status": "重置收到新的[TYPE]状态", "_response for listener [ID]": "监听器[ID]的回应", "_select room(s) [ROOMS] for next packet": "为下一个数据包选择房间(列表)[ROOMS]", "_send [DATA]": "发送[DATA]", "_send [DATA] to [ID]": "发送[DATA]给[ID]", "_send command [CMD] [ID] [DATA]": "发送命令[CMD][ID][DATA]", "_send command without ID [CMD] [DATA]": "发送没有ID[CMD][DATA]的命令", "_send request with method [method] for URL [url] with data [data] and headers [headers]": "发送[method]方法的请求给URL[url]携带数据[data]头部信息 [headers]", "_send variable [VAR] to [ID] with data [DATA]": "发送变量[VAR]给[ID]附带数据[DATA]", "_send variable [VAR] with data [DATA]": "发送变量[VAR]附带数据[DATA]", "_server MOTD": "服务器MOTD", "_server list": "服务器列表", "_server version": "服务器版本", "_set [NAME] as username": "设置[NAME]为用户名", "_size of queue for [TYPE]": "[TYPE]的队列大小", "_status code": "状态码", "_unlink from all rooms": "从所有房间断开连接", "_username synced?": "已同步用户名?", "_usernames": "用户名列表", "_when I receive new [TYPE] message": "当我收到新的[TYPE]信息", "_when I receive new message with listener [ID]": "当我通过监听器[ID]接收到新消息时`", "_when connected": "当建立连接", "_when disconnected": "当断开连接" } });
/* end generated l10n code */
(function (Scratch) {
/*
CloudLink Extension for TurboWarp v0.1.2.
This extension should be fully compatible with projects developed using
extensions S4.1, S4.0, and B3.0.
Server versions supported via backward compatibility:
- CL3 0.1.5 (was called S2.2)
- CL3 0.1.7
- CL4 0.1.8.x
- CL4 0.1.9.x
- CL4 0.2.0 (latest)
MIT License
Copyright 2023 Mike J. Renaker / "MikeDEV".
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Require extension to be unsandboxed.
'use strict';
if (!Scratch.extensions.unsandboxed) {
throw new Error('The CloudLink extension must run unsandboxed.');
}
// Declare VM
const vm = Scratch.vm;
const runtime = vm.runtime;
/*
This versioning system is intended for future use with CloudLink.
When the client sends the handshake request, it will provide the server with the following details:
{
"cmd": "handshake",
"val": {
"language": "Scratch",
"version": {
"editorType": String,
"fullString": String
}
}
}
version.editorType - Provides info regarding the Scratch IDE this Extension variant natively supports. Intended for server-side version identification.
version.versionNumber - Numerical version info. Increment by 1 every Semantic Versioning Patch. Intended for server-side version identification.
version.versionString - Semantic Versioning string. Intended for source-code versioning only.
The extension will auto-generate a version string by using generateVersionString().
*/
const version = {
editorType: "TurboWarp",
versionNumber: 2,
versionString: "0.1.3", // Styling/Parity and Translation Strings Update
};
// Store extension state
var clVars = {
// Editor-specific variable for hiding old, legacy-support blocks.
hideCLDeprecatedBlocks: true,
// WebSocket object.
socket: null,
// Disable nags about old servers.
currentServerUrl: "",
lastServerUrl: "",
// gmsg.queue - An array of all currently queued gmsg values.
// gmsg.varState - The value of the most recently received gmsg message.
// gmsg.hasNew - Returns true if a new gmsg value has been received.
gmsg: {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
},
// pmsg.queue - An array of all currently queued pmsg values.
// pmsg.varState - The value of the most recently received pmsg message.
// pmsg.hasNew - Returns true if a new pmsg value has been received.
pmsg: {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
},
// gvar.queue - An array of all currently queued gvar values.
// gvar.varStates - A dictionary storing each gvar variable.
gvar: {
queue: [],
varStates: {},
eventHatTick: false,
},
// pvar.queue - An array of all currently queued pvar values.
// pvar.varStates - A dictionary storing each pvar variable.
pvar: {
queue: [],
varStates: {},
eventHatTick: false,
},
// direct.queue - An array of all currently queued direct values.
// direct.varState - The value of the most recently received direct message.
// direct.hasNew - Returns true if a new direct value has been received.
direct: {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
},
// statuscode.queue - An array of all currently queued statuscode values.
// statuscode.varState - The value of the most recently received statuscode message.
// statuscode.hasNew - Returns true if a new statuscode value has been received.
statuscode: {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
},
// ulist stores all currently connected client objects in the server/all subscribed room(s).
ulist: [],
// Message-Of-The-Day
motd: "",
// Client IP address
client_ip: "",
// Server version string
server_version: "",
// listeners.enablerState - Set to true when "createListener" is used.
// listeners.enablerValue - Set to a new listener ID when "createListener" is used.
// listeners.current - Keeps track of all current listener IDs being awaited.
// listeners.varStates - Storage for all successfully awaited messages from specific listener IDs.
listeners: {
enablerState: false,
enablerValue: "",
current: [],
varStates: {},
},
// rooms.enablerState - Set to true when "selectRoomsInNextPacket" is used.
// rooms.enablerValue - Set to a new list of rooms when "selectRoomsInNextPacket" is used.
// rooms.current - Keeps track of all current rooms being used.
// rooms.varStates - Storage for all per-room messages.
// rooms.isLinked - Set to true when a room link request is successful. False when unlinked.
// rooms.isAttemptingLink - Set to true when running "linkToRooms()".
// rooms.isAttemptingUnlink - Set to true when running "unlinkFromRooms()".
rooms: {
enablerState: false,
enablerValue: "",
isLinked: false,
isAttemptingLink: false,
isAttemptingUnlink: false,
current: [],
varStates: {},
},
// Username state
username: {
attempted: false,
accepted: false,
temp: "",
value: "",
},
// Store user_obj messages.
myUserObject: {},
/*
linkState.status - Current state of the connection.
0 - Ready
1 - Connecting
2 - Connected
3 - Disconnected, gracefully (OK)
4 - Disconnected, abruptly (Connection failed / dropped)
linkState.isAttemptingGracefulDisconnect - Boolean used to ignore websocket codes when disconnecting.
linkstate.disconnectType - Type of disconnect that has occurred.
0 - Safely disconnected (connected OK and gracefully disconnected)
1 - Connection dropped (connected OK but lost connection afterwards)
2 - Connection failed (attempted connection but did not succeed)
linkstate.identifiedProtocol - Enables backwards compatibility for CL servers.
0 - CL3 0.1.5 "S2.2" - Doesn't support listeners, MOTD, or statuscodes.
1 - CL3 0.1.7 - Doesn't support listeners, has early MOTD support, and early statuscode support.
2 - CL4 0.1.8.x - First version to support listeners, and modern server_version support. First version to implement rooms support.
3 - CL4 0.1.9.x - First version to implement the handshake command and better ulist events.
4 - CL4 0.2.0 - Latest version. First version to implement client_obj and enhanced ulists.
*/
linkState: {
status: 0,
isAttemptingGracefulDisconnect: false,
disconnectType: 0,
identifiedProtocol: 0,
},
// Timeout of 500ms upon connection to try and handshake. Automatically aborted if server_version is received within that timespan.
handshakeTimeout: null,
// Prevent accidentally sending the handshake command more than once per connection.
handshakeAttempted: false,
// Storage for the publically available CloudLink instances.
serverList: {},
}
function generateVersionString() {
return `${version.editorType} ${version.versionString}`;
}
// Makes values safe for Scratch to represent.
async function makeValueScratchSafe(data) {
if (typeof data == "object") {
try {
return JSON.stringify(data);
} catch (SyntaxError) {
return String(data);
}
} else {
return String(data);
}
}
// Clears out and resets the various values of clVars upon disconnect.
function resetOnClose() {
window.clearTimeout(clVars.handshakeTimeout);
clVars.handshakeAttempted = false;
clVars.socket = null;
clVars.motd = "";
clVars.client_ip = "";
clVars.server_version = "";
clVars.linkState.identifiedProtocol = 0;
clVars.linkState.isAttemptingGracefulDisconnect = false;
clVars.myUserObject = {};
clVars.gmsg = {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
};
clVars.pmsg = {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
};
clVars.gvar = {
queue: [],
varStates: {},
eventHatTick: false,
};
clVars.pvar = {
queue: [],
varStates: {},
eventHatTick: false,
};
clVars.direct = {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
};
clVars.statuscode = {
queue: [],
varState: "",
hasNew: false,
eventHatTick: false,
};
clVars.ulist = [];
clVars.listeners = {
enablerState: false,
enablerValue: "",
current: [],
varStates: {},
};
clVars.rooms = {
enablerState: false,
enablerValue: "",
isLinked: false,
isAttemptingLink: false,
isAttemptingUnlink: false,
current: [],
varStates: {},
};
clVars.username = {
attempted: false,
accepted: false,
temp: "",
value: "",
};
}
// CL-specific netcode needed for sending messages
function sendMessage(message) {
// Prevent running this while disconnected
if (clVars.socket == null) {
//console.warn("[CloudLink] Ignoring attempt to send a packet while disconnected.");
return;
}
// See if the outgoing val argument can be converted into JSON
if (message.hasOwnProperty("val")) {
try {
message.val = JSON.parse(message.val);
} catch { }
}
// Attach listeners
if (clVars.listeners.enablerState) {
// 0.1.8.x was the first server version to support listeners.
if (clVars.linkState.identifiedProtocol >= 2) {
message.listener = clVars.listeners.enablerValue;
// Create listener
clVars.listeners.varStates[String(args.ID)] = {
hasNew: false,
varState: {},
eventHatTick: false,
};
} else {
//console.warn("[CloudLink] Server is too old! Must be at least 0.1.8.x to support listeners.");
}
clVars.listeners.enablerState = false;
}
// Check if server supports rooms
if (((message.cmd == "link") || (message.cmd == "unlink")) && (clVars.linkState.identifiedProtocol < 2)) {
// 0.1.8.x was the first server version to support rooms.
//console.warn("[CloudLink] Server is too old! Must be at least 0.1.8.x to support room linking/unlinking.");
return;
}
// Convert the outgoing message to JSON
let outgoing = "";
try {
outgoing = JSON.stringify(message);
} catch (SyntaxError) {
//console.warn("[CloudLink] Failed to send a packet, invalid syntax:", message);
return;
}
// Send the message
//console.log("[CloudLink] TX:", message);
clVars.socket.send(outgoing);
}
// Only sends the handshake command.
function sendHandshake() {
if (clVars.handshakeAttempted) return;
//console.log("[CloudLink] Sending handshake...");
sendMessage({
cmd: "handshake",
val: {
language: "Scratch",
version: {
editorType: version.editorType,
versionNumber: version.versionNumber,
},
},
listener: "handshake_cfg"
});
clVars.handshakeAttempted = true;
}
// Compare the version string of the server to known compatible variants to configure clVars.linkState.identifiedProtocol.
async function setServerVersion(version) {
//console.log(`[CloudLink] Server version: ${String(version)}`);
clVars.server_version = version;
// Auto-detect versions
const versions = {
"0.2.": 4,
"0.1.9": 3,
"0.1.8": 2,
"0.1.7": 1,
"0.1.5": 0,
"S2.2": 0, // 0.1.5
"0.1.": 0, // 0.1.5 or legacy
"S2.": 0, // Legacy
"S1.": -1 // Obsolete
};
for (const [key, value] of Object.entries(versions)) {
if (version.includes(key)) {
if (clVars.linkState.identifiedProtocol < value) {
// Disconnect if protcol is too old
if (value == -1) {
//console.warn(`[CloudLink] Server is too old to enable leagacy support. Disconnecting.`);
return clVars.socket.close(1000, "");
}
// Set the identified protocol variant
clVars.linkState.identifiedProtocol = value;
}
}
};
// Log configured spec version
// // ////console.log(`[CloudLink] Configured protocol spec to v${clVars.linkState.identifiedProtocol}.`);
// Fix timing bug
clVars.linkState.status = 2;
// Fire event hats (only one not broken)
runtime.startHats('cloudlink_onConnect');
// Don't nag user if they already trusted this server
if (clVars.currentServerUrl === clVars.lastServerUrl) return;
// Ask user if they wish to stay connected if the server is unsupported
if ((clVars.linkState.identifiedProtocol < 4) && (!confirm(
`You have connected to an old CloudLink server, running version ${clVars.server_version}.\n\nFor your security and privacy, we recommend you disconnect from this server and connect to an up-to-date server.\n\nClick/tap \"OK\" to stay connected.`
))) {
// Close the connection if they choose "Cancel"
clVars.linkState.isAttemptingGracefulDisconnect = true;
clVars.socket.close(1000, "Client going away (legacy server rejected by end user)");
return;
}
// Don't nag user the next time they connect to this server
clVars.lastServerUrl = clVars.currentServerUrl;
}
// CL-specific netcode needed to make the extension work
async function handleMessage(data) {
// Parse the message JSON
let packet = {};
try {
packet = JSON.parse(data)
} catch (SyntaxError) {
//console.error("[CloudLink] Incoming message parse failure! Is this really a CloudLink server?", data);
return;
};
// Handle packet commands
if (!packet.hasOwnProperty("cmd")) {
//console.error("[CloudLink] Incoming message read failure! This message doesn't contain the required \"cmd\" key. Is this really a CloudLink server?", packet);
return;
}
//console.log("[CloudLink] RX:", packet);
switch (packet.cmd) {
case "gmsg":
clVars.gmsg.varState = packet.val;
clVars.gmsg.hasNew = true;
clVars.gmsg.queue.push(packet);
clVars.gmsg.eventHatTick = true;
break;
case "pmsg":
clVars.pmsg.varState = packet.val;
clVars.pmsg.hasNew = true;
clVars.pmsg.queue.push(packet);
clVars.pmsg.eventHatTick = true;
break;
case "gvar":
clVars.gvar.varStates[String(packet.name)] = {
hasNew: true,
varState: packet.val,
eventHatTick: true,
};
clVars.gvar.queue.push(packet);
clVars.gvar.eventHatTick = true;
break;
case "pvar":
clVars.pvar.varStates[String(packet.name)] = {
hasNew: true,
varState: packet.val,
eventHatTick: true,
};
clVars.pvar.queue.push(packet);
clVars.pvar.eventHatTick = true;
break;
case "direct":
// Handle events from older server versions
if (packet.val.hasOwnProperty("cmd")) {
switch (packet.val.cmd) {
// Server 0.1.5 (at least)
case "vers":
window.clearTimeout(clVars.handshakeTimeout);
await setServerVersion(packet.val.val);
return;
// Server 0.1.7 (at least)
case "motd":
//console.log(`[CloudLink] Message of the day: \"${packet.val.val}\"`);
clVars.motd = packet.val.val;
return;
}
}
// Store direct value
clVars.direct.varState = packet.val;
clVars.direct.hasNew = true;
clVars.direct.queue.push(packet);
clVars.direct.eventHatTick = true;
break;
case "client_obj":
//console.log("[CloudLink] Client object for this session:", packet.val);
clVars.myUserObject = packet.val;
break;
case "statuscode":
// Store direct value
// Protocol v0 (0.1.5 and legacy) don't implement status codes.
if (clVars.linkState.identifiedProtocol == 0) {
//console.warn("[CloudLink] Received a statuscode message while using protocol v0. This event shouldn't happen. It's likely that this server is modified (did MikeDEV overlook some unexpected behavior?).");
return;
}
// Protocol v1 (0.1.7) uses "val" to represent the code.
else if (clVars.linkState.identifiedProtocol == 1) {
clVars.statuscode.varState = packet.val;
}
// Protocol v2 (0.1.8.x) uses "code" instead.
// Protocol v3-v4 (0.1.9.x - latest, 0.2.0) adds "code_id" to the payload. Ignored by Scratch clients.
else {
// Handle setup listeners
if (packet.hasOwnProperty("listener")) {
switch (packet.listener) {
case "username_cfg":
// Username accepted
if (packet.code.includes("I:100")) {
clVars.myUserObject = packet.val;
clVars.username.value = packet.val.username;
clVars.username.accepted = true;
//console.log(`[CloudLink] Username has been set to \"${clVars.username.value}\" successfully!`);
// Username rejected / error
} else {
//console.log(`[CloudLink] Username rejected by the server! Error code ${packet.code}.}`);
}
return;
case "handshake_cfg":
// Prevent handshake responses being stored in the statuscode variables
//console.log("[CloudLink] Server responded to our handshake!");
return;
case "link":
// Room link accepted
if (!clVars.rooms.isAttemptingLink) return;
if (packet.code.includes("I:100")) {
clVars.rooms.isAttemptingLink = false;
clVars.rooms.isLinked = true;
//console.log("[CloudLink] Room linked successfully!");
// Room link rejected / error
} else {
//console.log(`[CloudLink] Room link rejected! Error code ${packet.code}.}`);
}
return;
case "unlink":
// Room unlink accepted
if (!clVars.rooms.isAttemptingUnlink) return;
if (packet.code.includes("I:100")) {
clVars.rooms.isAttemptingUnlink = false;
clVars.rooms.isLinked = false;
//console.log("[CloudLink] Room unlinked successfully!");
// Room link rejected / error
} else {
//console.log(`[CloudLink] Room unlink rejected! Error code ${packet.code}.}`);
}
return;
}
}
// Update state
clVars.statuscode.varState = packet.code;
}
// Update state
clVars.statuscode.hasNew = true;
clVars.statuscode.queue.push(packet);
clVars.statuscode.eventHatTick = true;
break;
case "ulist":
// Protocol v0-v1 (0.1.5 and legacy - 0.1.7) use a semicolon (;) separated string for the userlist.
if (
(clVars.linkState.identifiedProtocol == 0)
||
(clVars.linkState.identifiedProtocol == 1)
) {
// Split the username list string
clVars.ulist = String(packet.val).split(';');
// Get rid of blank entry at the end of the list
clVars.ulist.pop(clVars.ulist.length);
// Check if username has been set (since older servers don't implement statuscodes or listeners)
if ((clVars.username.attempted) && (clVars.ulist.includes(clVars.username.temp))) {
clVars.username.value = clVars.username.temp;
clVars.username.accepted = true;
//console.log(`[CloudLink] Username has been set to \"${clVars.username.value}\" successfully!`);
}
}
// Protocol v2 (0.1.8.x) uses a list of objects w/ "username" and "id" instead.
else if (clVars.linkState.identifiedProtocol == 2) {
clVars.ulist = packet.val;
}
// Protocol v3-v4 (0.1.9.x - latest, 0.2.0) uses "mode" to add/set/remove entries to the userlist.
else {
// Check for "mode" key
if (!packet.hasOwnProperty("mode")) {
//console.warn("[CloudLink] Userlist message did not specify \"mode\" while running in protocol mode 3 or 4.");
return;
};
// Handle methods
switch (packet.mode) {
case 'set':
clVars.ulist = packet.val;
break;
case 'add':
clVars.ulist.push(packet.val);
clVars.recentlyJoinedUser = packet.val;
Scratch.vm.runtime.startHats('cloudlink_whenuserconnects');
break;
case 'remove':
case 'remove':
let index = -1
for (let i = 0; i < clVars.ulist.length; i++) {
let user = clVars.ulist[i]
if (user.uuid == packet.val.uuid) {
index = i
break;
}
}
clVars.ulist.splice(index, 1);
clVars.recentlyLeftUser = packet.val;
Scratch.vm.runtime.startHats('cloudlink_whenuserdisconnects');
break;
default:
//console.warn(`[CloudLink] Unrecognised userlist mode: \"${packet.mode}\".`);
break;
}
}
//console.log("[CloudLink] Updating userlist:", clVars.ulist);
break;
case "server_version":
window.clearTimeout(clVars.handshakeTimeout);
await setServerVersion(packet.val);
break;
case "client_ip":
//console.log(`[CloudLink] Client IP address: ${packet.val}`);
//console.warn("[CloudLink] This server has relayed your identified IP address to you. Under normal circumstances, this will be erased server-side when you disconnect, but you should still be careful. Unless you trust this server, it is not recommended to send login credentials or personal info.");
clVars.client_ip = packet.val;
break;
case "motd":
//console.log(`[CloudLink] Message of the day: \"${packet.val}\"`);
clVars.motd = packet.val;
break;
default:
//console.warn(`[CloudLink] Unrecognised command: \"${packet.cmd}\".`);
return;
}
// Handle listeners
if (packet.hasOwnProperty("listener")) {
if (clVars.listeners.current.includes(String(packet.listener))) {
// Remove the listener from the currently listening list
clVars.listeners.current.splice(
clVars.listeners.current.indexOf(String(packet.listener)),
1
);
// Update listener states
clVars.listeners.varStates[String(packet.listener)] = {
hasNew: true,
varState: packet,
eventHatTick: true,
};
}
}
}
// Basic netcode needed to make the extension work
async function newClient(url) {
if (!(await Scratch.canFetch(url))) {
//console.warn("[CloudLink] Did not get permission to connect, aborting...");
return;
}
// Set the link state to connecting
clVars.linkState.status = 1;
clVars.linkState.disconnectType = 0;
// Establish a connection to the server
//console.log("[CloudLink] Connecting to server:", url);
try {
clVars.socket = new WebSocket(url);
} catch (e) {
//console.warn("[CloudLink] An exception has occurred:", e);
return;
}
// Bind connection established event
clVars.socket.onopen = function (event) {
clVars.currentServerUrl = url;
// Set the link state to connected.
//console.log("[CloudLink] Connected.");
// If a server_version message hasn't been received in over half a second, try to broadcast a handshake
clVars.handshakeTimeout = window.setTimeout(function () {
//console.log("[CloudLink] Hmm... This server hasn't sent us it's server info. Going to attempt a handshake.");
sendHandshake();
}, 500);
// Return promise (during setup)
return;
};
// Bind message handler event
clVars.socket.onmessage = function (event) {
handleMessage(event.data);
};
// Bind connection closed event
clVars.socket.onclose = function (event) {
switch (clVars.linkState.status) {
case 1: // Was connecting
// Set the link state to ungraceful disconnect.
//console.log(`[CloudLink] Connection failed (${event.code}).`);
clVars.linkState.status = 4;
clVars.linkState.disconnectType = 1;
break;
case 2: // Was already connected
if (event.wasClean || clVars.linkState.isAttemptingGracefulDisconnect) {
// Set the link state to graceful disconnect.
//console.log(`[CloudLink] Disconnected (${event.code} ${event.reason}).`);
clVars.linkState.status = 3;
clVars.linkState.disconnectType = 0;
} else {
// Set the link state to ungraceful disconnect.
//console.log(`[CloudLink] Lost connection (${event.code} ${event.reason}).`);
clVars.linkState.status = 4;
clVars.linkState.disconnectType = 2;
}
break;
}
// Reset clVars values
resetOnClose();
// Run all onClose event blocks
runtime.startHats('cloudlink_onClose');
// Return promise (during setup)
return;
}
}
// GET the serverList
try {
Scratch.fetch(
"https://raw.githubusercontent.com/MikeDev101/cloudlink/master/serverlist.json"
)
.then((response) => {
return response.text();
})
.then((data) => {
clVars.serverList = JSON.parse(data);
})
.catch((err) => {
//console.log("[CloudLink] An error has occurred while parsing the public server list:", err);
clVars.serverList = {};
});
} catch (err) {
//console.log("[CloudLink] An error has occurred while fetching the public server list:", err);
clVars.serverList = {};
}
// Declare the CloudLink library.
class CloudLink {
getInfo() {
return {
id: 'cloudlink',
name: 'CloudLink',
docsURI: "https://github.com/MikeDev101/cloudlink/wiki/Scratch-Client",
blocks: [
{
opcode: "returnGlobalData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("global data")
},
{
opcode: "returnPrivateData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("private data")
},
{
opcode: "returnDirectData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("direct data")
},
"---",
{
opcode: "returnLinkData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("link status")
},
{
opcode: "returnStatusCode",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("status code")
},
"---",
{
opcode: "returnUserListData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("usernames")
},
{
opcode: "returnUsernameDataNew",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("my username")
},
{
opcode: "returnUsernameData",
blockType: Scratch.BlockType.REPORTER,
hideFromPalette: clVars.hideCLDeprecatedBlocks,
text: Scratch.translate("(OLD - DO NOT USE IN NEW PROJECTS) my username")
},
"---",
{
opcode: "returnVersionData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("extension version")
},
{
opcode: "returnServerVersion",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("server version")
},
{
opcode: "returnServerList",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("server list")
},
{
opcode: "returnMOTD",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("server MOTD")
},
"---",
{
opcode: "returnClientIP",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("my IP address")
},
{
opcode: "returnUserObject",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("my user object")
},
"---",
{
opcode: "returnListenerData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("response for listener [ID]"),
arguments: {
ID: {
type: Scratch.ArgumentType.STRING,
defaultValue: "example-listener",
},
},
},
{
opcode: "readQueueSize",
blockType: Scratch.BlockType.REPORTER,
hideFromPalette: clVars.hideCLDeprecatedBlocks,
text: Scratch.translate("size of queue for [TYPE]"),
arguments: {
TYPE: {
type: Scratch.ArgumentType.STRING,
menu: "allmenu",
defaultValue: "All data",
},
},
},
{
opcode: "readQueueData",
blockType: Scratch.BlockType.REPORTER,
hideFromPalette: clVars.hideCLDeprecatedBlocks,
text: Scratch.translate("packet queue for [TYPE]"),
arguments: {
TYPE: {
type: Scratch.ArgumentType.STRING,
menu: "allmenu",
defaultValue: "All data",
},
},
},
"---",
{
opcode: "returnVarData",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("[TYPE] [VAR] data"),
arguments: {
VAR: {
type: Scratch.ArgumentType.STRING,
defaultValue: Scratch.translate("Apple"),
},
TYPE: {
type: Scratch.ArgumentType.STRING,
menu: "varmenu",
defaultValue: "Global variables",
},
},
},
"---",
{
opcode: "parseJSON",
blockType: Scratch.BlockType.REPORTER,
hideFromPalette: clVars.hideCLDeprecatedBlocks,
text: Scratch.translate("[PATH] of [JSON_STRING]"),
arguments: {
PATH: {
type: Scratch.ArgumentType.STRING,
defaultValue: 'fruit/apples',
},
JSON_STRING: {
type: Scratch.ArgumentType.STRING,