Repository navigation
Expand file tree
/
Copy pathNet.lua
More file actions
executable file
·599 lines (498 loc) · 21.2 KB
/
Copy pathNet.lua
File metadata and controls
executable file
·599 lines (498 loc) · 21.2 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
--[[
CeeLo Dice Addon
Net module: Addon communication (SendAddonMessage / CHAT_MSG_ADDON)
]]
local addonName, ns = ...
ns.Net = {}
-- Message types
local MSG_TYPES = {
INVITE = "INV",
ACCEPT = "ACC",
DECLINE = "DEC",
CANCEL = "CAN",
COMMIT = "CMT",
REVEAL = "REV",
RESULT = "RES",
VERSION = "VER",
-- Group tables (sent by the host to the whole party/raid)
OPEN = "GOP",
LOCK = "GLK",
DROP = "GDR",
TIE = "GTI",
DONE = "GDN",
CLOSE = "GCL",
}
-- Group message type -> ns.Group handler
local GROUP_HANDLERS = {
OPEN = "OnOpenMessage",
LOCK = "OnLockMessage",
DROP = "OnDropMessage",
TIE = "OnTieMessage",
DONE = "OnDoneMessage",
CLOSE = "OnCloseMessage",
}
-- Reverse lookup
local MSG_TYPE_LOOKUP = {}
for k, v in pairs(MSG_TYPES) do
MSG_TYPE_LOOKUP[v] = k
end
-- ============================================================================
-- Initialization
-- ============================================================================
function ns.Net:Initialize()
-- Create event frame for addon messages
self.frame = CreateFrame("Frame")
self.frame:RegisterEvent("CHAT_MSG_ADDON")
-- Store reference to self for the closure
local netModule = self
self.frame:SetScript("OnEvent", function(_, event, prefix, message, channel, sender, ...)
if event == "CHAT_MSG_ADDON" then
-- Midnight/Forever can hand out secret values; comparing or
-- printing them throws, and they can't be ours anyway
local IsSecret = ns.Utils.IsSecret
if IsSecret(prefix) or IsSecret(message) or IsSecret(sender) then
return
end
-- Debug: Log ALL addon messages (before any filtering), and for a
-- few seconds after /ceeloping so its results show without debug mode
if ns.Utils.debugMode or (netModule.pingUntil and GetTime() < netModule.pingUntil) then
print(string.format("|cff888888[CeeLo Raw]|r prefix=%s channel=%s sender=%s msg=%s",
tostring(prefix), tostring(channel), tostring(sender), tostring(message):sub(1, 50)))
end
netModule:OnAddonMessage(prefix, message, channel, sender)
end
end)
ns.Utils.Debug("Net module initialized - listening for CHAT_MSG_ADDON")
ns.Utils.Debug("Network ready - addon messaging enabled")
end
-- ============================================================================
-- Message Sending
-- ============================================================================
--- Serialize data to string
local function Serialize(data)
if not data then return "" end
local parts = {}
for k, v in pairs(data) do
table.insert(parts, string.format("%s=%s", tostring(k), tostring(v)))
end
return table.concat(parts, "&")
end
--- Deserialize string to data
local function Deserialize(str)
if not str or str == "" then return {} end
local data = {}
for part in string.gmatch(str, "[^&]+") do
local k, v = strsplit("=", part, 2)
if k and v then
data[k] = v
end
end
return data
end
--- Send a raw addon whisper. SendAddonMessage returns an
--- Enum.SendAddonMessageResult code (0 = Success) since 10.2.7, not a boolean.
--- Returns: success (bool), result code
local function SendAddonWhisper(payload, target)
local result = C_ChatInfo.SendAddonMessage(ns.prefix, payload, "WHISPER", target)
local codes = Enum and Enum.SendAddonMessageResult
local success = result == true or (codes ~= nil and result == codes.Success)
return success, result
end
--- Human-readable reason for a failed SendAddonMessage
local function DescribeSendFailure(result, target)
local codes = Enum and Enum.SendAddonMessageResult or {}
if result == codes.TargetOffline then
return target .. " is offline."
elseif result == codes.AddonMessageThrottle or result == codes.ChannelThrottle then
return "Sending too fast (throttled by the server). Try again in a moment."
elseif result == codes.AddOnMessageLockdown then
return "Addon messages are blocked right now (e.g. during an encounter)."
end
return "Couldn't reach " .. target .. " (error " .. tostring(result) .. "). Are they online?"
end
--- Send a message to a player
function ns.Net:SendMessage(msgType, data, target)
if not target then
ns.Utils.Debug("SendMessage: No target specified")
return false
end
local typeCode = MSG_TYPES[msgType]
if not typeCode then
ns.Utils.Debug("SendMessage: Unknown message type:", msgType)
return false
end
-- Tag every message with the current game so stale ones can be ignored
data = data or {}
if data.gid == nil then
data.gid = ns.session.gameId
end
-- Format: TYPE:serialized_data
local payload = typeCode .. ":" .. Serialize(data)
-- Use WHISPER channel for player-to-player
local success, result = SendAddonWhisper(payload, target)
ns.Utils.Debug("SendMessage:", msgType, "->", target, "| Payload:", payload, "| Result:", tostring(result))
if not success then
print("|cffff6600CeeLo:|r " .. DescribeSendFailure(result, target))
end
return success
end
--- Send a message to our whole party/raid (group tables)
function ns.Net:SendGroupMessage(msgType, data)
local channel = ns.Utils.GetGroupChannel()
if not channel then
ns.Utils.Debug("SendGroupMessage: not in a group")
return false
end
local payload = MSG_TYPES[msgType] .. ":" .. Serialize(data)
local result = C_ChatInfo.SendAddonMessage(ns.prefix, payload, channel)
local codes = Enum and Enum.SendAddonMessageResult
local success = result == true or (codes ~= nil and result == codes.Success)
ns.Utils.Debug("SendGroupMessage:", msgType, "->", channel, "| Payload:", payload, "| Result:", tostring(result))
if not success then
print("|cffff6600CeeLo:|r " .. DescribeSendFailure(result, "your group"))
end
return success
end
-- ============================================================================
-- Message Receiving
-- ============================================================================
function ns.Net:OnAddonMessage(prefix, message, channel, sender)
-- Ignore messages from other addons
if prefix ~= ns.prefix then return end
-- Normalize sender name first
sender = Ambiguate(sender, "none")
-- Ignore our own messages (compare after Ambiguate for consistency)
if ns.Utils.NamesMatch(sender, ns.Utils.MyName()) then return end
ns.Utils.Debug("Received message from", sender, ":", message, "| channel:", channel)
-- Parse message
local typeCode, dataStr = strsplit(":", message, 2)
local msgType = MSG_TYPE_LOOKUP[typeCode]
if not msgType then
ns.Utils.Debug("Unknown message type code:", typeCode)
return
end
local data = Deserialize(dataStr or "")
-- Handle message
self:HandleMessage(msgType, data, sender)
end
function ns.Net:HandleMessage(msgType, data, sender)
ns.Utils.Debug("HandleMessage:", msgType, "from", sender)
if msgType == "INVITE" then
self:OnInvite(data, sender)
elseif msgType == "ACCEPT" then
self:OnAccept(data, sender)
elseif msgType == "DECLINE" then
self:OnDecline(data, sender)
elseif msgType == "CANCEL" then
self:OnCancel(data, sender)
elseif msgType == "COMMIT" then
self:OnCommit(data, sender)
elseif msgType == "REVEAL" then
self:OnReveal(data, sender)
elseif msgType == "RESULT" then
self:OnResult(data, sender)
elseif msgType == "VERSION" then
self:OnVersion(data, sender)
elseif GROUP_HANDLERS[msgType] and ns.Group then
ns.Group[GROUP_HANDLERS[msgType]](ns.Group, data, sender)
end
end
-- ============================================================================
-- Message Handlers
-- ============================================================================
--- True if a message comes from our opponent and belongs to the current game
local function IsCurrentGame(data, sender)
return ns.Utils.NamesMatch(sender, ns.session.opponent) and data.gid == ns.session.gameId
end
--- Like IsCurrentGame, but also accepts messages without a game id, which is
--- how clients older than protocol 2 decline or cancel
local function IsCurrentGameOrLegacy(data, sender)
return ns.Utils.NamesMatch(sender, ns.session.opponent)
and (data.gid == nil or data.gid == ns.session.gameId)
end
--- Commits and seeds are always 16 hex characters
local function IsHex16(str)
return str ~= nil and #str == 16 and str:match("^%x+$") ~= nil
end
function ns.Net:OnInvite(data, sender)
-- Check if we're already in a game
-- RESOLVED is treated like IDLE - the game is over and we're just viewing results -
-- unless it was a tie and the tiebreaker is about to start
if (ns.session.state ~= ns.STATE.IDLE and ns.session.state ~= ns.STATE.RESOLVED)
or ns.session.pendingTiebreaker then
-- Auto-decline if busy
self:SendMessage("DECLINE", { reason = "busy", gid = data.gid }, sender)
return
end
-- Refuse games with clients that would derive different dice
if tonumber(data.proto) ~= ns.PROTOCOL_VERSION or not data.gid then
self:SendMessage("DECLINE", { reason = "version", gid = data.gid }, sender)
print(string.format("|cffff6600CeeLo:|r %s challenged you, but their CeeLo version (%s) isn't compatible with yours (%s). Both players need the latest version.",
sender, data.version or "unknown", ns.version))
return
end
-- If we're in RESOLVED state, clean up the previous session first
if ns.session.state == ns.STATE.RESOLVED then
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
-- Check auto-decline setting
if ns.charDB.autoDecline then
self:SendMessage("DECLINE", { reason = "auto", gid = data.gid }, sender)
return
end
-- Check if in combat
if InCombatLockdown() then
self:SendMessage("DECLINE", { reason = "combat", gid = data.gid }, sender)
print("|cffff6600CeeLo:|r " .. sender .. " challenged you, but you're in combat!")
return
end
-- Version check
local theirVersion = data.version or "unknown"
ns.Utils.Debug("Invite from", sender, "version:", theirVersion)
-- Accept the invite as pending
ns.session.state = ns.STATE.INVITED
ns.session.opponent = sender
ns.session.gameId = data.gid
ns.session.isChallenger = false
-- Play sound
ns.Utils.PlaySound("UI_EPICLOOT_TOAST")
print(string.format("|cff00ff00CeeLo:|r %s has challenged you! Type |cff00ffff/ceelo accept|r or |cff00ffff/ceelo decline|r", sender))
-- Show invite popup
if ns.UI then
ns.UI:ShowInvite(sender, theirVersion)
end
-- Set timeout for the invite (the challenger also sends CANCEL when theirs expires)
ns:StartTimeout(ns.INVITE_TIMEOUT, function()
if ns.session.state == ns.STATE.INVITED and ns.session.opponent == sender then
print("|cffff6600CeeLo:|r Challenge from " .. sender .. " expired.")
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
end)
end
function ns.Net:OnAccept(data, sender)
-- Verify this is from who we challenged
if ns.session.state ~= ns.STATE.PENDING_INVITE then
return
end
if not ns.Utils.NamesMatch(sender, ns.session.opponent) then
ns.Utils.Debug("Accept from unexpected sender:", sender)
return
end
-- Clients older than protocol 2 accept without a version; their dice
-- wouldn't match ours, so call the game off
if tonumber(data.proto) ~= ns.PROTOCOL_VERSION then
print(string.format("|cffff6600CeeLo:|r %s accepted, but their CeeLo version isn't compatible with yours (%s). Both players need the latest version.",
sender, ns.version))
self:SendMessage("CANCEL", {}, sender)
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
return
end
if data.gid ~= ns.session.gameId then
ns.Utils.Debug("Accept for a different game:", tostring(data.gid))
return
end
ns:ClearTimeout()
-- Use the name exactly as the server reports it from here on
ns.session.opponent = sender
ns.session.state = ns.STATE.COUNTDOWN
print(string.format("|cff00ff00CeeLo:|r %s accepted your challenge!", sender))
-- Start countdown
ns:StartCountdown()
end
function ns.Net:OnDecline(data, sender)
if ns.session.state ~= ns.STATE.PENDING_INVITE then
return
end
if not IsCurrentGameOrLegacy(data, sender) then
return
end
local reason = data.reason or ""
local reasonText = ""
if reason == "busy" then
reasonText = " (already in a game)"
elseif reason == "version" then
reasonText = " (incompatible CeeLo version - both players need the latest version)"
elseif reason == "combat" then
reasonText = " (in combat)"
elseif reason == "auto" then
reasonText = " (auto-decline enabled)"
end
print(string.format("|cffff6600CeeLo:|r %s declined your challenge%s.", sender, reasonText))
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
function ns.Net:OnCancel(data, sender)
if not IsCurrentGameOrLegacy(data, sender) then
return
end
print(string.format("|cffff6600CeeLo:|r %s cancelled the game.", sender))
ns:ResetSession()
if ns.UI then ns.UI:HideAll() end
end
function ns.Net:OnCommit(data, sender)
ns.Utils.Debug("OnCommit called from: " .. tostring(sender))
ns.Utils.Debug(" My opponent is: " .. tostring(ns.session.opponent))
ns.Utils.Debug(" My state is: " .. tostring(ns.session.state))
if not IsCurrentGame(data, sender) then
ns.Utils.Debug("REJECTED: not from opponent or not for this game")
return
end
local round = tonumber(data.round)
-- Opponent started the next tiebreaker round before our delay ran out
if ns.session.pendingTiebreaker and round == ns.session.tiebreakerRound + 1 then
ns.Utils.Debug("Opponent started tiebreaker early - joining")
ns:StartTiebreaker()
end
if round ~= ns.session.tiebreakerRound then
ns.Utils.Debug("REJECTED: commit for round " .. tostring(data.round))
return
end
-- If we're still in COUNTDOWN, we need to start our commit phase first
if ns.session.state == ns.STATE.COUNTDOWN then
ns.Utils.Debug("In COUNTDOWN - starting our commit phase first")
-- Start our commit phase (this will generate and send our commit)
ns:StartCommitPhase()
end
if ns.session.state ~= ns.STATE.COMMITTING then
ns.Utils.Debug("REJECTED: wrong state (need COMMITTING, got " .. tostring(ns.session.state) .. ")")
return
end
local commit = data.commit
if not IsHex16(commit) then
ns.Utils.Debug("REJECTED: malformed commit data")
return
end
ns.Utils.Debug("ACCEPTED: Processing commit")
ns:OnReceivedCommit(commit)
end
function ns.Net:OnReveal(data, sender)
ns.Utils.Debug("OnReveal called from: " .. tostring(sender))
ns.Utils.Debug(" My opponent is: " .. tostring(ns.session.opponent))
ns.Utils.Debug(" My state is: " .. tostring(ns.session.state))
if not IsCurrentGame(data, sender) then
ns.Utils.Debug("REJECTED: not from opponent or not for this game")
return
end
if tonumber(data.round) ~= ns.session.tiebreakerRound then
ns.Utils.Debug("REJECTED: reveal for round " .. tostring(data.round))
return
end
-- If we're still in COMMITTING but have both commits, move to reveal
if ns.session.state == ns.STATE.COMMITTING then
if ns.session.myCommit and ns.session.theirCommit then
ns.Utils.Debug("In COMMITTING with both commits - starting reveal phase")
ns:StartRevealPhase()
else
ns.Utils.Debug("REJECTED: still waiting for commits")
return
end
end
if ns.session.state ~= ns.STATE.REVEALING then
ns.Utils.Debug("REJECTED: wrong state (need REVEALING, got " .. tostring(ns.session.state) .. ")")
return
end
-- A malformed seed can't match the commit, so let the check in
-- OnReceivedReveal treat it as a forfeit rather than waiting for a timeout
local seed = data.seed
if not seed then
ns.Utils.Debug("REJECTED: empty seed data")
return
end
ns.Utils.Debug("Received reveal:", seed)
ns:OnReceivedReveal(seed)
end
function ns.Net:OnResult(data, sender)
-- Informational only - we calculate results ourselves
ns.Utils.Debug("Received result confirmation from", sender)
end
function ns.Net:OnVersion(data, sender)
-- Version handshake for future compatibility
ns.Utils.Debug("Version check from", sender, ":", data.version)
end
-- ============================================================================
-- Diagnostic Commands
-- ============================================================================
-- Test command: send a ping to yourself or another player
SLASH_CEELOPING1 = "/ceeloping"
SlashCmdList["CEELOPING"] = function(target)
ns.Net.pingUntil = GetTime() + 5
-- No target: whisper ourselves using every spelling of our name the client
-- gives us, to find which one the server accepts (WoW Forever names are
-- "First Last", with the last name where the realm normally goes)
if not target or target == "" then
local first, second = UnitName("player")
local spellings, seen = {}, {}
local function try(spelling)
if not ns.Utils.IsEmpty(spelling) and not seen[spelling] then
seen[spelling] = true
spellings[#spellings + 1] = spelling
end
end
try(first)
try(GetUnitName("player", true))
if not ns.Utils.IsEmpty(second) then try(first .. "-" .. second) end
try(ns.Utils.FullName(ns.Utils.MyName()))
print("|cff00ff00CeeLo Ping:|r Whispering yourself with each spelling of your name:")
for i, spelling in ipairs(spellings) do
local _, result = SendAddonWhisper("TEST:ping=" .. i, spelling)
print(string.format("|cff888888 #%d %s|r -> result %s", i, spelling, tostring(result)))
end
print("|cff888888 Lines starting [CeeLo Raw] below show which ones arrived (msg=TEST:ping=#) and how the sender is spelled.|r")
return
end
print("|cff00ff00CeeLo Ping:|r Sending test message to: " .. target)
print("|cff888888 Prefix:|r " .. ns.prefix)
print("|cff888888 Frame exists:|r " .. tostring(ns.Net.frame ~= nil))
print("|cff888888 Debug mode:|r " .. tostring(ns.Utils.debugMode))
local success, result = SendAddonWhisper("TEST:ping=1", target)
print("|cff888888 SendAddonMessage returned:|r " .. tostring(result))
if success then
print("|cff00ff00CeeLo:|r Message sent! If debug is enabled, you should see [CeeLo Raw] output.")
else
print("|cffff0000CeeLo:|r SendAddonMessage failed: " .. DescribeSendFailure(result, target))
end
end
-- Diagnostic info command
SLASH_CEELODIAG1 = "/ceelodiag"
SlashCmdList["CEELODIAG"] = function()
print("|cff00ff00=== CeeLo Diagnostics ===|r")
print("Addon version: " .. (ns.version or "unknown"))
print("Prefix: " .. (ns.prefix or "NOT SET"))
print("Net module loaded: " .. tostring(ns.Net ~= nil))
print("Net frame exists: " .. tostring(ns.Net and ns.Net.frame ~= nil))
print("UI module loaded: " .. tostring(ns.UI ~= nil))
print("Debug mode: " .. tostring(ns.Utils.debugMode))
print("Session state: " .. tostring(ns.session and ns.session.state or "nil"))
-- How the client spells names in different places (these differ on WoW Forever)
local unitName, unitRealm = UnitName("player")
print("UnitName(player): " .. tostring(unitName) .. " | second value: " .. tostring(unitRealm))
print("GetUnitName(player, true): " .. tostring(GetUnitName("player", true)))
if UnitFullName then
local fullName, fullRealm = UnitFullName("player")
print("UnitFullName(player): " .. tostring(fullName) .. " | " .. tostring(fullRealm))
end
print("Normalized realm: " .. tostring(GetNormalizedRealmName and GetNormalizedRealmName()))
print("Addon's name for you: " .. tostring(ns.Utils.MyName()))
if UnitExists("party1") then
local partyName, partyRealm = UnitName("party1")
print("party1: UnitName " .. tostring(partyName) .. " | " .. tostring(partyRealm)
.. " | GetUnitName " .. tostring(GetUnitName("party1", true)))
end
-- Check registered prefixes
local prefixes = C_ChatInfo.GetRegisteredAddonMessagePrefixes and C_ChatInfo.GetRegisteredAddonMessagePrefixes() or {}
local found = false
for _, p in ipairs(prefixes) do
if p == ns.prefix then
found = true
break
end
end
print("Prefix registered: " .. tostring(found))
if not found then
print("|cffff0000WARNING:|r Prefix not in registered list! Re-registering...")
C_ChatInfo.RegisterAddonMessagePrefix(ns.prefix)
end
end