-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathTovy2-activity-alpha.rbxmx
3541 lines (2879 loc) · 95.6 KB
/
Tovy2-activity-alpha.rbxmx
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
<roblox xmlns:xmime="http://www.w3.org/2005/05/xmlmime" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.roblox.com/roblox.xsd" version="4">
<Meta name="ExplicitAutoJoints">true</Meta>
<External>null</External>
<External>nil</External>
<Item class="Script" referent="RBXCECA62ACDA2D4192A6C8F8D8F115829C">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<bool name="Disabled">false</bool>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">TovyActivity</string>
<token name="RunContext">0</token>
<string name="ScriptGuid">{57280D02-3DDB-4992-BA62-09F779557E92}</string>
<ProtectedString name="Source"><![CDATA[
if game:GetService("RunService"):IsStudio() or game.PrivateServerId ~= "" and game.PrivateServerOwnerId ~= 0 then
return warn("Tovy: Your activity does not track in private servers or Studio.")
end
-- Define services
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local HttpQueue = require(script.Components.HttpQueue)
local FastWait = require(script.Components.FastWait)
-- Set up Tovy events
local TovyFolder = Instance.new("Folder", ReplicatedStorage)
TovyFolder.Name = "Tovy Assets"
local TovyEvent = Instance.new("RemoteEvent", TovyFolder)
TovyEvent.Name = "Activity"
local TovyClient = script:WaitForChild("Components"):WaitForChild("TovyClient")
TovyClient.Event.Value = TovyEvent
local Close = Instance.new("BindableEvent")
-- Set up critical tables
local messageTable = {}
local rankTable = {}
local afkTable = {}
-- Configuration
local Configuration = {
-- Do not touch
url = "<url>",
auth = "<apikey>",
-- Edit to your liking
bansEnabled = false, -- Set to false if you do not want Tovy to handle bans (This will use less HTTP requests)
cooldownPeriod = 30, -- The interval (seconds) between retrying failed HTTP requests
rankChecking = false, -- Enables rank checking on player join/leave to ensure only relevant data is sent to Tovy
groupId = 3167534, -- The group ID to perform activity tracking for
minTrackedRank = 99, -- The minimum rank ID to perform activity tracking for (This value is retrieved from your Tovy instance on game launch)
minutesTillAFK = 2, -- How long a player can last without moving before being marked AFK
}
warn("Tovy: Module loaded; activity will be tracked.")
-- Functions
local function isUserTracked(Player)
if not Configuration.rankChecking then
return true
elseif rankTable[Player.UserId].Rank >= Configuration.minTrackedRank then
return true
end
return false
end
local function CreateSession(Player)
local request = HttpQueue.HttpRequest.new(
Configuration.url .. "/api/activity/session?type=create",
"POST",
HttpService:JSONEncode({ userid = Player.UserId, placeid = game.GameId }),
nil,
{
["Content-Type"] = "application/json",
['authorization'] = Configuration.auth
}
);
local result = request:Send()
end
local function EndSession(Player)
if isUserTracked(Player) then
local request = HttpQueue.HttpRequest.new(
Configuration.url .. "/api/activity/session?type=end",
"POST",
HttpService:JSONEncode({ userid = Player.UserId, idleTime = Player["Tovy AFK Timer"].Value, messages = messageTable[Player.UserId] }),
nil,
{
["Content-Type"] = "application/json",
['authorization'] = Configuration.auth
}
);
local result = request:Send()
end
end
local function InputChange(Player, Status)
if Status and not table.find(afkTable, Player) then
table.insert(afkTable, Player)
elseif not Status then
table.remove(afkTable, table.find(afkTable, Player))
end
end
local function MovementDetection(Player)
local lastMovement = os.clock()
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local function MovementChanged(Speed)
if Speed <= 0 then
local CurrentTime = os.clock()
lastMovement = CurrentTime
FastWait(60*Configuration.minutesTillAFK)
if lastMovement == CurrentTime then
if not table.find(afkTable, Player) then
table.insert(afkTable, Player)
end
end
else
if table.find(afkTable, Player) then
table.remove(afkTable, table.find(afkTable, Player))
end
end
end
local function MovementListeners()
Humanoid.Swimming:Connect(MovementChanged);
Humanoid.Climbing:Connect(MovementChanged);
Humanoid.Running:Connect(MovementChanged);
end
MovementListeners()
end
local function InitiateTovy(Player)
rankTable[Player.UserId] = {
Rank = Player:GetRankInGroup(Configuration.groupId)
}
messageTable[Player.UserId] = 0
if isUserTracked(Player) then
local TovyAFKTimer = Instance.new("NumberValue", Player)
TovyAFKTimer.Name = "Tovy AFK Timer"
TovyClient:Clone().Parent = Player:WaitForChild("PlayerGui")
CreateSession(Player)
MovementDetection(Player)
end
end
-- Events
TovyEvent.OnServerEvent:Connect(InputChange)
Players.PlayerAdded:Connect(function(Player)
InitiateTovy(Player)
Player.CharacterAdded:Connect(function()
MovementDetection(Player)
end)
Player.Chatted:Connect(function()
if isUserTracked(Player) then
messageTable[Player.UserId] += 1
end
end)
end)
Players.PlayerRemoving:Connect(function(Player)
EndSession(Player)
rankTable[Player.UserId] = nil
if messageTable[Player.UserId] then
messageTable[Player.UserId] = nil
end
if afkTable[Player] then
afkTable[Player] = nil
end
end)
game:BindToClose(function()
task.wait(10)
Close.Event:Connect()
end)
for _,Player in pairs(Players:GetPlayers()) do
InitiateTovy(Player)
end
while true do
for index, Player in pairs(afkTable) do
local t = Player["Tovy AFK Timer"]
if Players:GetPlayerByUserId(Player.UserId) and t then
t.Value += 1
else
table.remove(afkTable, index)
end
end
task.wait(60)
end]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
<Item class="Folder" referent="RBX238D356AB25F4F25852A0C920DE85681">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<string name="Name">Components</string>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
<Item class="ModuleScript" referent="RBXD471738D591B46AB9AB6226958E77B5C">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">HttpQueue</string>
<string name="ScriptGuid">{2BB9B888-6C73-4B84-A683-74D862D82A62}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/init.lua
Description: Front-end for the http-queue library
SPDX-License-Identifier: MIT
]]
local exports = {
HttpRequestPriority = require(script.HttpRequestPriority),
HttpRequest = require(script.HttpRequest),
HttpQueue = require(script.HttpQueue)
}
for name, guard in pairs(require(script.TypeGuards)) do
exports[name] = guard
end
return exports
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
<Item class="ModuleScript" referent="RBX7E0BBDEB21ED4C68B2E8427578E00916">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">DataUtils</string>
<string name="ScriptGuid">{95267CF8-5E6D-4D0B-AA31-743CF67888AA}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/DataUtils.lua
Description: Data structures and basic synchronization utilities
SPDX-License-Identifier: MIT
]]
local dataUtils = {}
-- Small linked list implementation
function dataUtils.newLLNode(item)
return {Data = item, Prev = nil, Next = nil}
end
function dataUtils.addNodeToFirst(node, root)
if not root.First then
root.First = node
root.Last = node
else
root.First.Prev = node
node.Next = root.First
node.Prev = nil
root.First = node
end
end
function dataUtils.addNodeToLast(node, root)
if not root.Last then
root.First = node
root.Last = node
else
root.Last.Next = node
node.Prev = root.Last
node.Next = nil
root.Last = node
end
end
return dataUtils
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBX070B0F0303354FDEA2282EB34F1385D4">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">HttpQueue</string>
<string name="ScriptGuid">{7E2B1575-0241-440F-8611-F7080AA6D8F2}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/HttpQueue.lua
Description: Creates a self-regulating queue for rate-limited services
SPDX-License-Identifier: MIT
]]
local Priority = require(script.Parent.HttpRequestPriority)
local newHttpResponse = require(script.Parent.HttpResponse)
local datautil = require(script.Parent.DataUtils)
local guards = require(script.Parent.TypeGuards)
local deps = require(script.Parent.DependencyLoader)
local Promise, t = deps.Promise, deps.t
local HttpQueue = {}
local validInt = t.intersection(t.integer, t.numberPositive)
local newHttpQueueCheck = t.strict(t.strictInterface({
retryAfter = t.union(
t.strictInterface({
header = t.string
}),
t.strictInterface({
cooldown = validInt
}),
t.strictInterface({
callback = t.callback
})
),
maxSimultaneousSendOperations = t.optional(validInt)
}))
local pushCheck = t.strict(t.tuple(guards.isHttpRequest, t.optional(guards.isHttpRequestPriority)))
--[[**
Creates an HttpQueue. It is a self-regulating queue for REST APIs that impose rate limits. When you push a request to the queue,
the queue will send the ones added first to the remote server (unless you specify a priority). The queue automatically handles
the rate limits in order to, as humanly as possible, respect the service's rate limits and Terms of Service.
A queue is NOT A SILVER BULLET NEITHER A GUARANTEE of not spamming invalid requests, though. Depending on your game's
playerbase/number of servers compared to the rate limit of the services, it might not scale well.
@param options The options for the queue.
@param [t:string|nil] options.retryAfter.header If the reqeuest is rate limited, look for this header to determine how long to wait (in seconds). If defined, don't provide options.retryAfter.cooldown
@param [t:number|nil] options.retryAfter.cooldown Define a cooldown period directly. If defined, do not define options.retryAfter.header
@param [t:number(HttpResponse)|nil] options.retryAfter.callback Pass a function that takes a rate-limited response and returns the cooldown period (in seconds). If defined, do not define options.retryAfter.header
@param [t:number|nil] options.maxSimultaneousSendOperations How many requests should be sent at the same time (maximum). Defaults to 10.
**--]]
function HttpQueue.new(options)
newHttpQueueCheck(options)
local prioritaryQueue = {}
local regularQueue = {}
local queueSize = 0
local queueExecutor = coroutine.create(function()
local interrupted = false
local restart = false
local main = coroutine.running()
local availableWorkers = options.maxSimultaneousSendOperations or 10
local cooldown
if options.retryAfter.header then
local header = options.retryAfter.header
cooldown = function(response)
wait(response.Headers[header])
end
elseif options.retryAfter.cooldown then
local cooldownPeriod = options.retryAfter.cooldown
cooldown = function()
wait(cooldownPeriod)
end
else
local callback = options.retryAfter.callback
cooldown = function(response)
wait(callback(response))
end
end
local function resolveNode(node)
-- Resolve the request
if node.Next then
node.Next.Prev = nil
end
node.Next = nil
-- Release resources
queueSize = queueSize - 1
availableWorkers = availableWorkers + 1
if coroutine.status(main) == "suspended" then
coroutine.resume(main)
end
end
local function httpStall()
-- HttpService stalled (number of requests exceeded)
wait(30)
end
local function stall(stallMethod, response)
interrupted = true
restart = true
stallMethod(response)
interrupted = false
end
local function sendNode(node)
return Promise.async(function(resolve)
node.Data.Request:Send():andThen(function(response)
if response.StatusCode == 429 then
stall(cooldown, response)
sendNode(node) -- try again!
else
coroutine.resume(node.Data.Callback, response)
end
resolve(node)
end):catch(function(err)
-- Did we exceed the HttpService limits?
if err:match("Number of requests exceeded limit") then
stall(httpStall)
sendNode(node) -- try again!
else
coroutine.resume(node.Data.Callback, err)
end
resolve(node)
end)
end)
end
local function doQueue(queue)
while queue.First do
while interrupted or availableWorkers == 0 do
coroutine.yield()
end
if restart then
break
end
local node = queue.First
availableWorkers = availableWorkers - 1
sendNode(node):andThen(resolveNode)
queue.First = node.Next
if not queue.First then
queue.Last = nil
end
end
end
while true do
restart = false
doQueue(prioritaryQueue)
doQueue(regularQueue)
if not restart then
coroutine.yield()
end
end
end)
local httpQueue = {}
--[[**
Pushes a request to the queue to be sent whenever possible.
@param [t:HttpRequest] request The request to be sent.
@param [t:HttpRequestPriority] priority The priority of the request in relation to other requests in the same queue.
@returns [t:Promise<HttpResponse>] A promise to a HttpResponse that is resolved when it is available.
**--]]
function httpQueue:Push(request, priority)
pushCheck(request, priority)
local requestBody = {Request = request}
local promise = Promise.async(function(resolve, reject)
requestBody.Callback = coroutine.running()
local response = coroutine.yield()
if guards.isHttpResponse(response) then
resolve(response)
else
reject(response)
end
end)
if not priority or priority == Priority.Normal then
datautil.addNodeToLast(datautil.newLLNode(requestBody), regularQueue)
elseif priority == Priority.Prioritary then
datautil.addNodeToLast(datautil.newLLNode(requestBody), prioritaryQueue)
elseif priority == Priority.First then
datautil.addNodeToFirst(datautil.newLLNode(requestBody), prioritaryQueue)
end
queueSize = queueSize + 1
coroutine.resume(queueExecutor)
return promise
end
--[[**
Pushes a request to the queue to be sent whenever possible.
@param [t:HttpRequest] request The request to be sent.
@param [t:HttpRequestPriority] priority The priority of the request in relation to other requests in the same queue.
@returns [t:HttpResponse] The server's response to the request.
**--]]
function httpQueue:AwaitPush(request, priority)
local resolved, response = self:Push(request, priority):await()
return resolved and response or newHttpResponse(false, response)
end
--[[**
@returns [t:number] The number of unsent requests in the queue.
**--]]
function httpQueue:QueueSize()
return queueSize
end
return setmetatable(httpQueue, {
__metatable = "HttpQueue",
__index = function(_, index)
error("Attempt to index non-existant value HttpQueue." .. tostring(index))
end
})
end
return setmetatable(HttpQueue, {
__metatable = "HttpQueue",
__index = function(_, index)
error("Attempt to index non-existant value HttpQueue." .. tostring(index))
end
})
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBX505E14CEEF064E10A46CA8741F4EE1EB">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">HttpRequest</string>
<string name="ScriptGuid">{5B4551CE-AFE0-4077-82F8-84C15E5C3909}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/HttpRequest.lua
Description: Wrapper for an HttpService request
SPDX-License-Identifier: MIT
]]
local deps = require(script.Parent.DependencyLoader)
local newHttpResponse = require(script.Parent.HttpResponse)
local HttpService, Promise, t = deps.HttpService, deps.Promise, deps.t
local HttpRequest = {}
local requestCheck = t.strict(
t.tuple(t.string, t.string, t.optional(t.string),
t.optional(t.map(t.string, t.union(t.string, t.number, t.boolean))),
t.optional(t.map(t.string, t.string))
)
)
--[[**
Creates an HttpRequest.
@param [t:String] Url The url endpoint the request is being sent to.
@param [t:String] Method A string containing the method/verb being used in the request.
@param [t:String|nil] Body The body of the request. Only applicable if you're going to send data (POST, PUT, etc.)
@param [t:Dictionary<string,string|bool|number>|nil] Query Url query options (which are then appended to the url)
@param [t:Dictionary<string,string>|nil] Headers Additional headers to be included in the request
**--]]
function HttpRequest.new(Url, Method, Body, Query, Headers)
requestCheck(Url, Method, Body, Query, Headers)
-- Now we can assume type-safety!
local endpoint = Url
local url = Url:split("://")
if url[1] == Url then
error("\"" .. Url .. "\" doesn't look like a valid Url!")
end
-- Never hurts to check for this and correct
-- https://example.org?query1=a is invalid
-- https://example.org/?query1=a is not!
-- We also need to check if there's already a path in the URL
-- e.g https://example.com/file is different from https://example.com/file/
if not url[2]:find("/") then
endpoint = endpoint .. "/"
end
if t.table(Query) then
local queryString = "?"
for i, v in pairs (Query) do
queryString = queryString .. HttpService:UrlEncode(i) .. "=" .. HttpService:UrlEncode(tostring(v)) .. "&"
end
endpoint = endpoint .. queryString:sub(1, -2)
end
local httpRequest = {}
httpRequest.Url = endpoint
--[[**
Sends the request to the specified Url.
@returns [t:HttpResponse] The server's response to the request.
**--]]
function httpRequest:AwaitSend()
-- Placeholder
local success, result = pcall(function()
return HttpService:RequestAsync({
Url = endpoint,
Method = Method,
Headers = Headers,
Body = (Method == "GET" or Method == "HEAD") and nil or Body
})
end)
return newHttpResponse(success, result)
end
--[[**
Sends the request to the specified Url.
@returns [t:Promise<HttpResponse>] A promise to a HttpResponse that is resolved when it is available.
**--]]
function httpRequest:Send()
return Promise.async(function(resolve, reject)
local response = self:AwaitSend()
if response.ConnectionSuccessful then
resolve(response)
else
reject(response.StatusMessage)
end
end)
end
return setmetatable(httpRequest, {
__metatable = "HttpRequest",
__index = function(_, index)
error("Attempt to index non-existant value HttpRequest." .. tostring(index))
end
})
end
return setmetatable(HttpRequest, {
__metatable = "HttpRequest",
__index = function(_, index)
error("Attempt to index non-existant value HttpRequest." .. tostring(index))
end
})
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBXB6A56CF0E979456D95C53662EA450E1C">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">HttpRequestPriority</string>
<string name="ScriptGuid">{C9C86114-C43E-4081-AE12-A924A8204282}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/HttpRequestPriority.lua
Description: Enum to determine how a request should be queued.
SPDX-License-Identifier: MIT
]]
local PriorityMeta = {
__metatable = "HttpRequestPriority",
__index = function(_, index)
error("Attempt to index non-existant value HttpRequestPriority." .. tostring(index))
end,
__eq = function(me, other)
return getmetatable(me) == getmetatable(other) and me.Value == other.Value
end
}
return setmetatable({
First = setmetatable({ Value = 1 }, PriorityMeta),
Prioritary = setmetatable({ Value = 2 }, PriorityMeta),
Normal = setmetatable({ Value = 3 }, PriorityMeta)
}, {
__index = function(_, index)
error(tostring(index) .. " is not a valid HttpRequestPriority!")
end
})
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBX3DE7A579686B4A2AA64706359FCBEAEE">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">HttpResponse</string>
<string name="ScriptGuid">{6C392898-FC92-4814-9E19-644205D11DC1}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/HttpResponse.lua
Description: Private wrapper for an HttpService response
SPDX-License-Identifier: MIT
]]
local function newHttpResponse(success, result)
local HttpResponse = {}
HttpResponse.ConnectionSuccessful = success
HttpResponse.RequestSuccessful = success and result.Success
HttpResponse.StatusCode = success and result.StatusCode or 0
HttpResponse.StatusMessage = success and (result.StatusCode .. " " .. result.StatusMessage) or result
HttpResponse.Headers = success and result.Headers or {}
HttpResponse.Body = success and (result.Body or "") or nil
return setmetatable(HttpResponse, {
__metatable = "HttpResponse",
__index = function(_, index)
error("Attempt to index non-existant value HttpResponse." .. tostring(index))
end
})
end
return newHttpResponse
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBX77245AE0C27B4592B46B384745C8C143">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">TypeGuards</string>
<string name="ScriptGuid">{382423F1-5F84-44A8-A2DF-13BD679896B5}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: https-queue/TypeGuards.lua
Description: Type guards to validate http-queue interfaces
SPDX-License-Identifier: MIT
]]
local t = require(script.Parent.DependencyLoader).t
local guards = {}
guards.isHttpRequest = t.intersection(t.strictInterface({
Url = t.string,
Send = t.callback,
AwaitSend = t.callback
}), function(o)
return getmetatable(o) == "HttpRequest"
end)
guards.isHttpRequestPriority = t.intersection(t.strictInterface({
Value = t.number,
}), function(o)
return getmetatable(o) == "HttpRequestPriority"
end)
guards.isHttpResponse = t.intersection(t.strictInterface({
ConnectionSuccessful = t.boolean,
RequestSuccessful = t.boolean,
StatusCode = t.number,
StatusMessage = t.string,
Headers = t.map(t.string, t.string),
Body = t.string
}), function(o)
return getmetatable(o) == "HttpResponse"
end)
guards.isHttpQueue = t.intersection(t.strictInterface({
__metatable = t.literal("HttpQueue"),
QueueSize = t.callback,
Push = t.callback,
AwaitPush = t.callback
}), function(o)
return getmetatable(o) == "HttpQueue"
end)
return guards
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
</Item>
<Item class="ModuleScript" referent="RBXBE0CB7CD96284A88BDECE31F32EB25C0">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">DependencyLoader</string>
<string name="ScriptGuid">{EF6C05AA-C118-4C7A-BF02-071824745A03}</string>
<ProtectedString name="Source"><![CDATA[--[[
File: http-queue/DependencyLoader.lua
Description: Loads runtime dependencies
SPDX-License-Identifier: MIT
]]
--[[
EXTERNAL DEPENDENCIES:
- evaera/roblox-lua-promise (Built in the roblox-ts runtime)
- osyrisrblx/t (@rbxts/t)
]]
local dependencies = {}
local TS = _G[script.Parent]
if TS then
-- Module was loaded via Roblox-TS
dependencies.Promise = TS.Promise
dependencies.t = TS.import(script.Parent, TS.getModule(script.Parent, "t").lib.ts).t
else
-- Load dependencies locally
dependencies.Promise = require(script.Promise)
dependencies.t = require(script.t)
end
dependencies.HttpService = game:GetService("HttpService")
return dependencies
]]></ProtectedString>
<int64 name="SourceAssetId">-1</int64>
<BinaryString name="Tags"></BinaryString>
</Properties>
<Item class="ModuleScript" referent="RBX428159ECAF6A4FE0BD2D69AA07030F52">
<Properties>
<BinaryString name="AttributesSerialize"></BinaryString>
<Content name="LinkedSource"><null></null></Content>
<string name="Name">Promise</string>
<string name="ScriptGuid">{FEAE220C-41AE-42E8-A99E-7B6B2C89983A}</string>
<ProtectedString name="Source"><![CDATA[--[[
An implementation of Promises similar to Promise/A+.
]]
local ERROR_NON_PROMISE_IN_LIST = "Non-promise value passed into %s at index %s"
local ERROR_NON_LIST = "Please pass a list of promises to %s"
local ERROR_NON_FUNCTION = "Please pass a handler function to %s!"
local MODE_KEY_METATABLE = {__mode = "k"}
--[[
Creates an enum dictionary with some metamethods to prevent common mistakes.
]]
local function makeEnum(enumName, members)
local enum = {}
for _, memberName in ipairs(members) do
enum[memberName] = memberName
end
return setmetatable(enum, {
__index = function(_, k)
error(string.format("%s is not in %s!", k, enumName), 2)
end,
__newindex = function()
error(string.format("Creating new members in %s is not allowed!", enumName), 2)
end,
})
end
--[[
An object to represent runtime errors that occur during execution.
Promises that experience an error like this will be rejected with
an instance of this object.
]]
local Error do
Error = {
Kind = makeEnum("Promise.Error.Kind", {
"ExecutionError",
"AlreadyCancelled",
"NotResolvedInTime",
"TimedOut",
}),
}
Error.__index = Error
function Error.new(options, parent)
options = options or {}
return setmetatable({
error = tostring(options.error) or "[This error has no error text.]",
trace = options.trace,
context = options.context,
kind = options.kind,
parent = parent,
createdTick = os.clock(),
createdTrace = debug.traceback(),
}, Error)
end
function Error.is(anything)
if type(anything) == "table" then
local metatable = getmetatable(anything)
if type(metatable) == "table" then
return rawget(anything, "error") ~= nil and type(rawget(metatable, "extend")) == "function"
end
end
return false
end
function Error.isKind(anything, kind)
assert(kind ~= nil, "Argument #2 to Promise.Error.isKind must not be nil")
return Error.is(anything) and anything.kind == kind
end
function Error:extend(options)
options = options or {}
options.kind = options.kind or self.kind
return Error.new(options, self)
end
function Error:getErrorChain()
local runtimeErrors = { self }
while runtimeErrors[#runtimeErrors].parent do
table.insert(runtimeErrors, runtimeErrors[#runtimeErrors].parent)
end
return runtimeErrors
end
function Error:__tostring()
local errorStrings = {
string.format("-- Promise.Error(%s) --", self.kind or "?"),
}
for _, runtimeError in ipairs(self:getErrorChain()) do
table.insert(errorStrings, table.concat({
runtimeError.trace or runtimeError.error,
runtimeError.context,
}, "\n"))
end
return table.concat(errorStrings, "\n")
end
end
--[[
Packs a number of arguments into a table and returns its length.
Used to cajole varargs without dropping sparse values.
]]
local function pack(...)
return select("#", ...), { ... }
end
--[[
Returns first value (success), and packs all following values.
]]
local function packResult(success, ...)
return success, select("#", ...), { ... }
end
local function makeErrorHandler(traceback)
assert(traceback ~= nil)
return function(err)
-- If the error object is already a table, forward it directly.
-- Should we extend the error here and add our own trace?
if type(err) == "table" then
return err
end
return Error.new({
error = err,
kind = Error.Kind.ExecutionError,
trace = debug.traceback(tostring(err), 2),
context = "Promise created at:\n\n" .. traceback,
})
end
end
--[[
Calls a Promise executor with error handling.
]]
local function runExecutor(traceback, callback, ...)
return packResult(xpcall(callback, makeErrorHandler(traceback), ...))
end
--[[
Creates a function that invokes a callback with correct error handling and
resolution mechanisms.
]]
local function createAdvancer(traceback, callback, resolve, reject)
return function(...)