-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBulkMail.lua
More file actions
1984 lines (1807 loc) · 73.7 KB
/
BulkMail.lua
File metadata and controls
1984 lines (1807 loc) · 73.7 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
BulkMail = LibStub("AceAddon-3.0"):NewAddon("BulkMail", "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0", "AceHook-3.0")
local mod, self, BulkMail = BulkMail, BulkMail, BulkMail
local VERSION = " @project-version@"
local LibStub = LibStub
local L = LibStub("AceLocale-3.0"):GetLocale("BulkMail", false)
local pt = LibStub("LibPeriodicTable-3.1")
local abacus = LibStub("LibAbacus-3.0")
local gratuity = LibStub("LibGratuity-3.0")
local QTIP = LibStub("LibQTip-1.0")
local LD = LibStub("LibDropdown-1.0")
local AC = LibStub("AceConfig-3.0")
local ACD = LibStub("AceConfigDialog-3.0")
local ACONS = LibStub("AceConsole-3.0")
local DB = LibStub("AceDB-3.0")
local LDB = LibStub("LibDataBroker-1.1", true)
local MagicUtil = LibStub("LibMagicUtil-1.0")
BulkMail.L = L
local SUFFIX_CHAR = "\32"
function CompatGetAuctionItemSubClasses(i)
return {GetAuctionItemSubClasses(i)}
end
local _G = _G
local strmatch = string.match
local strsub = string.sub
local tinsert = table.insert
local tremove = table.remove
local tconcat = table.concat
local fmt = string.format
local ClickSendMailItemButton = ClickSendMailItemButton
local GetItemInfo = GetItemInfo
local GetSendMailItem = GetSendMailItem
local GetSendMailItemLink = GetSendMailItemLink
local GetSendMailPrice = GetSendMailPrice
local ITEM_BIND_ON_EQUIP = ITEM_BIND_ON_EQUIP
local ITEM_BIND_ON_PICKUP = ITEM_BIND_ON_PICKUP
local ITEM_BIND_QUEST = ITEM_BIND_QUEST
local ITEM_CONJURED = ITEM_CONJURED
local ITEM_SOULBOUND = ITEM_SOULBOUND
local IsAltKeyDown = IsAltKeyDown
local IsControlKeyDown = IsControlKeyDown
local IsShiftKeyDown = IsShiftKeyDown
local MoneyInputFrame_GetCopper = MoneyInputFrame_GetCopper
local MoneyFrame_Update = MoneyFrame_Update
local NUM_BAG_SLOTS = NUM_BAG_SLOTS
local SendMailCODButton = SendMailCODButton
local ChatEdit_GetActiveWindow = ChatEdit_GetActiveWindow
local CursorHasItem = CursorHasItem
local SetItemRef = SetItemRef
local ATTACHMENTS_MAX_SEND = ATTACHMENTS_MAX_SEND
local DressUpItemLink = DressUpItemLink
local GetAddOnInfo = GetAddOnInfo or C_AddOns.GetAddOnInfo
local GetAddOnMetadata = GetAddOnMetadata or C_AddOns.GetAddOnMetadata
local GetAuctionItemSubClasses = (C_AuctionHouse and C_AuctionHouse.GetAuctionItemSubClasses) or CompatGetAuctionItemSubClasses
local GetNumAddOns = GetNumAddOns or C_AddOns.GetNumAddOns
local LoadAddOn = LoadAddOn or C_AddOns.LoadAddOn
local NUM_CONTAINER_FRAMES = NUM_CONTAINER_FRAMES
local MailFrame = MailFrame
local MailFrameTab1 = MailFrameTab1
local MailFrameTab2 = MailFrameTab2
local MoneyInputFrame_SetCopper = MoneyInputFrame_SetCopper
local SetItemButtonDesaturated = SetItemButtonDesaturated
local StaticPopup_Visible = StaticPopup_Visible
local UnitName = UnitName
local min = math.min
local print = print
local strlen = strlen
local strsplit = strsplit
local SendMailMailButton = SendMailMailButton
local SendMailMoney = SendMailMoney
local SendMailNameEditBox = SendMailNameEditBox
local SendMailSendMoneyButton = SendMailSendMoneyButton
local SendMailSubjectEditBox = SendMailSubjectEditBox
local StaticPopupDialogs = StaticPopupDialogs
local StaticPopup_Show = StaticPopup_Show
local ipairs = ipairs
local next = next
local pairs = pairs
local select = select
local setmetatable = setmetatable
local tonumber = tonumber
local tostring = tostring
local type = type
local unpack = unpack
local NUM_LE_ITEM_CLASSES = _G.NUM_LE_ITEM_CLASSES or _G.NUM_LE_ITEM_CLASSS or 19
local auctionItemClasses, sendCache, destCache, reverseDestCache, destSendCache, rulesCache, autoSendRules, globalExclude -- tables
local cacheLock, sendDest, numItems, rulesAltered -- variables
local GetContainerItemInfo = GetContainerItemInfo
local GetContainerItemLink = GetContainerItemLink
local GetContainerNumSlots = GetContainerNumSlots
local PickupContainerItem = PickupContainerItem
-- Dragonlands changes.
if not GetContainerNumSlots then
-- Reagent bag is bag #5
NUM_BAG_SLOTS = NUM_BAG_SLOTS + 1
GetContainerNumSlots = C_Container.GetContainerNumSlots
GetContainerItemLink = C_Container.GetContainerItemLink
GetContainerItemInfo = function(bag, slot)
local item = C_Container.GetContainerItemInfo(bag, slot)
if item == nil then return end
return item.iconFileID, item.stackCount, item.isLocked, item.quality, item.isReadable, item.hasLoot,
item.hyperLink, item.isFiltered, item.hasNoValue, item.itemID, item.isBound
end
PickupContainerItem = C_Container.PickupContainerItem
end
--[[----------------------------------------------------------------------------
Table Handling
------------------------------------------------------------------------------]]
local new, del, newHash, newSet, deepDel
do
local list = setmetatable({}, {__mode='k'})
function new(...)
local t = next(list)
if t then
list[t] = nil
for i = 1, select('#', ...) do
t[i] = select(i, ...)
end
return t
else
return { ... }
end
end
function newHash(...)
local t = next(list)
if t then
list[t] = nil
else
t = {}
end
for i = 1, select('#', ...), 2 do
t[select(i, ...)] = select(i+1, ...)
end
return t
end
function newSet(...)
local t = next(list)
if t then
list[t] = nil
else
t = {}
end
for i = 1, select('#', ...) do
t[select(i, ...)] = true
end
return t
end
function del(t)
for k in pairs(t) do
t[k] = nil
end
list[t] = true
return nil
end
function deepDel(t)
if type(t) ~= "table" then
return nil
end
for k,v in pairs(t) do
t[k] = deepDel(v)
end
return del(t)
end
end
--[[----------------------------------------------------------------------------
Local Processing
------------------------------------------------------------------------------]]
-- utility method to get item id.
local function linkToId(itemLink)
return type(item) == 'number' and item or tonumber(strmatch(itemLink, "|H[^:]+:(%d+)"))
end
-- Bag iterator, shamelessly stolen from PeriodicTable-2.0 (written by Tekkub)
local iterbag, iterslot
local function iter()
if iterslot > GetContainerNumSlots(iterbag) then iterbag, iterslot = iterbag + 1, 1 end
if iterbag > NUM_BAG_SLOTS then return end
for b = iterbag,NUM_BAG_SLOTS do
for s = iterslot,GetContainerNumSlots(b) do
iterslot = s + 1
local link = GetContainerItemLink(b,s)
if link then return b, s, link end
end
iterbag, iterslot = b + 1, 1
end
end
local function bagIter()
iterbag, iterslot = 0, 1
return iter
end
-- Unpacks the UI-friendly autoSendRules table into rulesCache, a simple
-- item/rules lookup table, in the following manner:
-- ItemIDs - inserted as table keys
-- PT31Sets - set is unpacked and each item is inserted as a table key
-- ItemTypes - ItemType is inserted as a table key pointing to a table of
-- desired subtype keys
-- Exclusions are processed after all include rules are handled,
-- and will nil out the appropriate keys in the table.
rulesCache = {}
local function rulesCacheBuild()
if next(rulesCache) and not rulesAltered then return end
for k in pairs(rulesCache) do
rulesCache[k] = deepDel(rulesCache[k])
end
for dest, rules in pairs(autoSendRules) do
rulesCache[dest] = new()
-- include rules
for _, itemID in ipairs(rules.include.items) do rulesCache[dest][tonumber(itemID)] = true end
for _, set in ipairs(rules.include.pt31Sets) do
for itemID in pt:IterateSet(set) do rulesCache[dest][tonumber(itemID)] = true end
end
for _, itemTypeTable in ipairs(rules.include.itemTypes) do
local itype, isubtype = itemTypeTable.type, itemTypeTable.subtype
if isubtype then
rulesCache[dest][itype] = rulesCache[dest][itype] or new()
rulesCache[dest][itype][isubtype] = true
else -- need to add all subtypes individually
if rulesCache[dest][itype] then rulesCache[dest][itype] = del(rulesCache[dest][itype]) end
rulesCache[dest][itype] = newSet(unpack(auctionItemClasses[itype]))
end
end
-- exclude rules
for _, itemID in ipairs(rules.exclude.items) do rulesCache[dest][tonumber(itemID)] = nil end
for _, itemID in ipairs(globalExclude.items) do rulesCache[dest][tonumber(itemID)] = nil end
for _, set in ipairs(rules.exclude.pt31Sets) do
for itemID in pt:IterateSet(set) do rulesCache[dest][itemID] = nil end
end
for _, set in ipairs(globalExclude.pt31Sets) do
for itemID in pt:IterateSet(set) do rulesCache[dest][itemID] = nil end
end
for _, itemTypeTable in ipairs(rules.exclude.itemTypes) do
local rtype, rsubtype = itemTypeTable.type, itemTypeTable.subtype
if rsubtype and rulesCache[dest][rtype] then
rulesCache[dest][rtype][rsubtype] = nil
else
rulesCache[dest][rtype] = nil
end
end
for _, itemTypeTable in ipairs(globalExclude.itemTypes) do
local rtype, rsubtype = itemTypeTable.type, itemTypeTable.subtype
if rsubtype ~= rtype and rulesCache[dest][rtype] then
rulesCache[dest][rtype][rsubtype] = nil
else
rulesCache[dest][rtype] = nil
end
end
end
rulesAltered = false
end
-- Returns the autosend destination of an itemID, according to the
-- rulesCache, or nil if no rules for this item are found.
local function rulesCacheDest(item)
if not item then return end
local rdest
local itemID = linkToId(item)
if not itemID then return end
for _, xID in ipairs(globalExclude.items) do if itemID == xID then return end end
for _, xset in ipairs(globalExclude.pt31Sets) do
if pt:ItemInSet(itemID, xset) == true then return end
end
local quality = select(3, GetItemInfo(itemID))
local equippable = IsEquippableItem(itemID)
if quality and ((equippable and quality < self.db.char.minItemLevel)
or (not equippable and quality < self.db.char.minItemLevelMisc)) then
return nil
end
local itype, isubtype = select(6, GetItemInfo(itemID)) -- old string based lookup
local iclass, isubclass = select(12, GetItemInfo(itemID)) -- new class id based lookup
if C_PetJournal and not iclass then
local name, icon, petType, creatureID, sourceText, description, isWild, canBattle, isTradeable, isUnique, obtainable, displayID, speciesID = C_PetJournal.GetPetInfoByItemID(itemID)
if name then
iclass, isubclass = speciesID, creatureID
itype, isubtype = petType, name
print(iclass, isubclass, itype, isubtype)
end
end
if not itype or not iclass then
return nil
end
for dest, rules in pairs(rulesCache) do
local canddest
if string.lower(dest) ~= string.lower(UnitName('player')) and (rules[itemID] or
(itype and rules[itype] and rules[itype][isubtype]) or
(iclass and rules[iclass] and rules[iclass][isubclass])) then
canddest = dest
end
if canddest then
local xrules = autoSendRules[canddest].exclude
for _, xID in ipairs(xrules.items) do if itemID == xID then canddest = nil end end
for _, xset in ipairs(xrules.pt31Sets) do
if pt:ItemInSet(itemID, xset) == true then canddest = nil end
end
end
rdest = canddest or rdest
end
return rdest
end
-- Returns the frame associated with bag, slot
local function getBagSlotFrame(bag,slot)
if bag >= 0 and bag < NUM_CONTAINER_FRAMES and slot > 0 then
local bagslots = GetContainerNumSlots(bag)
if bagslots >= slot then
return _G["ContainerFrame" .. (bag + 1) .. "Item" .. (bagslots - slot + 1)]
end
end
end
-- Shades or unshades the given bag slot
local function shadeBagSlot(bag,slot,shade)
local frame = getBagSlotFrame(bag, slot)
if frame ~= nil then
SetItemButtonDesaturated(frame, shade)
end
end
-- Updates the "Postage" field in the Send Mail frame to reflect the total
-- price of all the items that BulkMail will send.
local function updateSendCost()
if sendCache and next(sendCache) then
local basePrice = 0
for slot = 1,8 do
if GetSendMailItem(slot) ~= nil then
basePrice = GetSendMailPrice()
break
end
end
MoneyFrame_Update('SendMailCostMoneyFrame', basePrice + 30 * numItems)
else
MoneyFrame_Update('SendMailCostMoneyFrame', GetSendMailPrice())
end
end
local function findPattern (str, pattern)
return string.find(str, pattern)
end
local function findExact(str, pattern)
if (str == pattern) then
return string.find(str, pattern)
end
end
local function dumpTable(tbl, indent)
if not indent then indent = 0 end
if type(tbl) ~= 'table' then return tostring(tbl) end
local formatStr = string.rep(" ", indent) -- Create an indentation string
local endFormatStr = string.rep(" ", indent - 1)
local result = "{\n"
for k, v in pairs(tbl) do
local formattedKey = type(k) == "number" and k or '"' .. k .. '"'
result = result .. formatStr .. "[" .. formattedKey .. "] = "
if type(v) == "table" then
result = result .. dumpTable(v, indent + 1) .. ",\n"
else
result = result .. tostring(v) .. ",\n"
end
end
return result .. endFormatStr .. "}"
end
local function simpleFind(tt, exact, text)
if not tt or not tt.lines then
return
end
local searchFunction = exact and findExact or findPattern
for _,data in ipairs(tt.lines) do
-- if exact then
-- print(data.leftText, "[", text, "]", searchFunction(data.leftText, text))
-- end
if data.args then
for _,field in ipairs(data.args) do
if field.field == "leftText" then
-- print("Matching ", text, "with tooltip line", field.stringVal)
if searchFunction(field.stringVal, text) then
return true
end
break
end
end
elseif data.leftText then
if searchFunction(data.leftText, text) then
return true
end
end
end
end
local function multiFind(tt, exact, t1, t2, t3, t4, t5, t6)
local found = simpleFind(tt, exact, t1)
if not found and t2 then
return multiFind(tt, exact, t2, t3, t4, t5, t6)
end
return found
end
local function isItemMailable(bag, slot)
if _G.C_TooltipInfo == nil then
local item = ItemLocation:CreateFromBagAndSlot(bag, slot)
if item then
return not C_Item.IsBound(item)
end
gratuity:SetBagItem(bag, slot)
return not gratuity:MultiFind(2, 7, false, false, ITEM_SOULBOUND, ITEM_BIND_QUEST, ITEM_CONJURED, ITEM_BIND_ON_PICKUP)
or gratuity:Find(ITEM_BIND_ON_EQUIP, 2, 7, false, false, true)
end
local tt = C_TooltipInfo.GetBagItem(bag, slot)
return not (multiFind(tt, false, ITEM_BIND_QUEST, ITEM_CONJURED, ITEM_BIND_ON_PICKUP)
or simpleFind(tt, true, ITEM_SOULBOUND))
or simpleFind(tt, true, ITEM_BIND_ON_EQUIP)
end
-- Add a container slot to BulkMail's send queue.
sendCache = {}
local function sendCacheAdd(bag, slot, squelch)
-- convert to (bag, slot, squelch) if called as (frame, squelch)
if type(slot) ~= 'number' then
bag, slot, squelch = bag:GetParent():GetID(), bag:GetID(), slot
end
local didAdd = false
if GetContainerItemInfo(bag, slot) and not (sendCache[bag] and sendCache[bag][slot]) then
if isItemMailable(bag, slot) then
sendCache[bag] = sendCache[bag] or new()
sendCache[bag][slot] = true;
numItems = numItems + 1
shadeBagSlot(bag,slot,true)
if not squelch then mod:RefreshSendQueueGUI() end
SendMailFrame_CanSend()
didAdd = true
elseif not squelch then
mod:Print(fmt(L["Item cannot be mailed: %s."], GetContainerItemLink(bag, slot)))
end
end
if not squelch and didAdd then
updateSendCost()
end
return didAdd
end
-- Remove a container slot from BulkMail's send queue.
local function sendCacheRemove(bag, slot, isBulk)
bag, slot = slot and bag or bag:GetParent():GetID(), slot or bag:GetID() -- convert to (bag, slot) if called as (frame)
if sendCache and sendCache[bag] then
if sendCache[bag][slot] then
sendCache[bag][slot] = nil
numItems = numItems - 1
shadeBagSlot(bag,slot,false)
end
if not next(sendCache[bag]) then sendCache[bag] = del(sendCache[bag]) end
end
if not isBulk then
mod:RefreshSendQueueGUI()
updateSendCost()
SendMailFrame_CanSend()
end
end
local function bulkToggleBagItem(bag, slot, itemLink)
itemLink = itemLink or GetContainerItemLink(bag, slot)
if not itemLink then return end
local itemId = linkToId(itemLink)
local shouldRemove = sendCache and sendCache[bag] and sendCache[bag][slot]
mod:Print(fmt(L["Attempting to %s all %s."], shouldRemove and L["remove"] or L["add"], itemLink))
for addlBag, addlSlot, item in bagIter() do
if linkToId(item) == itemId then
if shouldRemove then
sendCacheRemove(addlBag, addlSlot, true)
elseif not sendCacheAdd(addlBag, addlSlot, true) then
mod:Print(fmt(L["Item cannot be mailed: %s."], GetContainerItemLink(addlBag, addlSlot)))
end
end
end
mod:RefreshSendQueueGUI()
updateSendCost()
SendMailFrame_CanSend()
end
-- Toggle a container slot's presence in BulkMail's send queue.
local function sendCacheToggle(bag, slot)
bag, slot = slot and bag or bag:GetParent():GetID(), slot or bag:GetID() -- convert to (bag, slot) if called as (frame)
local result
if sendCache and sendCache[bag] and sendCache[bag][slot] then
result = sendCacheRemove(bag, slot)
else
result = sendCacheAdd(bag, slot)
end
return result
end
-- Removes all entries in BulkMail's send queue.
-- If passed with the argument 'true', will only remove the entries created by
-- BulkMail (used for refreshing the list as the destination changes without
-- clearing the items the user has added manually this session).
local function sendCacheCleanup(autoOnly)
if sendCache then
for bag, slots in pairs(sendCache) do
for slot in pairs(slots) do
local item = GetContainerItemLink(bag, slot)
if autoOnly ~= true or rulesCacheDest(item) then
sendCacheRemove(bag, slot, true)
end
end
end
end
cacheLock = false
mod:RefreshSendQueueGUI()
updateSendCost()
SendMailFrame_CanSend()
end
-- Populate BulkMail's send queue with container slots holding items following
-- the autosend rules for the current destination (or any destinations
-- if the destination field is blank).
local function sendCacheBuild(dest)
if not cacheLock then
sendCacheCleanup(true)
local destLower = dest and dest:lower()
-- Check destCache case-insensitively
local destHasRules = false
if dest ~= '' then
for d in pairs(destCache) do
if d:lower() == destLower then
destHasRules = true
break
end
end
end
if BulkMail.db.char.isSink or dest ~= '' and not destHasRules then
-- no need to check for an item in the autosend list if this character is a sink or if the destination string doesn't have any rules set
mod:RefreshSendQueueGUI()
return
end
for bag, slot, item in bagIter() do
local target = rulesCacheDest(item)
if target then
if dest == '' or target:lower() == destLower then
sendCacheAdd(bag, slot, true)
end
end
end
end
mod:RefreshSendQueueGUI()
end
-- Organize the send queue by recipient in order to reduce fragmentation of multi-item mails
destSendCache = {}
local function organizeSendCache()
destSendCache = deepDel(destSendCache)
local dest
for bag, slots in pairs(sendCache) do
for slot in pairs(slots) do
dest = sendDest ~= '' and sendDest or rulesCacheDest(GetContainerItemLink(bag, slot)) or self.db.char.defaultDestination
if dest then
destSendCache = destSendCache or new()
destSendCache[dest] = destSendCache[dest] or new()
tinsert(destSendCache[dest], new(bag, slot))
else
self:Print(L["No default destination set."])
self:Print(L["Enter a name in the To: field or set a default destination with |cff00ffaa/bulkmail defaultdest|r."])
end
end
end
end
--[[----------------------------------------------------------------------------
A little color never hurts
------------------------------------------------------------------------------]]
local function color(text, color)
return fmt("|cff%s%s|r", color, text)
end
--[[----------------------------------------------------------------------------
Setup
------------------------------------------------------------------------------]]
local function _convertAce2ToAce3Realm(realm)
-- This could be more elegant but I hate lua patterns so ... whatever :P
startPos = realm:find(" - Horde", 1, true)
if startPos then
return "Horde - ".. realm:sub(1, startPos-1)
end
startPos = realm:find(" - Alliance", 1, true)
return "Alliance - ".. realm:sub(1, startPos-1)
end
local function _convertBulkMail2DB()
if not BulkMail2DB then
return
end
mod:Print("Converting BulkMail 2 configuration...")
local startPos
BulkMail3DB = new()
if BulkMail2DB.realms then
BulkMail3DB.factionrealm = new()
for realm, data in pairs(BulkMail2DB.realms) do
realm = _convertAce2ToAce3Realm(realm)
BulkMail3DB.factionrealm[realm] = data
end
end
if BulkMail2DB.chars then
BulkMail3DB.char = new()
for char, data in pairs(BulkMail2DB.chars) do
BulkMail3DB.char[char] = data
end
end
end
function mod:OnInitialize()
-- Convert BulkMail2 config to new format
if not BulkMail3DB then
_convertBulkMail2DB()
end
_convertAce2ToAce3Realm = nil
_convertBulkMail2DB = nil
self.db = DB:New("BulkMail3DB", {
factionrealm = {
autoSendRules = {
['*'] = {
include = {
['*'] = {},
},
exclude = {
['*'] = {},
},
},
},
},
char = {
isSink = false,
attachMulti = true,
globalExclude = {
['*'] = {}
},
},
profile = {
sizeMode = "free",
freePosition = false,
savedPos = nil,
},
}, "Default")
self.db.char.minItemLevel= self.db.char.minItemLevel or 1
self.db.char.minItemLevelMisc = self.db.char.minItemLevelMisc or 1
autoSendRules = self.db.factionrealm.autoSendRules -- local variable for speed/convenience
destCache = new() -- destinations for which we have rules (or are going to add rules)
reverseDestCache = new() -- integer-indexed table of destinations
for dest in pairs(autoSendRules) do
destCache[dest] = true
tinsert(reverseDestCache, dest)
end
globalExclude = self.db.char.globalExclude -- local variable for speed/convenience
local obsoletes
if GetItemClassInfo(Enum.ItemClass.Battlepet) then
-- retail
obsoletes = newHash(
Enum.ItemClass.Reagent, true,
Enum.ItemClass.Projectile, true,
Enum.ItemClass.Quiver, true,
Enum.ItemClass.Questitem, true, -- can't send quest items
Enum.ItemClass.Key, true,
10, true, -- Money
14, true -- Permanent
)
else
-- classic
obsoletes = newHash(
(LE_ITEM_CLASS_GEM or Enum.ItemClass.Gem), true,
(LE_ITEM_CLASS_GLYPH or Enum.ItemClass.Glyph), true,
(LE_ITEM_CLASS_ITEM_ENHANCEMENT or Enum.ItemClass.ItemEnhancement), true,
(LE_ITEM_CLASS_WOW_TOKEN or Enum.ItemClass.WoWToken), true,
(LE_ITEM_CLASS_BATTLEPET or Enum.ItemClass.Battlepet), true,
(LE_ITEM_CLASS_QUESTITEM or Enum.ItemClass.Questitem), true, -- can't send quest items
10, true, -- Money
14, true -- Permanent
)
end
auctionItemClasses = {} -- local itemType value association table
for i = 0, NUM_LE_ITEM_CLASSES-1 do
if not obsoletes[i] then
auctionItemClasses[i] = GetAuctionItemSubClasses(i)
end
end
numItems = 0
rulesAltered = true
local itemQualities = {}
for k in pairs(Enum.ItemQuality) do
local v = Enum.ItemQuality[k]
if v < Enum.ItemQuality.Rare then
itemQualities[v] = k
end
end
self.opts = {
type = 'group',
handler = mod,
args = {
defaultdest = {
name = L["Default destination"], type = 'input',
desc = L["Set the default recipient of your AutoSend rules"],
get = function() return self.db.char.defaultDestination end,
set = function(args, dest) self.db.char.defaultDestination = dest end,
},
autosend = {
name = L["Auto Send Commands"], type = 'group',
desc = L["AutoSend Options"],
args = {
edit = {
name = L["Edit Destinations"], type = 'execute',
desc = L["Edit AutoSend definitions."],
func = function() mod:OpenEditTooltipGUI() end,
order = 30,
},
clear = {
name = L["Clear Realm rules"], type = 'execute',
desc = L["Clear all rules for this realm."],
func = function()
self.db.factionrealm = new()
for i in pairs(autoSendRules) do
autoSendRules[i] = nil
end
mod:RefreshEditTooltipGUI() end,
confirm = true,
order = 40
},
},
},
sink = {
name = L["Sink"], type = 'toggle',
desc = L["Disable AutoSend queue auto-filling for this character."],
get = function() return self.db.char.isSink end,
set = function(args,v) self.db.char.isSink = v end,
order = 4000,
},
attachmulti = {
name = L["Attach multiple items"], type = 'toggle',
desc = L["Attach as many items as possible per mail."],
get = function() return self.db.char.attachMulti end,
set = function(args, v) self.db.char.attachMulti = v end,
order = 4100,
},
attachItemLevelMin = {
name = L["Min Matched Equipped Quality"], type = 'select',
desc = L["The minimum quality level matched for automatic destinations for equippable items / gear."],
values = itemQualities,
get = function() return self.db.char.minItemLevel end,
set = function(args, v) self.db.char.minItemLevel = v end,
},
attachItemLevelMinMisc = {
name = L["Min Matched Quality"], type = 'select',
desc = L["The minimum quality level matched for automatic destinations."],
values = itemQualities,
get = function() return self.db.char.minItemLevelMisc end,
set = function(args, v) self.db.char.minItemLevelMisc = v end,
},
sizeMode = {
name = L["Window Size"],
type = 'select',
desc = L["How the window height is determined. Match sets height to mail frame. Max limits height to mail frame. Free sizes to content."],
values = {
free = L["Free"],
match = L["Match Mail Frame"],
max = L["Max Mail Frame"],
},
get = function() return self.db.profile.sizeMode end,
set = function(_, v) self.db.profile.sizeMode = v mod:RefreshSendQueueGUI() end,
disabled = function() return self.db.profile.freePosition end,
order = 2500,
},
freePosition = {
name = L["Free Position"],
type = 'toggle',
desc = L["Disable automatic anchoring to the mail frame. The window will remember its position when dragged."],
get = function() return self.db.profile.freePosition end,
set = function(_, v)
self.db.profile.freePosition = v
if not v then
self.db.profile.savedPos = nil
end
mod:RefreshSendQueueGUI()
end,
order = 3000,
},
},
}
-- set up LDB
if LDB then
self.ldb =
LDB:NewDataObject("BulkMail",
{
type = "data source",
label = L["Bulk Mail"]..VERSION,
icon = [[Interface\Addons\BulkMail2\icon]],
tooltiptext = color(L["Bulk Mail"]..VERSION.."\n\n", "ffff00")..color(L["Hint: Click to show the AutoSend Rules editor."].."\n"..
L["Middle click to open the config panel."].."\n"..
L["Right click to open the config menu."], "ffd200"),
OnClick = function(clickedframe, button)
if button == "LeftButton" then
mod:OpenEditTooltipGUI(clickedframe)
elseif button == "MiddleButton" then
mod:ToggleConfigDialog()
elseif button == "RightButton" then
mod:OpenConfigMenu(clickedframe)
end
end,
})
end
self._mainConfig = self:OptReg(L["Bulk Mail"]..VERSION, self.opts, { "bm", "bulkmail" })
-- LoD PT31 Sets; yanked from Baggins
local PT31Modules
for i = 1, GetNumAddOns() do
local metadata = GetAddOnMetadata(i, "X-PeriodicTable-3.1-Module")
if metadata then
local name, _, _, enabled = GetAddOnInfo(i)
if enabled then
LoadAddOn(name)
end
end
end
end
function mod:OnEnable()
self:RegisterEvent('MAIL_SHOW')
self:RegisterEvent('MAIL_CLOSED')
self:RegisterEvent('PLAYER_ENTERING_WORLD')
if not _G.GetContainerItemInfo then
self:RegisterEvent('PLAYER_INTERACTION_MANAGER_FRAME_HIDE')
end
-- Handle being LoD loaded while at the mailbox
if MailFrame:IsVisible() then
self:MAIL_SHOW()
end
end
function mod:OnDisable()
self:UnregisterAllEvents()
self:UnhookAll()
end
--[[----------------------------------------------------------------------------
Events
------------------------------------------------------------------------------]]
local mailIsVisible
function mod:PLAYER_INTERACTION_MANAGER_FRAME_HIDE(_, type)
if type == Enum.PlayerInteractionType.MailInfo then
mod:MAIL_CLOSED()
end
end
function mod:MAIL_SHOW()
-- Allow TSM frame detection to re-scan (TSM may create its frame lazily)
MagicUtil:ResetTSMFrameCache()
if not mailIsVisible then
mailIsVisible = true
if rulesAltered then rulesCacheBuild() end
if ContainerFrameItemButton_OnModifiedClick then
self:SecureHook('ContainerFrameItemButton_OnModifiedClick')
self:SecureHook('ContainerFrame_Update')
else
self:SecureHook('HandleModifiedItemClick')
for _, frame in ContainerFrameUtil_EnumerateContainerFrames() do
self:SecureHook(frame, "Update", 'ContainerFrame_Update')
end
end
self:SecureHook('SendMailFrame_CanSend')
self:SecureHook('MoneyInputFrame_OnTextChanged', SendMailFrame_CanSend)
self:SecureHook('SetItemRef')
self:RawHookScript(SendMailMailButton, 'OnClick', 'SendMailMailButton_OnClick')
self:RawHookScript(MailFrameTab1, 'OnClick', 'MailFrameTab1_OnClick')
self:RawHookScript(MailFrameTab2, 'OnClick', 'MailFrameTab2_OnClick')
self:RawHookScript(SendMailNameEditBox, 'OnTextChanged', 'SendMailNameEditBox_OnTextChanged')
self:RegisterEvent('MAIL_SEND_SUCCESS')
self:RegisterEvent('SECURE_TRANSFER_CANCEL')
self:RegisterEvent('MAIL_FAILED')
SendMailMailButton:Enable()
--[[
-- This should have its own config option somewhere.
-- Ideally, this operation should be done without the
-- mail window opening to the user. The user should
-- simply hold shift, right click on the mailbox,
-- and BulkMail mails all items without ever opening
-- the mail frame to the user. The only thing the user
-- would see is 'Mail Sent' along with the sound.
-- Note: There should likely be a config option to print
-- to the chat frame of what items were sent and to where.
]]--
if IsShiftKeyDown() then
mod:MailFrameTab2_OnClick(MailFrameTab2)
mod:SendMailMailButton_OnClick(MailFrameTab2)
end
end
-- Watch for mail frame changes (e.g. TSM toggling between its UI and the default)
mod._lastMailFrame = nil
if not mod._mailFrameWatcher then
mod._mailFrameWatcher = self:ScheduleRepeatingTimer("CheckMailFrameChanged", 0.2)
end
end
function mod:CheckMailFrameChanged()
local mailFrame, isTSM = MagicUtil:GetMailFrame()
if mailFrame ~= mod._lastMailFrame then
mod._lastMailFrame = mailFrame
if isTSM then
-- TSM active: always show the send queue alongside inbox
rulesCacheBuild()
sendCacheBuild(SendMailNameEditBox:GetText())
self:ShowSendQueueGUI()
else
-- Switching to normal UI: show send queue only if on Send tab
if SendMailFrame and SendMailFrame:IsShown() then
self:ShowSendQueueGUI()
elseif mod.sendQueueTooltip then
self:HideSendQueueGUI()
end
end
end
end
function mod:MAIL_CLOSED()
if mailIsVisible then
mailIsVisible = nil
if mod._mailFrameWatcher then
self:CancelTimer(mod._mailFrameWatcher)
mod._mailFrameWatcher = nil
end
mod._lastMailFrame = nil
self:UnhookAll()
sendCacheCleanup()
self:HideSendQueueGUI()
self:StopBulkSend()
end
end
BulkMail.PLAYER_ENTERING_WORLD = BulkMail.MAIL_CLOSED -- MAIL_CLOSED doesn't get called if, for example, the player accepts a port with the mail window open
function mod:MAIL_SEND_SUCCESS()
if self._sendingBulk then
self:RefreshSendQueueGUI()
-- Small delay to let WoW process the sent mail before loading the next one
self:ScheduleTimer("Send", 0.1, self._sendCOD)
end
end
function mod:SECURE_TRANSFER_CANCEL()
if self._sendingBulk then
self:StopBulkSend()
SendMailNameEditBox:SetText('')
sendDest = ''
sendCacheCleanup()
self:Print(L["Send cancelled."])
end
end
function mod:MAIL_FAILED()