Repository navigation
Expand file tree
/
Copy pathComms.lua
More file actions
1834 lines (1700 loc) · 67.9 KB
/
Copy pathComms.lua
File metadata and controls
1834 lines (1700 loc) · 67.9 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 group routes and the
public whisper mesh. Custom channels provide peer directories only.
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: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
if self:IsPublicSharingAllowed() then routes[#routes + 1] = { distribution = "MESH", scope = "global" } end
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("^3|([^|]+)|")
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" or kind == "serverChannelRefusals" or kind == "whisperUnavailable" 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
-- Channel membership is a discovery directory, never a data-delivery route.
-- A refusal can delay a missing directory join; it says nothing about whisper
-- delivery and must not discard an otherwise readable member list.
function QuestTogether:CHAT_MSG_CHANNEL_NOTICE(_, notice, _, _, channelName, _, _, _, _, channelBaseName)
if not self.isEnabled or self.isLoggingOut or not self:CanAccessValue(notice)
or notice ~= "NOT_ALLOWED_IN_CHANNEL" then
return false
end
local name = self:SafeTrimString(channelBaseName, "")
if name == "" then name = self:SafeTrimString(channelName, "") end
name = name:gsub("^%d+%.%s+", "")
if not MatchesAnnouncementChannelName(self, name) and not self:IsGeographicChannelName(name) then
return false
end
self:RecordMeshDirectoryRefusal(name)
self:RecordCommsDiagnostic("meshDirectoryRefusals", "directory=" .. name .. " notice=NOT_ALLOWED_IN_CHANNEL")
return true
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
-- Offline-recipient notices identify a player, but not the originating send.
-- Correlate only actual native QT whispers, and fail open for ordinary whispers
-- to that player. Keep the decision across chat frames; filters are not a queue
-- of one-use events, and can run before or after our event handler.
local WHISPER_NOTICE_SECONDS, WHISPER_UNAVAILABLE_SECONDS = 120, 60
local WHISPER_TARGET_LIMIT, WHISPER_PRIVATE_RESERVE = 128, 16
local WHISPER_FILTER_RETRY_SECONDS = 5
local WHISPER_OBSERVER_METRICS = {
"filterInvocations", "filterSuppressed", "filterPassed", "filterErrors", "filterRegistrationFailures",
"filterMatched", "filterOrdinary", "filterOrdinaryUnknown", "filterUntracked", "filterExpired",
"filterUnavailable", "filterInaccessible", "filterUnsupportedFormat", "cleanupErrors", "noticeLogErrors",
}
local WHISPER_FILTER_DECISIONS = {
matched = "filterMatched", ordinary = "filterOrdinary", ordinaryUnknown = "filterOrdinaryUnknown",
untracked = "filterUntracked", expired = "filterExpired", unavailableFilter = "filterUnavailable",
inaccessible = "filterInaccessible", unsupportedFormat = "filterUnsupportedFormat",
}
local function CountWhisperObserver(s, key)
if not s then return end
s.observerMetrics = s.observerMetrics or {}
s.observerMetrics[key] = math.min(2147483647, (s.observerMetrics[key] or 0) + 1)
end
local function WhisperNow(a)
return a:SafeToNumber(a.API and a.API.GetTime and a.API.GetTime()) or 0
end
local function WhisperName(a, value)
if not a:CanAccessValue(value) or type(value) ~= "string" or #value > 120 or value:find("[%c|,:]") then
return nil
end
local name = a:NormalizeMemberName(value)
if not a:CanAccessValue(name) or type(name) ~= "string" or name == "" or #name > 120
or name:find("[%c|,:]") then return nil end
return name
end
local function WhisperState(a, create)
-- Native notices and ordinary whisper intent belong to the UI lifetime,
-- not a transport generation. Loading screens/disable cannot retract sends
-- already accepted by the engine or retire the observer protecting humans.
local s = rawget(a, "addonWhisperState")
if not s and create then
s = { targets = {}, ordinary = {} }
a.addonWhisperState = s
end
return s
end
local function WhisperRoutingCurrent(a, s, row, now, exactAttempt)
local transport = rawget(a, "transportState")
return WhisperState(a) == s and transport ~= nil and a.isEnabled and not a.isLoggingOut
and not transport.departing and row.transport == transport and row.generation == transport.generation
and s.targets[row.name:lower()] == row and now >= row.at and now < row.at + WHISPER_NOTICE_SECONDS
and (exactAttempt or not (row.olderLifetimeUntil and now < row.olderLifetimeUntil))
end
local function ApplyWhisperUnavailable(a, s, row, key, now, exactAttempt)
if not WhisperRoutingCurrent(a, s, row, now, exactAttempt) or row.replied or row.unavailableUntil then return end
-- Install the barrier before cancelling transfers: their cleanup and
-- completion callbacks can themselves try to send more packets.
row.unavailableUntil = now + WHISPER_UNAVAILABLE_SECONDS
row.expires = math.max(row.expires, row.unavailableUntil)
if a.RetireMeshPeer then a:RetireMeshPeer(row.name, "unavailable") end
if not WhisperRoutingCurrent(a, s, row, now, exactAttempt) then return end
a:CancelCommunicationWhere(function(work)
if not WhisperRoutingCurrent(a, s, row, now, exactAttempt) then return false end
local route = work.route
-- A targeted group response still uses the group route. A failed whisper
-- to its recipient must not cancel that transfer or its cached reply.
if not route or route.distribution ~= "WHISPER" then return false end
local recipient = WhisperName(a, route.target)
return recipient ~= nil and recipient:lower() == key
end, "unavailable")
end
local function ProcessWhisperUnavailable(a, s, row, key, now, exactAttempt)
local shouldLog = not row.noticeRecorded
row.noticeRecorded = true
-- The send barrier must precede every callback, including diagnostic sinks.
local ok = pcall(ApplyWhisperUnavailable, a, s, row, key, now, exactAttempt)
if shouldLog then
local ok = pcall(a.RecordCommsDiagnostic, a, "whisperUnavailable", exactAttempt
and "route=WHISPER result=12 TargetOffline" or "route=WHISPER notice=PLAYER_NOT_FOUND")
if not ok then CountWhisperObserver(s, "noticeLogErrors") end
end
if not ok then
CountWhisperObserver(s, "cleanupErrors")
-- This is deliberately separate from display filtering. Keep the native
-- receipt and the already-installed send barrier even if cleanup fails.
-- Do not copy an exception's possible player names into routine reports.
pcall(a.RecordDiagnosticError, a, "whisper failure cleanup", "Unavailable-peer cleanup failed; receipt retained.")
end
end
local function PruneWhisperTargets(rows, now)
local count = 0
for key, row in pairs(rows) do
if now < row.at or now >= row.expires then
rows[key] = nil
else
count = count + 1
end
end
return count
end
local function WhisperTargetCount(s, now)
-- A drain can inspect many queued destinations in one frame. Prune the
-- bounded ledger once per clock value, then maintain its count on inserts.
if s.targetsPrunedAt ~= now then
s.targetCount, s.targetsPrunedAt = PruneWhisperTargets(s.targets, now), now
end
return s.targetCount or 0
end
local function WhisperNoticeResult(s, now, suppress, decision)
-- Even unrelated system traffic releases expired receipts after disable.
-- Call after matching so the current event can still report an expiry.
if s then WhisperTargetCount(s, now) end
return suppress, decision
end
local function PruneWhisperObserver(a, s)
WhisperTargetCount(s, WhisperNow(a))
end
local function PlayerNotFoundPattern(format)
local parts, index, captures = { "^" }, 1, 0
local function Literal(text)
return (text:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1"))
end
while index <= #format do
local marker = format:find("%", index, true)
if not marker then
parts[#parts + 1] = Literal(format:sub(index))
break
end
parts[#parts + 1] = Literal(format:sub(index, marker - 1))
if format:sub(marker, marker + 1) == "%%" then
parts[#parts + 1], index = "%%", marker + 2
elseif format:sub(marker, marker + 1) == "%s" or format:sub(marker, marker + 3) == "%1$s" then
captures = captures + 1
parts[#parts + 1] = "(.+)"
index = marker + (format:sub(marker, marker + 1) == "%s" and 2 or 4)
else
return nil
end
end
parts[#parts + 1] = "$"
return captures == 1 and table.concat(parts) or nil
end
local function ReadWhisperNoticePattern(a)
local getter = a.API.GetPlayerNotFoundMessageFormat
if type(getter) ~= "function" then return nil end
local ok, format = pcall(getter)
if not ok or not a:CanAccessValue(format) or type(format) ~= "string" or #format > 512 then return nil end
return PlayerNotFoundPattern(format)
end
local function WhisperNoticeFormatSupported(a, s, now)
if s.noticeFormatCheckedAt and now >= s.noticeFormatCheckedAt
and now < s.noticeFormatCheckedAt + WHISPER_FILTER_RETRY_SECONDS then
return s.noticeFormatSupported
end
local ok, pattern = pcall(ReadWhisperNoticePattern, a)
s.noticeFormatCheckedAt, s.noticeFormatSupported = now, ok and pattern ~= nil
return s.noticeFormatSupported
end
function QuestTogether:RecordOrdinaryWhisperAttempt(distribution, target)
local s = WhisperState(self)
if not s then
return
end
local now = WhisperNow(self)
WhisperTargetCount(s, now)
if not self:CanAccessValue(distribution) or type(distribution) ~= "string" then
s.ordinaryUnknownUntil = now + WHISPER_NOTICE_SECONDS
return
end
if distribution ~= "WHISPER" then
return
end
local name = WhisperName(self, target)
local count = PruneWhisperTargets(s.ordinary, now)
local key = name and name:lower()
if not key or (not s.ordinary[key] and count >= WHISPER_TARGET_LIMIT) then
-- An unreadable target or an unusually large burst must never cause us
-- to conceal an ordinary whisper failure.
s.ordinaryUnknownUntil = now + WHISPER_NOTICE_SECONDS
return
end
s.ordinary[key] = { at = now, expires = now + WHISPER_NOTICE_SECONDS }
end
local ClassifyWhisperNotice
function QuestTogether:RegisterAddonWhisperChatFilter()
if rawget(self, "addonWhisperChatFilterRegistered") then return end
local s = WhisperState(self, true)
local now = WhisperNow(self)
if s.filterRetryAt and now < s.filterRetryAt then return end
-- A missing adapter must not turn a queued mesh probe into a native hook
-- installation attempt on every frame. Recovery remains lazy and bounded.
s.filterRetryAt = now + WHISPER_FILTER_RETRY_SECONDS
if not self.API.SetOrdinaryWhisperObserver or not self.API.AddMessageEventFilter then
CountWhisperObserver(s, "filterRegistrationFailures")
return
end
local ok, observing = pcall(self.API.SetOrdinaryWhisperObserver, function(distribution, target)
if WhisperState(self) == s then self:RecordOrdinaryWhisperAttempt(distribution, target) end
end)
if not ok or observing ~= true then
CountWhisperObserver(s, "filterRegistrationFailures")
return
end
-- Reuse the callback if an adapter fails after partially registering it.
-- Native registration deduplicates by callback identity.
s.filterCallback = s.filterCallback or function(_, event, message)
if WhisperState(self) ~= s or event ~= "CHAT_MSG_SYSTEM" then return false end
CountWhisperObserver(s, "filterInvocations")
-- Native chat treats a throwing filter as "show the message". Keep this
-- path independent of mesh retirement, transfer callbacks and logging.
local classified, suppress, decision = pcall(ClassifyWhisperNotice, self, message)
if not classified then
CountWhisperObserver(s, "filterErrors")
suppress = false
elseif WHISPER_FILTER_DECISIONS[decision] then
CountWhisperObserver(s, WHISPER_FILTER_DECISIONS[decision])
end
CountWhisperObserver(s, suppress and "filterSuppressed" or "filterPassed")
-- Release expired receipt references on passive activity as well. This
-- bounded maintenance cannot affect the already-computed decision.
pcall(PruneWhisperObserver, self, s)
return suppress == true
end
self.addonWhisperChatFilterFunc = s.filterCallback
local added, result = pcall(self.API.AddMessageEventFilter, "CHAT_MSG_SYSTEM", self.addonWhisperChatFilterFunc)
self.addonWhisperChatFilterRegistered = added and result == true or nil
if not self.addonWhisperChatFilterRegistered then CountWhisperObserver(s, "filterRegistrationFailures") end
end
function QuestTogether:CanRecordAddonWhisperAttempt(target, meshTraffic)
local name, transport = WhisperName(self, target), rawget(self, "transportState")
if not name or not transport then return false, "invalid" end
local s = WhisperState(self, true)
local now = WhisperNow(self)
if meshTraffic then
self:RegisterAddonWhisperChatFilter()
if not rawget(self, "addonWhisperChatFilterRegistered")
or (s.ordinaryUnknownUntil and now < s.ordinaryUnknownUntil)
or not WhisperNoticeFormatSupported(self, s, now) then
return false, "filter-unavailable"
end
end
local count = WhisperTargetCount(s, now)
local limit = meshTraffic and WHISPER_TARGET_LIMIT - WHISPER_PRIVATE_RESERVE or WHISPER_TARGET_LIMIT
if s.targets[name:lower()] == nil and count >= limit then return false, "capacity" end
return true
end
function QuestTogether:RecordAddonWhisperAttempt(target, meshTraffic)
local allowed, reason = self:CanRecordAddonWhisperAttempt(target, meshTraffic)
if not allowed then return false, reason end
local s, name = WhisperState(self), WhisperName(self, target)
local transport = rawget(self, "transportState")
if not s or not name or not transport then return false, "invalid" end
self:RegisterAddonWhisperChatFilter()
local now, key = WhisperNow(self), name:lower()
local count = WhisperTargetCount(s, now)
local limit = meshTraffic and WHISPER_TARGET_LIMIT - WHISPER_PRIVATE_RESERVE or WHISPER_TARGET_LIMIT
if count >= limit and not s.targets[key] then
return false, "capacity"
end
local prior = s.targets[key]
local olderUntil = prior and prior.olderLifetimeUntil
if prior and (prior.transport ~= transport or prior.generation ~= transport.generation) then
olderUntil = math.max(olderUntil or 0, prior.at + WHISPER_NOTICE_SECONDS)
end
if not s.targets[key] then s.targetCount = count + 1 end
local row = { name = name, at = now, expires = now + WHISPER_NOTICE_SECONDS,
transport = transport, generation = transport.generation, olderLifetimeUntil = olderUntil }
s.targets[key] = row
return { state = s, key = key, row = row, prior = prior, transport = transport, generation = transport.generation }
end
function QuestTogether:FinalizeAddonWhisperAttempt(token, definitelyUnsent)
if type(token) ~= "table" or token.finalized then return end
token.finalized = true
if not definitelyUnsent then return end
local s, transport = WhisperState(self), rawget(self, "transportState")
if s ~= token.state or not transport or transport ~= token.transport or transport.generation ~= token.generation
or s.targets[token.key] ~= token.row or token.row.noticeRecorded or token.row.replied then return end
local prior, now = token.prior, WhisperNow(self)
if prior and (now < prior.at or now >= prior.expires) then prior = nil end
s.targets[token.key], s.targetsPrunedAt = prior, nil
end
function QuestTogether:MarkAddonWhisperAttemptUnavailable(token)
if type(token) ~= "table" then return end
local s, row, now = WhisperState(self), token.row, WhisperNow(self)
if s ~= token.state or not row or not WhisperRoutingCurrent(self, s, row, now, true) or row.replied then return end
-- TargetOffline identifies this exact native call, unlike a target-only
-- system notice. It can safely stop current work despite an older receipt.
ProcessWhisperUnavailable(self, s, row, token.key, now, true)
end
function QuestTogether:IsAddonWhisperTargetUnavailable(target)
local s, name = WhisperState(self), WhisperName(self, target)
local row = s and name and s.targets[name:lower()]
local now = WhisperNow(self)
return row ~= nil and now >= row.at and row.unavailableUntil ~= nil and now < row.unavailableUntil
end
function QuestTogether:ClearAddonWhisperFailure(target)
local s, name = WhisperState(self), WhisperName(self, target)
local transport = rawget(self, "transportState")
if s and name and transport and not transport.departing and self.isEnabled and not self.isLoggingOut then
local row = s.targets[name:lower()]
if row then
-- A reply proves the address is reachable, but cannot acknowledge every
-- earlier native send. Preserve correlation for delayed failure notices.
row.unavailableUntil = nil
row.replied = true
end
end
end
local WHISPER_NOTICE_METRICS = {
matched = "matched", ordinary = "ordinary", ordinaryUnknown = "ordinaryUnknown",
untracked = "untracked", expired = "expired", unavailableFilter = "unavailableFilter",
inaccessible = "systemMessagesInaccessible", unsupportedFormat = "unsupportedFormat", classificationError = "classificationErrors",
}
function QuestTogether:RecordAddonWhisperNoticeDecision(reason)
local key = WHISPER_NOTICE_METRICS[reason]
if not key then return end
local diagnostics = self:GetCommsDiagnostics()
diagnostics.whisperNotices = diagnostics.whisperNotices or {}
diagnostics.whisperNotices[key] = (diagnostics.whisperNotices[key] or 0) + 1
end
function QuestTogether:GetAddonWhisperMetrics()
local metrics = {}
local diagnostics = self:GetCommsDiagnostics().whisperNotices or {}
for _, key in pairs(WHISPER_NOTICE_METRICS) do metrics[key] = diagnostics[key] or 0 end
metrics.filterRegistered = rawget(self, "addonWhisperChatFilterRegistered") == true
metrics.trackedTargets, metrics.ordinaryTargets, metrics.ordinaryUnknownSeconds = 0, 0, 0
local s = WhisperState(self)
for _, key in ipairs(WHISPER_OBSERVER_METRICS) do
metrics[key] = s and s.observerMetrics and s.observerMetrics[key] or 0
end
if s then
local now = WhisperNow(self)
WhisperTargetCount(s, now)
PruneWhisperTargets(s.ordinary, now)
for _, row in pairs(s.targets) do
if now >= row.at and now < row.expires then metrics.trackedTargets = metrics.trackedTargets + 1 end
end
for _, row in pairs(s.ordinary) do
if now >= row.at and now < row.expires then metrics.ordinaryTargets = metrics.ordinaryTargets + 1 end
end
metrics.ordinaryUnknownSeconds = math.max(0, (s.ordinaryUnknownUntil or now) - now)
end
metrics.noticeFormatSupported = s and WhisperNoticeFormatSupported(self, s, WhisperNow(self)) == true or false
metrics.meshAdmissionBlocked = not metrics.filterRegistered or metrics.ordinaryUnknownSeconds > 0 or not metrics.noticeFormatSupported
return metrics
end
ClassifyWhisperNotice = function(self, message)
local s, now = WhisperState(self), WhisperNow(self)
if not self:CanAccessValue(message) then return false, "inaccessible" end
if type(message) ~= "string" or #message > 1024 then return false end
local pattern = ReadWhisperNoticePattern(self)
if not pattern then return false, "unsupportedFormat" end
local name = WhisperName(self, message:match(pattern))
local key = name and name:lower()
if not key then return false end
local row = s and s.targets[key]
if not row then return false, "untracked" end
if now < row.at or now >= row.at + WHISPER_NOTICE_SECONDS then
return false, "expired"
end
local suppress, decision = true, "matched"
if not rawget(self, "addonWhisperChatFilterRegistered") then
suppress, decision = false, "unavailableFilter"
elseif s.ordinaryUnknownUntil and now < s.ordinaryUnknownUntil then
suppress, decision = false, "ordinaryUnknown"
elseif s.ordinary[key] and now >= s.ordinary[key].at and now < s.ordinary[key].expires then
suppress, decision = false, "ordinary"
end
return suppress, decision, s, row, key, now
end
function QuestTogether:HandleAddonWhisperSystemMessage(message)
local ok, suppress, decision, s, row, key, now = pcall(ClassifyWhisperNotice, self, message)
if not ok then return false, "classificationError" end
-- A human whisper makes the notice ambiguous for display, not evidence
-- that QT should keep sending to an address just reported unavailable.
-- Keep that feedback visible while applying the same bounded send hold.
-- Delayed notices still filter after retirement, but cannot affect a new
-- transport lifetime or a peer that has replied since the attempt.
if row then ProcessWhisperUnavailable(self, s, row, key, now) end
return WhisperNoticeResult(s or WhisperState(self), now or WhisperNow(self), suppress, decision)
end
function QuestTogether:ResetAddonWhisperFailures(preserveReceipts)
if preserveReceipts then
local s = WhisperState(self)
if s then
local now = WhisperNow(self)
s.targetCount, s.targetsPrunedAt = PruneWhisperTargets(s.targets, now), now
PruneWhisperTargets(s.ordinary, now)
end
return
end
if rawget(self, "addonWhisperChatFilterRegistered") and self.API.RemoveMessageEventFilter then
pcall(self.API.RemoveMessageEventFilter, "CHAT_MSG_SYSTEM", self.addonWhisperChatFilterFunc)
end
if self.API.SetOrdinaryWhisperObserver then
pcall(self.API.SetOrdinaryWhisperObserver, nil)
end
self.addonWhisperChatFilterRegistered, self.addonWhisperChatFilterFunc, self.addonWhisperState = nil, nil, 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
local function ChannelClock(self)
local getter = self.API and self.API.GetTime
local ok, value = false, nil
if type(getter) == "function" then ok, value = pcall(getter) end
local now = ok and SafeNumber(self, value)
return now and now >= 0 and now < math.huge and now or nil
end
-- Blizzard's normal channels get the first opportunity to join after loading.
-- Saved memberships remain usable immediately; no delayed callback owns a join.
function QuestTogether:BeginAnnouncementChannelStartup()
self.chatChannelJoinState = { awaitingWorld = true }
end
function QuestTogether:SuspendAnnouncementChannelJoins()
local state = rawget(self, "chatChannelJoinState") or {}
self.chatChannelJoinState = state
state.awaitingWorld, state.notBefore, state.needsClock = true, nil, nil
end
function QuestTogether:ResumeAnnouncementChannelJoins()
local state = rawget(self, "chatChannelJoinState")
if state and state.awaitingWorld then
local now = ChannelClock(self)
if now then
state.awaitingWorld, state.notBefore, state.lastTime, state.needsClock = false, now + 10, now, nil
else
state.awaitingWorld, state.needsClock = false, true
end
end
self:InvalidateAnnouncementChannelOrder()
end
function QuestTogether:CanJoinAnnouncementChannel()
if not self.isEnabled or self.isLoggingOut or self:IsRuntimeRestricted()
or self:IsRuntimeRestrictionTypeActive("chat") then return false end
local state = rawget(self, "chatChannelJoinState")
if not state then return true end
if state.awaitingWorld then return false end
local now = ChannelClock(self)
if not now then return false end
if state.needsClock or state.lastTime and now < state.lastTime then
state.needsClock, state.notBefore = nil, now + 10
end
state.lastTime = now
return not state.notBefore or now >= state.notBefore
end
function QuestTogether:EnsureAnnouncementChannelJoined(channelName)
if not self:IsPublicSharingAllowed() then return false end
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()
and not self:IsRuntimeRestrictionTypeActive("chat") 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:CanJoinAnnouncementChannel() then return false end
if not self.API or not self.API.JoinPermanentChannel then
self:Debug("JoinPermanentChannel API unavailable", "comms")
return false
end
-- Directory text is hidden from every chat window after joining. Use the
-- native primary window rather than inspecting a replaceable foreign frame.
local chatFrameId = 1
self:Debugf(
"comms",
"Joining peer directory name=%s chatFrameId=%s",
SafeAddonString(self, channelName),
SafeAddonString(self, chatFrameId)
)
local joined = pcall(self.API.JoinPermanentChannel, channelName, nil, chatFrameId, 1)
self:InvalidateAnnouncementChannelOrder()
if not joined or not self.isEnabled or self.isLoggingOut then return false end
currentLocalID = self:GetAnnouncementChannelLocalID(channelName)
if currentLocalID then
if cacheKey then
self[cacheKey] = currentLocalID
end
if self.HideAnnouncementChannelFromChatWindows and not self:IsRuntimeRestricted()
and not self:IsRuntimeRestrictionTypeActive("chat") then
self:HideAnnouncementChannelFromChatWindows(channelName)
self.announcementChannelBindings = self.announcementChannelBindings or {}
self.announcementChannelBindings[channelName] = currentLocalID
end
self:Debugf("comms", "Joined peer directory localID=%s", SafeAddonString(self, currentLocalID))
return true
end
self:Debug("Unable to join peer directory " .. SafeAddonString(self, channelName), "comms")
return false
end
-- Keep hidden directories behind human channels. RuntimeCoordinator owns the
-- cadence; every step resolves names again instead of retaining native indices.
local function OwnedDirectory(self, name)
if MatchesAnnouncementChannelName(self, name) or self:IsGeographicChannelName(name) then return true end
local base = name:gsub("^%d+%.%s+", ""):lower()
if base == "questtogether3" or base == "questtogetherannounce1" then return true end
local zone = tonumber(base:match("^questtogether3z([1-9]%d*)$") or base:match("^questtogetherz([1-9]%d*)$"))
return zone ~= nil and zone <= 1000000
end
function QuestTogether:InvalidateAnnouncementChannelOrder()
local state = rawget(self, "chatChannelOrderState")
if not state then return end
state.dirty = true
if not state.recoveryPending then state.lastResult, state.lastStage = "pending", "channel_change" end
-- Channel events can fire synchronously inside a native swap. Wake an idle
-- check without ever bypassing the current attempt's one-second floor.
local now = ChannelClock(self)
if now then state.nextAt = math.max(state.nextAttemptAt or now, math.min(state.nextAt or now, now)) end
end
local function ReadChannelOrder(self, api)
if type(api.GetChatChannelList) ~= "function" then return nil, "unavailable" end
local ok, list = pcall(api.GetChatChannelList)
if not ok or not self:CanAccessTable(list) or type(list) ~= "table" then return nil, "unreadable" end
if #list > 90 or #list % 3 ~= 0 then return nil, "invalid" end