forked from Tercioo/Open-Raid-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLibOpenRaid.lua
2725 lines (2243 loc) · 119 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
--[=[
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]
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
--]=]
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 = 98
if (not LIB_OPEN_RAID_MAX_VERSION) then
LIB_OPEN_RAID_MAX_VERSION = CONST_LIB_VERSION
else
LIB_OPEN_RAID_MAX_VERSION = math.max(LIB_OPEN_RAID_MAX_VERSION, CONST_LIB_VERSION)
end
LIB_OPEN_RAID_CAN_LOAD = false
local unpack = table.unpack or _G.unpack
--declae 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
openRaidLib.__errors = {} --/dump LibStub:GetLibrary("LibOpenRaid-1.0").__errors
--default values
openRaidLib.inGroup = false
openRaidLib.UnitIDCache = {}
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_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_PLAYERINFO_TALENTS_PREFIX = "T"
local CONST_COMM_PLAYERINFO_PVPTALENTS_PREFIX = "V"
local CONST_COMM_KEYSTONE_DATA_PREFIX = "K"
local CONST_COMM_KEYSTONE_DATAREQUEST_PREFIX = "J"
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_ONE_SECOND
local CONST_COOLDOWN_TIMELEFT_HAS_CHANGED = CONST_ONE_SECOND
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 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 = nil
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 data = text
local LibDeflate = LibStub:GetLibrary("LibDeflate")
local dataCompressed = LibDeflate:DecodeForWoWAddonChannel(data)
data = LibDeflate:DecompressDeflate(dataCompressed)
--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)
tremove(dataAsTable, 1)
--trigger callbacks
for i = 1, #callbackTable do
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: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_PLAYERINFO_TALENTS_PREFIX] = {}, --talents info
[CONST_COMM_PLAYERINFO_PVPTALENTS_PREFIX] = {}, --pvp talents info
[CONST_COMM_KEYSTONE_DATA_PREFIX] = {}, --received keystone data
[CONST_COMM_KEYSTONE_DATAREQUEST_PREFIX] = {}, --received a request to send keystone data
}
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
--@flags
--0x1: to party
--0x2: to raid
--0x4: to guild
local sendData = function(dataEncoded, channel)
local aceComm = LibStub:GetLibrary("AceComm-3.0", true)
if (aceComm) then
aceComm:SendCommMessage(CONST_COMM_PREFIX, dataEncoded, channel, nil, "ALERT")
else
C_ChatInfo.SendAddonMessage(CONST_COMM_PREFIX, dataEncoded, channel)
end
end
function openRaidLib.commHandler.SendCommData(data, flags)
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
sendData(dataEncoded, IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "PARTY")
end
end
if (bit.band(flags, CONST_COMM_SENDTO_RAID)) then --send to raid
if (IsInRaid()) then
sendData(dataEncoded, IsInRaid(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "RAID")
end
end
if (bit.band(flags, CONST_COMM_SENDTO_GUILD)) then --send to guild
if (IsInGuild()) then
sendData(dataEncoded, "GUILD")
end
end
else
if (IsInGroup() and not IsInRaid()) then --in party only
sendData(dataEncoded, IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "PARTY")
elseif (IsInRaid()) then
sendData(dataEncoded, IsInRaid(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT" or "RAID")
end
end
end
--------------------------------------------------------------------------------------------------------------------------------
--~schedule ~timers
openRaidLib.Schedules = {
registeredUniqueTimers = {}
}
--run a scheduled function with its payload
local triggerScheduledTick = function(tickerObject)
local payload = tickerObject.payload
local callback = tickerObject.callback
if (tickerObject.isUnique) then
local namespace = tickerObject.namespace
local scheduleName = tickerObject.scheduleName
openRaidLib.Schedules.CancelUniqueTimer(namespace, scheduleName)
end
local result, errortext = xpcall(callback, geterrorhandler(), 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, ...)
local payload = {...}
local newTimer = C_Timer.NewTimer(time, triggerScheduledTick)
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
function openRaidLib.Schedules.NewUniqueTimer(time, callback, namespace, scheduleName, ...)
openRaidLib.Schedules.CancelUniqueTimer(namespace, scheduleName)
local newTimer = openRaidLib.Schedules.NewTimer(time, callback, ...)
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
--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",
"PvPTalentUpdate",
"KeystoneUpdate",
"KeystoneWipe",
}
--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
tremove(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
tremove(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(3, 6), 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
if (openRaidLib.inGroup) then
openRaidLib.inGroup = false
openRaidLib.internalCallback.TriggerEvent("onLeaveGroup")
bEventTriggered = true
end
end
if (not bEventTriggered and openRaidLib.IsInGroup()) then --the player didn't left or enter a group
--the group has changed, trigger a long timer to send full data
--as the timer is unique, a new change to the group will replace and refresh the time
--using random time, players won't trigger all at the same time
local randomTime = 5 + math.random() + math.random(1, 5)
openRaidLib.Schedules.NewUniqueTimer(randomTime, openRaidLib.mainControl.SendFullData, "mainControl", "sendFullData_Schedule")
end
openRaidLib.UpdateUnitIDCache()
end,
["UNIT_SPELLCAST_SUCCEEDED"] = function(...)
local unitId, castGUID, spellId = ...
C_Timer.After(0.1, function()
--some spells has many different spellIds, get the default
spellId = LIB_OPEN_RAID_SPELL_DEFAULT_IDS[spellId] or spellId
--trigger internal callbacks
openRaidLib.internalCallback.TriggerEvent("playerCast", spellId, UnitIsUnit(unitId, "pet"))
end)
end,
["PLAYER_ENTERING_WORLD"] = function(...)
--has the selected character just loaded?
if (not openRaidLib.bHasEnteredWorld) then
--register events
openRaidLib.OnEnterWorldRegisterEvents()
--openRaidLib.AuraTracker.StartScanUnitAuras("player")
if (IsInGroup()) then
openRaidLib.RequestAllData()
openRaidLib.UpdateUnitIDCache()
end
--this part is under development
if (Details) then
local detailsEventListener = Details:CreateEventListener()
function detailsEventListener:UnitSpecFound(event, unitId, specId, unitGuid)
local unitName = GetUnitName(unitId, true) or unitId
if (not UnitInParty(unitName) and not UnitInRaid(unitName)) then
return
end
--check if there's unit information about this unit
--is still did not received a list of cooldowns from this player
if (not openRaidLib.CooldownManager.HasFullCooldownList[unitName]) then
--build a generic list from the spec
end
end
function detailsEventListener:UnitTalentsFound(event, unitId, talentTable, unitGuid)
local unitName = GetUnitName(unitId, true) or unitId
if (not UnitInParty(unitName) and not UnitInRaid(unitName)) then
return
end
end
detailsEventListener:RegisterEvent("UNIT_SPEC", "UnitSpecFound")
detailsEventListener:RegisterEvent("UNIT_TALENTS", "UnitTalentsFound")
end
openRaidLib.bHasEnteredWorld = true
end
openRaidLib.internalCallback.TriggerEvent("onEnterWorld")
end,
["PLAYER_SPECIALIZATION_CHANGED"] = function(...)
delayedTalentChange()
end,
["PLAYER_TALENT_UPDATE"] = function(...)
delayedTalentChange()
end,
["TRAIT_CONFIG_UPDATED"] = function(...)
delayedTalentChange()
end,
["TRAIT_TREE_CURRENCY_INFO_UPDATED"] = function(...)
delayedTalentChange()
end,
--SPELLS_CHANGED
["PLAYER_PVP_TALENT_UPDATE"] = function(...)
openRaidLib.internalCallback.TriggerEvent("pvpTalentUpdate")
end,
["PLAYER_DEAD"] = function(...)
openRaidLib.mainControl.UpdatePlayerAliveStatus()
end,
["PLAYER_ALIVE"] = function(...)
openRaidLib.mainControl.UpdatePlayerAliveStatus()
end,
["PLAYER_UNGHOST"] = function(...)
openRaidLib.mainControl.UpdatePlayerAliveStatus()
end,
["PLAYER_REGEN_DISABLED"] = function(...)
--entered in combat
end,
["PLAYER_REGEN_ENABLED"] = function(...)
openRaidLib.internalCallback.TriggerEvent("onLeaveCombat")
end,
["UPDATE_INVENTORY_DURABILITY"] = function(...)
--an item has changed its durability
--do not trigger this event while in combat
if (not InCombatLockdown()) then
openRaidLib.Schedules.NewUniqueTimer(5 + math.random(0, 4), openRaidLib.GearManager.SendDurability, "GearManager", "sendDurability_Schedule")
end
end,
["PLAYER_EQUIPMENT_CHANGED"] = function(...)
--player changed an equipment
openRaidLib.Schedules.NewUniqueTimer(4 + math.random(0, 5), openRaidLib.GearManager.SendAllGearInfo, "GearManager", "sendAllGearInfo_Schedule")
end,
["ENCOUNTER_END"] = function()
if (IsInRaid()) then
openRaidLib.internalCallback.TriggerEvent("raidEncounterEnd")
end
end,
["CHALLENGE_MODE_START"] = function()
openRaidLib.internalCallback.TriggerEvent("mythicDungeonStart")
end,
["UNIT_PET"] = function(unitId)
if (UnitIsUnit(unitId, "player")) then
openRaidLib.Schedules.NewUniqueTimer(1.1, function() openRaidLib.internalCallback.TriggerEvent("playerPetChange") end, "mainControl", "petStatus_Schedule")
--if the pet is alive, register to know when it dies
if (UnitExists("pet") and UnitHealth("pet") >= 1) then
eventFrame:RegisterUnitEvent("UNIT_FLAGS", "pet")
end
end
end,
["UNIT_FLAGS"] = function(unitId)
local petHealth = UnitHealth(unitId)
if (petHealth < 1) then
eventFrame:UnregisterEvent("UNIT_FLAGS")
openRaidLib.eventFunctions["UNIT_PET"]("player")
end
end,
["CHALLENGE_MODE_COMPLETED"] = function()
openRaidLib.internalCallback.TriggerEvent("mythicDungeonEnd")
end,
["PLAYER_LOGOUT"] = function()
tempCache.SaveData()
end,
}
openRaidLib.eventFunctions = eventFunctions
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
eventFrame:SetScript("OnEvent", function(self, event, ...)
local eventCallbackFunc = eventFunctions[event]
eventCallbackFunc(...)
end)
--run when PLAYER_ENTERING_WORLD triggers, this avoid any attempt of getting information without the game has completed the load process
function openRaidLib.OnEnterWorldRegisterEvents()
eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
eventFrame:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", "player", "pet")
eventFrame:RegisterEvent("PLAYER_REGEN_DISABLED")
eventFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
eventFrame:RegisterEvent("UPDATE_INVENTORY_DURABILITY")
eventFrame:RegisterEvent("PLAYER_EQUIPMENT_CHANGED")
eventFrame:RegisterEvent("UNIT_PET")
eventFrame:RegisterEvent("PLAYER_DEAD")
eventFrame:RegisterEvent("PLAYER_ALIVE")
eventFrame:RegisterEvent("PLAYER_UNGHOST")
eventFrame:RegisterEvent("PLAYER_LOGOUT")
if (checkClientVersion("retail")) then
eventFrame:RegisterEvent("PLAYER_TALENT_UPDATE")
eventFrame:RegisterEvent("PLAYER_PVP_TALENT_UPDATE")
eventFrame:RegisterEvent("ENCOUNTER_END")
eventFrame:RegisterEvent("CHALLENGE_MODE_START")
eventFrame:RegisterEvent("CHALLENGE_MODE_COMPLETED")
eventFrame:RegisterEvent("PLAYER_SPECIALIZATION_CHANGED")
eventFrame:RegisterEvent("TRAIT_TREE_CURRENCY_INFO_UPDATED")
eventFrame:RegisterEvent("TRAIT_CONFIG_UPDATED")
end
end
--------------------------------------------------------------------------------------------------------------------------------
--~main ~control
openRaidLib.mainControl = {
playerAliveStatus = {},
}
--send full data (all data available)
function openRaidLib.mainControl.SendFullData()
--send player data
openRaidLib.UnitInfoManager.SendAllPlayerInfo()
--send gear data
openRaidLib.GearManager.SendAllGearInfo()
--send cooldown data
openRaidLib.CooldownManager.SendAllPlayerCooldowns()
end
openRaidLib.mainControl.onEnterWorld = function()
--update the alive status of the player
openRaidLib.mainControl.UpdatePlayerAliveStatus(true)
--the game client is fully loadded and all information is available
if (openRaidLib.IsInGroup()) then
openRaidLib.Schedules.NewUniqueTimer(1.0, openRaidLib.mainControl.SendFullData, "mainControl", "sendFullData_Schedule")
end