Repository navigation
Expand file tree
/
Copy pathComms.lua
More file actions
1385 lines (1267 loc) · 44.5 KB
/
Copy pathComms.lua
File metadata and controls
1385 lines (1267 loc) · 44.5 KB
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
local L = _G.QuestTogether.Translate
--[[
QuestTogether Announcement Communication Layer
This file handles lightweight announcement events over a shared addon channel.
Local quest events are always published. Each receiving client applies its own
display preferences when deciding whether to render bubbles or print chat logs.
]]
local QuestTogether = _G.QuestTogether
local ANNOUNCEMENT_WIRE_VERSION = 2
local ANNOUNCEMENT_MAX_TEXT_LENGTH = 220
local ANNOUNCEMENT_CHANNEL_FILTER_EVENTS = {
"CHAT_MSG_CHANNEL",
"CHAT_MSG_CHANNEL_NOTICE",
"CHAT_MSG_CHANNEL_NOTICE_USER",
}
local GROUP_ANNOUNCEMENT_DISTRIBUTIONS = {
PARTY = true,
RAID = true,
INSTANCE_CHAT = true,
}
-- Receiving an addon message grants no authority to choose an arbitrary local
-- emote. Snapshot our shipped selection list so local and remote celebrations
-- share one source without allowing later table mutations to expand acceptance.
local REMOTE_CELEBRATION_EMOTES = {}
for _, token in ipairs(QuestTogether.completionEmotes) do
REMOTE_CELEBRATION_EMOTES[token] = true
end
local raw_issecretvalue = type(issecretvalue) == "function" and issecretvalue or nil
local function IsSecretValue(value)
if not raw_issecretvalue then
return false
end
return raw_issecretvalue(value) and true or false
end
local function SafeAddonString(addon, value, fallback)
if addon and addon.SafeToString then
return addon:SafeToString(value, fallback or "")
end
if IsSecretValue(value) then
return fallback or ""
end
local valueType = type(value)
if valueType == "string" or valueType == "number" or valueType == "boolean" or valueType == "nil" then
return tostring(value)
end
local ok, textValue = pcall(tostring, value)
if ok then
return textValue
end
return fallback or ""
end
local function SafePrimitiveString(addon, value, fallback)
if addon and addon.CanAccessValue and not addon:CanAccessValue(value) then
return fallback or ""
end
local valueType = type(value)
if valueType == "string" or valueType == "number" or valueType == "boolean" then
return tostring(value)
end
return fallback or ""
end
local function SafeTrimAddonString(addon, value, fallback)
if addon and addon.SafeTrimString then
return addon:SafeTrimString(value, fallback or "")
end
return SafeAddonString(addon, value, fallback or "")
end
local function SafeChannelNumber(addon, value)
if addon and addon.SafeToNumber then
return addon:SafeToNumber(value)
end
if IsSecretValue(value) then
return nil
end
local numberValue = tonumber(value)
if type(numberValue) ~= "number" then
return nil
end
return numberValue
end
local function MatchesAnnouncementChannelName(addon, value)
value = SafeTrimAddonString(addon, value, "")
if value == "" then
return false
end
local channelName = SafeAddonString(addon, addon.announcementChannelName or "", "")
if channelName == "" then
return false
end
if value == channelName then
return true
end
local base = string.match(value, "^%d+%.%s+(.+)$") or value
base = string.lower(base)
return base == string.lower(channelName)
end
local function SafeNumber(addon, value)
if addon and addon.SafeToNumber then
return addon:SafeToNumber(value)
end
if IsSecretValue(value) then
return nil
end
local numberValue = tonumber(value)
if type(numberValue) ~= "number" then
return nil
end
return numberValue
end
-- Lua's substring limit is measured in bytes. Preserve complete UTF-8 code
-- points when shortening local text or fitting escaped text into a wire packet.
local function TruncateUtf8(text, maxBytes)
if #text <= maxBytes then
return text
end
local nextIndex = math.max(0, maxBytes) + 1
while nextIndex > 1 do
local byte = string.byte(text, nextIndex)
if not byte or byte < 128 or byte >= 192 then
break
end
nextIndex = nextIndex - 1
end
return string.sub(text, 1, nextIndex - 1)
end
function QuestTogether:SanitizeAnnouncementText(text)
local sanitized = SafeTrimAddonString(self, text, "")
return TruncateUtf8(sanitized, ANNOUNCEMENT_MAX_TEXT_LENGTH)
end
function QuestTogether:GetAnnouncementServerTime()
local getter = self.API and self.API.GetServerTime
if type(getter) ~= "function" then
return nil
end
local ok, value = pcall(getter)
local now = ok and SafeNumber(self, value) or nil
return now and now >= 1000000000 and now < 100000000000 and now == math.floor(now) and now or nil
end
function QuestTogether:SanitizeAnnouncementExtraData(extraData)
local sanitized = {}
if type(extraData) ~= "table" or not self:CanAccessTable(extraData) then
return sanitized
end
local iconAsset = SafePrimitiveString(self, extraData.iconAsset, "")
local iconKind = SafePrimitiveString(self, extraData.iconKind, "")
local emoteToken = SafePrimitiveString(self, extraData.emoteToken, "")
local facts = SafePrimitiveString(self, extraData.eventFacts, "")
if self.DecodeAnnouncementFacts and self:DecodeAnnouncementFacts(facts) then
sanitized.eventFacts = facts
end
if iconAsset ~= "" then
sanitized.iconAsset = iconAsset
end
if iconKind ~= "" then
sanitized.iconKind = iconKind
end
if emoteToken ~= "" then
sanitized.emoteToken = emoteToken
end
return sanitized
end
function QuestTogether:SanitizeAnnouncementEventData(eventData)
if type(eventData) ~= "table" or not self:CanAccessTable(eventData) then
return nil
end
local eventType = SafePrimitiveString(self, eventData.eventType, "")
local senderName = SafePrimitiveString(self, eventData.senderName, "")
local text = self:SanitizeAnnouncementText(eventData.text)
if eventType == "" or senderName == "" or text == "" then
return nil
end
local sanitizedExtraData = self:SanitizeAnnouncementExtraData(eventData)
local normalizedQuestId = self.NormalizeQuestID and self:NormalizeQuestID(eventData.questId) or nil
local numericCoordX = self.SafeToNumber and self:SafeToNumber(eventData.coordX) or nil
local numericCoordY = self.SafeToNumber and self:SafeToNumber(eventData.coordY) or nil
local numericMapID = SafeNumber(self, eventData.mapID)
if numericMapID and (numericMapID <= 0 or numericMapID ~= math.floor(numericMapID)) then
numericMapID = nil
end
local eventId = SafePrimitiveString(self, eventData.eventId, "")
if #eventId > 64 or not eventId:match("^%d+%-%d+%-%d+$") then
eventId = ""
end
local normalizedWarMode = nil
local occurredAt = SafeNumber(self, eventData.occurredAt)
if
occurredAt and (occurredAt < 1000000000 or occurredAt >= 100000000000 or occurredAt ~= math.floor(occurredAt))
then
occurredAt = nil
end
if self.NormalizeAnnouncementWarModeValue then
normalizedWarMode = self:NormalizeAnnouncementWarModeValue(eventData.warMode)
end
return {
version = SafeNumber(self, eventData.version) or ANNOUNCEMENT_WIRE_VERSION,
occurredAt = occurredAt,
eventId = eventId,
eventType = SafePrimitiveString(self, eventType, ""),
senderGUID = SafePrimitiveString(self, eventData.senderGUID, ""),
classFile = SafePrimitiveString(self, eventData.classFile, ""),
senderName = senderName,
text = text,
questId = normalizedQuestId and SafePrimitiveString(self, normalizedQuestId, "") or "",
iconAsset = sanitizedExtraData.iconAsset or "",
iconKind = sanitizedExtraData.iconKind or "",
zoneName = SafePrimitiveString(self, eventData.zoneName, ""),
coordX = numericCoordX and string.format("%.1f", numericCoordX) or "",
coordY = numericCoordY and string.format("%.1f", numericCoordY) or "",
warMode = normalizedWarMode == nil and "" or (normalizedWarMode and "1" or "0"),
emoteToken = sanitizedExtraData.emoteToken or "",
eventFacts = sanitizedExtraData.eventFacts or "",
mapID = numericMapID and SafePrimitiveString(self, numericMapID, "") or "",
}
end
function QuestTogether:GetAnnouncementChannelLocalID(channelName)
if not self.API or not self.API.GetChannelName then
return nil
end
local localID = self.API.GetChannelName(channelName or self.announcementChannelName)
local numericLocalID = SafeChannelNumber(self, localID)
if numericLocalID and numericLocalID > 0 then
return numericLocalID
end
return nil
end
function QuestTogether:GetAnnouncementChannelTarget(channelName)
channelName = channelName or self.announcementChannelName
local localID = self:GetAnnouncementChannelLocalID(channelName)
if type(localID) == "number" and localID > 0 then
return localID
end
return channelName
end
function QuestTogether:GetGroupAnnouncementDistribution()
if self.API and self.API.IsInInstanceGroup and self.API.IsInInstanceGroup() then
return "INSTANCE_CHAT"
end
if self.API and self.API.IsInRaid and self.API.IsInRaid() then
return "RAID"
end
if self.API and self.API.IsInParty and self.API.IsInParty() then
return "PARTY"
end
return nil
end
function QuestTogether:GetAnnouncementWireRoutes()
local groupedDistribution = self:GetGroupAnnouncementDistribution()
local routes = {}
if groupedDistribution then
routes[#routes + 1] = {
distribution = groupedDistribution,
target = nil,
requiresChannelJoin = false,
}
end
routes[#routes + 1] = {
distribution = "CHANNEL",
target = self:GetAnnouncementChannelTarget(),
requiresChannelJoin = true,
}
return routes
end
function QuestTogether:GetCommsDiagnostics()
local runtime = self:GetRuntimeWorkStateStore()
runtime.commsDiagnostics = runtime.commsDiagnostics or {}
return runtime.commsDiagnostics
end
-- Fixed command buckets keep unknown traffic from growing diagnostic state.
function QuestTogether:RecordCommsTraffic(kind, message, result)
local diagnostics = self:GetCommsDiagnostics()
local now = SafeNumber(self, self.API.GetTime and self.API.GetTime())
diagnostics.trafficStartedAt = diagnostics.trafficStartedAt or now
diagnostics.trafficObservedAt = now
diagnostics.traffic = diagnostics.traffic or {}
local command = message:match("^2|([^|]+)|")
command = self:GetCommOperation(command) and command or "OTHER"
local bucket = diagnostics.traffic[command] or {}
diagnostics.traffic[command] = bucket
bucket[kind] = (bucket[kind] or 0) + 1
bucket[kind .. "Bytes"] = (bucket[kind .. "Bytes"] or 0) + #message
if result == 3 or result == 8 then
bucket.throttled = (bucket.throttled or 0) + 1
end
end
function QuestTogether:RecordAnnouncementLatency(eventData)
local now = self:GetAnnouncementServerTime()
local age = now and eventData.occurredAt and now - eventData.occurredAt or nil
local diagnostics = self:GetCommsDiagnostics()
-- These are sender-reported, second-resolution timestamps, not trusted
-- network telemetry. Future or implausibly old values remain unknown.
if age and age >= 0 and age <= 86400 then
diagnostics.announcementAgeSamples = (diagnostics.announcementAgeSamples or 0) + 1
diagnostics.announcementAgeTotal = (diagnostics.announcementAgeTotal or 0) + age
diagnostics.announcementAgeMax = math.max(diagnostics.announcementAgeMax or 0, age)
diagnostics.announcementAgeLast = age
else
age = nil
diagnostics.announcementAgeUnknown = (diagnostics.announcementAgeUnknown or 0) + 1
end
self:Debugf(
"comms",
"announcement age sender=%s event=%s reportedAgeSeconds=%s",
eventData.senderName,
eventData.eventType,
age and tostring(age) or "unknown"
)
end
function QuestTogether:RecordCommsDiagnostic(kind, detail)
local diagnostics = self:GetCommsDiagnostics()
diagnostics[kind] = (diagnostics[kind] or 0) + 1
if kind == "failedRoutes" or kind == "invalidMessages" then
diagnostics.lastFailure = detail
end
-- Keep every display decision: these are needed to explain a user's bubble.
-- Sample transport chatter, while retaining its exact aggregate counters.
local count = diagnostics[kind]
if kind == "acceptedAnnouncements" or kind == "suppressedAnnouncements" or count <= 5 or count % 100 == 0 then
self:Debugf("comms", "%s count=%d %s", kind, count, detail or "")
end
end
function QuestTogether:AnnouncementChannelChatFilter(_, _, ...)
-- Only channel metadata identifies this channel. Scanning message text and
-- player names both hides unrelated conversations and touches secret data.
return MatchesAnnouncementChannelName(self, select(4, ...))
or MatchesAnnouncementChannelName(self, select(9, ...))
or self:IsGeographicChannelName(select(4, ...))
or self:IsGeographicChannelName(select(9, ...))
end
function QuestTogether:RegisterAnnouncementChannelChatFilters()
if self.announcementChannelChatFiltersRegistered then
return
end
if not self.API or not self.API.AddMessageEventFilter then
return
end
self.announcementChannelChatFilterFunc = self.announcementChannelChatFilterFunc
or function(...)
return QuestTogether:AnnouncementChannelChatFilter(...)
end
for _, eventName in ipairs(ANNOUNCEMENT_CHANNEL_FILTER_EVENTS) do
self.API.AddMessageEventFilter(eventName, self.announcementChannelChatFilterFunc)
end
self.announcementChannelChatFiltersRegistered = true
end
function QuestTogether:UnregisterAnnouncementChannelChatFilters()
if not self.announcementChannelChatFiltersRegistered then
return
end
if not self.API or not self.API.RemoveMessageEventFilter or not self.announcementChannelChatFilterFunc then
self.announcementChannelChatFiltersRegistered = nil
return
end
for _, eventName in ipairs(ANNOUNCEMENT_CHANNEL_FILTER_EVENTS) do
self.API.RemoveMessageEventFilter(eventName, self.announcementChannelChatFilterFunc)
end
self.announcementChannelChatFiltersRegistered = nil
end
function QuestTogether:HideAnnouncementChannelFromChatWindows(channelName)
if
not self.API
or not self.API.GetNumChatWindows
or not self.API.GetChatFrameByID
or not self.API.RemoveChatWindowChannel
then
return
end
local maxWindows = SafeNumber(self, self.API.GetNumChatWindows()) or 0
for chatFrameID = 1, maxWindows do
local chatFrame = self.API.GetChatFrameByID(chatFrameID)
if chatFrame then
-- Some chat frames reject channel removal in edge states; keep cleanup best-effort.
for _, name in ipairs(channelName and { channelName } or { self.announcementChannelName }) do
pcall(self.API.RemoveChatWindowChannel, chatFrame, name)
end
end
end
end
function QuestTogether:EnsureAnnouncementChannelJoined(channelName)
if not channelName then
return self:EnsureAnnouncementChannelJoined(self.announcementChannelName)
end
local cacheKey = channelName == self.announcementChannelName and "announcementChannelLocalID" or nil
if not cacheKey and not self:IsGeographicChannelName(channelName) then
return false
end
if not self.isEnabled then
self:Debug("Skipping channel join because addon is disabled", "comms")
return false
end
-- Existing permanent channels survive /reload too; they need our filters
-- even when no JoinPermanentChannel call is necessary.
self:RegisterAnnouncementChannelChatFilters()
local currentLocalID = self:GetAnnouncementChannelLocalID(channelName)
if currentLocalID then
if cacheKey then
self[cacheKey] = currentLocalID
end
local bindings = rawget(self, "announcementChannelBindings") or {}
self.announcementChannelBindings = bindings
if bindings[channelName] ~= currentLocalID and not self:IsRuntimeRestricted() then
self:HideAnnouncementChannelFromChatWindows(channelName)
bindings[channelName] = currentLocalID
end
return true
end
if cacheKey then
self[cacheKey] = nil
end
if self.announcementChannelBindings then
self.announcementChannelBindings[channelName] = nil
end
if not self.API or not self.API.JoinPermanentChannel then
self:Debug("JoinPermanentChannel API unavailable", "comms")
return false
end
local chatFrameId = (DEFAULT_CHAT_FRAME and DEFAULT_CHAT_FRAME.GetID and DEFAULT_CHAT_FRAME:GetID()) or 1
self:Debugf(
"comms",
"Joining announcement channel name=%s chatFrameId=%s",
SafeAddonString(self, channelName),
SafeAddonString(self, chatFrameId)
)
self.API.JoinPermanentChannel(channelName, nil, chatFrameId, 1)
currentLocalID = self:GetAnnouncementChannelLocalID(channelName)
if currentLocalID then
if cacheKey then
self[cacheKey] = currentLocalID
end
if self.HideAnnouncementChannelFromChatWindows then
self:HideAnnouncementChannelFromChatWindows(channelName)
self.announcementChannelBindings = self.announcementChannelBindings or {}
self.announcementChannelBindings[channelName] = currentLocalID
end
self:Debugf("comms", "Joined announcement channel localID=%s", SafeAddonString(self, currentLocalID))
return true
end
self:Debug("Unable to join announcement channel " .. SafeAddonString(self, channelName), "comms")
return false
end
-- Stable partition using the public channel-order API, never ChatTypeInfo or
-- Blizzard frame fields. Non-QT channels retain their relative ordering.
function QuestTogether:MoveAnnouncementChannelsToEnd()
if not self.isEnabled or self:IsRuntimeRestricted() or self:IsRuntimeRestrictionTypeActive("chat") then
return false
end
local api = self.API or {}
if not api.GetChatChannelList or not api.SwapChatChannelIndices then
return false
end
local ok, list = pcall(api.GetChatChannelList)
if not ok or not self:CanAccessTable(list) or #list > 90 or #list % 3 ~= 0 then
return false
end
local channels, seen = {}, {}
for i = 1, #list, 3 do
local id, name = SafeChannelNumber(self, list[i]), SafeTrimAddonString(self, list[i + 1], "")
if not id or id < 1 or id > 30 or id ~= math.floor(id) or name == "" or seen[id] then
return false
end
seen[id] = true
channels[#channels + 1] = {
id = id,
name = name,
qt = MatchesAnnouncementChannelName(self, name) or self:IsGeographicChannelName(name),
}
end
table.sort(channels, function(a, b)
return a.id < b.id
end)
for i = 2, #channels do
local j = i
while j > 1 and not channels[j].qt and channels[j - 1].qt do
if self:IsRuntimeRestricted() then
return false
end
local swapped, result = pcall(api.SwapChatChannelIndices, channels[j - 1].id, channels[j].id)
-- Native channel indices can change; never retain a stale receive fallback.
self.announcementChannelLocalID = nil
if not swapped or result ~= true then
return false
end
channels[j - 1].qt, channels[j].qt = channels[j].qt, channels[j - 1].qt
channels[j - 1].name, channels[j].name = channels[j].name, channels[j - 1].name
j = j - 1
end
end
-- Keep the human chat channel before the machine-only zone subscriptions.
local firstQT, current
for _, channel in ipairs(channels) do
if channel.qt and not firstQT then
firstQT = channel.id
end
if channel.name == self.announcementChannelName then
current = channel.id
end
end
if firstQT and current and current ~= firstQT then
local swapped, result = pcall(api.SwapChatChannelIndices, current, firstQT)
self.announcementChannelLocalID = nil
if not swapped or result ~= true then
return false
end
end
self.announcementChannelLocalID = self:GetAnnouncementChannelLocalID()
return true
end
function QuestTogether:ScheduleAnnouncementChannelOrder()
if
not self.isEnabled
or not self.API.GetChatChannelList
or not self.API.SwapChatChannelIndices
or not self.API.Delay
or rawget(self, "channelOrderWork")
then
return
end
local work = {}
self.channelOrderWork = work
self.API.Delay(0.2, function()
if rawget(self, "channelOrderWork") ~= work then
return
end
self:MoveAnnouncementChannelsToEnd()
self.channelOrderWork = nil
end)
end
function QuestTogether:CHANNEL_COUNT_UPDATE()
local state = rawget(self, "geographicCommsState")
if state then
state.reconciledChannels = nil
end
self:ScheduleAnnouncementChannelOrder()
end
function QuestTogether:CHANNEL_UI_UPDATE()
self:ScheduleAnnouncementChannelOrder()
end
function QuestTogether:LeaveAnnouncementChannel()
if self.API and self.API.LeaveChannelByName then
self:Debugf(
"comms",
"Leaving announcement channel name=%s",
SafeAddonString(self, self.announcementChannelName)
)
-- Channel leave can fail if Blizzard already removed it; no need to hard fail disable.
pcall(self.API.LeaveChannelByName, self.announcementChannelName)
end
self.announcementChannelLocalID = nil
self:ResetCommsState()
if self.UnregisterAnnouncementChannelChatFilters then
self:UnregisterAnnouncementChannelChatFilters()
end
end
function QuestTogether:ResetCommsState()
if self.ResetRuntimeCoordinator then
self:ResetRuntimeCoordinator()
end
self:EndCommunicationSession()
self.communicationState = nil
self:ResetTransport()
self:ClosePartyChatReminderPreview()
self:ResetPartyChatReminder()
if self.ResetGeographicComms then
self:ResetGeographicComms()
end
self.channelOrderWork = nil
self.announcementChannelBindings = nil
self:ResetLocalizedQuestTitles()
if self.ResetPartyJoin then
self:ResetPartyJoin()
end
if self.ResetPartyVisuals then
self:ResetPartyVisuals()
end
if self.ResetQTPlayerPresence then
self:ResetQTPlayerPresence()
end
if self.ResetPlayerLocations then
self:ResetPlayerLocations()
end
if self.ResetPartyQuestCompare then
self:ResetPartyQuestCompare()
end
self.pendingPingRequests = {}
self.pendingQuestCompareRequests = {}
self.recentCommMessageSignatures = {}
self.recentCommSignatureIndex = nil
-- Pending timer closures retain the old state only; they cannot send after
-- disable/re-enable or remove work from a replacement queue.
self.questComparePendingResponses = nil
self.questCompareResponseCache = nil
self.questCompareLocalRevision = nil
self.pingReplyState = nil
if self.ResetDeveloperDiagnostics then
self:ResetDeveloperDiagnostics()
end
if self.ResetPlayerDetails then
self:ResetPlayerDetails()
end
if self.ResetPeerSnapshots then
self:ResetPeerSnapshots()
end
end
function QuestTogether:GetPlayerPingMetadata()
local fullName = self:GetPlayerFullName() or self:GetPlayerName() or "Unknown"
local realmName = ""
if not self:UsesRegionalPlayerNames() then
local unitRealm
if self.API.UnitFullName then
local _
_, unitRealm = self.API.UnitFullName("player")
end
realmName = SafeTrimAddonString(self, unitRealm, "")
if realmName == "" and self.API.GetRealmName then
realmName = self.API.GetRealmName()
end
end
local className, classFile
if self.API.UnitClass then
className, classFile = self.API.UnitClass("player")
end
local raceName = nil
if self.API.UnitRace then
raceName = self.API.UnitRace("player")
end
local level = self.API.UnitLevel and self.API.UnitLevel("player") or ""
local locationInfo = (not self.CanPublishPlayerLocation or self:CanPublishPlayerLocation())
and not self:IsRuntimeRestricted()
and self.GetPlayerAnnouncementLocationInfo
and self:GetPlayerAnnouncementLocationInfo()
or {}
local numericCoordX = locationInfo and self.SafeToNumber and self:SafeToNumber(locationInfo.coordX) or nil
local numericCoordY = locationInfo and self.SafeToNumber and self:SafeToNumber(locationInfo.coordY) or nil
local warMode
if locationInfo and self:SupportsWarMode() == true then
warMode = self:NormalizeAnnouncementWarModeValue(locationInfo.warMode)
end
return {
senderName = SafeAddonString(self, fullName or "", ""),
realmName = SafeAddonString(self, realmName or "", ""),
raceName = SafeAddonString(self, raceName or "", ""),
classFile = SafeAddonString(self, classFile or "", ""),
className = SafeAddonString(self, className or "", ""),
addonVersion = SafeAddonString(self, self:GetAddonVersion() or "", ""),
level = level and SafeAddonString(self, level, "") or "",
zoneName = locationInfo and SafeAddonString(self, locationInfo.zoneName or "", "") or "",
coordX = numericCoordX and string.format("%.1f", numericCoordX) or "",
coordY = numericCoordY and string.format("%.1f", numericCoordY) or "",
warMode = warMode == nil and "" or (warMode and "1" or "0"),
mapID = locationInfo and SafeAddonString(self, locationInfo.mapID or "", "") or "",
}
end
function QuestTogether:BuildChannelRequestId(prefix)
return (prefix or "req") .. "-" .. self:GetCommunicationSession() .. "-" .. self:NextCommunicationSequence()
end
function QuestTogether:BuildLocalAnnouncementEvent(eventType, text, questId, extraData)
local senderName = self:GetPlayerFullName() or self:GetPlayerName()
local senderGUID = ""
if self.API.UnitGUID then
local okGuid, guidValue = pcall(self.API.UnitGUID, "player")
if okGuid and not self:IsSecretValue(guidValue) then
senderGUID = SafeAddonString(self, guidValue or "", "")
end
end
local sanitizedText = self:SanitizeAnnouncementText(text)
local iconAsset, iconKind = self:GetAnnouncementIconInfo(eventType, questId)
local sanitizedExtraData = self:SanitizeAnnouncementExtraData(extraData)
if sanitizedExtraData.iconAsset then
iconAsset = sanitizedExtraData.iconAsset
iconKind = sanitizedExtraData.iconKind or iconKind
end
local locationInfo = (not self.CanPublishPlayerLocation or self:CanPublishPlayerLocation())
and self.GetPlayerAnnouncementLocationInfo
and self:GetPlayerAnnouncementLocationInfo()
or nil
local numericCoordX = locationInfo and self.SafeToNumber and self:SafeToNumber(locationInfo.coordX) or nil
local numericCoordY = locationInfo and self.SafeToNumber and self:SafeToNumber(locationInfo.coordY) or nil
local warMode
if locationInfo and self:SupportsWarMode() == true then
warMode = self:NormalizeAnnouncementWarModeValue(locationInfo.warMode)
end
if sanitizedText == "" then
return nil
end
return self:SanitizeAnnouncementEventData({
version = ANNOUNCEMENT_WIRE_VERSION,
occurredAt = self:GetAnnouncementServerTime(),
eventType = SafeAddonString(self, eventType or "", ""),
senderGUID = SafeAddonString(self, senderGUID or "", ""),
classFile = SafeAddonString(self, self:GetPlayerClassFile() or "", ""),
senderName = SafeAddonString(self, senderName or "", ""),
text = sanitizedText,
questId = questId and SafeAddonString(self, questId, "") or "",
iconAsset = SafeAddonString(self, iconAsset or "", ""),
iconKind = SafeAddonString(self, iconKind or "", ""),
zoneName = locationInfo and SafeAddonString(self, locationInfo.zoneName or "", "") or "",
coordX = numericCoordX and string.format("%.1f", numericCoordX) or "",
coordY = numericCoordY and string.format("%.1f", numericCoordY) or "",
warMode = warMode == nil and "" or (warMode and "1" or "0"),
emoteToken = sanitizedExtraData.emoteToken or "",
eventFacts = sanitizedExtraData.eventFacts or (self.BuildAnnouncementFacts and self:BuildAnnouncementFacts(
eventType
)) or "",
mapID = locationInfo and locationInfo.mapID or nil,
})
end
function QuestTogether:BuildAnnouncementEventForUnit(unitToken, eventType, text)
if type(unitToken) ~= "string" or unitToken == "" then
return nil
end
local sanitizedText = self:SanitizeAnnouncementText(text)
if sanitizedText == "" then
return nil
end
local senderName = self:GetUnitFullName(unitToken)
if not senderName then
return nil
end
local _, classFile = self.API.UnitClass(unitToken)
local senderGUID = ""
if self.API.UnitGUID then
local okGuid, guidValue = pcall(self.API.UnitGUID, unitToken)
if okGuid and not self:IsSecretValue(guidValue) then
senderGUID = SafeAddonString(self, guidValue or "", "")
end
end
return self:SanitizeAnnouncementEventData({
version = ANNOUNCEMENT_WIRE_VERSION,
eventType = SafeAddonString(self, eventType or "", ""),
senderGUID = SafeAddonString(self, senderGUID or "", ""),
classFile = SafeAddonString(self, classFile or "", ""),
senderName = senderName,
text = sanitizedText,
questId = "",
iconAsset = "",
iconKind = "",
zoneName = "",
coordX = "",
coordY = "",
warMode = "",
emoteToken = "",
})
end
function QuestTogether:IsAnnouncementChannelEvent(channel, localID, name)
channel = SafePrimitiveString(self, channel, "")
name = SafePrimitiveString(self, name, "")
if GROUP_ANNOUNCEMENT_DISTRIBUTIONS[channel] then
return true
end
if channel ~= "CHANNEL" then
return false
end
if name ~= "" then
return MatchesAnnouncementChannelName(self, name) or self:IsGeographicChannelName(name)
end
local expectedLocalID = SafeChannelNumber(self, self.announcementChannelLocalID)
local incomingLocalID = SafeChannelNumber(self, localID)
return incomingLocalID ~= nil
and incomingLocalID > 0
and (expectedLocalID == incomingLocalID or self:IsGeographicChannelEvent(channel, incomingLocalID))
end
function QuestTogether:IsGlobalAnnouncementChannelEvent(distribution, localID, name)
if distribution ~= "CHANNEL" then
return false
end
name = SafePrimitiveString(self, name, "")
if name ~= "" then
return MatchesAnnouncementChannelName(self, name)
end
local expected = self:GetAnnouncementChannelLocalID(self.announcementChannelName)
return expected ~= nil and expected == SafeChannelNumber(self, localID)
end
function QuestTogether:SendAnnouncementEvent(eventType, text, questId, extraData)
if not self.isEnabled then
return false
end
local eventData = self:BuildLocalAnnouncementEvent(eventType, text, questId, extraData)
if not eventData then
self:Debugf(
"comms",
"Failed to build local announcement event eventType=%s",
SafeAddonString(self, eventType, "")
)
return false
end
return self:SendAnnouncementWireEvent(eventData)
end
function QuestTogether:GetSafeRemoteCompletionEmote(emoteToken)
if not self:CanAccessValue(emoteToken) or type(emoteToken) ~= "string" then
return nil
end
local token = string.lower(self:SafeTrimString(emoteToken, ""))
if REMOTE_CELEBRATION_EMOTES[token] then
return token
end
return nil
end
function QuestTogether:PlayRemoteCelebrationEmote(eventData, nearbyUnitToken, senderName)
if
type(eventData) ~= "table"
or not self.isEnabled
or self:IsRuntimeRestricted()
or self:IsRuntimeRestrictionTypeActive("chat")
then
return false
end
local optionKey = eventData.eventType == "PLAYER_LEVEL_UP" and "emoteOnNearbyPlayerLevelUp"
or "emoteOnNearbyPlayerQuestCompletion"
if not self:GetOption(optionKey) then
return false
end
-- Revalidate immediately before the action: aliases and plates can be
-- recycled, and coordinate proximity says nothing about another layer.
local api = self.API or {}
if
not self:CanAccessValue(nearbyUnitToken)
or type(nearbyUnitToken) ~= "string"
or not api.CanTargetUnitForEmote
or not api.DoEmote
then
return false
end
local ok, targetable = pcall(api.CanTargetUnitForEmote, nearbyUnitToken)
if not ok or not self:CanAccessValue(targetable) or targetable ~= true then
return false
end
local matched, matches =
pcall(self.DoesUnitTokenMatchSender, self, nearbyUnitToken, eventData.senderGUID, senderName)
if not matched or not self:CanAccessValue(matches) or matches ~= true then
return false
end
local token = self:GetSafeRemoteCompletionEmote(eventData.emoteToken)
if not token then
return false
end
self.API.DoEmote(token, nearbyUnitToken)
return true
end
function QuestTogether:SendAnnouncementWireEvent(eventData)
if not self.isEnabled or type(eventData) ~= "table" then
return false
end
eventData = self:SanitizeAnnouncementEventData(eventData)
if not eventData then
return false
end
if not self:CanPublishPlayerLocation() then
eventData.coordX, eventData.coordY, eventData.mapID, eventData.zoneName = "", "", "", ""
end
local operation = eventData.eventType == "PLAYER_LEVEL_UP" and "LVL" or "ANN"
return self:Emit(operation, eventData, nil, { owner = self, expires = self.API.GetTime() + 30 })
end
function QuestTogether:SendBubbleAnnouncementTest(text, senderName)
if not self.isEnabled then
return false, L("QuestTogether is disabled.")
end
local eventData = nil
if self.API.UnitExists and self.API.UnitExists("target") then
if not self.API.UnitIsPlayer or not self.API.UnitIsPlayer("target") then
return false, L("Your target must be a player.")
end
eventData = self:BuildAnnouncementEventForUnit("target", "QUEST_PROGRESS", text)
if not eventData then
return false, L("Unable to build a test announcement from your target.")
end
else
local trimmedSenderName = SafeTrimAddonString(self, senderName or "", "")
if trimmedSenderName == "" then
return false, L("Target a nearby player or provide a visible player name.")
end
if not self.FindVisiblePlayerNameplateForSender then
return false, L("Visible player lookup is unavailable.")
end
local nameplate = self:FindVisiblePlayerNameplateForSender("", trimmedSenderName)
local unitToken = nameplate and nameplate.GetUnit and nameplate:GetUnit() or nil
if not unitToken or unitToken == "" then
return false, L("No visible nearby player matched that name.")
end
eventData = self:BuildAnnouncementEventForUnit(unitToken, "QUEST_PROGRESS", text)
if not eventData then
return false, L("Unable to build a test announcement for that player.")
end
end
-- This is a local preview of the selected player. A network packet claiming
-- that identity cannot pass the receiver's authoritative transport check.
if not self:HandleAnnouncementEvent(eventData, false) then
return false, L("The local preview was suppressed by your announcement settings.")
end
return true, eventData.senderName
end
function QuestTogether:ShouldShowAnnouncementsForRemoteSender(senderName, hasNearbyNameplate)
if self:IsIgnoredPlayerName(senderName) then
return false
end
local isGrouped = self:IsGroupedSender(senderName)
local scope = self:GetOption("showProgressFor")
if scope == "party_only" then
return isGrouped
end
return isGrouped or hasNearbyNameplate
end
function QuestTogether:ShouldPlayRemoteEmoteForAnnouncement(eventData)
if type(eventData) ~= "table" then