Repository navigation
Expand file tree
/
Copy pathLevelTrail.lua
More file actions
1905 lines (1797 loc) · 75.7 KB
/
Copy pathLevelTrail.lua
File metadata and controls
1905 lines (1797 loc) · 75.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
-- LevelTrail
-- Copyright (c) 2026 Bencepo. All rights reserved. See LICENSE.
--
-- Records a character's leveling into SavedVariables: a snapshot of the character
-- (gold, bags, gear, professions, quests, talents, reputation) plus a history of
-- level splits, XP sources, play sessions, deaths, gold, repairs and time/XP per zone.
-- A small tracker window (/trail hud) shows the pace: XP per hour and the time to the
-- next level and to the level cap.
-- /trail shows everything as JSON to copy into a companion app.
-- The game writes the file on /reload and on logout:
-- WTF\Account\<ACCOUNT>\SavedVariables\LevelTrail.lua
-- Nothing here sends input to the game; it only reads.
LevelTrailDB = LevelTrailDB or {}
local ADDON, ns = ...
ns = ns or {}
local VERSION = 9 -- data version
local BUG_URL = "https://github.com/Bencepo/LevelTrail/issues/new/choose"
local GetMetadata = C_AddOns.GetAddOnMetadata
-- Item and money functions live in C_Item / C_CurrencyInfo on current clients. The old
-- globals are only fallbacks for clients without them and are read in this one place.
---@diagnostic disable: deprecated
local GetItemInfo = (C_Item and C_Item.GetItemInfo) or GetItemInfo
local GetItemInfoInstant = (C_Item and C_Item.GetItemInfoInstant) or GetItemInfoInstant
local GetDetailedItemLevelInfo = (C_Item and C_Item.GetDetailedItemLevelInfo) or GetDetailedItemLevelInfo
local GetCoinTextureString = (C_CurrencyInfo and C_CurrencyInfo.GetCoinTextureString) or GetCoinTextureString
---@diagnostic enable: deprecated
local ADDON_VERSION = GetMetadata and GetMetadata(ADDON, "Version") or ""
if ADDON_VERSION == "" or ADDON_VERSION:find("^@") then ADDON_VERSION = "dev" end
local TITLE = "LevelTrail " .. ADDON_VERSION
local function try(fn, ...)
if type(fn) ~= "function" then return nil end
local ok, a, b, c, d, e, f, g, h = pcall(fn, ...)
if ok then return a, b, c, d, e, f, g, h end
return nil
end
---------------------------------------------------------------- XP table and level cap
-- XP needed for each level up to 60 (Classic table). If the game reports a different
-- value for the current level, the other levels are scaled by the same factor.
local XP_TABLE = { 400, 900, 1400, 2100, 2800, 3600, 4500, 5400, 6500, 7600, 8800, 10100, 11400, 12900, 14400,
16000, 17700, 19400, 21300, 23200, 25200, 27300, 29400, 31700, 34000, 36400, 38900, 41400, 44300, 47400,
50800, 54500, 58600, 62800, 67100, 71600, 76100, 80800, 85700, 90700, 95800, 101000, 106300, 111800, 117500,
123200, 129100, 135100, 141200, 147500, 153900, 160400, 167100, 173900, 180800, 187900, 195000, 202300, 209800 }
local function maxLevel()
local m = try(GetMaxPlayerLevel)
if type(m) == "number" and m > 0 then return m end
return 60
end
local function xpForLevel(level, scale)
local v = XP_TABLE[level]
if not v then return nil end
return math.floor(v * (scale or 1) + 0.5)
end
-- XP values are 0 for a moment at login and logout; at the level cap UnitXPMax may stay 0.
local function xpReady()
local level = UnitLevel("player") or 0
if level == 0 then return false end
return (UnitXPMax("player") or 0) > 0 or level >= maxLevel()
end
-- Last character bag: 4 on Classic clients, 5 where a reagent bag exists. Bank bags follow it.
local function lastBagID()
return NUM_TOTAL_EQUIPPED_BAG_SLOTS or NUM_BAG_SLOTS or 4
end
local function charKey()
local name = UnitName("player") or "?"
local realm = GetRealmName and GetRealmName() or "?"
return name .. "-" .. realm, name, realm
end
local function store()
local key = charKey()
LevelTrailDB[key] = LevelTrailDB[key] or {}
return LevelTrailDB[key]
end
---------------------------------------------------------------- online clock and level splits
-- Online time is counted by the addon itself (once a minute while logged in), so it
-- starts at the install. A level the addon did not see from its start is "partial".
local clockLast, clockZone
local function currentZone()
local z = GetRealZoneText and GetRealZoneText() or ""
if z == "" then return nil end
return z
end
-- Per-zone totals: online seconds, XP and deaths.
local function zoneRec(s, zone)
if not zone then return nil end
s.zones = s.zones or {}
local z = s.zones[zone]
if not z then
z = { time = 0, xp = 0, deaths = 0, first = date("%Y-%m-%d") }
s.zones[zone] = z
end
return z
end
-- Per zone and level: online seconds (t) and XP (x), for the best zone per level range.
local function zoneLevelRec(s, zone, level)
level = tonumber(level)
if not zone or not level or level < 1 then return nil end
s.zoneLevels = s.zoneLevels or {}
local z = s.zoneLevels[zone] or {}
s.zoneLevels[zone] = z
local r = z[level]
if not r then r = { t = 0, x = 0 }; z[level] = r end
return r
end
local sessionTouch -- defined with the sessions below
local function clockTick()
local s = store()
local now = time()
if clockLast then
local d = now - clockLast
if d > 0 and d <= 600 then
s.online = (s.online or 0) + d
local z = zoneRec(s, clockZone)
if z then z.time = z.time + d; z.last = date("%Y-%m-%d") end
local zl = zoneLevelRec(s, clockZone, UnitLevel("player"))
if zl then zl.t = zl.t + d end
-- a dungeon visit only runs on while the player is inside
if s.dungeonRun and try(IsInInstance) then s.dungeonRun.last = now end
-- being online keeps the play session going, XP or not
if sessionTouch then pcall(sessionTouch) end
end
end
clockLast = now
clockZone = currentZone()
end
local function levelInit()
local s = store()
local L = UnitLevel("player") or 0
if L == 0 then return end
s.firstLevel = s.firstLevel or (s.splits and s.splits[1] and s.splits[1].level and s.splits[1].level - 1) or L
if not s.levelSince or s.levelSince.level ~= L then
s.levelSince = { level = L, online = s.online or 0, ts = time(), date = date("%Y-%m-%d %H:%M"), partial = true }
end
end
local function onLevelUp(newLevel)
clockTick()
local s = store()
newLevel = tonumber(newLevel) or UnitLevel("player")
local since = s.levelSince
s.splits = s.splits or {}
local rec = { level = newLevel, date = date("%Y-%m-%d %H:%M"), ts = time(), online = s.online or 0 }
if since and since.level == newLevel - 1 then
rec.dur = (s.online or 0) - (since.online or 0)
rec.partial = since.partial or nil
end
s.splits[#s.splits + 1] = rec
s.levelSince = { level = newLevel, online = s.online or 0, ts = time(), date = rec.date }
end
---------------------------------------------------------------- XP sources
-- Quest XP comes with QUEST_TURNED_IN, kill and exploration XP from the game's own
-- (localized) chat lines. Everything else (e.g. profession or turn-in items) shows as
-- the difference to the total.
local function toPattern(fmt)
if type(fmt) ~= "string" or fmt == "" then return nil end
local p = fmt:gsub("%%%%", "\1") -- a literal percent sign
p = p:gsub("%%%d+%$", "%%")
p = p:gsub("([%(%)%.%+%-%*%?%[%]%^%$])", "%%%1")
p = p:gsub("%%s", "(.-)")
p = p:gsub("%%d", "(%%d+)")
p = p:gsub("\1", "%%%%")
return "^" .. p
end
local KILL_PATTERN = toPattern(COMBATLOG_XPGAIN_FIRSTPERSON)
local EXPLORE_PATTERN = toPattern(ERR_ZONE_EXPLORED_XP)
local function numberIn(msg, pattern)
if not (msg and pattern) then return nil end
local captures = { msg:match(pattern) }
for _, c in ipairs(captures) do
local n = tonumber(c)
if n then return n end
end
return nil
end
local function addXP(level, field, amount)
amount = tonumber(amount)
if not amount or amount <= 0 then return end
local s = store()
local x = s.xpSources or { quest = 0, kill = 0, explore = 0, total = 0, byLevel = {} }
s.xpSources = x
x.byLevel = x.byLevel or {}
x[field] = (x[field] or 0) + amount
local key = tostring(level or UnitLevel("player") or 0)
local b = x.byLevel[key] or { quest = 0, kill = 0, explore = 0, total = 0 }
x.byLevel[key] = b
b[field] = (b[field] or 0) + amount
if field == "total" then
local zone = currentZone()
local z = zoneRec(s, zone)
if z then z.xp = z.xp + amount end
local zl = zoneLevelRec(s, zone, level or UnitLevel("player"))
if zl then zl.x = zl.x + amount end
end
end
---------------------------------------------------------------- counters (session recap and dungeon runs)
-- Kills (with XP), quests, deaths and loot value count for the running play session
-- and, inside an instance, for the running dungeon visit.
local function bump(field, n)
n = tonumber(n) or 1
local s = store()
local cur = sessionTouch and sessionTouch()
if cur then cur[field] = (cur[field] or 0) + n end
if s.dungeonRun then s.dungeonRun[field] = (s.dungeonRun[field] or 0) + n end
end
-- Vendor value of looted items, from the game's own loot lines.
-- For an item the client has not cached yet it returns 0 plus the item ID and count,
-- so the value can be added once the item data arrives.
local LOOT_MULTI = toPattern(LOOT_ITEM_SELF_MULTIPLE)
local LOOT_SINGLE = toPattern(LOOT_ITEM_SELF)
local function lootValue(msg)
if type(msg) ~= "string" then return 0 end
local link, count
if LOOT_MULTI then link, count = msg:match(LOOT_MULTI) end
if not link and LOOT_SINGLE then link = msg:match(LOOT_SINGLE) end
if not link then return 0 end
count = tonumber(count) or 1
if not GetItemInfo then return 0 end
-- try() returns at most 8 values; the sell price is the 11th
local r = { pcall(GetItemInfo, link) }
if not r[1] then return 0 end
if r[2] == nil then return 0, tonumber(link:match("item:(%d+)")), count end
return (tonumber(r[12]) or 0) * count
end
-- Loot of uncached items: item ID -> count, valued on GET_ITEM_INFO_RECEIVED.
local lootPending = {}
local function lootQueue(id, count)
if not id then return end
lootPending[id] = (lootPending[id] or 0) + (count or 1)
if C_Item and C_Item.RequestLoadItemDataByID then try(C_Item.RequestLoadItemDataByID, id) end
end
local function lootReceived(id, ok)
local count = id and lootPending[id]
if not count then return end
lootPending[id] = nil
if ok == false then return end
local r = { pcall(GetItemInfo, id) }
local v = r[1] and (tonumber(r[12]) or 0) * count or 0
if v > 0 then bump("loot", v) end
end
---------------------------------------------------------------- dungeon runs
local function xpTotal(s) return (s.xpSources and s.xpSources.total) or 0 end
local function dungeonFinish(s)
local run = s.dungeonRun
if not run then return end
s.dungeonRun = nil
local stop = run.last or time()
local minutes = math.floor((stop - run.start) / 60)
if minutes < 2 then return end
s.dungeons = s.dungeons or {}
s.dungeons[#s.dungeons + 1] = { name = run.name, type = run.type, date = run.date, level = run.level,
minutes = minutes, xp = xpTotal(s) - (run.xp0 or 0), copper = (GetMoney() or 0) - (run.copper0 or 0),
kills = run.kills or 0, deaths = run.deaths or 0, loot = run.loot or 0 }
while #s.dungeons > 50 do table.remove(s.dungeons, 1) end
end
local function dungeonCheck()
local s = store()
local inside, kind = try(IsInInstance)
local name = inside and (try(GetInstanceInfo)) or nil
local run = s.dungeonRun
if run and (time() - (run.last or run.start)) > 1800 then dungeonFinish(s); run = nil end
if inside and (kind == "party" or kind == "raid") and name then
if run and run.name ~= name then dungeonFinish(s); run = nil end
if not run then
s.dungeonRun = { name = name, type = kind, start = time(), last = time(), date = date("%Y-%m-%d %H:%M"),
level = UnitLevel("player"), xp0 = xpTotal(s), copper0 = GetMoney() or 0 }
else
run.last = time()
run.outDead = nil
end
elseif run then
if UnitIsDeadOrGhost and UnitIsDeadOrGhost("player") then
-- released outside: a corpse run back in keeps the visit going; the clock stops meanwhile
if not run.outDead then run.last = time(); run.outDead = true end
else
-- left the instance alive, or came back to life outside it
if not run.outDead then run.last = time() end
dungeonFinish(s)
end
end
end
---------------------------------------------------------------- travel (flights and corpse runs)
local flightStart, deadStart
local function travelRec(s)
local t = s.travel or { flight = 0, flights = 0, ghost = 0, ghostRuns = 0, byLevel = {} }
t.byLevel = t.byLevel or {}
s.travel = t
return t
end
local function travelAdd(kind, sec)
if not sec or sec <= 0 or sec > 3600 then return end
local s = store()
local t = travelRec(s)
t[kind] = (t[kind] or 0) + sec
if kind == "flight" then t.flights = (t.flights or 0) + 1 else t.ghostRuns = (t.ghostRuns or 0) + 1 end
local key = tostring(UnitLevel("player") or 0)
local b = t.byLevel[key] or { flight = 0, ghost = 0 }
b[kind] = (b[kind] or 0) + sec
t.byLevel[key] = b
end
local function flightCheck()
local onTaxi = UnitOnTaxi and UnitOnTaxi("player")
if onTaxi and not flightStart then
flightStart = time()
elseif not onTaxi and flightStart then
travelAdd("flight", time() - flightStart)
flightStart = nil
end
end
local function ghostCheck()
if deadStart and not (UnitIsDeadOrGhost and UnitIsDeadOrGhost("player")) then
travelAdd("ghost", time() - deadStart)
deadStart = nil
end
end
---------------------------------------------------------------- library books (WoW Forever)
-- Every library book is handed in with a quest of its own (same IDs for both factions),
-- so the count is simply the number of these quests the character has completed.
-- Quest IDs from Questie's Forever data (QuestieDB, foreverQuestFixes.lua).
local BOOK_QUESTS = {
{ 78124, "Nar'thalas Almanac, Vol. 74" },
{ 78127, "The Dalaran Digest, Vol. 23" },
{ 78142, "Bewitchments and Glamours" },
{ 78143, "Secrets of the Dreamers" },
{ 78145, "Arcanic Systems Manual" },
{ 78146, "Goaz Scrolls" },
{ 78147, "Crimes Against Anatomy" },
{ 78148, "Runes of the Sorcerer-Kings" },
{ 78149, "Fury of the Land" },
{ 79091, "Archmage Antonidas: The Unabridged Autobiography" },
{ 79092, "Archmage Theocritus' Research Journal" },
{ 79093, "Rumi of Gnomeregan: The Collected Works" },
{ 79094, "The Lessons of Ta'zo" },
{ 79095, "The Apothecary's Metaphysical Primer" },
{ 79096, "Ataeric: On Arcane Curiosities" },
{ 79097, "Baxtan: On Destructive Magics" },
{ 79535, "Basilisks: Should Petrification be Feared?" },
{ 79947, "Geomancy: The Stone-Cold Truth" },
{ 79948, "Defensive Magics 101" },
{ 79949, "A Web of Lies: Debunking Myths and Legends" },
{ 79950, "Demons and You" },
{ 79951, "Mummies: A Guide to the Unsavory Undead" },
{ 79952, "RwlRwlRwlRwl!" },
{ 79953, "A Ludite's Guide to Caring for Your Demonic Pet" },
{ 81947, "Sanguine Sorcery" },
{ 81949, "Legends of the Tidesages" },
{ 81951, "The Liminal and the Arcane" },
{ 81952, "Everyday Etiquette" },
{ 81953, "Stonewrought Design" },
{ 81954, "Venomous Journeys" },
{ 81955, "A Mind of Metal" },
{ 81956, "Conjurer's Codex" },
{ 84395, "Undead Potatoes" },
{ 84396, "Magma or Lava?" },
{ 84397, "Northern Kalimdor - A Comprehensive Guide" },
{ 84398, "A Study of the Light" },
{ 84399, "Ka-Boom!" },
{ 84400, "The Knight and the Lady" },
{ 84401, "Scourge: Undead Menace or Misunderstood?" },
{ 84402, "Necromancy 101" },
}
local BOOK_REWARDS = { friend = 78150, greater20 = 79536, greater25 = 82208 }
local BOOK_IDS = {}
for _, b in ipairs(BOOK_QUESTS) do BOOK_IDS[b[1]] = b[2] end
local function questDone(id)
if C_QuestLog and C_QuestLog.IsQuestFlaggedCompleted then return try(C_QuestLog.IsQuestFlaggedCompleted, id) and true or false end
if IsQuestFlaggedCompleted then return try(IsQuestFlaggedCompleted, id) and true or false end
return false
end
local function libraryBooks()
local done, missing = {}, {}
for _, b in ipairs(BOOK_QUESTS) do
local list = questDone(b[1]) and done or missing
list[#list + 1] = { quest = b[1], title = b[2] }
end
local rewards = {}
for k, id in pairs(BOOK_REWARDS) do rewards[k] = questDone(id) end
return { count = #done, total = #BOOK_QUESTS, done = done, missing = missing, rewards = rewards }
end
---------------------------------------------------------------- deaths, gold and repairs
local function onDeath()
local s = store()
s.deaths = s.deaths or {}
s.deaths[#s.deaths + 1] = { date = date("%Y-%m-%d %H:%M"), ts = time(), level = UnitLevel("player"),
zone = GetRealZoneText and GetRealZoneText() or "", subzone = GetSubZoneText and GetSubZoneText() or "" }
while #s.deaths > 100 do table.remove(s.deaths, 1) end
s.deathCount = (s.deathCount or 0) + 1
-- every death per level (the list above keeps only the latest)
s.deathsByLevel = s.deathsByLevel or {}
local key = tostring(UnitLevel("player") or 0)
s.deathsByLevel[key] = (s.deathsByLevel[key] or 0) + 1
local z = zoneRec(s, currentZone())
if z then z.deaths = z.deaths + 1 end
bump("deaths")
deadStart = time()
end
local function goldDay(s)
s.goldDays = s.goldDays or {}
s.goldDays[date("%Y-%m-%d")] = GetMoney and GetMoney() or 0
local keys = {}
for k in pairs(s.goldDays) do keys[#keys + 1] = k end
if #keys > 120 then
table.sort(keys)
for i = 1, #keys - 120 do s.goldDays[keys[i]] = nil end
end
end
-- A repair shows as the repair cost dropping while a merchant is open: the drop is
-- what was paid (single-item repairs included, guild bank repairs too).
local merchantOpen, repairCost = false, nil
local function repairCheck()
if not (merchantOpen and GetRepairAllCost) then return end
local cost = try(GetRepairAllCost) or 0
if repairCost and cost < repairCost then
local s = store()
local r = s.repairs or { total = 0, count = 0 }
r.total, r.count = r.total + (repairCost - cost), r.count + 1
r.last = { date = date("%Y-%m-%d %H:%M"), cost = repairCost - cost }
s.repairs = r
end
repairCost = cost
end
---------------------------------------------------------------- items
local function itemName(link)
return (try(GetItemInfo, link))
end
local function itemEquipLoc(link)
local r = GetItemInfoInstant and { pcall(GetItemInfoInstant, link) }
-- returns ok, itemID, itemType, itemSubType, itemEquipLoc, icon, classID, subclassID
if r and r[1] then return r[5], r[2] end
return nil
end
local function itemStats(link)
local t
if C_Item and C_Item.GetItemStats then t = try(C_Item.GetItemStats, link) end
if type(t) ~= "table" and GetItemStats then t = try(GetItemStats, link) end
if type(t) ~= "table" then return nil end
local out = {}
for k, v in pairs(t) do out[k] = v end
return out
end
local function itemLevel(link)
return (try(GetDetailedItemLevelInfo, link))
end
local function itemRecord(link, count)
if not link then return nil end
local loc, id = itemEquipLoc(link)
return {
id = id,
link = link,
name = itemName(link),
ilvl = itemLevel(link),
equipLoc = loc,
count = count,
stats = itemStats(link),
}
end
local SLOT_NAMES = {
[1] = "head", [2] = "neck", [3] = "shoulder", [4] = "shirt", [5] = "chest", [6] = "waist",
[7] = "legs", [8] = "feet", [9] = "wrist", [10] = "hands", [11] = "finger1", [12] = "finger2",
[13] = "trinket1", [14] = "trinket2", [15] = "back", [16] = "mainhand", [17] = "offhand",
[18] = "relic", [19] = "tabard",
}
local function equipped()
local out = {}
for slot, name in pairs(SLOT_NAMES) do
local link = try(GetInventoryItemLink, "player", slot)
if link then out[name] = itemRecord(link, 1) end
end
return out
end
---------------------------------------------------------------- containers
local function numSlots(bag)
---@diagnostic disable-next-line: deprecated
local fn = C_Container and C_Container.GetContainerNumSlots or GetContainerNumSlots
return try(fn, bag) or 0
end
local function slotItem(bag, slot)
if C_Container and C_Container.GetContainerItemInfo then
local info = try(C_Container.GetContainerItemInfo, bag, slot)
if type(info) == "table" then return info.itemID, info.stackCount or 1, info.hyperlink end
end
if C_Container and C_Container.GetContainerItemID then
local id = try(C_Container.GetContainerItemID, bag, slot)
if id then return id, 1, C_Container.GetContainerItemLink and try(C_Container.GetContainerItemLink, bag, slot) or nil end
end
return nil
end
local function freeSlots(bag)
---@diagnostic disable-next-line: deprecated
local fn = C_Container and C_Container.GetContainerNumFreeSlots or GetContainerNumFreeSlots
return (try(fn, bag)) or 0
end
-- returns sizes per bag, item counts by id, and equippable gear found
local function scanBags(first, last)
local sizes, items, gear, free = {}, {}, {}, 0
for bag = first, last do
local n = numSlots(bag)
sizes[bag] = n
free = free + freeSlots(bag)
for slot = 1, n do
local id, count, link = slotItem(bag, slot)
if id then
items[id] = (items[id] or 0) + (count or 1)
if link then
local loc = itemEquipLoc(link)
if loc and loc ~= "" and loc ~= "INVTYPE_BAG" and loc ~= "INVTYPE_NON_EQUIP_IGNORE" and loc ~= "INVTYPE_AMMO" then
gear[#gear + 1] = itemRecord(link, count)
end
end
end
end
end
return sizes, items, gear, free
end
---------------------------------------------------------------- professions
local function addProf(out, name, rank, max)
if name and rank and max and max > 1 then out[name] = { rank = rank, max = max } end
end
local function professions()
local out = {}
if GetProfessions and GetProfessionInfo then
local r = { pcall(GetProfessions) }
if r[1] then
for i = 2, 7 do
if r[i] then
local name, _, rank, maxRank = try(GetProfessionInfo, r[i])
addProf(out, name, rank, maxRank)
end
end
end
end
if C_TradeSkillUI and C_TradeSkillUI.GetAllProfessionTradeSkillLines and C_TradeSkillUI.GetProfessionInfoBySkillLineID then
local lines = try(C_TradeSkillUI.GetAllProfessionTradeSkillLines)
if type(lines) == "table" then
for _, id in ipairs(lines) do
local info = try(C_TradeSkillUI.GetProfessionInfoBySkillLineID, id)
if type(info) == "table" and (info.skillLevel or 0) > 0 then
-- the base name ("Mining"), not the expansion skill line, so it merges with GetProfessionInfo
addProf(out, info.parentProfessionName or info.professionName, info.skillLevel, info.maxSkillLevel)
end
end
end
end
return out
end
-- Recipes can only be read while a profession window is open.
local function scanRecipes()
if not (C_TradeSkillUI and C_TradeSkillUI.GetAllRecipeIDs and C_TradeSkillUI.GetRecipeInfo) then return end
-- someone else's profession (a link, the guild list, an NPC crafter) is not the player's
if try(C_TradeSkillUI.IsTradeSkillLinked) or try(C_TradeSkillUI.IsTradeSkillGuild)
or try(C_TradeSkillUI.IsNPCCrafting) or try(IsTradeSkillLinked) then return end
local ids = try(C_TradeSkillUI.GetAllRecipeIDs)
if type(ids) ~= "table" or #ids == 0 then return end
local profName = "?"
if C_TradeSkillUI.GetBaseProfessionInfo then
local info = try(C_TradeSkillUI.GetBaseProfessionInfo)
if type(info) == "table" and info.professionName then profName = info.professionName end
end
local known, unknown = {}, {}
for _, id in ipairs(ids) do
local info = try(C_TradeSkillUI.GetRecipeInfo, id)
if type(info) == "table" and info.name then
local rec = { id = id, name = info.name, difficulty = info.relativeDifficulty }
if info.learned then known[#known + 1] = rec else unknown[#unknown + 1] = rec end
end
end
local s = store()
s.recipes = s.recipes or {}
s.recipes[profName] = { date = date("%Y-%m-%d %H:%M"), known = known, unknown = unknown }
end
---------------------------------------------------------------- quests
local function questLog()
local out = {}
if not (C_QuestLog and C_QuestLog.GetNumQuestLogEntries and C_QuestLog.GetInfo) then return out end
local n = try(C_QuestLog.GetNumQuestLogEntries) or 0
for i = 1, n do
local info = try(C_QuestLog.GetInfo, i)
if type(info) == "table" and info.title and not info.isHeader then
local done = C_QuestLog.IsComplete and try(C_QuestLog.IsComplete, info.questID) or false
local objectives = {}
if C_QuestLog.GetQuestObjectives then
local objs = try(C_QuestLog.GetQuestObjectives, info.questID)
if type(objs) == "table" then
for _, o in ipairs(objs) do
objectives[#objectives + 1] = { text = o.text, done = o.finished and true or false, have = o.numFulfilled, need = o.numRequired }
end
end
end
out[#out + 1] = { id = info.questID, title = info.title, level = info.level,
complete = done and true or false, objectives = objectives }
end
end
return out
end
local function completedQuests()
if C_QuestLog and C_QuestLog.GetAllCompletedQuestIDs then
local ids = try(C_QuestLog.GetAllCompletedQuestIDs)
if type(ids) == "table" then return ids end
end
return {}
end
---------------------------------------------------------------- talents
local function spellName(id)
if not id then return nil end
if C_Spell and C_Spell.GetSpellName then
local n = try(C_Spell.GetSpellName, id)
if n then return n end
end
return (try(GetSpellInfo, id))
end
local function funcNames(t)
local names = {}
if type(t) == "table" then
for k, v in pairs(t) do if type(v) == "function" then names[#names + 1] = k end end
table.sort(names)
end
return table.concat(names, ",")
end
local function talents()
local out = { trees = {}, list = {} }
-- old style trees
if GetNumTalentTabs and GetNumTalents and GetTalentInfo then
local tabs = try(GetNumTalentTabs) or 0
for tab = 1, tabs do
local tree = { talents = {}, points = 0 }
if GetTalentTabInfo then
-- the tree name is the first text value (older clients start with it, newer ones with an id)
for _, v in ipairs({ try(GetTalentTabInfo, tab) }) do
if type(v) == "string" and v ~= "" then tree.name = v; break end
end
end
local n = try(GetNumTalents, tab) or 0
for i = 1, n do
local name, _, tier, column, rank, maxRank = try(GetTalentInfo, tab, i)
if name and (rank or 0) > 0 then
tree.talents[#tree.talents + 1] = { name = name, tier = tier, column = column, rank = rank, max = maxRank }
tree.points = tree.points + rank
end
end
out.trees[#out.trees + 1] = tree
end
end
-- trait system
if C_ClassTalents and C_ClassTalents.GetActiveConfigID and C_Traits and C_Traits.GetConfigInfo then
local cfg = try(C_ClassTalents.GetActiveConfigID)
out.configID = cfg
local info = cfg and try(C_Traits.GetConfigInfo, cfg)
if type(info) == "table" and type(info.treeIDs) == "table" then
for _, treeID in ipairs(info.treeIDs) do
local nodes = try(C_Traits.GetTreeNodes, treeID)
if type(nodes) == "table" then
for _, nodeID in ipairs(nodes) do
local node = try(C_Traits.GetNodeInfo, cfg, nodeID)
-- currentRank includes granted (free) nodes, ranksPurchased does not
local rank = 0
if type(node) == "table" then rank = node.currentRank or node.ranksPurchased or 0 end
if type(node) == "table" and rank > 0 then
local name
local entryID = node.activeEntry and node.activeEntry.entryID or (node.entryIDs and node.entryIDs[1])
local entry = entryID and try(C_Traits.GetEntryInfo, cfg, entryID)
local def = type(entry) == "table" and entry.definitionID and try(C_Traits.GetDefinitionInfo, entry.definitionID)
if type(def) == "table" then name = def.overrideName or spellName(def.spellID) end
out.list[#out.list + 1] = { name = name, rank = rank, max = node.maxRanks,
tree = treeID, node = nodeID, x = node.posX, y = node.posY }
end
end
end
end
end
end
out.debug = {
C_SpecializationInfo = funcNames(C_SpecializationInfo),
C_ClassTalents = funcNames(C_ClassTalents),
GetNumTalents = GetNumTalents and true or false,
}
if UnitCharacterPoints then out.unspent = (try(UnitCharacterPoints, "player")) end
return out
end
---------------------------------------------------------------- reputation
-- One reputation API for both client styles: count, row(i) and expand/collapse.
-- row(i) returns a table: name, isHeader, isCollapsed, hasRep and the standing fields.
local function repAPI()
if C_Reputation and C_Reputation.GetNumFactions and C_Reputation.GetFactionDataByIndex then
return C_Reputation.GetNumFactions, function(i)
local f = try(C_Reputation.GetFactionDataByIndex, i)
if type(f) ~= "table" or not f.name then return nil end
return { name = f.name, isHeader = f.isHeader, isCollapsed = f.isCollapsed, hasRep = f.isHeaderWithRep,
standing = f.reaction, value = f.currentStanding, min = f.currentReactionThreshold, max = f.nextReactionThreshold }
end, C_Reputation.ExpandFactionHeader, C_Reputation.CollapseFactionHeader
elseif GetNumFactions and GetFactionInfo then
return GetNumFactions, function(i)
local name, _, standing, min, max, value, _, _, isHeader, isCollapsed, hasRep = try(GetFactionInfo, i)
if not name then return nil end
return { name = name, isHeader = isHeader, isCollapsed = isCollapsed, hasRep = hasRep,
standing = standing, value = value, min = min, max = max }
end, ExpandFactionHeader, CollapseFactionHeader
end
end
-- The game lists only the rows the player has expanded: open every header for the
-- scan and close the ones that were closed again afterwards.
local function reputation()
local out = {}
local numFn, row, expand, collapse = repAPI()
if not numFn then return out end
local reopened = {}
if expand then
local i, guard = 1, 0
while i <= (try(numFn) or 0) and guard < 500 do
guard = guard + 1
local f = row(i)
if f and f.isHeader and f.isCollapsed then
reopened[f.name] = true
try(expand, i)
end
i = i + 1
end
end
for i = 1, try(numFn) or 0 do
local f = row(i)
-- headers with a standing of their own (hasRep) are factions too
if f and (not f.isHeader or f.hasRep) then
out[#out + 1] = { name = f.name, standing = f.standing, value = f.value, min = f.min, max = f.max }
end
end
if collapse and next(reopened) then
for i = try(numFn) or 0, 1, -1 do
local f = row(i)
if f and f.isHeader and reopened[f.name] and not f.isCollapsed then try(collapse, i) end
end
end
return out
end
---------------------------------------------------------------- character sheet
local function sheet()
local t = {}
local names = { "str", "agi", "sta", "int", "spi" }
for i, n in ipairs(names) do
local base, total = try(UnitStat, "player", i)
t[n] = total or base
end
local b, p, n = try(UnitAttackPower, "player")
if b then t.ap = b + (p or 0) + (n or 0) end
local _, armor = try(UnitArmor, "player")
t.armor = armor
t.crit = try(GetCritChance)
t.dodge = try(GetDodgeChance)
t.health = try(UnitHealthMax, "player")
t.form = try(GetShapeshiftForm)
return t
end
---------------------------------------------------------------- spells (known, for trainer reminders)
local function spells()
local out = {}
if C_SpellBook and C_SpellBook.GetNumSpellBookSkillLines and C_SpellBook.GetSpellBookSkillLineInfo and C_SpellBook.GetSpellBookItemInfo then
local lines = try(C_SpellBook.GetNumSpellBookSkillLines) or 0
local bank = Enum and Enum.SpellBookSpellBank and Enum.SpellBookSpellBank.Player or 0
-- only learned spells: no "future" (not yet learned) entries, no flyouts, no off-spec lines
local SPELL = Enum and Enum.SpellBookItemType and Enum.SpellBookItemType.Spell
for l = 1, lines do
local li = try(C_SpellBook.GetSpellBookSkillLineInfo, l)
if type(li) == "table" and not li.offSpecID then
for i = (li.itemIndexOffset or 0) + 1, (li.itemIndexOffset or 0) + (li.numSpellBookItems or 0) do
local si = try(C_SpellBook.GetSpellBookItemInfo, i, bank)
if type(si) == "table" and si.name and not si.isPassive and not si.isOffSpec
and (not SPELL or si.itemType == nil or si.itemType == SPELL) then
out[#out + 1] = { id = si.spellID, name = si.name, sub = si.subName, tab = li.name }
end
end
end
end
elseif GetNumSpellTabs and GetSpellTabInfo and GetSpellBookItemName then
local tabs = try(GetNumSpellTabs) or 0
for tab = 1, tabs do
local tabName, _, offset, num = try(GetSpellTabInfo, tab)
for i = (offset or 0) + 1, (offset or 0) + (num or 0) do
local name, sub, id = try(GetSpellBookItemName, i, "spell")
local kind = GetSpellBookItemInfo and try(GetSpellBookItemInfo, i, "spell")
if name and kind ~= "FUTURESPELL" then out[#out + 1] = { id = id, name = name, sub = sub, tab = tabName } end
end
end
end
return out
end
---------------------------------------------------------------- api info
local function apiInfo()
local t = {}
local function has(name, v) t[name] = v and true or false end
has("GetNumTalentTabs", GetNumTalentTabs)
has("GetTalentInfo", GetTalentInfo)
has("GetTalentTabInfo", GetTalentTabInfo)
has("C_ClassTalents", C_ClassTalents)
has("C_Traits", C_Traits)
has("C_SpecializationInfo", C_SpecializationInfo)
has("C_Item.GetItemStats", C_Item and C_Item.GetItemStats)
has("GetItemStats", GetItemStats)
has("C_Reputation.GetFactionDataByIndex", C_Reputation and C_Reputation.GetFactionDataByIndex)
has("GetFactionInfo", GetFactionInfo)
has("C_SpellBook.GetSpellBookItemInfo", C_SpellBook and C_SpellBook.GetSpellBookItemInfo)
has("GetSpellBookItemName", GetSpellBookItemName)
has("C_TradeSkillUI.GetAllRecipeIDs", C_TradeSkillUI and C_TradeSkillUI.GetAllRecipeIDs)
has("C_Bank", C_Bank)
if GetBuildInfo then
local v, build, _, toc = try(GetBuildInfo)
t.build = tostring(v) .. " " .. tostring(build) .. " toc " .. tostring(toc)
end
return t
end
---------------------------------------------------------------- VendorFloor (optional)
-- If Bencepo's VendorFloor is installed, its ledger (account-wide) is read through
-- VendorFloor_Ledger(). Without it nothing changes.
local function vendorFloorLedger()
if type(VendorFloor_Ledger) ~= "function" then return nil end
local ok, l = pcall(VendorFloor_Ledger)
if ok and type(l) == "table" then return l end
return nil
end
local function flipProfit()
local l = vendorFloorLedger()
return l and tonumber(l.profit) or nil
end
---------------------------------------------------------------- sessions (xp and gold per play session)
-- The current session lives in the saved data so a /reload continues it. It ends after
-- 15 minutes without the player being online (the minute clock keeps it alive).
local SESSION_GAP = 900
-- Writes a session into the list. A closed session ends at its last activity.
local function sessionSave(cur, closed)
if not cur or not cur.start then return end
local s = store()
s.sessions = s.sessions or {}
local stop = closed and (cur.last or cur.start) or time()
local copperNow = closed and cur.lastCopper or GetMoney() or 0
local rec = { date = cur.date, minutes = math.floor(math.max(0, stop - cur.start) / 60),
levelStart = cur.level, levelEnd = closed and (cur.lastLevel or cur.level) or UnitLevel("player"),
xpGained = cur.xpGained or 0, copperDelta = copperNow - (cur.copper or copperNow),
kills = cur.kills or 0, quests = cur.quests or 0, deaths = cur.deaths or 0, loot = cur.loot or 0 }
local flip = closed and cur.lastFlip or flipProfit()
if flip then
if not cur.flip then cur.flip = flip end
rec.flipProfit = flip - cur.flip
end
local list = s.sessions
if list[#list] and list[#list].date == rec.date then list[#list] = rec else list[#list + 1] = rec end
-- older sessions are summed up per month instead of being dropped
while #list > 30 do
local old = table.remove(list, 1)
s.sessionMonths = s.sessionMonths or {}
local m = tostring(old.date or ""):sub(1, 7)
local agg = s.sessionMonths[m] or { sessions = 0, minutes = 0, xp = 0, copper = 0 }
agg.sessions = agg.sessions + 1
agg.minutes = agg.minutes + (old.minutes or 0)
agg.xp = agg.xp + (old.xpGained or 0)
agg.copper = agg.copper + (old.copperDelta or 0)
s.sessionMonths[m] = agg
end
end
local function sessionExpired(cur)
return not cur or (time() - (cur.last or 0)) > SESSION_GAP
end
-- The running session; an expired one is saved and a new one started.
local function sessionGet()
if not xpReady() then return nil end
local s = store()
local cur = s.session
if cur and sessionExpired(cur) then
sessionSave(cur, true)
cur = nil
end
if not cur then
local now = time()
cur = { start = now, last = now, date = date("%Y-%m-%d %H:%M"), level = UnitLevel("player"),
copper = GetMoney() or 0, xpGained = 0, flip = flipProfit() }
s.session = cur
end
return cur
end
-- Marks activity: keeps the session from expiring and remembers where it stands.
sessionTouch = function()
local cur = sessionGet()
if not cur then return nil end
cur.last = time()
cur.lastCopper = GetMoney() or cur.lastCopper
cur.lastLevel = UnitLevel("player") or cur.lastLevel
cur.lastFlip = flipProfit() or cur.lastFlip
return cur
end
-- XP gained since the last check, kept apart from the session so no gain is lost when a
-- session starts. A jump over several levels adds the full XP of the levels in between.
local function trackXP()
if not xpReady() then return end
local s = store()
local xp, max, lvl = UnitXP("player") or 0, UnitXPMax("player") or 0, UnitLevel("player") or 0
local t = s.xpTrack
local gained = 0
if t and t.level then
if lvl > t.level then
local scale = XP_TABLE[t.level] and (t.max or 0) > 0 and t.max / XP_TABLE[t.level] or 1
local first = math.max(0, (t.max or 0) - (t.xp or 0))
addXP(t.level, "total", first)
gained = first
for L = t.level + 1, lvl - 1 do
local need = xpForLevel(L, scale) or 0
addXP(L, "total", need)
gained = gained + need
end
addXP(lvl, "total", xp)
gained = gained + xp
elseif lvl == t.level and xp > (t.xp or 0) then
gained = xp - (t.xp or 0)
addXP(lvl, "total", gained)
elseif lvl == t.level and xp < (t.xp or 0) and not t.dropSeen then
-- the XP event can come before the level changes: wait for the level instead of
-- taking the small value as the new start (a second drop in a row is taken as it is)
t.dropSeen = true
return
end
end
s.xpTrack = { xp = xp, max = max, level = lvl }
if gained > 0 then
local cur = sessionTouch()
if cur then cur.xpGained = (cur.xpGained or 0) + gained end
end
end
---------------------------------------------------------------- bank (only readable while the bank is open)
-- Bank bag IDs: the bank itself plus the bank bags after the character bags (5-10 on
-- Classic clients); the character bank tabs where the client has them.
local function bankBagIDs()
local B = Enum and Enum.BagIndex
if B and B.CharacterBankTab_1 then
local ids = {}
for i = 1, 6 do