-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLootMonitor.lua
More file actions
2036 lines (1767 loc) · 74.1 KB
/
Copy pathLootMonitor.lua
File metadata and controls
2036 lines (1767 loc) · 74.1 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
-- Loot Monitor for Turtle WoW
-- Shows recent loot as fading text notifications
-- Local references for better performance in Lua 5.0
local strfind = string.find
local strlower = string.lower
local strsub = string.sub
local strformat = string.format
local strgsub = string.gsub
local strlen = string.len
local tinsert = table.insert
local tremove = table.remove
local tgetn = table.getn
local mathsin = math.sin
local mathcos = math.cos
local mathpi = math.pi
local mathmod = mod -- Lua 5.0 uses global mod, not math.mod
local gettime = GetTime
local tonumber = tonumber
local tostring = tostring
local getglobal = getglobal
local pairs = pairs
local ipairs = ipairs
local type = type
-- Cache frequently used WoW API functions
local CreateFrame = CreateFrame
local GetTime = GetTime
local GetContainerNumSlots = GetContainerNumSlots
local GetContainerItemLink = GetContainerItemLink
local GetContainerItemInfo = GetContainerItemInfo
local UIParent = UIParent
local DEFAULT_CHAT_FRAME = DEFAULT_CHAT_FRAME
local WorldFrame = WorldFrame
-- Cache frequently accessed constants
local TEXTURE_PATH_QUESTION = "Interface\\Icons\\INV_Misc_QuestionMark"
local BACKDROP_TOOLTIP_BG = "Interface\\Tooltips\\UI-Tooltip-Background"
local BACKDROP_TOOLTIP_BORDER = "Interface\\Tooltips\\UI-Tooltip-Border"
-- Cache coin icon paths
local COIN_ICON_COPPER = "Interface\\Icons\\INV_Misc_Coin_01"
local COIN_ICON_SILVER = "Interface\\Icons\\INV_Misc_Coin_03"
local COIN_ICON_GOLD = "Interface\\Icons\\INV_Misc_Coin_05"
-- Cache math constants and frequently used numbers
local MATH_2PI = mathpi * 2
local COIN_SCALE_FACTOR = 0.8
local COIN_FADEIN_FACTOR = 0.7
local COIN_DISPLAY_FACTOR = 0.6
local COIN_FADEOUT_FACTOR = 0.8
local GLOW_SCALE_MIN = 1.0
local GLOW_SCALE_VARIATION = 0.08
-- Pre-compile common patterns for better regex performance
local QUEST_ITEM_PATTERN = "quest item"
local QUEST_PATTERN = "quest"
local BIND_PATTERN = "binds when picked up"
local YOU_LOOT_PATTERN = "You loot"
local YOU_RECEIVE_PATTERNS = {"You receive loot:", "You receive item:", "Received item"}
local COIN_PATTERNS = {"Copper", "Silver", "Gold"}
local BRACKET_OPEN = "%["
local BRACKET_CLOSE = "%]"
-- Initialize addon
LootMonitor = {}
LootMonitor.activeNotifications = {}
LootMonitor.maxNotifications = 5
LootMonitor.frame = nil
LootMonitor.moveFrame = nil
LootMonitor.moveMode = false
-- Security fix: Rate limiting variables
LootMonitor.lastMessageTime = 0
LootMonitor.messageThrottle = 0.05 -- 50ms between messages
-- Security fix: OnUpdate frame tracking
LootMonitor.activeOnUpdateFrames = 0
LootMonitor.maxOnUpdateFrames = 15
-- Loot history tracking
LootMonitor.lootHistory = {}
LootMonitor.sessionStats = {
itemsLooted = 0,
goldEarned = 0,
startTime = 0
}
-- Minimap button
LootMonitor.minimapButton = nil
-- Custom print function for WoW 1.12.1 compatibility
local function Print(msg)
if DEFAULT_CHAT_FRAME then
DEFAULT_CHAT_FRAME:AddMessage(msg)
end
end
-- Get item quality from item link
function LootMonitor:GetItemQuality(itemLink)
if not itemLink or not strfind(itemLink, "|Hitem:") then
return nil
end
-- Extract item ID from link: |Hitem:itemID:...
local _, _, itemString = strfind(itemLink, "|Hitem:([%d:]+)")
if not itemString then return nil end
-- Get the first number (item ID)
local _, _, itemID = strfind(itemString, "^(%d+)")
if not itemID then return nil end
-- Use GetItemInfo to get quality
local _, _, quality = GetItemInfo(tonumber(itemID))
return quality
end
-- Check if item should be filtered
function LootMonitor:ShouldFilterItem(itemName, itemData)
-- Check whitelist first (always show)
if LootMonitorDB.useWhitelist and LootMonitorDB.whitelist[itemName] then
return false
end
-- Check blacklist (never show)
if LootMonitorDB.blacklist[itemName] then
return true
end
-- Check quality filter
if not self:IsCoinItem(itemName) and itemData and not strfind(itemData, "^%d+ ") then
local quality = self:GetItemQuality(itemData)
if quality then
-- Filter by quality setting
if not LootMonitorDB.qualityFilter[quality] then
return true
end
-- Filter by minimum quality
if quality < LootMonitorDB.minQuality then
return true
end
end
end
return false
end
-- Add item to loot history
function LootMonitor:AddToHistory(itemName, quantity, itemData)
if not LootMonitorDB.trackHistory then return end
local historyEntry = {
name = itemName,
quantity = quantity,
time = GetTime(),
link = itemData
}
tinsert(LootMonitorHistory, 1, historyEntry)
-- Trim history to max size
while tgetn(LootMonitorHistory) > LootMonitorDB.historyMaxItems do
tremove(LootMonitorHistory)
end
-- Update session stats
self.sessionStats.itemsLooted = self.sessionStats.itemsLooted + quantity
end
-- Create a hidden tooltip frame for scanning item tooltips
local LootMonitorTooltip = CreateFrame("GameTooltip", "LootMonitorTooltip", nil, "GameTooltipTemplate")
LootMonitorTooltip:SetOwner(WorldFrame, "ANCHOR_NONE")
-- Check if an item is a quest item by scanning its tooltip
function LootMonitor:IsQuestItem(itemName)
if not itemName then return false end
-- First try to find the item in bags and scan its tooltip
local texture, bag, slot = self:FindItemInBags(itemName)
if bag and slot then
-- Clear the tooltip
LootMonitorTooltip:ClearLines()
-- Set the tooltip to the item
LootMonitorTooltip:SetBagItem(bag, slot)
-- Cache tooltip line count to avoid repeated calls
local numLines = LootMonitorTooltip:NumLines()
-- Security fix: Validate numLines to prevent unsafe getglobal usage
if type(numLines) == "number" and numLines >= 1 and numLines <= 30 then
-- Scan tooltip lines for quest indicators (left side)
for i = 1, numLines do
local line = getglobal("LootMonitorTooltipTextLeft" .. i)
if line then
local text = line:GetText()
if text then
local lowerText = strlower(text)
-- Look for quest item indicators in tooltip
if strfind(lowerText, QUEST_ITEM_PATTERN) or
strfind(lowerText, QUEST_PATTERN) or
strfind(lowerText, BIND_PATTERN) then
return true
end
end
end
end
-- Also check right side of tooltip
for i = 1, numLines do
local line = getglobal("LootMonitorTooltipTextRight" .. i)
if line then
local text = line:GetText()
if text then
local lowerText = strlower(text)
if strfind(lowerText, QUEST_ITEM_PATTERN) or
strfind(lowerText, QUEST_PATTERN) then
return true
end
end
end
end
end
end
return false
end
-- Schedule a delayed quest item check (item needs time to appear in bags)
function LootMonitor:ScheduleQuestItemCheck(notification)
-- Security fix: Limit OnUpdate frames to prevent resource exhaustion
if self.activeOnUpdateFrames >= self.maxOnUpdateFrames then
return -- Skip this OnUpdate
end
self.activeOnUpdateFrames = self.activeOnUpdateFrames + 1
local checkFrame = CreateFrame("Frame")
local elapsed = 0
local accum = 0
local maxCheckTime = 2.0 -- Check for up to 2 seconds
local checkInterval = 0.2 -- Check every 0.2 seconds
checkFrame:SetScript("OnUpdate", function()
elapsed = elapsed + arg1
accum = accum + arg1
-- Stop checking after max time
if elapsed > maxCheckTime then
checkFrame:SetScript("OnUpdate", nil)
LootMonitor.activeOnUpdateFrames = LootMonitor.activeOnUpdateFrames - 1
return
end
-- Only check at intervals
if accum < checkInterval then
return
end
accum = 0
-- Try to detect quest item
local isQuestItem = LootMonitor:IsQuestItem(notification.name)
if isQuestItem and LootMonitorDB.questItemGlow then
notification.isQuestItem = true
notification.glow:Show()
notification.glow:SetBackdropBorderColor(1, 0.8, 0, 1) -- Bright orange-yellow border
notification.glow:SetBackdropColor(1, 1, 0, 0.4) -- Visible yellow background
LootMonitor:StartGlowAnimation(notification)
checkFrame:SetScript("OnUpdate", nil) -- Stop checking
LootMonitor.activeOnUpdateFrames = LootMonitor.activeOnUpdateFrames - 1
else
checkFrame:SetScript("OnUpdate", nil) -- Stop checking even if glow is disabled
LootMonitor.activeOnUpdateFrames = LootMonitor.activeOnUpdateFrames - 1
end
end)
end
-- Schedule a delayed total count update (item needs time to appear in bags)
function LootMonitor:ScheduleTotalCountUpdate(notification)
-- Security fix: Limit OnUpdate frames to prevent resource exhaustion
if self.activeOnUpdateFrames >= self.maxOnUpdateFrames then
return -- Skip this OnUpdate
end
self.activeOnUpdateFrames = self.activeOnUpdateFrames + 1
local updateFrame = CreateFrame("Frame")
local elapsed = 0
local accum = 0
local maxUpdateTime = 1.5 -- Check for up to 1.5 seconds
local updateInterval = 0.3 -- Update every 0.3 seconds
updateFrame:SetScript("OnUpdate", function()
elapsed = elapsed + arg1
accum = accum + arg1
-- Stop checking after max time
if elapsed > maxUpdateTime then
updateFrame:SetScript("OnUpdate", nil)
LootMonitor.activeOnUpdateFrames = LootMonitor.activeOnUpdateFrames - 1
return
end
-- Only update at intervals
if accum < updateInterval then
return
end
accum = 0
-- Fetch count here (async) and cache it, then refresh text
notification.totalCount = LootMonitor:CountItemInBags(notification.name)
LootMonitor:UpdateNotificationText(notification)
end)
end
-- Default settings
local defaults = {
enabled = true,
scale = 1.2,
fadeInTime = 0.3,
displayTime = 5.0,
fadeOutTime = 1.0,
questItemGlow = true,
showTotalCount = true,
position = {
point = "CENTER",
relativePoint = "CENTER",
x = 200,
y = 100
},
-- Quality filtering (0=Poor, 1=Common, 2=Uncommon, 3=Rare, 4=Epic, 5=Legendary)
minQuality = 0, -- Show all qualities
qualityFilter = {
[0] = true, -- Poor (gray)
[1] = true, -- Common (white)
[2] = true, -- Uncommon (green)
[3] = true, -- Rare (blue)
[4] = true, -- Epic (purple)
[5] = true -- Legendary (orange)
},
animationStyle = "fade", -- "fade", "slide", or "bounce"
-- Blacklist/Whitelist
blacklist = {}, -- Items to never show
whitelist = {}, -- Items to always show (overrides quality filter)
useWhitelist = false,
-- Loot history
trackHistory = true,
historyMaxItems = 100,
-- Click interactions
clickToLink = true,
clickTooltip = true,
-- Customization
fontFace = "Fonts\\FRIZQT__.TTF",
fontSize = 14,
fontOutline = "OUTLINE",
backgroundColor = {0, 0, 0, 0}, -- Transparent by default
borderColor = {1, 1, 1, 0.3},
-- Animation
animationStyle = "fade", -- fade, slide, bounce
stackDirection = "down", -- down, up
-- Minimap
minimapButton = {
hide = false,
position = 180
}
}
-- Deep copy a table
local function DeepCopy(original)
local copy = {}
for k, v in pairs(original) do
if type(v) == "table" then
copy[k] = DeepCopy(v)
else
copy[k] = v
end
end
return copy
end
-- Initialize saved variables
function LootMonitor:OnLoad()
if not LootMonitorDB then
LootMonitorDB = {}
end
-- Security fix: Validate saved variable types to prevent crashes from corrupted data
for key, value in pairs(defaults) do
if LootMonitorDB[key] == nil or type(LootMonitorDB[key]) ~= type(value) then
if type(value) == "table" then
-- Deep copy table defaults
LootMonitorDB[key] = DeepCopy(value)
else
LootMonitorDB[key] = value
end
elseif type(value) == "table" then
-- Validate nested table structures
if key == "position" then
if type(LootMonitorDB[key].point) ~= "string" then
LootMonitorDB[key].point = value.point
end
if type(LootMonitorDB[key].relativePoint) ~= "string" then
LootMonitorDB[key].relativePoint = value.relativePoint
end
if type(LootMonitorDB[key].x) ~= "number" then
LootMonitorDB[key].x = value.x
end
if type(LootMonitorDB[key].y) ~= "number" then
LootMonitorDB[key].y = value.y
end
elseif key == "qualityFilter" or key == "blacklist" or key == "whitelist" then
-- Ensure these tables exist
if type(LootMonitorDB[key]) ~= "table" then
LootMonitorDB[key] = DeepCopy(value)
end
elseif key == "minimapButton" then
if type(LootMonitorDB[key].hide) ~= "boolean" then
LootMonitorDB[key].hide = value.hide
end
if type(LootMonitorDB[key].position) ~= "number" then
LootMonitorDB[key].position = value.position
end
elseif key == "backgroundColor" or key == "borderColor" then
-- Ensure color tables have 4 values
if type(LootMonitorDB[key]) ~= "table" or tgetn(LootMonitorDB[key]) ~= 4 then
LootMonitorDB[key] = {value[1], value[2], value[3], value[4]}
end
end
end
end
-- Initialize loot history if tracking is enabled
if not LootMonitorHistory then
LootMonitorHistory = {}
end
-- Initialize session stats
self.sessionStats.startTime = GetTime()
self:CreateNotificationFrame()
self:CreateMinimapButton()
Print("[Loot Monitor] Loaded! Type /lm for settings.")
end
-- Save current frame position
function LootMonitor:SavePosition()
if self.frame then
local point, _, relativePoint, x, y = self.frame:GetPoint()
if point and x and y then
if not LootMonitorDB.position then
LootMonitorDB.position = {}
end
LootMonitorDB.position.point = point
LootMonitorDB.position.relativePoint = relativePoint or point
LootMonitorDB.position.x = x
LootMonitorDB.position.y = y
end
end
end
-- Create minimap button
function LootMonitor:CreateMinimapButton()
if LootMonitorDB.minimapButton.hide then return end
if self.minimapButton then return end -- Already created
local button = CreateFrame("Button", "LootMonitorMinimapButton", Minimap)
button:SetWidth(31)
button:SetHeight(31)
button:SetFrameStrata("MEDIUM")
button:SetFrameLevel(8)
button:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
-- Icon
local icon = button:CreateTexture("BACKGROUND")
icon:SetWidth(20)
icon:SetHeight(20)
icon:SetPoint("CENTER", 0, 1)
icon:SetTexture("Interface\\Icons\\INV_Misc_Coin_05") -- Gold coin icon
-- Border
local overlay = button:CreateTexture("OVERLAY")
overlay:SetWidth(53)
overlay:SetHeight(53)
overlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
overlay:SetPoint("TOPLEFT", 0, 0)
-- Position on minimap
local angle = LootMonitorDB.minimapButton.position
local x = 80 * mathsin(angle)
local y = 80 * mathcos(angle)
button:SetPoint("CENTER", Minimap, "CENTER", x, y)
-- Make draggable
button:RegisterForDrag("LeftButton")
button:SetScript("OnDragStart", function()
button:LockHighlight()
button:SetScript("OnUpdate", function()
local mx, my = Minimap:GetCenter()
local px, py = GetCursorPosition()
local scale = Minimap:GetEffectiveScale()
px, py = px / scale, py / scale
local angle = mathmod(math.atan2(py - my, px - mx), 2 * mathpi)
LootMonitorDB.minimapButton.position = angle
local x = 80 * mathsin(angle)
local y = 80 * mathcos(angle)
button:ClearAllPoints()
button:SetPoint("CENTER", Minimap, "CENTER", x, y)
end)
end)
button:SetScript("OnDragStop", function()
button:SetScript("OnUpdate", nil)
button:UnlockHighlight()
end)
-- Click handlers
button:SetScript("OnClick", function()
LootMonitor:ShowSettings()
end)
button:SetScript("OnEnter", function()
GameTooltip:SetOwner(button, "ANCHOR_LEFT")
GameTooltip:AddLine("Loot Monitor")
GameTooltip:AddLine("Left-click: Open settings", 1, 1, 1)
GameTooltip:AddLine("Drag: Reposition button", 1, 1, 1)
GameTooltip:AddLine(" ", 1, 1, 1)
GameTooltip:AddLine("Session: " .. LootMonitor.sessionStats.itemsLooted .. " items looted", 0.7, 0.7, 1)
GameTooltip:Show()
end)
button:SetScript("OnLeave", function()
GameTooltip:Hide()
end)
self.minimapButton = button
end
-- Create the notification container frame
function LootMonitor:CreateNotificationFrame()
-- Create invisible container frame for notifications
local frame = CreateFrame("Frame", "LootMonitorNotificationFrame", UIParent)
frame:SetWidth(400) -- Compact width for notifications
frame:SetHeight(300)
-- Set position from saved settings (with fallback to defaults)
local point = LootMonitorDB.position.point or "CENTER"
local relativePoint = LootMonitorDB.position.relativePoint or point
local x = LootMonitorDB.position.x
local y = LootMonitorDB.position.y
if x == nil then x = 200 end
if y == nil then y = 100 end
frame:SetPoint(point, UIParent, relativePoint, x, y)
-- Make it movable with Shift+Ctrl+Click (for positioning)
frame:SetMovable(true)
frame:EnableMouse(false) -- Disabled by default, enabled only when moving
frame:RegisterForDrag("LeftButton")
-- Store reference
self.frame = frame
frame:Show()
end
-- Register events to track loot
function LootMonitor:RegisterEvents()
local frame = CreateFrame("Frame")
frame:RegisterEvent("CHAT_MSG_LOOT")
frame:RegisterEvent("CHAT_MSG_MONEY")
frame:RegisterEvent("CHAT_MSG_SYSTEM")
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PLAYER_LOGOUT")
frame:SetScript("OnEvent", function()
if event == "ADDON_LOADED" then
if not LootMonitor.initialized then
LootMonitor:OnLoad()
LootMonitor.initialized = true
end
elseif event == "CHAT_MSG_LOOT" then
LootMonitor:ProcessLootMessage(arg1)
elseif event == "CHAT_MSG_MONEY" then
LootMonitor:ProcessMoneyMessage(arg1)
elseif event == "CHAT_MSG_SYSTEM" then
LootMonitor:ProcessSystemMessage(arg1)
elseif event == "PLAYER_LOGOUT" then
-- Save position before logout
LootMonitor:SavePosition()
end
end)
end
-- Extract quantity from loot message (looks for x2, x3, etc.)
function LootMonitor:ExtractQuantityFromMessage(message, startPos)
if not message or not startPos then return 1 end
-- Look for "x" followed by numbers after the item name/link
local remainingText = strsub(message, startPos)
local xPos = strfind(remainingText, "x")
if xPos then
-- Extract the number after "x"
local numberStart = xPos + 1
local numberEnd = numberStart
-- Find the end of the number
while numberEnd <= strlen(remainingText) do
local char = strsub(remainingText, numberEnd, numberEnd)
if char >= "0" and char <= "9" then
numberEnd = numberEnd + 1
else
break
end
end
if numberEnd > numberStart then
local quantityStr = strsub(remainingText, numberStart, numberEnd - 1)
local quantity = tonumber(quantityStr)
-- Security fix: Add bounds checking to prevent integer overflow
if quantity and quantity > 0 and quantity <= 999 then
return quantity
elseif quantity and quantity > 999 then
return 999 -- Cap at reasonable maximum
end
end
end
return 1 -- Default to 1 if no quantity found
end
-- Process loot messages and extract item information
function LootMonitor:ProcessLootMessage(message)
if not message or not LootMonitorDB.enabled then return end
-- Security fix: Rate limiting to prevent spam
local now = GetTime()
if now - self.lastMessageTime < self.messageThrottle then
return -- Throttle
end
self.lastMessageTime = now
-- Check for coin loot messages first (e.g., "You loot 2 Copper")
if strfind(message, YOU_LOOT_PATTERN) then
-- Check if it contains coin types
for i = 1, tgetn(COIN_PATTERNS) do
if strfind(message, COIN_PATTERNS[i]) then
self:ProcessCoinLoot(message)
return
end
end
end
-- Check if this is a receive message using pre-compiled patterns
local isReceiveMessage = false
for i = 1, tgetn(YOU_RECEIVE_PATTERNS) do
if strfind(message, YOU_RECEIVE_PATTERNS[i]) then
isReceiveMessage = true
break
end
end
if isReceiveMessage then
-- Look for full item links (|cXXXXXXXX|Hitem:...|h[Name]|h|r)
local linkStart = strfind(message, "|c")
if linkStart then
local hStart = strfind(message, "|H", linkStart)
if hStart then
local linkEnd = strfind(message, "|r", hStart)
if linkEnd then
local itemLink = strsub(message, linkStart, linkEnd + 1)
-- Validate that it's a proper item link with |Hitem:
if strfind(itemLink, "|Hitem:") then
-- Extract quantity after the link
local quantity = self:ExtractQuantityFromMessage(message, linkEnd + 2)
self:AddLootItem(itemLink, false, quantity)
return
end
end
end
end
-- Extract item name in brackets (this is what we're actually getting)
local bracketStart = strfind(message, BRACKET_OPEN)
if bracketStart then
local bracketEnd = strfind(message, BRACKET_CLOSE, bracketStart)
if bracketEnd then
local itemName = strsub(message, bracketStart + 1, bracketEnd - 1)
-- Extract quantity after the brackets
local quantity = self:ExtractQuantityFromMessage(message, bracketEnd + 1)
self:AddLootItem(itemName, true, quantity) -- true indicates it's just a name, not a full link
end
end
end
end
-- Process coin loot messages (e.g., "You loot 2 Copper")
function LootMonitor:ProcessCoinLoot(message)
if not message then return end
-- Extract coin information from message
local coinAmount = 0
local coinType = ""
-- Look for patterns like "You loot 2 Copper", "You loot 1 Silver", etc.
local amountStart = strfind(message, YOU_LOOT_PATTERN)
if amountStart then
local afterLoot = strsub(message, amountStart + 9) -- Skip "You loot "
-- Find the number
local spacePos = strfind(afterLoot, " ")
if spacePos then
local amountStr = strsub(afterLoot, 1, spacePos - 1)
coinAmount = tonumber(amountStr) or 0
-- Find the coin type using pre-compiled patterns
local coinTypeStr = strsub(afterLoot, spacePos + 1)
for i = 1, tgetn(COIN_PATTERNS) do
if strfind(coinTypeStr, COIN_PATTERNS[i]) then
coinType = COIN_PATTERNS[i]
break
end
end
end
end
if coinAmount > 0 and coinType ~= "" then
local coinText = coinAmount .. " " .. coinType
self:AddLootItem(coinText, true, 1) -- Treat as name-only item
end
end
-- Process money loot messages from CHAT_MSG_MONEY event
function LootMonitor:ProcessMoneyMessage(message)
if not message or not LootMonitorDB.enabled then return end
-- Security fix: Rate limiting to prevent spam
local now = GetTime()
if now - self.lastMessageTime < self.messageThrottle then
return -- Throttle
end
self.lastMessageTime = now
-- Money messages might be in different formats
-- Common patterns might be "You loot 2 Copper" or just "2 Copper"
local coinAmount = 0
local coinType = ""
-- Try different patterns
if strfind(message, "Copper") then
coinType = "Copper"
elseif strfind(message, "Silver") then
coinType = "Silver"
elseif strfind(message, "Gold") then
coinType = "Gold"
end
if coinType ~= "" then
-- Extract the number - look for any number in the message
local numberMatch = strgsub(message, ".*(%d+).*", "%1")
coinAmount = tonumber(numberMatch) or 0
if coinAmount > 0 then
local coinText = coinAmount .. " " .. coinType
self:AddLootItem(coinText, true, 1)
end
end
end
-- Process system messages for quest rewards and other item gains
function LootMonitor:ProcessSystemMessage(message)
if not message or not LootMonitorDB.enabled then return end
-- Security fix: Rate limiting to prevent spam
local now = GetTime()
if now - self.lastMessageTime < self.messageThrottle then
return -- Throttle
end
self.lastMessageTime = now
-- Debug: Print system messages that might contain item information
if LootMonitor.debugMode and (
strfind(message, "You receive") or
strfind(message, "%[")) then
Print("[LootMonitor Debug] System message: " .. message)
end
-- Check for various quest reward patterns
if strfind(message, "Received item:") or
strfind(message, "You receive item:") or
strfind(message, "You receive") or
strfind(message, "receive") then
-- Look for full item links (|cXXXXXXXX|Hitem:...|h[Name]|h|r)
local linkStart = strfind(message, "|c")
if linkStart then
local hStart = strfind(message, "|H", linkStart)
if hStart then
local linkEnd = strfind(message, "|r", hStart)
if linkEnd then
local itemLink = strsub(message, linkStart, linkEnd + 1)
-- Validate that it's a proper item link with |Hitem:
if strfind(itemLink, "|Hitem:") then
-- Extract quantity after the link
local quantity = self:ExtractQuantityFromMessage(message, linkEnd + 2)
self:AddLootItem(itemLink, false, quantity)
return
end
end
end
end
-- Extract item name in brackets
local bracketStart = strfind(message, "%[")
if bracketStart then
local bracketEnd = strfind(message, "%]", bracketStart)
if bracketEnd then
local itemName = strsub(message, bracketStart + 1, bracketEnd - 1)
-- Extract quantity after the brackets
local quantity = self:ExtractQuantityFromMessage(message, bracketEnd + 1)
self:AddLootItem(itemName, true, quantity)
end
end
end
end
-- Add a looted item and create fading notification
function LootMonitor:AddLootItem(itemData, isNameOnly, quantity)
if not LootMonitorDB.enabled then return end
local itemName
local actualQuantity = quantity or 1
-- Extract item name
if not isNameOnly then
-- It's a full item link, extract name
local bracketStart = strfind(itemData, BRACKET_OPEN)
local bracketEnd = strfind(itemData, BRACKET_CLOSE)
if bracketStart and bracketEnd then
itemName = strsub(itemData, bracketStart + 1, bracketEnd - 1)
else
itemName = "Unknown Item"
end
else
-- It's just a name
itemName = itemData
end
-- Security fix: Limit item name length to prevent resource exhaustion
if itemName and strlen(itemName) > 100 then
itemName = strsub(itemName, 1, 97) .. "..."
end
-- Check quality filter, blacklist, whitelist
if self:ShouldFilterItem(itemName, not isNameOnly and itemData or nil) then
return -- Item is filtered
end
-- Add to history
self:AddToHistory(itemName, actualQuantity, not isNameOnly and itemData or itemName)
-- Check if we already have a notification for this item (optimized)
local existingNotification = nil
local activeList = self.activeNotifications
for i = 1, tgetn(activeList) do
local notification = activeList[i]
if notification.name == itemName and not notification.fadingOut then
existingNotification = notification
break
end
end
if existingNotification then
-- Update existing notification
existingNotification.count = existingNotification.count + actualQuantity
existingNotification.startTime = GetTime() -- Reset timer
self:UpdateNotificationText(existingNotification)
else
-- Create new notification
self:CreateLootNotification(itemName, actualQuantity, itemData, isNameOnly)
end
end
-- Find item texture and bag position in player's bags (optimized)
function LootMonitor:FindItemInBags(itemName)
if not itemName then return nil, nil, nil end
-- Search through bags (start with bag 0 which is most likely to have recent loot)
for bag = 0, 4 do
local numSlots = GetContainerNumSlots(bag)
if numSlots and numSlots > 0 then
-- Search backwards through slots (recent items are often at the end)
for slot = numSlots, 1, -1 do
local itemLink = GetContainerItemLink(bag, slot)
if itemLink then
-- Use more efficient string matching
local linkStart = strfind(itemLink, BRACKET_OPEN)
local linkEnd = strfind(itemLink, BRACKET_CLOSE)
if linkStart and linkEnd then
local linkName = strsub(itemLink, linkStart + 1, linkEnd - 1)
if linkName == itemName then
local texture = GetContainerItemInfo(bag, slot)
if texture then
return texture, bag, slot
end
end
end
end
end
end
end
return nil, nil, nil
end
-- Find item texture in player's bags (backward compatibility)
function LootMonitor:FindItemTextureInBags(itemName)
local texture, _, _ = self:FindItemInBags(itemName)
return texture
end
-- Check if an item is a coin/money item (actual currency, not items containing these words)
function LootMonitor:IsCoinItem(itemName)
if not itemName then return false end
local lowerName = strlower(itemName)
-- Only match exact coin patterns like "5 Copper", "2 Silver", "1 Gold"
-- Check if it starts with a number followed by space and then the coin type
return strfind(lowerName, "^%d+ copper$") or
strfind(lowerName, "^%d+ silver$") or
strfind(lowerName, "^%d+ gold$") or
lowerName == "copper" or
lowerName == "silver" or
lowerName == "gold"
end
-- Count total amount of an item in all bags
function LootMonitor:CountItemInBags(itemName)
if not itemName then return 0 end
local totalCount = 0
-- Search through all bags
for bag = 0, 4 do
local numSlots = GetContainerNumSlots(bag)
if numSlots and numSlots > 0 then
for slot = 1, numSlots do
local itemLink = GetContainerItemLink(bag, slot)
if itemLink then
-- Extract item name from link
local linkStart = strfind(itemLink, BRACKET_OPEN)
local linkEnd = strfind(itemLink, BRACKET_CLOSE)
if linkStart and linkEnd then
local linkName = strsub(itemLink, linkStart + 1, linkEnd - 1)
if linkName == itemName then
local _, itemCount = GetContainerItemInfo(bag, slot)
if itemCount then
totalCount = totalCount + itemCount
end
end
end
end
end
end
end
return totalCount
end
-- Create a new loot notification
function LootMonitor:CreateLootNotification(itemName, quantity, itemData, isNameOnly)
-- Clean up old notifications first
self:CleanupNotifications()
-- Limit active notifications
while tgetn(self.activeNotifications) >= self.maxNotifications do
local oldest = self.activeNotifications[tgetn(self.activeNotifications)]
self:RemoveNotification(oldest)
end
-- Check if this is a coin notification
local isCoin = self:IsCoinItem(itemName)
-- Create notification frame with different size for coins
local notification = CreateFrame("Frame", nil, self.frame)
if isCoin then
notification:SetWidth(320) -- Generous width for coins with count
notification:SetHeight(32) -- Smaller height for coins
else
notification:SetWidth(380) -- Generous width for items with count
notification:SetHeight(40)
end
-- Position notifications vertically (with different spacing for coins)
local yOffset = tgetn(self.activeNotifications) * (isCoin and -28 or -35)
notification:SetPoint("TOP", self.frame, "TOP", 0, yOffset)
-- Create icon with different size for coins
local icon = notification:CreateTexture(nil, "ARTWORK")
if isCoin then
icon:SetWidth(24) -- Smaller icon for coins