-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathLibOpenRaid.lua
3236 lines (2678 loc) · 138 KB
/
LibOpenRaid.lua
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
--[=[
search keys:
~internal
~comms
~timers
~callbacks
~unitinfo
~equipment
~opennotes
~cooldowns
~keystones
Please refer to the docs.txt within this file folder for a guide on how to use this library.
If you get lost on implementing the lib, be free to contact Tercio on Details! discord: https://discord.gg/AGSzAZX or email to [email protected]
--PLAYER_AVG_ITEM_LEVEL_UPDATE
UnitID:
UnitID use: "player", "target", "raid18", "party3", etc...
If passing the unit name, use GetUnitName(unitId, true) or Ambiguate(playerName, 'none')
Code Rules:
- When a function or variable name refers to 'Player', it indicates the local player.
- When 'Unit' is use instead, it indicates any entity.
- Internal callbacks are the internal communication of the library, e.g. when an event triggers it send to all modules that registered that event.
- Public callbacks are callbacks registered by an external addon.
TODO:
- add into gear info how many tier set parts the player has
- raid lockouts normal-heroic-mythic
BUGS:
- after a /reload, it is not starting new tickers for spells under cooldown
--]=]
---@alias castername string
---@alias castspellid string
---@alias schedulename string
LIB_OPEN_RAID_CAN_LOAD = false
local versionString, revision, launchDate, gameVersion = GetBuildInfo()
local isExpansion_Dragonflight = function()
if (gameVersion >= 100000) then
return true
end
end
--don't load if it's not retail, emergencial patch due to classic and bcc stuff not transposed yet
if (WOW_PROJECT_ID ~= WOW_PROJECT_MAINLINE and not isExpansion_Dragonflight()) then
return
end
local major = "LibOpenRaid-1.0"
local CONST_LIB_VERSION = 148
if (LIB_OPEN_RAID_MAX_VERSION) then
if (CONST_LIB_VERSION <= LIB_OPEN_RAID_MAX_VERSION) then
return
end
end
--declare the library within the LibStub
local libStub = _G.LibStub
local openRaidLib = libStub:NewLibrary(major, CONST_LIB_VERSION)
if (not openRaidLib) then
return
end
openRaidLib.__version = CONST_LIB_VERSION
LIB_OPEN_RAID_CAN_LOAD = true
LIB_OPEN_RAID_MAX_VERSION = CONST_LIB_VERSION
--locals
local unpack = table.unpack or _G.unpack
openRaidLib.__errors = {} --/dump LibStub:GetLibrary("LibOpenRaid-1.0").__errors
--default values
openRaidLib.inGroup = false
openRaidLib.UnitIDCache = {}
openRaidLib.Util = openRaidLib.Util or {}
local CONST_CVAR_TEMPCACHE = "LibOpenRaidTempCache"
local CONST_CVAR_TEMPCACHE_DEBUG = "LibOpenRaidTempCacheDebug"
--delay to request all data from other players
local CONST_REQUEST_ALL_DATA_COOLDOWN = 30
--delay to send all data to other players
local CONST_SEND_ALL_DATA_COOLDOWN = 30
--show failures (when the function return an error) results to chat
local CONST_DIAGNOSTIC_ERRORS = false
--show the data to be sent and data received from comm
local CONST_DIAGNOSTIC_COMM = false
--show data received from other players
local CONST_DIAGNOSTIC_COMM_RECEIVED = false
local CONST_COMM_PREFIX = "LRS"
local CONST_COMM_PREFIX_LOGGED = "LRS_LOGGED"
local CONST_COMM_FULLINFO_PREFIX = "F"
local CONST_COMM_COOLDOWNUPDATE_PREFIX = "U"
local CONST_COMM_COOLDOWNFULLLIST_PREFIX = "C"
local CONST_COMM_COOLDOWNCHANGES_PREFIX = "S"
local CONST_COMM_COOLDOWNREQUEST_PREFIX = "Z"
local CONST_COMM_GEARINFO_FULL_PREFIX = "G"
local CONST_COMM_GEARINFO_DURABILITY_PREFIX = "R"
local CONST_COMM_PLAYER_DEAD_PREFIX = "D"
local CONST_COMM_PLAYER_ALIVE_PREFIX = "A"
local CONST_COMM_PLAYERINFO_PREFIX = "P"
local CONST_COMM_KEYSTONE_DATA_PREFIX = "K"
local CONST_COMM_KEYSTONE_DATAREQUEST_PREFIX = "J"
local CONST_COMM_OPENNOTES_RECEIVED_PREFIX = "N" --when a note is received
local CONST_COMM_OPENNOTES_REQUESTED_PREFIX = "Q" --when received a request to send your note
local CONST_COMM_SENDTO_PARTY = "0x1"
local CONST_COMM_SENDTO_RAID = "0x2"
local CONST_COMM_SENDTO_GUILD = "0x4"
local CONST_ONE_SECOND = 1.0
local CONST_TWO_SECONDS = 2.0
local CONST_THREE_SECONDS = 3.0
local CONST_SPECIALIZATION_VERSION_CLASSIC = 0
local CONST_SPECIALIZATION_VERSION_MODERN = 1
local CONST_COOLDOWN_CHECK_INTERVAL = CONST_THREE_SECONDS
local CONST_COOLDOWN_TIMELEFT_HAS_CHANGED = CONST_THREE_SECONDS
local CONST_COOLDOWN_INDEX_TIMELEFT = 1
local CONST_COOLDOWN_INDEX_CHARGES = 2
local CONST_COOLDOWN_INDEX_TIMEOFFSET = 3
local CONST_COOLDOWN_INDEX_DURATION = 4
local CONST_COOLDOWN_INDEX_UPDATETIME = 5
local CONST_COOLDOWN_INDEX_AURA_DURATION = 6
local CONST_COOLDOWN_INFO_SIZE = 6
local CONST_USE_DEFAULT_SCHEDULE_TIME = true
-- Real throttle is 10 messages per 1 second, but we want to be safe due to fact we dont know when it actually resets
local CONST_COMM_BURST_BUFFER_COUNT = 9
local GetContainerNumSlots = GetContainerNumSlots or C_Container.GetContainerNumSlots
local GetContainerItemID = GetContainerItemID or C_Container.GetContainerItemID
local GetContainerItemLink = GetContainerItemLink or C_Container.GetContainerItemLink
--from vanilla to cataclysm, the specID did not existed, hence its considered version 0
--for mists of pandaria and beyond it's version 1
local getSpecializationVersion = function()
if (gameVersion >= 50000) then
return CONST_SPECIALIZATION_VERSION_MODERN
else
return CONST_SPECIALIZATION_VERSION_CLASSIC
end
end
function openRaidLib.ShowDiagnosticErrors(value)
CONST_DIAGNOSTIC_ERRORS = value
end
--make the 'pri-nt' word be only used once, this makes easier to find lost debug pri-nts in the code
local sendChatMessage = function(...)
print(...)
end
openRaidLib.DiagnosticError = function(msg, ...)
if (CONST_DIAGNOSTIC_ERRORS) then
sendChatMessage("|cFFFF9922OpenRaidLib|r:", msg, ...)
end
end
local diagnosticFilter = nil
local diagnosticComm = function(msg, ...)
if (CONST_DIAGNOSTIC_COMM) then
if (diagnosticFilter) then
local lowerMessage = msg:lower()
if (lowerMessage:find(diagnosticFilter)) then
sendChatMessage("|cFFFF9922OpenRaidLib|r:", msg, ...)
--dumpt(msg)
end
else
sendChatMessage("|cFFFF9922OpenRaidLib|r:", msg, ...)
end
end
end
local diagnosticCommReceivedFilter = false
openRaidLib.diagnosticCommReceived = function(msg, ...)
if (diagnosticCommReceivedFilter) then
local lowerMessage = msg:lower()
if (lowerMessage:find(diagnosticCommReceivedFilter)) then
sendChatMessage("|cFFFF9922OpenRaidLib|r:", msg, ...)
end
else
sendChatMessage("|cFFFF9922OpenRaidLib|r:", msg, ...)
end
end
openRaidLib.DeprecatedMessage = function(msg)
sendChatMessage("|cFFFF9922OpenRaidLib|r:", "|cFFFF5555" .. msg .. "|r")
end
local isTimewalkWoW = function()
local _, _, _, buildInfo = GetBuildInfo()
if (buildInfo < 40000) then
return true
end
end
local checkClientVersion = function(...)
for i = 1, select("#", ...) do
local clientVersion = select(i, ...)
if (clientVersion == "retail" and (WOW_PROJECT_ID == WOW_PROJECT_MAINLINE or isExpansion_Dragonflight())) then --retail
return true
elseif (clientVersion == "classic_era" and WOW_PROJECT_ID == WOW_PROJECT_CLASSIC) then --classic era (vanila)
return true
elseif (clientVersion == "bcc" and WOW_PROJECT_ID == WOW_PROJECT_BURNING_CRUSADE_CLASSIC) then --the burning crusade classic
return true
end
end
end
--------------------------------------------------------------------------------------------------------------------------------
--~internal cache
--use a console variable to create a flash cache to keep data while the game reload
--this is not a long term database as saved variables are and it get clean up often
C_CVar.RegisterCVar(CONST_CVAR_TEMPCACHE)
C_CVar.RegisterCVar(CONST_CVAR_TEMPCACHE_DEBUG)
--internal namespace
local tempCache = {
debugString = "",
}
tempCache.copyCache = function(t1, t2)
for key, value in pairs(t2) do
if (type(value) == "table") then
t1[key] = t1[key] or {}
tempCache.copyCache(t1[key], t2[key])
else
t1[key] = value
end
end
return t1
end
--use debug cvar to find issues that occurred during the logoff process
function openRaidLib.PrintTempCacheDebug()
local debugMessage = C_CVar.GetCVar(CONST_CVAR_TEMPCACHE_DEBUG)
sendChatMessage("|cFFFF9922OpenRaidLib|r Temp CVar Result:\n", debugMessage)
end
function tempCache.SaveDebugText()
C_CVar.SetCVar(CONST_CVAR_TEMPCACHE_DEBUG, "0")
--C_CVar.SetCVar(CONST_CVAR_TEMPCACHE_DEBUG, tempCache.debugString)
end
function tempCache.AddDebugText(text)
tempCache.debugString = tempCache.debugString .. date("%H:%M:%S") .. "| " .. text .. "\n"
end
function tempCache.SaveCacheOnCVar(data)
C_CVar.SetCVar(CONST_CVAR_TEMPCACHE, "0")
--C_CVar.SetCVar(CONST_CVAR_TEMPCACHE, data)
tempCache.AddDebugText("CVars Saved on saveCahceOnCVar(), Size: " .. #data)
end
function tempCache.RestoreData()
local data = C_CVar.GetCVar(CONST_CVAR_TEMPCACHE)
if (data and type(data) == "string" and string.len(data) > 2) then
local LibAceSerializer = LibStub:GetLibrary("AceSerializer-3.0", true)
if (LibAceSerializer) then
local okay, cacheInfo = LibAceSerializer:Deserialize(data)
if (okay) then
local age = cacheInfo.createdAt
--if the data is older than 5 minutes, much has been changed from the group and the data is out dated
if (age + (60 * 5) < time()) then
return
end
local unitsInfo = cacheInfo.unitsInfo
local cooldownsInfo = cacheInfo.cooldownsInfo
local gearInfo = cacheInfo.gearInfo
local okayUnitsInfo, unitsInfo = LibAceSerializer:Deserialize(unitsInfo)
local okayCooldownsInfo, cooldownsInfo = LibAceSerializer:Deserialize(cooldownsInfo)
local okayGearInfo, gearInfo = LibAceSerializer:Deserialize(gearInfo)
if (okayUnitsInfo and unitsInfo) then
openRaidLib.UnitInfoManager.UnitData = tempCache.copyCache(openRaidLib.UnitInfoManager.UnitData, unitsInfo)
else
tempCache.AddDebugText("invalid UnitInfo")
end
if (okayCooldownsInfo and cooldownsInfo) then
openRaidLib.CooldownManager.UnitData = tempCache.copyCache(openRaidLib.CooldownManager.UnitData, cooldownsInfo)
else
tempCache.AddDebugText("invalid CooldownsInfo")
end
if (okayGearInfo and gearInfo) then
openRaidLib.GearManager.UnitData = tempCache.copyCache(openRaidLib.GearManager.UnitData, gearInfo)
else
tempCache.AddDebugText("invalid GearInfo")
end
else
tempCache.AddDebugText("Deserialization not okay, reason: " .. cacheInfo)
end
else
tempCache.AddDebugText("LibAceSerializer not found")
end
else
if (not data) then
tempCache.AddDebugText("invalid temporary cache: getCVar returned nil")
elseif (type(data) ~= "string") then
tempCache.AddDebugText("invalid temporary cache: getCVar did not returned a string")
elseif (string.len(data) < 2) then
tempCache.AddDebugText("invalid temporary cache: data length lower than 2 bytes (first login?)")
else
tempCache.AddDebugText("invalid temporary cache: no reason found")
end
end
end
function tempCache.SaveData()
tempCache.AddDebugText("SaveData() called.")
local LibAceSerializer = LibStub:GetLibrary("AceSerializer-3.0", true)
if (LibAceSerializer) then
local allUnitsInfo = openRaidLib.UnitInfoManager.UnitData
local allUnitsCooldowns = openRaidLib.CooldownManager.UnitData
local allPlayersGear = openRaidLib.GearManager.UnitData
local cacheInfo = {
createdAt = time(),
}
local unitsInfoSerialized = LibAceSerializer:Serialize(allUnitsInfo)
local unitsCooldownsSerialized = LibAceSerializer:Serialize(allUnitsCooldowns)
local playersGearSerialized = LibAceSerializer:Serialize(allPlayersGear)
if (unitsInfoSerialized) then
cacheInfo.unitsInfo = unitsInfoSerialized
tempCache.AddDebugText("SaveData() units info serialized okay.")
else
tempCache.AddDebugText("SaveData() units info serialized failed.")
end
if (unitsCooldownsSerialized) then
cacheInfo.cooldownsInfo = unitsCooldownsSerialized
tempCache.AddDebugText("SaveData() cooldowns info serialized okay.")
else
tempCache.AddDebugText("SaveData() cooldowns info serialized failed.")
end
if (playersGearSerialized) then
cacheInfo.gearInfo = playersGearSerialized
tempCache.AddDebugText("SaveData() gear info serialized okay.")
else
tempCache.AddDebugText("SaveData() gear info serialized failed.")
end
local cacheInfoSerialized = LibAceSerializer:Serialize(cacheInfo)
tempCache.SaveCacheOnCVar(cacheInfoSerialized)
else
tempCache.AddDebugText("SaveData() AceSerializer not found.")
end
tempCache.SaveDebugText()
end
--------------------------------------------------------------------------------------------------------------------------------
--~comms
openRaidLib.commHandler = {}
function openRaidLib.commHandler.OnReceiveComm(self, event, prefix, text, channel, sender, target, zoneChannelID, localID, name, instanceID)
--check if the data belong to us
if (prefix == CONST_COMM_PREFIX) then
sender = Ambiguate(sender, "none")
--don't receive comms from the player it self
local playerName = UnitName("player")
if (playerName == sender) then
return
end
local commId = 0
--verify if this is a safe comm
local data = ""
local bIsSafe = event == "CHAT_MSG_ADDON_LOGGED"
if (bIsSafe) then
data = text:gsub("%%", "\n")
--replace the the first ";" found in the data string with a ",", only the first occurence
data = data:gsub(";", ",", 1)
--get the commId
commId = data:match("#([^#]+)$")
--remove the commId from the data
data = data:gsub("#([^#]+)$", "")
--add the commId to the end of the data after a comma
data = data .. "," .. commId
else
data = text
local LibDeflate = LibStub:GetLibrary("LibDeflate")
local dataCompressed = LibDeflate:DecodeForWoWAddonChannel(data)
data = LibDeflate:DecompressDeflate(dataCompressed)
end
--some users are reporting errors where 'data is nil'. Making some sanitization
if (not data) then
openRaidLib.DiagnosticError("Invalid data from player:", sender, "data:", text)
return
elseif (type(data) ~= "string") then
openRaidLib.DiagnosticError("Invalid data from player:", sender, "data:", text, "data type is:", type(data))
return
end
--get the first byte of the data, it indicates what type of data was transmited
local dataTypePrefix = data:match("^.")
if (not dataTypePrefix) then
openRaidLib.DiagnosticError("Invalid dataTypePrefix from player:", sender, "data:", data, "dataTypePrefix:", dataTypePrefix)
return
elseif (openRaidLib.commPrefixDeprecated[dataTypePrefix]) then
openRaidLib.DiagnosticError("Invalid dataTypePrefix from player:", sender, "data:", data, "dataTypePrefix:", dataTypePrefix)
return
end
--if this is isn't a keystone data comm, check if the lib can receive comms
if (dataTypePrefix ~= CONST_COMM_KEYSTONE_DATA_PREFIX and dataTypePrefix ~= CONST_COMM_KEYSTONE_DATAREQUEST_PREFIX) then
if (not openRaidLib.IsCommAllowed()) then
openRaidLib.DiagnosticError("comm not allowed.")
return
end
end
if (CONST_DIAGNOSTIC_COMM_RECEIVED) then
openRaidLib.diagnosticCommReceived(data)
end
--get the table with functions regitered for this type of data
local callbackTable = openRaidLib.commHandler.commCallback[dataTypePrefix]
if (not callbackTable) then
openRaidLib.DiagnosticError("Not callbackTable for dataTypePrefix:", dataTypePrefix, "from player:", sender, "data:", data)
return
end
--convert to table
local dataAsTable = {strsplit(",", data)}
--remove the first index (prefix)
table.remove(dataAsTable, 1)
--trigger callbacks
for i = 1, #callbackTable do
--dumpt(dataAsTable)
callbackTable[i](dataAsTable, sender)
end
end
end
C_ChatInfo.RegisterAddonMessagePrefix(CONST_COMM_PREFIX)
openRaidLib.commHandler.eventFrame = CreateFrame("frame")
openRaidLib.commHandler.eventFrame:RegisterEvent("CHAT_MSG_ADDON")
openRaidLib.commHandler.eventFrame:RegisterEvent("CHAT_MSG_ADDON_LOGGED")
openRaidLib.commHandler.eventFrame:SetScript("OnEvent", openRaidLib.commHandler.OnReceiveComm)
openRaidLib.commHandler.commCallback = {
--when transmiting
[CONST_COMM_FULLINFO_PREFIX] = {}, --update all
[CONST_COMM_COOLDOWNFULLLIST_PREFIX] = {}, --all cooldowns of a player
[CONST_COMM_COOLDOWNUPDATE_PREFIX] = {}, --an update of a single cooldown
[CONST_COMM_COOLDOWNCHANGES_PREFIX] = {}, --cooldowns got added or removed
[CONST_COMM_COOLDOWNREQUEST_PREFIX] = {}, --a unit requested an update on a spell
[CONST_COMM_GEARINFO_FULL_PREFIX] = {}, --an update of gear information
[CONST_COMM_GEARINFO_DURABILITY_PREFIX] = {}, --an update of the player gear durability
[CONST_COMM_PLAYER_DEAD_PREFIX] = {}, --player is dead
[CONST_COMM_PLAYER_ALIVE_PREFIX] = {}, --player is alive
[CONST_COMM_PLAYERINFO_PREFIX] = {}, --info about the player
[CONST_COMM_KEYSTONE_DATA_PREFIX] = {}, --received keystone data
[CONST_COMM_KEYSTONE_DATAREQUEST_PREFIX] = {}, --received a request to send keystone data
[CONST_COMM_OPENNOTES_RECEIVED_PREFIX] = {}, --received notes
[CONST_COMM_OPENNOTES_REQUESTED_PREFIX] = {}, --requested notes
}
function openRaidLib.commHandler.RegisterComm(prefix, func)
--the table for the prefix need to be declared at the 'openRaidLib.commHandler.commCallback' table
tinsert(openRaidLib.commHandler.commCallback[prefix], func)
end
local charactesrPerMessage = 251
local receivingMsgInParts = {}
local debugCommReception = CreateFrame("frame")
debugCommReception:RegisterEvent("CHAT_MSG_ADDON_LOGGED")
debugCommReception:SetScript("OnEvent", function(self, event, prefix, text, channel, sender, target, zoneChannelID, localID, name, instanceID)
if (prefix == CONST_COMM_PREFIX_LOGGED) then
local chunkNumber, totalChunks, data = text:match("^%$(%d+)%$(%d+)(.*)")
local onlyData = text:match("^(.*)")
if (not chunkNumber and not totalChunks and onlyData) then
openRaidLib.commHandler.OnReceiveComm(self, "CHAT_MSG_ADDON_LOGGED", CONST_COMM_PREFIX, onlyData, channel, sender, target, zoneChannelID, localID, name, instanceID)
elseif (chunkNumber and totalChunks and data) then
chunkNumber = tonumber(chunkNumber)
totalChunks = tonumber(totalChunks)
if (chunkNumber and totalChunks) then
if (chunkNumber <= totalChunks and chunkNumber >= 1) then
if (not receivingMsgInParts[sender]) then
local parts = {}
for i = 1, totalChunks do
parts[i] = false
end
receivingMsgInParts[sender] = {
totalChunks = totalChunks,
chunks = parts
}
end
receivingMsgInParts[sender].chunks[chunkNumber] = data
--verify if all parts were received
local allPartsReceived = true
for i = 1, totalChunks do
if (not receivingMsgInParts[sender].chunks[i]) then
allPartsReceived = false
break
end
end
if (allPartsReceived) then
local fullData = ""
--sew the parts together
for i = 1, totalChunks do
fullData = fullData .. receivingMsgInParts[sender].chunks[i]
end
receivingMsgInParts[sender] = nil
openRaidLib.commHandler.OnReceiveComm(self, "CHAT_MSG_ADDON_LOGGED", CONST_COMM_PREFIX, fullData, channel, sender, target, zoneChannelID, localID, name, instanceID)
end
end
end
else
openRaidLib.DiagnosticError("Logged comm in parts missing information, sender:", sender, "chunkNumber:", chunkNumber, "totalChunks:", totalChunks, "data:", type(data))
end
end
end)
--@flags
--0x1: to party
--0x2: to raid
--0x4: to guild
local sendData = function(dataEncoded, channel, bIsSafe, plainText)
local aceComm = LibStub:GetLibrary("AceComm-3.0", true)
if (aceComm) then
if (bIsSafe) then
plainText = plainText:gsub("\n", "%%")
plainText = plainText:gsub(",", ";")
local commId = tostring(GetServerTime() + GetTime())
plainText = plainText .. "#" .. commId
if (plainText:len() > 255) then
local totalMessages = math.ceil(plainText:len() / charactesrPerMessage)
for i = 1, totalMessages do
local chunk = plainText:sub((i - 1) * charactesrPerMessage + 1, i * charactesrPerMessage)
local chunkNumberAndTotalChuncks = "$" .. i .. "$" .. totalMessages
local chunkMessage = chunkNumberAndTotalChuncks .. chunk
ChatThrottleLib:SendAddonMessageLogged("NORMAL", CONST_COMM_PREFIX_LOGGED, chunkMessage, channel)
end
else
ChatThrottleLib:SendAddonMessageLogged("NORMAL", CONST_COMM_PREFIX_LOGGED, plainText, channel)
end
else
aceComm:SendCommMessage(CONST_COMM_PREFIX, dataEncoded, channel, nil, "ALERT")
end
else
C_ChatInfo.SendAddonMessage(CONST_COMM_PREFIX, dataEncoded, channel)
end
end
if (C_ChatInfo) then
C_ChatInfo.RegisterAddonMessagePrefix(CONST_COMM_PREFIX_LOGGED)
else
RegisterAddonMessagePrefix(CONST_COMM_PREFIX_LOGGED)
end
---@class commdata : table
---@field data string
---@field channel string
---@field bIsSafe boolean
---@field plainText string
---@type {}[]
local commScheduler = {};
local commBurstBufferCount = CONST_COMM_BURST_BUFFER_COUNT;
local commServerTimeLastThrottleUpdate = GetServerTime();
do
--if there's an old version that already registered the comm ticker, cancel it
if (LIB_OPEN_RAID_COMM_SCHEDULER) then
LIB_OPEN_RAID_COMM_SCHEDULER:Cancel();
end
local newTickerHandle = C_Timer.NewTicker(0.05, function()
local serverTime = GetServerTime();
-- Replenish the counter if last server time is not the same as the last throttle update
-- Clamp it to CONST_COMM_BURST_BUFFER_COUNT
commBurstBufferCount = math.min((serverTime ~= commServerTimeLastThrottleUpdate) and commBurstBufferCount + 1 or commBurstBufferCount, CONST_COMM_BURST_BUFFER_COUNT);
commServerTimeLastThrottleUpdate = serverTime;
-- while (anything in queue) and (throttle allows it)
while(#commScheduler > 0 and commBurstBufferCount > 0) do
-- FIFO queue
---@type commdata
local commData = table.remove(commScheduler, 1);
sendData(commData.data, commData.channel, commData.bIsSafe, commData.plainText);
commBurstBufferCount = commBurstBufferCount - 1;
end
end);
LIB_OPEN_RAID_COMM_SCHEDULER = newTickerHandle
end
function openRaidLib.commHandler.SendCommData(data, flags, bIsSafe)
local LibDeflate = LibStub:GetLibrary("LibDeflate")
local dataCompressed = LibDeflate:CompressDeflate(data, {level = 9})
local dataEncoded = LibDeflate:EncodeForWoWAddonChannel(dataCompressed)
if (flags) then
if (bit.band(flags, CONST_COMM_SENDTO_PARTY)) then --send to party
if (IsInGroup() and not IsInRaid()) then
---@type commdata
local commData = {data = dataEncoded, channel = IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "PARTY", bIsSafe = bIsSafe, plainText = data}
table.insert(commScheduler, commData)
end
end
if (bit.band(flags, CONST_COMM_SENDTO_RAID)) then --send to raid
if (IsInRaid()) then
local commData = {data = dataEncoded, channel = IsInRaid(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "RAID", bIsSafe = bIsSafe, plainText = data}
table.insert(commScheduler, commData)
end
end
if (bit.band(flags, CONST_COMM_SENDTO_GUILD)) then --send to guild
if (IsInGuild()) then
--Guild has no 10 msg restriction so send it directly
sendData(dataEncoded, "GUILD");
end
end
else
if (IsInGroup() and not IsInRaid()) then --in party only
local commData = {data = dataEncoded, channel = IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "PARTY", bIsSafe = bIsSafe, plainText = data}
table.insert(commScheduler, commData)
elseif (IsInRaid()) then
local commData = {data = dataEncoded, channel = IsInRaid(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "RAID", bIsSafe = bIsSafe, plainText = data}
table.insert(commScheduler, commData)
end
end
end
--------------------------------------------------------------------------------------------------------------------------------
--~schedule ~timers
---@type table<schedulename, number>
local defaultScheduleCooldownTimeByScheduleName = {
["sendAllPlayerCooldownsFromTalentChange_Schedule"] = 2,
["talentChangedCallback_Schedule"] = 20,
["sendFullData_Schedule"] = 25,
["sendAllPlayerCooldowns_Schedule"] = 23,
["sendDurability_Schedule"] = 10,
["sendAllGearInfo_Schedule"] = 20,
["petStatus_Schedule"] = 8,
["updatePlayerData_Schedule"] = 22,
["sendTalent_Schedule"] = 20,
["sendPvPTalent_Schedule"] = 14,
["leaveCombat_Schedule"] = 18,
["encounterEndCooldownsCheck_Schedule"] = 24,
--["sendKeystoneInfoToParty_Schedule"] = 2,
--["sendKeystoneInfoToGuild_Schedule"] = 2,
}
openRaidLib.Schedules = {
registeredUniqueTimers = {}
}
local timersCanRunWithoutGroup = {
["mainControl"] = {
["updatePlayerData_Schedule"] = true
}
}
--run a scheduled function with its payload
local triggerScheduledTick = function(tickerObject)
local payload = tickerObject.payload
local callback = tickerObject.callback
local bCanRunWithoutGroup = tickerObject.bCanRunWithoutGroup
if (tickerObject.isUnique) then
local namespace = tickerObject.namespace
local scheduleName = tickerObject.scheduleName
openRaidLib.Schedules.CancelUniqueTimer(namespace, scheduleName)
end
--check if the player is still in group
if (not openRaidLib.IsInGroup()) then
if (not bCanRunWithoutGroup) then
return
end
end
local result, errortext = xpcall(callback, geterrorhandler(), unpack(payload))
--local result, errortext = pcall(callback, unpack(payload))
if (not result) then
sendChatMessage("openRaidLib: error on scheduler:", tickerObject.scheduleName, tickerObject.stack)
end
return result
end
--create a new schedule
function openRaidLib.Schedules.NewTimer(time, callback, bCanRunWithoutGroup, ...)
local payload = {...}
local newTimer = C_Timer.NewTimer(time, triggerScheduledTick)
newTimer.bCanRunWithoutGroup = bCanRunWithoutGroup
newTimer.payload = payload
newTimer.callback = callback
--newTimer.stack = debugstack()
return newTimer
end
--create an unique schedule
--if a schedule already exists, cancels it and make a new ~unique
function openRaidLib.Schedules.NewUniqueTimer(time, callback, namespace, scheduleName, ...)
--the the schedule uses a default time, get it from the table, if the timer already exists, quit
if (time == CONST_USE_DEFAULT_SCHEDULE_TIME) then
if (openRaidLib.Schedules.IsUniqueTimerOnCooldown(namespace, scheduleName)) then
return
end
time = defaultScheduleCooldownTimeByScheduleName[scheduleName] or time
else
openRaidLib.Schedules.CancelUniqueTimer(namespace, scheduleName)
end
local bCanRunWithoutGroup = timersCanRunWithoutGroup[namespace] and timersCanRunWithoutGroup[namespace][scheduleName]
local newTimer = openRaidLib.Schedules.NewTimer(time, callback, bCanRunWithoutGroup, ...)
newTimer.namespace = namespace
newTimer.scheduleName = scheduleName
--newTimer.stack = debugstack()
newTimer.isUnique = true
local registeredUniqueTimers = openRaidLib.Schedules.registeredUniqueTimers
registeredUniqueTimers[namespace] = registeredUniqueTimers[namespace] or {}
registeredUniqueTimers[namespace][scheduleName] = newTimer
end
--does timer by schedule name exists?
function openRaidLib.Schedules.IsUniqueTimerOnCooldown(namespace, scheduleName)
local registeredUniqueTimers = openRaidLib.Schedules.registeredUniqueTimers
local currentSchedule = registeredUniqueTimers[namespace] and registeredUniqueTimers[namespace][scheduleName]
if (currentSchedule) then
return true
end
return false
end
--cancel an unique schedule
function openRaidLib.Schedules.CancelUniqueTimer(namespace, scheduleName)
local registeredUniqueTimers = openRaidLib.Schedules.registeredUniqueTimers
local currentSchedule = registeredUniqueTimers[namespace] and registeredUniqueTimers[namespace][scheduleName]
if (currentSchedule) then
if (not currentSchedule:IsCancelled()) then
currentSchedule:Cancel()
end
registeredUniqueTimers[namespace][scheduleName] = nil
end
end
--cancel all unique timers
function openRaidLib.Schedules.CancelAllUniqueTimers()
local registeredUniqueTimers = openRaidLib.Schedules.registeredUniqueTimers
for namespace, schedulesTable in pairs(registeredUniqueTimers) do
for scheduleName, timerObject in pairs(schedulesTable) do
if (timerObject and not timerObject:IsCancelled()) then
timerObject:Cancel()
end
end
end
table.wipe(registeredUniqueTimers)
end
--------------------------------------------------------------------------------------------------------------------------------
--~public ~callbacks
--these are the events where other addons can register and receive calls
local allPublicCallbacks = {
"CooldownListUpdate",
"CooldownListWipe",
"CooldownUpdate",
"CooldownAdded",
"CooldownRemoved",
"UnitDeath",
"UnitAlive",
"GearListWipe",
"GearUpdate",
"GearDurabilityUpdate",
"UnitInfoUpdate",
"UnitInfoWipe",
"TalentUpdate", --deprecated
"PvPTalentUpdate", --deprecated
"KeystoneUpdate",
"KeystoneWipe",
"NoteUpdated",
}
--save build the table to avoid lose registered events on older versions
openRaidLib.publicCallback = openRaidLib.publicCallback or {}
openRaidLib.publicCallback.events = openRaidLib.publicCallback.events or {}
for _, callbackName in ipairs(allPublicCallbacks) do
openRaidLib.publicCallback.events[callbackName] = openRaidLib.publicCallback.events[callbackName] or {}
end
local checkRegisterDataIntegrity = function(addonObject, event, callbackMemberName)
--check of integrity
if (type(addonObject) == "string") then
addonObject = _G[addonObject]
end
if (type(addonObject) ~= "table") then
return 1
end
if (not openRaidLib.publicCallback.events[event]) then
return 2
elseif (not addonObject[callbackMemberName]) then
return 3
end
return true
end
--call the registered function within the addon namespace
--payload is sent together within the call
function openRaidLib.publicCallback.TriggerCallback(event, ...)
local eventCallbacks = openRaidLib.publicCallback.events[event]
for i = 1, #eventCallbacks do
local thisCallback = eventCallbacks[i] --got a case where this was nil, which is kinda impossible? | event: CooldownUpdate
local addonObject = thisCallback[1] --670: attempt to index local 'thisCallback' (a nil value)
local functionName = thisCallback[2]
--[=[
eventCallbacks = {
1 = {}
}
(for index) = 2
(for limit) = 2
(for step) = 1
i = 2
thisCallback = nil
--]=]
--get the function from within the addon object
local functionToCallback = addonObject[functionName]
if (functionToCallback) then
--if this isn't a function, xpcall trigger an error
local okay, errorMessage = xpcall(functionToCallback, geterrorhandler(), ...)
if (not okay) then
sendChatMessage("error on callback for event:", event)
end
else
--the registered function wasn't found
end
end
end
function openRaidLib.RegisterCallback(addonObject, event, callbackMemberName)
--check of integrity
local passIntegrityTest = checkRegisterDataIntegrity(addonObject, event, callbackMemberName)
if (passIntegrityTest and type(passIntegrityTest) ~= "boolean") then
return passIntegrityTest
end
--register
tinsert(openRaidLib.publicCallback.events[event], {addonObject, callbackMemberName})
return true
end
function openRaidLib.UnregisterCallback(addonObject, event, callbackMemberName)
--check of integrity
local passIntegrityTest = checkRegisterDataIntegrity(addonObject, event, callbackMemberName)
if (passIntegrityTest and type(passIntegrityTest) ~= "boolean") then
return passIntegrityTest
end
for i = 1, #openRaidLib.publicCallback.events[event] do
local registeredCallback = openRaidLib.publicCallback.events[event][i]
if (registeredCallback[1] == addonObject and registeredCallback[2] == callbackMemberName) then
table.remove(openRaidLib.publicCallback.events[event], i)
break
end
end
end
--------------------------------------------------------------------------------------------------------------------------------
--~internal ~callbacks
--internally, each module can register events through the internal callback to be notified when something happens in the game
openRaidLib.internalCallback = {}
openRaidLib.internalCallback.events = {
["onEnterGroup"] = {},
["onLeaveGroup"] = {},
["onLeaveCombat"] = {},
["playerCast"] = {},
["onEnterWorld"] = {},
["talentUpdate"] = {},
["pvpTalentUpdate"] = {},
["onPlayerDeath"] = {},
["onPlayerRess"] = {},
["raidEncounterEnd"] = {},
["mythicDungeonStart"] = {},
["playerPetChange"] = {},
["mythicDungeonEnd"] = {},
["unitAuraRemoved"] = {},
}
openRaidLib.internalCallback.RegisterCallback = function(event, func)
tinsert(openRaidLib.internalCallback.events[event], func)
end
openRaidLib.internalCallback.UnRegisterCallback = function(event, func)
local eventCallbacks = openRaidLib.internalCallback.events[event]
for i = 1, #eventCallbacks do
if (eventCallbacks[i] == func) then
table.remove(eventCallbacks, i)
break
end
end
end
function openRaidLib.internalCallback.TriggerEvent(event, ...)
local eventCallbacks = openRaidLib.internalCallback.events[event]
for i = 1, #eventCallbacks do
local functionToCallback = eventCallbacks[i]
functionToCallback(event, ...)
end
end
--create the frame for receiving game events
local eventFrame = _G.OpenRaidLibFrame
if (not eventFrame) then
eventFrame = CreateFrame("frame", "OpenRaidLibFrame", UIParent)
end
local talentChangedCallback = function()
openRaidLib.internalCallback.TriggerEvent("talentUpdate")
end
local delayedTalentChange = function()
openRaidLib.Schedules.NewUniqueTimer(math.random(4, 8), talentChangedCallback, "TalentChangeEventGroup", "talentChangedCallback_Schedule")
end
local eventFunctions = {
--check if the player joined a group
["GROUP_ROSTER_UPDATE"] = function()
local bEventTriggered = false
if (openRaidLib.IsInGroup()) then
if (not openRaidLib.inGroup) then
openRaidLib.inGroup = true
openRaidLib.internalCallback.TriggerEvent("onEnterGroup")
bEventTriggered = true
end
else