Repository navigation
Expand file tree
/
Copy pathDropShare.lua
More file actions
482 lines (444 loc) · 18.7 KB
/
Copy pathDropShare.lua
File metadata and controls
482 lines (444 loc) · 18.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
-- DropShare.lua: copy-paste export/import and party/guild sync of personal drop counts.
-- Only your own kills are sent (never dropDone, and never numbers you already imported).
-- Each source has an id: importing or receiving the same id again replaces that source's
-- snapshot, so pasting one string twice does not double the numbers. Different sources add up.
local _, ns = ...
local C, Core, Dr = ns.Compat, ns.Core, ns.Drops
local S = {}
ns.DropShare = S
S.PREFIX = "DEBDROPS"
S.MAX_CHUNK = 240
S.SEND_GAP = 0.25
S.ANNOUNCE_GAP = 15
S.DATA_GAP = 15
S.PUSH_GAP = 15
S.QUERY_GAP = 30
S.ASSEMBLE_TTL = 30
S.ALLOWED_CHANNELS = { PARTY = true, RAID = true, GUILD = true, INSTANCE_CHAT = true }
S.RESULT_SUCCESS, S.RESULT_THROTTLE, S.RESULT_CHANNEL_THROTTLE, S.RESULT_LOCKDOWN = 0, 3, 8, 11
local MAX_KILLS, MAX_ID, MAX_MOBS, MAX_ITEMS, MAX_NAME = 1000000, 99999999, 2000, 40, 80
local queue, pumping, pending = {}, false, false
local lastSentHash, lastAnnounceAt = nil, 0
local lastQueryAt, assembling = {}, {}
local lastDataByChannel = {}
local function lockdown()
return C_ChatInfo and C_ChatInfo.InChatMessagingLockdown and C_ChatInfo.InChatMessagingLockdown() == true
end
function S.CanSend()
if not (C_ChatInfo and C_ChatInfo.SendAddonMessage) then return false, "no api" end
if InCombatLockdown and InCombatLockdown() then return false, "combat" end
if C.InCombat() then return false, "combat" end
if lockdown() then return false, "lockdown" end
return true
end
function S.Channels()
local out = {}
if IsInRaid and IsInRaid() then out[#out + 1] = "RAID"
elseif IsInGroup and IsInGroup() then out[#out + 1] = "PARTY" end
if IsInGuild and IsInGuild() then out[#out + 1] = "GUILD" end
return out
end
-- Format --------------------------------------------------------------------------------
local function escapeName(s)
s = tostring(s or "")
return (s:gsub("%%", "%%25"):gsub(":", "%%3A"):gsub(",", "%%2C"):gsub("/", "%%2F"))
end
local function unescapeName(s)
s = tostring(s or "")
return (s:gsub("%%3[Aa]", ":"):gsub("%%2[Cc]", ","):gsub("%%2[Ff]", "/"):gsub("%%25", "%%"))
end
function S.Hash(s)
local h = 5381
for i = 1, #s do h = (h * 33 + s:byte(i)) % 4294967296 end
return ("%08x"):format(h)
end
local function sortedKeys(t)
local keys = {}
for k in pairs(t or {}) do keys[#keys + 1] = k end
table.sort(keys)
return keys
end
function S.RecordsOf(snap)
local parts = {}
for _, cid in ipairs(sortedKeys(snap and snap.kills or {})) do
local kills = snap.kills[cid]
local name = (snap.names and snap.names[cid]) or ""
local bits = { tostring(cid), tostring(kills), escapeName(name) }
local rec = snap.drops and snap.drops[cid]
if rec then
for _, id in ipairs(sortedKeys(rec)) do
local e = rec[id]
bits[#bits + 1] = ("%d:%d:%d"):format(id, e.seen, e.loots)
end
end
parts[#parts + 1] = table.concat(bits, ",")
end
return table.concat(parts, "/")
end
function S.Encode(sourceId, snap)
local rec = S.RecordsOf(snap or { kills = {}, drops = {}, names = {} })
sourceId = tostring(sourceId or "")
return "DEB1:" .. sourceId .. ":" .. S.Hash(sourceId .. ":" .. rec) .. ":" .. rec
end
function S.EncodePersonal()
if not Dr or not Dr.SourceId then return nil end
return S.Encode(Dr.SourceId(), Dr.PersonalSnapshot())
end
local function parseInt(s, minv, maxv)
if type(s) ~= "string" or not s:match("^%d+$") then return nil end
local n = tonumber(s)
if not n or n < minv or n > maxv then return nil end
return n
end
-- Strict: a bad checksum or header rejects the whole string; a bad mob or item is skipped.
function S.Decode(text)
if type(text) ~= "string" then return nil, nil, nil, "empty" end
text = text:gsub("^%s+", ""):gsub("%s+$", ""):gsub("[\r\n]+", "")
if text == "" then return nil, nil, nil, "empty" end
local sid, hash, rec = text:match("^DEB1:([%w]+):(%x+):(.*)$")
if not sid or #sid < 6 or #sid > 32 or not hash or #hash ~= 8 then return nil, nil, nil, "malformed" end
hash = hash:lower()
if S.Hash(sid .. ":" .. rec) ~= hash then return nil, nil, nil, "bad checksum" end
local snap = { kills = {}, drops = {}, names = {} }
if rec == "" then return snap, sid, hash, nil end
local nMobs = 0
for part in rec:gmatch("[^/]+") do
nMobs = nMobs + 1
if nMobs > MAX_MOBS then break end
local fields, i = {}, 0
for f in (part .. ","):gmatch("([^,]*),") do
i = i + 1; fields[i] = f
end
local cid = parseInt(fields[1], 1, MAX_ID)
local kills = parseInt(fields[2], 1, MAX_KILLS)
-- A second copy of the same mob in one string is skipped (first wins), so loots
-- cannot be stacked past that mob's kills.
if cid and kills and not snap.kills[cid] then
snap.kills[cid] = kills
local name = unescapeName(fields[3] or "")
name = name:gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", ""):gsub("|H.-|h(.-)|h", "%1"):gsub("|T.-|t", ""):gsub("|+", "")
if #name > MAX_NAME then name = name:sub(1, MAX_NAME) end
if name ~= "" then snap.names[cid] = name end
snap.drops[cid] = snap.drops[cid] or {}
local nItems = 0
for fi = 4, #fields do
local idS, seenS, lootsS = (fields[fi] or ""):match("^(%d+):(%d+):(%d+)$")
local id, seen, loots = parseInt(idS or "", 1, MAX_ID), parseInt(seenS or "", 0, MAX_KILLS), parseInt(lootsS or "", 1, MAX_KILLS)
nItems = nItems + 1
if nItems <= MAX_ITEMS and id and seen and loots and seen > 0 and seen <= loots and loots <= kills then
snap.drops[cid][id] = { seen = seen, loots = loots }
end
end
end
end
return snap, sid, hash, nil
end
function S.Import(text, silent, sender)
local snap, sid, hash, err = S.Decode(text)
if not snap then
if not silent then Core.Print(err == "empty" and "paste a drop string first." or "couldn't read that drop string.") end
return false, err or "malformed"
end
local ok, kind = Dr.ApplyShare(sid, snap, hash, sender)
if not silent then
local n = 0; for _ in pairs(snap.kills) do n = n + 1 end
if kind == "own" then Core.Print("that's your own export; nothing changed.")
elseif kind == "sender" then Core.Print("that drop id is already tied to another player.")
elseif kind == "same" then Core.Print("already had that drop string.")
elseif ok and kind == "replaced" then Core.Print(("updated drop counts from another player (%d mob%s)."):format(n, n == 1 and "" or "s"))
elseif ok then Core.Print(("added drop counts from another player (%d mob%s)."):format(n, n == 1 and "" or "s"))
else Core.Print("couldn't import that drop string.") end
end
if ok and kind ~= "same" and kind ~= "own" and ns.RM and ns.RM.Refresh then ns.RM.Refresh() end
return ok, kind
end
-- Line 1: the DEB1 drop string (1.2.1 reads it alone). Line 2, when you have any: the DEB2 vendor and gathering
-- sightings string (ShareData.lua). 1.3.0 imports either line or both.
function S.OpenExport()
local text, snap = S.EncodePersonal() or "", nil
if ns.ShareData then text, snap = ns.ShareData.ExportText() end
local n = 0
if Dr and Dr.PersonalSnapshot then for _ in pairs(Dr.PersonalSnapshot().kills) do n = n + 1 end end
local title = n > 0 and ("Drop data (%d mob%s)"):format(n, n == 1 and "" or "s") or "Drop data: you haven't looted any mobs yet"
if snap and not ns.ShareData.IsEmpty(snap) then
title = title .. (" + sightings (%d vendor%s, %d gathering)"):format(#snap.vendors, #snap.vendors == 1 and "" or "s", #snap.gather)
end
return Core.ShowText("DropExport", title .. ". Ctrl+C to copy" .. (snap and not ns.ShareData.IsEmpty(snap) and " (1.2.1 reads line 1 only)" or ""), text)
end
function S.OpenImport()
return Core.ShowText("DropImport", "Paste one or both lines (drops, then sightings), then click Import", "", {
actionLabel = "Import",
noHighlight = true,
action = function(s, w)
local ok
if ns.ShareData then ok = ns.ShareData.ImportText(s, false) else ok = S.Import(s, false) end
if ok and w then w:Hide() end
end,
})
end
-- Chunking / comms ----------------------------------------------------------------------
function S.BuildChunks(payload)
payload = payload or ""
local hash = payload:match("^DEB%d:[%w]+:(%x+):") or S.Hash(payload)
-- Reserve "D:<hash>:<iii>:<nnn>:" so a 3-digit index always fits in MAX_CHUNK.
local overhead = #("D:" .. hash .. ":000:000:")
local size = S.MAX_CHUNK - overhead
if size < 16 then size = 16 end
local n = math.max(1, math.ceil(math.max(#payload, 1) / size))
local chunks = {}
for i = 1, n do
local data = payload:sub((i - 1) * size + 1, i * size)
chunks[i] = ("D:%s:%d:%d:%s"):format(hash, i, n, data)
end
return chunks, hash
end
local function startPump()
if pumping then return end
pumping = true
local function step()
pumping = false
if #queue == 0 then return end
local ok = S.CanSend()
if not ok then
-- Includes "no api": never call SendAddonMessage when the function is missing.
pending = true
return
end
local item = table.remove(queue, 1)
-- All four arguments are plain strings this file built (SecretArguments = "NotAllowed").
-- One queue for both prefixes (DEBDROPS drops, DEBDATA sightings from ShareData.lua) so the throttle covers both.
local result = C_ChatInfo.SendAddonMessage(item.prefix or S.PREFIX, item.msg, item.chatType)
if result == S.RESULT_THROTTLE or result == S.RESULT_CHANNEL_THROTTLE or result == S.RESULT_LOCKDOWN then
table.insert(queue, 1, item)
pending = true
if result ~= S.RESULT_LOCKDOWN and C_Timer and C_Timer.After then
pumping = true
C_Timer.After(1, step)
end
return
end
if #queue > 0 and C_Timer and C_Timer.After then
pumping = true
C_Timer.After(S.SEND_GAP, step)
else
if pending then S.Flush() end
local SD = ns.ShareData
if SD and SD.Pending() and #queue == 0 then SD.Flush() end
end
end
step()
end
-- prefix: nil for DEBDROPS (this file), or another registered prefix (ShareData's DEBDATA).
function S.Enqueue(chatType, msg, prefix)
if type(chatType) ~= "string" or type(msg) ~= "string" or #msg > S.MAX_CHUNK then return end
if not S.ALLOWED_CHANNELS[chatType] then return end
queue[#queue + 1] = { chatType = chatType, msg = msg, prefix = prefix }
end
function S.QueueSize() return #queue end
function S.ClearQueue() queue = {} end
-- Drop queued data chunks for this channel (and announces for any other hash) so a newer
-- snapshot replaces the old one instead of stacking behind it.
function S.PurgeQueuedData(chatType, keepHash, prefix)
local kept = {}
for i = 1, #queue do
local item = queue[i]
local dh = item.msg:match("^D:(%x+):")
local ah = item.msg:match("^A:[%w]+:(%x+)$")
local stale = item.prefix == prefix and item.chatType == chatType and (dh or (ah and ah ~= keepHash))
if not stale then kept[#kept + 1] = item end
end
queue = kept
end
function S.DataInFlight(chatType, prefix)
for i = 1, #queue do
if queue[i].prefix == prefix and (not chatType or queue[i].chatType == chatType) and queue[i].msg:match("^D:") then return true end
end
return false
end
function S.QueueData(chans, payload, hash, prefix)
local chunks = S.BuildChunks(payload)
for _, ch in ipairs(chans) do
S.PurgeQueuedData(ch, hash, prefix)
if not prefix then lastDataByChannel[ch] = { hash = hash, at = C.Clock() } end
for i = 1, #chunks do S.Enqueue(ch, chunks[i], prefix) end
end
end
function S.OnPersonalChange()
pending = true
end
function S.Flush()
local ok = S.CanSend()
if not ok then pending = true; return false end
local chans = S.Channels()
if #chans == 0 then pending = false; return false end
if not Dr or not Dr.PersonalSnapshot then return false end
local snap = Dr.PersonalSnapshot()
if not next(snap.kills) then pending = false; return false end
local sid, payload = Dr.SourceId(), S.Encode(Dr.SourceId(), snap)
local hash = payload:match("^DEB1:[%w]+:(%x+):")
local now, hashChanged = C.Clock(), hash ~= lastSentHash
if hashChanged or (now - lastAnnounceAt) >= S.ANNOUNCE_GAP then
for _, ch in ipairs(chans) do S.Enqueue(ch, "A:" .. sid .. ":" .. hash) end
lastAnnounceAt = now
end
if hashChanged then
local inFlight, recent = S.DataInFlight(), false
for _, ch in ipairs(chans) do
local prev = lastDataByChannel[ch]
if prev and (now - (prev.at or 0)) < S.PUSH_GAP then recent = true end
end
if inFlight or recent then
-- Keep the queue to one payload: the send already in flight (or just started) finishes,
-- then Flush runs again with the latest hash (lastSentHash is left unchanged).
pending = true
if not inFlight and C_Timer and C_Timer.After then
C_Timer.After(S.PUSH_GAP, function() if pending then Core.SafeCall("drop sync", S.Flush) end end)
end
else
S.QueueData(chans, payload, hash)
lastSentHash = hash
pending = false
end
else
pending = false
end
startPump()
return true
end
local function assembleTTL(n)
-- Throttled chunks can arrive a second apart; keep the assembly alive for the
-- remaining chunks of a large payload, timed from the last chunk we saw.
return math.max(S.ASSEMBLE_TTL, (tonumber(n) or 1) * 2)
end
local function expireAssemblies()
local now = C.Clock()
for k, rec in pairs(assembling) do
if now - (rec.at or 0) > assembleTTL(rec.n) then assembling[k] = nil end
end
end
-- Collects D chunks per sender + hash (+ prefix) and calls done(payload) once all n arrived. Shared with ShareData.
function S.Assemble(sender, hash, i, n, data, done, prefix)
i, n = tonumber(i), tonumber(n)
if not (sender and hash and i and n and data) then return end
if n < 1 or n > 400 or i < 1 or i > n or #data > S.MAX_CHUNK then return end
expireAssemblies()
local key = (prefix or S.PREFIX) .. ":" .. sender .. ":" .. hash
local rec = assembling[key]
if not rec or rec.n ~= n then
rec = { hash = hash, n = n, parts = {}, at = C.Clock(), count = 0 }
assembling[key] = rec
end
if not rec.parts[i] then rec.parts[i] = data; rec.count = rec.count + 1 end
rec.at = C.Clock()
if rec.count ~= rec.n then return end
local bits = {}
for j = 1, rec.n do
if not rec.parts[j] then assembling[key] = nil; return end
bits[j] = rec.parts[j]
end
assembling[key] = nil
done(table.concat(bits))
end
local function handleData(sender, hash, i, n, data)
S.Assemble(sender, hash, i, n, data, function(text) S.Import(text, true, sender) end)
end
local function maybeQuery(channel, sid, hash)
if not sid or not hash or (Dr and Dr.SourceId and sid == Dr.SourceId()) then return end
local shares = KennyDwarfExplorersBibleDB and KennyDwarfExplorersBibleDB.dropShares
local have = shares and shares[sid]
if have and have.hash == hash then return end
local key, now = sid .. ":" .. hash, C.Clock()
for k, at in pairs(lastQueryAt) do
if now - at >= S.QUERY_GAP then lastQueryAt[k] = nil end
end
if lastQueryAt[key] and now - lastQueryAt[key] < S.QUERY_GAP then return end
lastQueryAt[key] = now
if S.CanSend() then S.Enqueue(channel, "Q:" .. sid .. ":" .. hash); startPump() else pending = true end
end
local function maybeAnswer(channel, wantSid, wantHash)
if not Dr or wantSid ~= Dr.SourceId() then return end
local payload = S.EncodePersonal()
local hash = payload and payload:match("^DEB1:[%w]+:(%x+):")
if not payload or hash ~= wantHash then return end
local prev, now = lastDataByChannel[channel], C.Clock()
if prev and prev.hash == wantHash and now - (prev.at or 0) < S.DATA_GAP then return end
if not S.CanSend() then pending = true; return end
S.QueueData({ channel }, payload, hash)
startPump()
end
-- Self-echo check, cross-realm safe: you are "Name-YourRealm" (UnitFullName, realm normalized); a sender with the
-- same name on another realm is someone else, and a bare "Name" means your own realm.
function S.Me()
local name, realm
if UnitFullName then name, realm = UnitFullName("player") end
name, realm = C.Safe(name), C.Safe(realm)
if type(name) ~= "string" or name == "" then name = UnitName and C.Safe(UnitName("player")) end
if type(name) ~= "string" or name == "" then return nil end
return Dr.NormalizeSender(name .. ((type(realm) == "string" and realm ~= "") and ("-" .. realm) or ""))
end
function S.IsSelf(sender)
local me, who = S.Me(), Dr.NormalizeSender(sender)
return me ~= nil and who ~= nil and me == who
end
function S.OnAddonMessage(prefix, text, channel, sender)
prefix, text, channel, sender = C.Safe(prefix), C.Safe(text), C.Safe(channel), C.Safe(sender)
if prefix ~= S.PREFIX or type(text) ~= "string" or text == "" then return end
if type(sender) ~= "string" or sender == "" then return end
if type(channel) ~= "string" or not S.ALLOWED_CHANNELS[channel:upper()] then return end
if S.IsSelf(sender) then return end
local kind, a = text:match("^([ADQ]):(.*)$")
if not kind then return end
if kind == "A" then
local sid, hash = a:match("^([%w]+):(%x+)$")
if sid and hash then maybeQuery(channel, sid, hash) end
elseif kind == "Q" then
local sid, hash = a:match("^([%w]+):(%x+)$")
if sid and hash then maybeAnswer(channel, sid, hash) end
elseif kind == "D" then
-- D:hash:i:n:data (data may contain colons)
local hash, i, n, data = a:match("^(%x+):(%d+):(%d+):(.*)$")
if hash then handleData(sender, hash, i, n, data) end
end
end
function S.Pending() return pending end
function S.SetPending(v) pending = v and true or false end
function S.Pump() startPump() end
function S.QueryMapSize()
local n = 0
for _ in pairs(lastQueryAt) do n = n + 1 end
return n
end
function S.ResetComms()
queue, pumping, pending = {}, false, false
lastSentHash, lastAnnounceAt = nil, 0
lastQueryAt, assembling, lastDataByChannel = {}, {}, {}
end
local function registerPrefix()
if C_ChatInfo and C_ChatInfo.RegisterAddonMessagePrefix then
C_ChatInfo.RegisterAddonMessagePrefix(S.PREFIX)
end
end
registerPrefix()
local f = CreateFrame("Frame")
f:RegisterEvent("PLAYER_LOGIN")
f:RegisterEvent("PLAYER_REGEN_ENABLED")
f:RegisterEvent("GROUP_ROSTER_UPDATE")
f:RegisterEvent("PLAYER_GUILD_UPDATE")
f:RegisterEvent("CHAT_MSG_ADDON")
f:SetScript("OnEvent", function(_, event, ...)
if event == "CHAT_MSG_ADDON" then
local prefix, text, channel, sender = ...
Core.SafeCall("addon message", S.OnAddonMessage, prefix, text, channel, sender)
elseif event == "PLAYER_LOGIN" then
registerPrefix()
pending = true
if C_Timer and C_Timer.After then C_Timer.After(2, function() Core.SafeCall("drop sync", S.Flush) end)
else Core.SafeCall("drop sync", S.Flush) end
elseif event == "PLAYER_REGEN_ENABLED" then
if pending or #queue > 0 then Core.SafeCall("drop sync", S.Flush); startPump() end
elseif event == "GROUP_ROSTER_UPDATE" or event == "PLAYER_GUILD_UPDATE" then
pending = true
Core.SafeCall("drop sync", S.Flush)
end
end)
S._frame = f