diff --git a/contrib/support_site/.gitignore b/contrib/support_site/.gitignore new file mode 100644 index 0000000000..4d9e475d7a --- /dev/null +++ b/contrib/support_site/.gitignore @@ -0,0 +1,2 @@ +support_site.json +__pycache__/ diff --git a/contrib/support_site/armory_icons.py b/contrib/support_site/armory_icons.py new file mode 100644 index 0000000000..a22726a7fe --- /dev/null +++ b/contrib/support_site/armory_icons.py @@ -0,0 +1,46 @@ +"""Fills world.armory_icon (icon file data id -> icon name) from the community listfile, for the armory's item, skill and achievement +icons (shown from the public icon CDN as .jpg). + +Usage: py -3 armory_icons.py [community-listfile.csv] [config.json] +Without a listfile path it downloads the latest one from https://github.com/wowdev/wow-listfile (about 150 MB, only icons are kept). +""" +import json +import os +import sys +import urllib.request + +import pymysql + +HERE = os.path.dirname(os.path.abspath(__file__)) +LISTFILE_URL = 'https://github.com/wowdev/wow-listfile/releases/latest/download/community-listfile.csv' + + +def icon_rows(lines): + for line in lines: + fid, _, path = line.strip().partition(';') + if path.startswith('interface/icons/') and path.endswith('.blp') and fid.isdigit(): + yield int(fid), path[len('interface/icons/'):-len('.blp')] + + +def main(): + listfile = sys.argv[1] if len(sys.argv) > 1 else None + cfg = json.load(open(sys.argv[2] if len(sys.argv) > 2 else os.path.join(HERE, 'support_site.json'), encoding='utf-8')) + if listfile: + rows = list(icon_rows(open(listfile, encoding='utf-8', errors='replace'))) + else: + print('downloading', LISTFILE_URL) + with urllib.request.urlopen(LISTFILE_URL) as r: + rows = list(icon_rows(line.decode('utf-8', 'replace') for line in r)) + db = cfg['db'] + conn = pymysql.connect(host=db['host'], port=int(db['port']), user=db['user'], password=db['password'], database=db.get('world', 'world'), + charset='utf8mb4', autocommit=False) + with conn, conn.cursor() as cur: + cur.execute('DELETE FROM armory_icon') + for i in range(0, len(rows), 5000): + cur.executemany('INSERT INTO armory_icon (fileDataId, name) VALUES (%s, %s)', rows[i:i + 5000]) + conn.commit() + print(len(rows), 'icons') + + +if __name__ == '__main__': + main() diff --git a/contrib/support_site/static/app.js b/contrib/support_site/static/app.js new file mode 100644 index 0000000000..2bb9a58c27 --- /dev/null +++ b/contrib/support_site/static/app.js @@ -0,0 +1,26 @@ +// Forever web theme: light/dark and text size. Saved in a cookie because the in-game browser has local storage turned off. +(function () { + var root = document.documentElement; + + function save(name, value) { + document.cookie = name + '=' + value + '; Path=/; Max-Age=31536000; SameSite=Lax'; + } + + document.addEventListener('click', function (e) { + var el = e.target.closest('[data-set-size],[data-toggle-theme]'); + if (!el) + return; + if (el.hasAttribute('data-toggle-theme')) { + var theme = root.getAttribute('data-theme') === 'light' ? 'dark' : 'light'; + root.setAttribute('data-theme', theme); + save('fs_theme', theme); + } else { + var size = el.getAttribute('data-set-size'); + root.setAttribute('data-size', size); + save('fs_size', size); + var buttons = document.querySelectorAll('[data-set-size]'); + for (var i = 0; i < buttons.length; ++i) + buttons[i].classList.toggle('on', buttons[i] === el); + } + }); +})(); diff --git a/contrib/support_site/static/armory.js b/contrib/support_site/static/armory.js new file mode 100644 index 0000000000..31ef6a2b44 --- /dev/null +++ b/contrib/support_site/static/armory.js @@ -0,0 +1,61 @@ +// Armory item tooltips (data from the page: window.ARMORY_ITEMS = { itemId: { name, q, ilvl, icon, lines: [[kind, text, right?]] } }). +(function () { + var items = window.ARMORY_ITEMS || {}; + var tip = document.createElement('div'); + tip.className = 'wow-tip'; + tip.hidden = true; + document.body.appendChild(tip); + + function text(s) { + var d = document.createElement('div'); + d.textContent = s; + return d.innerHTML; + } + + function render(item) { + var html = '
' + text(item.name) + '
'; + if (item.ilvl) + html += '
Item Level ' + item.ilvl + '
'; + item.lines.forEach(function (l) { + if (l[0] === 'split') + html += '
' + text(l[1]) + '' + text(l[2] || '') + '
'; + else + html += '
' + text(l[1]) + '
'; + }); + return html; + } + + function place(x, y) { + var w = tip.offsetWidth, h = tip.offsetHeight; + var left = x + 16, top = y + 16; + if (left + w > window.innerWidth - 8) left = Math.max(8, x - w - 16); + if (top + h > window.innerHeight - 8) top = Math.max(8, window.innerHeight - h - 8); + tip.style.left = left + 'px'; + tip.style.top = top + 'px'; + } + + function show(el, x, y) { + var item = items[el.getAttribute('data-item')]; + if (!item) return; + tip.innerHTML = render(item); + tip.hidden = false; + place(x, y); + } + + document.addEventListener('mouseover', function (e) { + var el = e.target.closest('[data-item]'); + if (el) show(el, e.clientX, e.clientY); else tip.hidden = true; + }); + document.addEventListener('mousemove', function (e) { + if (!tip.hidden) place(e.clientX, e.clientY); + }); + document.addEventListener('click', function (e) { // touch screens: tap a slot to show, tap elsewhere to hide + var el = e.target.closest('[data-item]'); + if (el) { + var r = el.getBoundingClientRect(); + show(el, r.right, r.top); + } else { + tip.hidden = true; + } + }); +})(); diff --git a/contrib/support_site/static/theme.css b/contrib/support_site/static/theme.css new file mode 100644 index 0000000000..9a3b219a4d --- /dev/null +++ b/contrib/support_site/static/theme.css @@ -0,0 +1,346 @@ +/* Forever web theme (support site, later the GM portal). + Runs in the in-game browser too: CEF / Chrome 83, so no flex gap, color-mix, :has, :is or aspect-ratio (grid gap is fine). */ + +:root { + --bg: #0b1118; + --side: #0e151d; + --panel: #111922; + --panel-2: #17212c; + --hover: #1a2531; + --line: #1e2a36; + --line-2: #2b3846; + --text: #e4e8ee; + --muted: #8693a3; + --faint: #5d6977; + --gold: #e6b04a; + --gold-ink: #1b1406; + --gold-soft: rgba(230, 176, 74, .12); + --gold-line: rgba(230, 176, 74, .45); + --green: #3cba7a; + --green-soft: rgba(60, 186, 122, .12); + --green-line: rgba(60, 186, 122, .4); + --red: #e5534b; + --red-soft: rgba(229, 83, 75, .12); + --red-line: rgba(229, 83, 75, .45); + --amber: #df9f36; + --amber-soft: rgba(223, 159, 54, .12); + --amber-line: rgba(223, 159, 54, .4); + --blue: #4a8cf0; + --blue-soft: rgba(74, 140, 240, .14); + --shadow: 0 1px 0 rgba(255, 255, 255, .02) inset; + --radius: 8px; + --fs: 15px; + --serif: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif; + --sans: "Segoe UI", system-ui, -apple-system, Roboto, "Helvetica Neue", Arial, sans-serif; + --mono: "Cascadia Mono", Consolas, "SFMono-Regular", Menlo, monospace; + color-scheme: dark; +} + +:root[data-theme="light"] { + --bg: #f3f0e9; + --side: #ebe6dc; + --panel: #fffdf9; + --panel-2: #f4f0e7; + --hover: #efe9dd; + --line: #e2dbcd; + --line-2: #cec5b2; + --text: #1c222a; + --muted: #5c6571; + --faint: #8b929b; + --gold: #9d6b0c; + --gold-ink: #fffaf0; + --gold-soft: rgba(157, 107, 12, .1); + --gold-line: rgba(157, 107, 12, .45); + --green: #1d8250; + --green-soft: rgba(29, 130, 80, .1); + --green-line: rgba(29, 130, 80, .35); + --red: #c4362e; + --red-soft: rgba(196, 54, 46, .09); + --red-line: rgba(196, 54, 46, .4); + --amber: #a86a08; + --amber-soft: rgba(168, 106, 8, .1); + --amber-line: rgba(168, 106, 8, .35); + --blue: #2563c9; + --blue-soft: rgba(37, 99, 201, .1); + color-scheme: light; +} + +:root[data-size="s"] { --fs: 13.5px; } +:root[data-size="l"] { --fs: 17px; } + +* { box-sizing: border-box; } +html { font-size: var(--fs); } +body { margin: 0; background: var(--bg); color: var(--text); font: 400 1rem/1.5 var(--sans); -webkit-font-smoothing: antialiased; } +a { color: var(--gold); text-decoration: none; } +a:hover { text-decoration: underline; } +b, strong { font-weight: 600; } +.muted { color: var(--muted); } +.faint { color: var(--faint); } +.mono { font-family: var(--mono); font-size: .9em; } +.nowrap { white-space: nowrap; } + +svg.i { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; vertical-align: middle; } +svg.i.sm { width: 15px; height: 15px; } + +/* ---------- app shell ---------- */ + +.app { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100vh; } + +.side { background: var(--side); border-right: 1px solid var(--line); position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; overflow-y: auto; } +.brand { display: flex; align-items: center; padding: 14px 16px 12px; color: var(--text); } +.brand:hover { text-decoration: none; } +.brand .logo { width: 30px; height: 30px; flex: none; margin-right: 11px; } +.brand b { display: block; font-family: var(--serif); font-weight: 500; font-size: 1.14rem; line-height: 1.15; letter-spacing: .1px; } +.brand small { display: block; color: var(--muted); font-size: .76rem; } + +.nav { display: grid; gap: 2px; padding: 6px 8px; } +.nav a { display: flex; align-items: center; padding: 8px 10px; border-radius: 6px; color: var(--text); font-size: .93rem; } +.nav a svg { margin-right: 12px; opacity: .8; } +.nav a:hover { background: var(--hover); text-decoration: none; } +.nav a.on { background: var(--gold-soft); color: var(--gold); box-shadow: inset 2px 0 0 var(--gold); } +.nav a.on svg { opacity: 1; } +.nav .count { margin-left: auto; min-width: 20px; text-align: center; background: var(--red); color: #fff; border-radius: 999px; font-size: .72rem; font-weight: 600; padding: 1px 7px; } +.nav .sep { height: 1px; background: var(--line); margin: 8px 6px; } + +.side-foot { margin-top: auto; border-top: 1px solid var(--line); padding: 10px 16px 12px; font-size: .8rem; color: var(--muted); display: grid; gap: 4px; } +.side-foot .row { display: flex; align-items: center; } +.side-foot .row .v { margin-left: auto; color: var(--text); } + +.dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--green); margin-right: 8px; flex: none; } +.dot.off { background: var(--faint); } +.dot.warn { background: var(--amber); } +.dot.bad { background: var(--red); } + +.main { min-width: 0; display: flex; flex-direction: column; } +.top { height: 56px; border-bottom: 1px solid var(--line); display: flex; align-items: center; padding: 0 20px; position: sticky; top: 0; background: var(--bg); z-index: 5; } +.top .crumb { color: var(--muted); font-size: .88rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.top .tools { margin-left: auto; display: grid; grid-auto-flow: column; gap: 10px; align-items: center; } + +.content { width: 100%; max-width: 1120px; margin: 0 auto; padding: 30px 32px 56px; } +h1 { font-family: var(--serif); font-weight: 500; font-size: 1.95rem; line-height: 1.2; margin: 0 0 6px; letter-spacing: .1px; } +h2 { font-size: 1rem; font-weight: 600; margin: 0; } +.lead { color: var(--muted); margin: 0 0 24px; max-width: 64ch; } +.stack { display: grid; gap: 18px; } + +/* ---------- controls ---------- */ + +.seg { position: relative; display: inline-grid; grid-auto-flow: column; gap: 2px; padding: 2px; border: 1px solid var(--line-2); border-radius: 7px; background: var(--panel); } +.seg button, .seg label, .seg a { appearance: none; border: 0; background: transparent; color: var(--muted); font: inherit; font-size: .84rem; padding: 4px 10px; border-radius: 5px; cursor: pointer; white-space: nowrap; } +.seg button:hover, .seg label:hover, .seg a:hover { color: var(--text); text-decoration: none; } +.seg .on, .seg input:checked + label { background: var(--panel-2); color: var(--text); box-shadow: 0 0 0 1px var(--line-2) inset; } +.seg input { position: absolute; opacity: 0; pointer-events: none; } +.seg .n { color: var(--gold); margin-left: 4px; } + +.icon-btn { appearance: none; width: 32px; height: 32px; display: grid; place-items: center; border-radius: 7px; border: 1px solid transparent; background: transparent; color: var(--muted); cursor: pointer; } +.icon-btn:hover { color: var(--text); border-color: var(--line-2); background: var(--panel); } + +.btn { appearance: none; display: inline-flex; align-items: center; justify-content: center; font: inherit; font-size: .9rem; font-weight: 500; color: var(--text); background: var(--panel-2); border: 1px solid var(--line-2); border-radius: 6px; padding: 7px 14px; cursor: pointer; white-space: nowrap; } +.btn svg { margin-right: 7px; } +.btn:hover { background: var(--hover); text-decoration: none; } +.btn.primary { background: var(--gold); border-color: var(--gold); color: var(--gold-ink); font-weight: 600; } +.btn.primary:hover { filter: brightness(1.06); } +.btn.danger { color: var(--red); background: var(--red-soft); border-color: var(--red-line); } +.btn.ghost { background: transparent; } +.actions { display: grid; grid-auto-flow: column; justify-content: start; gap: 10px; align-items: center; margin-top: 16px; } + +.field { display: grid; gap: 6px; margin-bottom: 14px; } +.field > span { color: var(--muted); font-size: .82rem; } +input[type=text], input[type=search], select, textarea { + width: 100%; font: inherit; font-size: .93rem; color: var(--text); background: var(--bg); border: 1px solid var(--line-2); border-radius: 6px; padding: 8px 10px; } +input:focus, select:focus, textarea:focus, .btn:focus-visible, .seg label:focus-visible { outline: 2px solid var(--gold-line); outline-offset: 1px; } +textarea { min-height: 140px; resize: vertical; line-height: 1.5; } +select { padding-right: 28px; } + +/* ---------- panels ---------- */ + +.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); min-width: 0; } +.panel-h { display: flex; align-items: center; padding: 13px 16px; border-bottom: 1px solid var(--line); min-height: 52px; } +.panel-h h2 { margin-right: 10px; } +.panel-h .sub { color: var(--muted); font-size: .9rem; } +.panel-h .right { margin-left: auto; } +.panel-b { padding: 16px; } +.panel.accent { border-color: var(--gold-line); } + +.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px; } +.tile { display: grid; grid-template-columns: 36px minmax(0, 1fr); gap: 4px 12px; align-items: start; align-content: start; padding: 16px; color: var(--text); background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); } +.tile:hover { text-decoration: none; border-color: var(--line-2); background: var(--panel-2); } +.tile .ic { grid-row: span 2; width: 36px; height: 36px; display: grid; place-items: center; border-radius: 8px; background: var(--gold-soft); color: var(--gold); } +.tile b { font-size: .98rem; } +.tile span { color: var(--muted); font-size: .86rem; line-height: 1.45; } +.tile .count { justify-self: start; margin-top: 6px; } + +.tag { display: inline-block; font-size: .76rem; line-height: 1.5; padding: 0 7px; border-radius: 5px; border: 1px solid var(--line-2); color: var(--muted); white-space: nowrap; } +.tag.green { color: var(--green); background: var(--green-soft); border-color: var(--green-line); } +.tag.amber { color: var(--amber); background: var(--amber-soft); border-color: var(--amber-line); } +.tag.red { color: var(--red); background: var(--red-soft); border-color: var(--red-line); } +.tag.gold { color: var(--gold); background: var(--gold-soft); border-color: var(--gold-line); } + +.fac { display: inline-block; width: 20px; height: 20px; line-height: 20px; text-align: center; font-size: .7rem; font-weight: 700; border-radius: 4px; } +.fac.h { color: var(--red); background: var(--red-soft); } +.fac.a { color: var(--blue); background: var(--blue-soft); } + +.alert { display: flex; align-items: flex-start; padding: 10px 14px; border-radius: 7px; border: 1px solid var(--line-2); background: var(--panel); margin-bottom: 18px; font-size: .93rem; } +.alert svg { margin: 2px 10px 0 0; } +.alert.ok { color: var(--green); background: var(--green-soft); border-color: var(--green-line); } +.alert.bad { color: var(--red); background: var(--red-soft); border-color: var(--red-line); } +.alert.info { color: var(--text); } +.alert .t { color: var(--text); } + +/* ---------- tables ---------- */ + +.tbl-wrap { overflow-x: auto; } +table.tbl { width: 100%; border-collapse: collapse; font-size: .9rem; } +.tbl th { text-align: left; font-weight: 500; font-size: .8rem; color: var(--muted); padding: 10px 14px; border-bottom: 1px solid var(--line); white-space: nowrap; } +.tbl td { padding: 11px 14px; border-bottom: 1px solid var(--line); vertical-align: middle; } +.tbl tr:last-child td { border-bottom: 0; } +.tbl tbody tr:hover { background: var(--hover); } +.tbl td.num, .tbl th.num { text-align: right; font-variant-numeric: tabular-nums; } +.tbl a.row-link { color: var(--text); font-weight: 500; } +.tbl label.pick { display: flex; align-items: center; cursor: pointer; } +.tbl input[type=radio] { accent-color: var(--gold); margin: 0 12px 0 0; width: 16px; height: 16px; } +.empty { padding: 28px 16px; text-align: center; color: var(--muted); } + +/* ---------- event list / conversation ---------- */ + +.events { list-style: none; margin: 0; padding: 0; } +.events li { display: grid; grid-template-columns: 22px minmax(0, 1fr) auto; gap: 2px 12px; padding: 12px 16px; border-bottom: 1px solid var(--line); } +.events li:last-child { border-bottom: 0; } +.events .ic { grid-row: span 2; color: var(--gold); padding-top: 1px; } +.events .ic.staff { color: var(--green); } +.events .ic.muted { color: var(--muted); } +.events .title { font-size: .92rem; } +.events .when { color: var(--faint); font-size: .8rem; white-space: nowrap; } +.events .meta { grid-column: 2 / 4; color: var(--muted); font-size: .8rem; } +.events .body { grid-column: 2 / 4; white-space: pre-wrap; word-wrap: break-word; margin-top: 4px; font-size: .93rem; } + +details.faq { border-bottom: 1px solid var(--line); } +details.faq:last-child { border-bottom: 0; } +details.faq summary { cursor: pointer; padding: 13px 16px; font-weight: 500; list-style: none; display: flex; align-items: center; } +details.faq summary::-webkit-details-marker { display: none; } +details.faq summary svg { margin-left: auto; color: var(--muted); transition: transform .15s; } +details.faq[open] summary svg { transform: rotate(180deg); } +details.faq .a { padding: 0 16px 14px; color: var(--muted); } + +.cols { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 18px; align-items: start; } + +/* WoW class colours */ +.c1 { color: #c69b6d; } .c2 { color: #f48cba; } .c3 { color: #aad372; } .c4 { color: #fff468; } .c5 { color: #ffffff; } +.c7 { color: #0070dd; } .c8 { color: #3fc7eb; } .c9 { color: #8788ee; } .c11 { color: #ff7c0a; } +:root[data-theme="light"] .c4 { color: #9a8a00; } +:root[data-theme="light"] .c5 { color: #6b6f76; } +:root[data-theme="light"] .c3 { color: #5e8f22; } +:root[data-theme="light"] .c8 { color: #1a8db0; } + +/* ---------- responsive ---------- */ + +@media (max-width: 1000px) { + .cols { grid-template-columns: minmax(0, 1fr); } + .content { padding: 24px 22px 44px; } +} + +@media (max-width: 860px) { + .app { grid-template-columns: 60px minmax(0, 1fr); } + .brand { justify-content: center; padding: 14px 0 10px; } + .brand .logo { margin: 0; } + .brand .txt, .nav .lbl, .side-foot { display: none; } + .nav a { justify-content: center; padding: 9px 0; position: relative; } + .nav a svg { margin: 0; } + .nav .count { position: absolute; top: 2px; right: 4px; font-size: .62rem; padding: 0 5px; min-width: 0; } +} + +@media (max-width: 600px) { + .app { grid-template-columns: minmax(0, 1fr); } + .side { position: sticky; top: 0; z-index: 10; height: auto; flex-direction: row; align-items: center; border-right: 0; border-bottom: 1px solid var(--line); overflow-x: auto; } + .brand { padding: 8px 10px; } + .nav { grid-auto-flow: column; padding: 6px; } + .nav a { padding: 8px 10px; } + .nav .sep { display: none; } + .top { position: static; height: 48px; padding: 0 14px; } + .content { padding: 20px 16px 40px; } + h1 { font-size: 1.6rem; } + .tiles { grid-template-columns: minmax(0, 1fr); } + .hide-sm { display: none; } +} + +/* ---------- armory ---------- */ + +.armory-search { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; margin-bottom: 18px; max-width: 640px; } +.armory-search .btn { margin: 0; } +.char-head { display: flex; align-items: flex-end; flex-wrap: wrap; margin-bottom: 18px; } +.char-head > div:first-child { margin-right: auto; } +.char-head h1 { margin-bottom: 2px; } +.char-head .surname { color: var(--muted); font-weight: 400; } +.char-head .lead { margin: 0; } +.char-head .fac { width: 24px; height: 24px; line-height: 24px; font-size: .8rem; } + +.doll { display: grid; grid-template-columns: 56px minmax(0, 1fr) 56px; gap: 8px; } +.doll .col { display: grid; gap: 8px; align-content: start; } +.doll .bottom { grid-column: 1 / 4; display: grid; grid-auto-flow: column; justify-content: center; gap: 8px; } +.slot { width: 52px; height: 52px; border-radius: 6px; border: 2px solid var(--line-2); background: var(--bg); overflow: hidden; cursor: default; } +.slot img { width: 100%; height: 100%; display: block; } +.slot.empty { opacity: .45; } +.slot.q0 { border-color: #9d9d9d; } .slot.q1 { border-color: #d8d8d8; } .slot.q2 { border-color: #1eff00; } .slot.q3 { border-color: #0070dd; } +.slot.q4 { border-color: #a335ee; } .slot.q5 { border-color: #ff8000; } .slot.q6 { border-color: #e6cc80; } .slot.q7 { border-color: #00ccff; } +.figure { display: grid; place-items: center; align-content: center; gap: 10px; border-radius: var(--radius); min-height: 300px; + background: radial-gradient(circle at 50% 40%, var(--gold-soft), transparent 70%); border: 1px solid var(--line); text-align: center; } +.figure img { width: 96px; height: 96px; border-radius: 50%; border: 2px solid var(--gold-line); } +.figure-cap { font-family: var(--serif); font-size: 1.1rem; line-height: 1.3; } + +.stat-groups { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: 16px 22px; } +.stat-groups h3 { font-size: .82rem; color: var(--gold); text-transform: uppercase; letter-spacing: .6px; margin: 0 0 6px; font-weight: 600; } +.kv { display: flex; font-size: .9rem; padding: 2px 0; } +.kv span:last-child { margin-left: auto; font-variant-numeric: tabular-nums; } +.stub { display: flex; align-items: center; padding: 5px 0; font-size: .92rem; } +.stub img { width: 22px; height: 22px; border-radius: 4px; margin-right: 10px; } +.stub .v { margin-left: auto; color: var(--muted); font-variant-numeric: tabular-nums; } +.small { font-size: .85rem; } + +/* WoW-style tooltip: fixed dark look in both themes, like the game */ +.wow-tip { position: fixed; z-index: 50; max-width: 320px; padding: 9px 11px; border-radius: 6px; pointer-events: none; + background: rgba(6, 10, 20, .96); border: 1px solid #5a6a80; box-shadow: 0 6px 24px rgba(0, 0, 0, .5); color: #fff; font-size: 13px; line-height: 1.45; } +.wow-tip .t-name { font-size: 14.5px; font-weight: 600; } +.wow-tip .t-ilvl { color: #ffd100; } +.wow-tip .t-split { display: flex; } .wow-tip .t-split span:last-child { margin-left: auto; padding-left: 16px; } +.wow-tip .t-green { color: #1eff00; } +.wow-tip .t-flavor { color: #ffd100; } +.wow-tip .q0 { color: #9d9d9d; } .wow-tip .q1 { color: #ffffff; } .wow-tip .q2 { color: #1eff00; } .wow-tip .q3 { color: #0070dd; } +.wow-tip .q4 { color: #a335ee; } .wow-tip .q5 { color: #ff8000; } .wow-tip .q6 { color: #e6cc80; } .wow-tip .q7 { color: #00ccff; } + +/* ---------- in-game Help window (963 x 602): icon rail, compact spacing, side-by-side columns ---------- */ + +:root[data-ingame] .app { grid-template-columns: 60px minmax(0, 1fr); } +:root[data-ingame] .brand { justify-content: center; padding: 12px 0 8px; } +:root[data-ingame] .brand .logo { margin: 0; } +:root[data-ingame] .brand .txt, :root[data-ingame] .nav .lbl, :root[data-ingame] .side-foot { display: none; } +:root[data-ingame] .nav a { justify-content: center; padding: 8px 0; position: relative; } +:root[data-ingame] .nav a svg { margin: 0; } +:root[data-ingame] .nav .count { position: absolute; top: 2px; right: 4px; font-size: .62rem; padding: 0 5px; min-width: 0; } +:root[data-ingame] .top { height: 44px; padding: 0 14px; } +:root[data-ingame] .content { padding: 14px 16px 24px; } +:root[data-ingame] h1 { font-size: 1.5rem; } +:root[data-ingame] .lead { margin-bottom: 14px; } +:root[data-ingame] .stack, :root[data-ingame] .cols { gap: 12px; } +:root[data-ingame] .cols { grid-template-columns: minmax(0, 1.45fr) minmax(0, 1fr); } +:root[data-ingame] .panel-h { min-height: 40px; padding: 9px 12px; } +:root[data-ingame] .panel-b { padding: 12px; } +:root[data-ingame] .tiles { grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 10px; } +:root[data-ingame] .tile { padding: 12px; } +:root[data-ingame] .doll { grid-template-columns: 40px minmax(0, 1fr) 40px; gap: 6px; } +:root[data-ingame] .doll .col { gap: 6px; } +:root[data-ingame] .doll .bottom { gap: 6px; } +:root[data-ingame] .slot { width: 40px; height: 40px; border-width: 1px; } +:root[data-ingame] .figure { min-height: 0; } +:root[data-ingame] .figure img { width: 64px; height: 64px; } +:root[data-ingame] .figure-cap { font-size: .95rem; } +:root[data-ingame] .char-head { margin-bottom: 12px; } +:root[data-ingame] .stat-groups { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px 16px; } + +/* slots are fixed squares (empty ones stretched to the row height otherwise) */ +.doll .col { grid-auto-rows: 52px; } +.doll .bottom { grid-auto-rows: 52px; } +.slot { align-self: start; min-height: 0; max-height: 52px; } +:root[data-ingame] .doll .col, :root[data-ingame] .doll .bottom { grid-auto-rows: 40px; } +:root[data-ingame] .slot { max-height: 40px; } +.slot.empty { padding: 0; } +.fac-img { width: 20px; height: 20px; vertical-align: middle; border-radius: 4px; } +.char-head .fac-img { width: 30px; height: 30px; margin-left: 4px; } diff --git a/contrib/support_site/support_server.py b/contrib/support_site/support_server.py new file mode 100644 index 0000000000..3854471ae0 --- /dev/null +++ b/contrib/support_site/support_server.py @@ -0,0 +1,1134 @@ +"""Forever support site: the page the in-game Support window (Help) opens. + +The worldserver answers the client's SSO token request (CMSG_GENERATE_SSO_TOKEN) with a token stored in +auth.battlenet_sso_tokens. The in-game browser then opens ?token=&ref=; /s, /sso and /login/sso +look the token up, start a session and show the support pages: unstuck, bug reports, help tickets, FAQ, staff view. +The look (static/theme.css, static/app.js) is shared with the planned GM portal. + +Usage: + py -3 support_server.py [config.json] run the site (default config: support_site.json next to this file) + py -3 support_server.py --make-token [config.json] + issue a 1 hour test token and print the URL (desktop browser test) +Needs: pip install pymysql +""" +import hmac +import html +import json +import os +import secrets +import socket +import ssl +import sys +import threading +import time +import traceback +from http.cookies import SimpleCookie +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlencode, urlsplit + +import pymysql + +HERE = os.path.dirname(os.path.abspath(__file__)) +STATIC_DIR = os.path.join(HERE, 'static') +# cache buster for /static links: newest file time in static/ +STATIC_VERSION = str(int(max(os.path.getmtime(os.path.join(STATIC_DIR, f)) for f in os.listdir(STATIC_DIR)))) +STATIC_TYPES = {'.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png'} + +RACES = {1: 'Human', 2: 'Orc', 3: 'Dwarf', 4: 'Night Elf', 5: 'Undead', 6: 'Tauren', 7: 'Gnome', 8: 'Troll'} +HORDE_RACES = {2, 5, 6, 8} +CLASSES = {1: 'Warrior', 2: 'Paladin', 3: 'Hunter', 4: 'Rogue', 5: 'Priest', 7: 'Shaman', 8: 'Mage', 9: 'Warlock', 11: 'Druid'} +CATEGORIES = { + 'bug': 'Bug report', + 'stuck': 'Stuck', + 'account': 'Account or character', + 'player': 'Report a player', + 'other': 'Something else', +} +STATUS = {'open': ('Waiting for staff', 'amber'), 'answered': ('Staff replied', 'green'), 'closed': ('Closed', '')} +MAX_OPEN_TICKETS = 10 +SUBJECT_MAX = 120 +MESSAGE_MAX = 4000 + +# line icons (24x24, stroke) +ICONS = { + 'home': '', + 'pin': '', + 'bug': '', + 'help': '', + 'tickets': '', + 'book': '', + 'shield': '', + 'sun': '', + 'check': '', + 'alert': '', + 'chevron': '', + 'send': '', + 'user': '', + 'plus': '', + 'x': '', + 'undo': '', + 'search': '', +} + +# ---------------------------------------------------------------- armory data + +# equipment slot -> label; paper-doll columns like the game's character frame +SLOT_NAMES = {0: 'Head', 1: 'Neck', 2: 'Shoulder', 3: 'Shirt', 4: 'Chest', 5: 'Waist', 6: 'Legs', 7: 'Feet', 8: 'Wrist', 9: 'Hands', + 10: 'Finger', 11: 'Finger', 12: 'Trinket', 13: 'Trinket', 14: 'Back', 15: 'Main Hand', 16: 'Off Hand', 17: 'Ranged', 18: 'Tabard'} +DOLL_LEFT = [0, 1, 2, 14, 4, 3, 18, 8] +DOLL_RIGHT = [9, 5, 6, 7, 10, 11, 12, 13] +DOLL_BOTTOM = [15, 16, 17] +INVENTORY_TYPES = {1: 'Head', 2: 'Neck', 3: 'Shoulder', 4: 'Shirt', 5: 'Chest', 6: 'Waist', 7: 'Legs', 8: 'Feet', 9: 'Wrist', 10: 'Hands', + 11: 'Finger', 12: 'Trinket', 13: 'One-Hand', 14: 'Off Hand', 15: 'Ranged', 16: 'Back', 17: 'Two-Hand', 18: 'Bag', 19: 'Tabard', + 20: 'Chest', 21: 'Main Hand', 22: 'Off Hand', 23: 'Held In Off-hand', 25: 'Thrown', 26: 'Ranged', 28: 'Relic'} +WEAPON_TYPES = {0: 'Axe', 1: 'Axe', 2: 'Bow', 3: 'Gun', 4: 'Mace', 5: 'Mace', 6: 'Polearm', 7: 'Sword', 8: 'Sword', 10: 'Staff', 13: 'Fist Weapon', + 14: 'Miscellaneous', 15: 'Dagger', 16: 'Thrown', 18: 'Crossbow', 19: 'Wand', 20: 'Fishing Pole'} +ARMOR_TYPES = {1: 'Cloth', 2: 'Leather', 3: 'Mail', 4: 'Plate', 6: 'Shield', 7: 'Libram', 8: 'Idol', 9: 'Totem'} +BONDING = {1: 'Binds when picked up', 2: 'Binds when equipped', 3: 'Binds when used', 4: 'Quest Item'} +# ItemModType -> (text, primary); primary stats show as "+N Stamina", the rest as "Equip: ..." lines +STAT_TYPES = {0: ('Mana', True), 1: ('Health', True), 3: ('Agility', True), 4: ('Strength', True), 5: ('Intellect', True), 6: ('Spirit', True), + 7: ('Stamina', True), 12: ('defense rating', False), 13: ('dodge rating', False), 14: ('parry rating', False), 15: ('block rating', False), + 16: ('hit rating', False), 18: ('spell hit rating', False), 19: ('critical strike rating', False), 21: ('spell critical rating', False), + 31: ('hit rating', False), 32: ('critical strike rating', False), 35: ('resilience rating', False), 36: ('haste rating', False), + 37: ('expertise rating', False), 38: ('attack power', False), 39: ('ranged attack power', False), 41: ('healing done', False), + 42: ('spell damage done', False), 43: ('mana per 5 sec.', False), 45: ('spell power', False), 46: ('health per 5 sec.', False), + 47: ('spell penetration', False), 48: ('block value', False), 50: ('Armor', True), 51: ('Fire Resistance', True), + 52: ('Frost Resistance', True), 53: ('Holy Resistance', True), 54: ('Shadow Resistance', True), 55: ('Nature Resistance', True), + 56: ('Arcane Resistance', True)} +TRIGGERS = {0: 'Use', 1: 'Equip', 2: 'Chance on hit'} +SKILL_PROFESSION, SKILL_SECONDARY = 11, 9 # SkillLine.CategoryID +CLASS_ICONS = {1: 'classicon_warrior', 2: 'classicon_paladin', 3: 'classicon_hunter', 4: 'classicon_rogue', 5: 'classicon_priest', + 7: 'classicon_shaman', 8: 'classicon_mage', 9: 'classicon_warlock', 11: 'classicon_druid'} + +RATE = {} # (ip, bucket) -> recent request times +RATE_LOCK = threading.Lock() + + +def rate_ok(ip, bucket, per_minute): + now = time.time() + with RATE_LOCK: + hits = [t for t in RATE.get((ip, bucket), []) if now - t < 60] + allowed = len(hits) < per_minute + if allowed: + hits.append(now) + RATE[(ip, bucket)] = hits + if len(RATE) > 50000: # forget idle visitors + for key in [k for k, v in RATE.items() if not v or now - v[-1] > 60]: + del RATE[key] + return allowed + + +def world_db(): + return CFG['db'].get('world', 'world') + + +def icon_url(name, size='large'): + return '%s/%s/%s.jpg' % (CFG.get('icon_cdn', 'https://wow.zamimg.com/images/wow/icons'), size, name or 'inv_misc_questionmark') + + +def names(kind): + """id -> (name, icon name, extra) for races, classes, skills, achievements (world.armory_name), cached for 10 minutes.""" + cache = NAMES_CACHE.get(kind) + if cache and cache[0] > time.time(): + return cache[1] + rows = query(world_db(), 'SELECT n.id, n.name, n.extra, i.name AS icon FROM armory_name n LEFT JOIN armory_icon i ON i.fileDataId = n.iconFileDataId ' + 'WHERE n.kind = %s', (kind,)) + data = {r['id']: (r['name'], r['icon'], r['extra']) for r in rows} + if data: # empty until ".armory export" has run: ask again next time + NAMES_CACHE[kind] = (time.time() + 600, data) + return data + + +NAMES_CACHE = {} + + +def item_tooltip_data(entries): + if not entries: + return {} + marks = ','.join(['%s'] * len(entries)) + rows = query(world_db(), 'SELECT a.*, i.name AS icon FROM armory_item a LEFT JOIN armory_icon i ON i.fileDataId = a.iconFileDataId ' + 'WHERE a.id IN (%s)' % marks, tuple(entries)) + out = {} + for r in rows: + stats = [(int(t), int(v)) for t, v in (s.split(':') for s in r['stats'].split(',') if s)] + effects = [] + for e in (x for x in r['effects'].split('|') if x): + trig, spell, name = (e.split(':', 2) + ['', ''])[:3] + if int(trig) in TRIGGERS and name: + effects.append('%s: %s' % (TRIGGERS[int(trig)], name)) + if r['class'] == 2: + kind = WEAPON_TYPES.get(r['subclass'], '') + elif r['class'] == 4: + kind = ARMOR_TYPES.get(r['subclass'], '') + else: + kind = '' + lines = [] + if r['bonding'] in BONDING: + lines.append(['', BONDING[r['bonding']]]) + lines.append(['split', INVENTORY_TYPES.get(r['inventoryType'], ''), kind]) + if r['dmgMax']: + speed = r['delay'] / 1000.0 + lines.append(['split', '%d - %d Damage' % (r['dmgMin'], r['dmgMax']), 'Speed %.2f' % speed]) + if speed: + lines.append(['', '(%.1f damage per second)' % ((r['dmgMin'] + r['dmgMax']) / 2 / speed)]) + if r['armor']: + lines.append(['', '%d Armor' % r['armor']]) + for t, v in stats: + text, primary = STAT_TYPES.get(t, ('stat %d' % t, True)) + if primary: + lines.append(['', '%+d %s' % (v, text)]) + if r['requiredLevel'] > 1: + lines.append(['', 'Requires Level %d' % r['requiredLevel']]) + for t, v in stats: + text, primary = STAT_TYPES.get(t, ('stat %d' % t, True)) + if not primary: + lines.append(['green', 'Equip: Increases %s by %d.' % (text, v)]) + lines += [['green', e] for e in effects] + if r['description']: + lines.append(['flavor', '"%s"' % r['description']]) + out[r['id']] = {'name': r['name'], 'q': r['quality'], 'ilvl': r['itemLevel'], 'icon': icon_url(r['icon']), 'lines': lines} + return out +LOGO = ('') + +CFG = {} +SESSIONS = {} +SESSIONS_LOCK = threading.Lock() + + +def log(*args): + print(time.strftime('%H:%M:%S'), *args, flush=True) + + +def icon(name, cls='i'): + return '' % (cls, ICONS[name]) + + +# ---------------------------------------------------------------- database + +def connect(database): + c = CFG['db'] + return pymysql.connect(host=c['host'], port=int(c['port']), user=c['user'], password=c['password'], database=database, + charset='utf8mb4', autocommit=True, cursorclass=pymysql.cursors.DictCursor) + + +def query(database, sql, args=()): + with connect(database) as conn, conn.cursor() as cur: + cur.execute(sql, args) + return cur.fetchall() + + +def query_one(database, sql, args=()): + rows = query(database, sql, args) + return rows[0] if rows else None + + +def execute(database, sql, args=()): + with connect(database) as conn, conn.cursor() as cur: + cur.execute(sql, args) + return cur.lastrowid + + +def auth_db(): + return CFG['db']['auth'] + + +def realm_cfg(realm_id): + return CFG['realms'].get(str(realm_id)) + + +def characters_db(realm_id): + rc = realm_cfg(realm_id) + if not rc: + raise RuntimeError('realm %s is not in the config' % realm_id) + return rc['characters'] + + +def realm_name(realm_id): + row = query_one(auth_db(), 'SELECT name FROM realmlist WHERE id = %s', (realm_id,)) + return row['name'] if row else 'Realm %s' % realm_id + + +def account_characters(realm_id, account_id): + return query(characters_db(realm_id), + 'SELECT guid, name, race, class, level, online, map, zone, position_x, position_y, position_z ' + 'FROM characters WHERE account = %s AND deleteInfos_Account IS NULL ORDER BY name', (account_id,)) + + +def staff_level(account_id, realm_id): + row = query_one(auth_db(), 'SELECT MAX(SecurityLevel) AS lvl FROM account_access WHERE AccountID = %s AND (RealmID = -1 OR RealmID = %s)', + (account_id, realm_id)) + return int(row['lvl'] or 0) if row else 0 + + +# ---------------------------------------------------------------- remote access (worldserver console) + +def ra_available(realm_id): + ra = CFG.get('ra') or {} + rc = realm_cfg(realm_id) or {} + return bool(ra.get('user') and rc.get('ra_port')) + + +def ra_command(realm_id, command): + """Runs one console command on the realm's worldserver through RA (worldserver.conf Ra.Enable) and returns its output.""" + ra = CFG['ra'] + port = int(realm_cfg(realm_id)['ra_port']) + with socket.create_connection((ra.get('host', '127.0.0.1'), port), timeout=15) as sock: + def read_until(*marks): + buf = b'' + while not any(m in buf for m in marks): + chunk = sock.recv(4096) + if not chunk: + break + buf += chunk + return buf.decode('utf-8', 'replace') + + read_until(b'Username: ') + sock.sendall(ra['user'].encode() + b'\r\n') + read_until(b'Password: ') + sock.sendall(ra['password'].encode() + b'\r\n') + if 'Authentication failed' in read_until(b'TC>', b'Authentication failed'): + raise RuntimeError('RA login failed (check ra.user / ra.password; the account needs Ra.MinLevel on realm -1)') + sock.sendall(command.encode('utf-8') + b'\r\n') + out = read_until(b'TC>') + sock.sendall(b'quit\r\n') + return out.replace('TC>', '').strip() + + +def ra_quote(text): + return text.replace('"', "'").replace('\r', ' ').replace('\n', ' ') + + +# ---------------------------------------------------------------- sessions + +def start_session(token_row): + sid = secrets.token_urlsafe(32) + session = { + 'bnet': token_row['battlenetAccountId'], + 'account': token_row['accountId'], + 'realm': token_row['realmId'], + 'char': token_row['characterGuid'], + 'expires': token_row['expires'], + 'csrf': secrets.token_urlsafe(24), + 'staff': staff_level(token_row['accountId'], token_row['realmId']) >= int(CFG.get('staff_min_level', 2)), + } + with SESSIONS_LOCK: + now = time.time() + for old in [k for k, v in SESSIONS.items() if v['expires'] < now]: + del SESSIONS[old] + SESSIONS[sid] = session + return sid + + +PENDING = {} # code checks for several players behind one address: id -> {row, code, ip, target, expires, tries} +PENDING_LOCK = threading.Lock() + + +def online_from_ip(ip): + """Characters online right now on accounts whose last login came from this address, as session rows.""" + accounts = query(auth_db(), 'SELECT id, battlenet_account FROM account WHERE last_ip = %s AND online <> 0 AND battlenet_account IS NOT NULL', (ip,)) + if not accounts: + return [] + by_id = {a['id']: a['battlenet_account'] for a in accounts} + rows = [] + for realm_id in CFG['realms']: + marks = ','.join(['%s'] * len(by_id)) + for c in query(characters_db(realm_id), 'SELECT guid, account, name FROM characters WHERE online = 1 AND account IN (%s)' % marks, tuple(by_id)): + rows.append({'battlenetAccountId': by_id[c['account']], 'accountId': c['account'], 'realmId': int(realm_id), + 'characterGuid': c['guid'], 'characterName': c['name'], 'expires': int(time.time()) + 4 * 3600}) + return rows + + +def same_player(candidates): + return len({c['battlenetAccountId'] for c in candidates}) == 1 + + +def get_session(sid): + with SESSIONS_LOCK: + session = SESSIONS.get(sid) + if session and session['expires'] < time.time(): + del SESSIONS[sid] + session = None + return session + + +# ---------------------------------------------------------------- html helpers + +def esc(value): + return html.escape(str(value), quote=True) + + +def fmt_time(ts): + return time.strftime('%Y-%m-%d %H:%M', time.localtime(int(ts))) + + +def fmt_ago(ts): + d = int(time.time() - int(ts)) + if d < 60: + return 'just now' + if d < 3600: + return '%d min ago' % (d // 60) + if d < 86400: + return '%d h ago' % (d // 3600) + return '%d d ago' % (d // 86400) + + +def status_tag(status): + label, color = STATUS.get(status, (status, '')) + return '%s' % (color, esc(label)) + + +def char_name(c): + return '%s' % (c['class'], esc(c['name'])) + + +def faction(race): + races = names('race') # extra = ChrRaces.Alliance (1 = Horde) once ".armory export" wrote it; else the vanilla Horde races + horde = races[race][2] == 1 if race in races and any(r[2] == 1 for r in races.values()) else race in HORDE_RACES + return '%s' % ( + icon_url('pvpcurrency-honor-horde' if horde else 'pvpcurrency-honor-alliance', 'medium'), 'H' if horde else 'A', 'Horde' if horde else 'Alliance') + + +def alert(kind, text): + return '
%s
%s
' % (kind, icon('check' if kind == 'ok' else 'alert'), text) + + +def panel(title, body, sub='', right='', flush=False, cls=''): + head = '

%s

%s%s
' % ( + title, '%s' % sub if sub else '', '
%s
' % right if right else '') if title else '' + return '
%s%s
' % (cls, head, body if flush else '
%s
' % body) + + +# ---------------------------------------------------------------- request handling + +class Handler(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + server_version = 'ForeverSupport/1' + + def do_GET(self): + self.route('GET') + + def do_POST(self): + self.route('POST') + + def log_message(self, fmt, *args): + pass + + # ---- plumbing + + def route(self, method): + url = urlsplit(self.path) + self.query = {k: v[0] for k, v in parse_qs(url.query).items()} + self.form = {} + if method == 'POST': + length = min(int(self.headers.get('Content-Length') or 0), 64 * 1024) + self.form = {k: v[0] for k, v in parse_qs(self.rfile.read(length).decode('utf-8', 'replace')).items()} + self.cookies = SimpleCookie(self.headers.get('Cookie') or '') + sid = self.cookies['fsid'].value if 'fsid' in self.cookies else '' + self.session = get_session(sid) if sid else None + self.route_path = url.path.rstrip('/') or '/' + path = self.route_path + if not path.startswith('/static/'): + log(method, path, '(session)' if self.session else '') + try: + if path.startswith('/static/'): + return self.static(path[len('/static/'):]) + if path in ('/s', '/sso', '/login/sso'): + return self.sso() + if path in DIRECT_ENTRY: + return self.direct_entry(DIRECT_ENTRY[path]) + if path == '/verify' and method == 'POST': + return self.verify() + if path == '/armory' or path.startswith('/armory/'): + return self.armory(path) + if path == '/favicon.ico': + return self.send(404, b'', 'text/plain') + if not self.session: + return self.page('Support', alert('info', 'Please open this page from the game: press Help (the question mark) ' + 'in the main menu.'), status=403) + if method == 'POST' and not hmac.compare_digest(self.form.get('csrf', ''), self.session['csrf']): + return self.page('Expired', alert('bad', 'This form has expired. Please go back and try again.'), status=400) + handler = ROUTES.get((method, path)) + if not handler: + return self.page('Not found', '

That page does not exist.

', status=404) + handler(self) + except Exception: + log('ERROR', traceback.format_exc()) + self.page('Error', alert('bad', 'Something went wrong on our side. Please try again in a moment.'), status=500) + + def send(self, status, body, content_type='text/html; charset=utf-8', headers=(), cache=False): + self.send_response(status) + self.send_header('Content-Type', content_type) + self.send_header('Content-Length', str(len(body))) + self.send_header('Cache-Control', 'public, max-age=300' if cache else 'no-store') + self.send_header('X-Frame-Options', 'DENY') + self.send_header('X-Content-Type-Options', 'nosniff') + for k, v in headers: + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def static(self, name): + ext = os.path.splitext(name)[1] + path = os.path.join(STATIC_DIR, os.path.basename(name)) + if ext not in STATIC_TYPES or not os.path.isfile(path): + return self.send(404, b'', 'text/plain') + with open(path, 'rb') as f: + self.send(200, f.read(), STATIC_TYPES[ext], cache=True) + + def redirect(self, location, headers=()): + self.send(303, b'', 'text/plain', [('Location', location), *headers]) + + def cookie(self, name, allowed, default): + value = self.cookies[name].value if name in self.cookies else default + return value if value in allowed else default + + def page(self, title, body, lead='', status=200, section='Support', head='', heading=True): + s = self.session + theme = self.cookie('fs_theme', ('dark', 'light'), 'dark') + size = self.cookie('fs_size', ('s', 'm', 'l'), 'm') + server = esc(CFG.get('server_name', 'Forever')) + + foot = '' + items = [] + if s: + answered = query_one(auth_db(), "SELECT COUNT(*) AS n FROM support_tickets WHERE battlenetAccountId = %s AND status = 'answered'", + (s['bnet'],))['n'] + items = [('/', 'home', 'Home', 0), ('/unstuck', 'pin', 'Unstuck', 0), ('/ticket/new?category=bug', 'bug', 'Report a bug', 0), + ('/ticket/new', 'help', 'Get help', 0), ('/tickets', 'tickets', 'My tickets', answered), ('/faq', 'book', 'FAQ', 0)] + if s['staff']: + waiting = query_one(auth_db(), "SELECT COUNT(*) AS n FROM support_tickets WHERE status = 'open'")['n'] + items.append(None) + items.append(('/staff', 'shield', 'Staff', waiting)) + items.append(None) + char = self.current_character() + foot = ('
%s
%s
') % ( + esc(realm_name(s['realm'])), + '
%s%s
' % ('Character', esc(char['name'])) if char else '') + items.append(('/armory', 'search', 'Armory', 0)) + current = self.route_path + ('?category=bug' if self.query.get('category') == 'bug' else '') + links = [] + for item in items: + if item is None: + links.append('
') + continue + href, ic, label, count = item + active = current == href or (href == '/tickets' and current == '/ticket') or (href == '/armory' and current.startswith('/armory')) + links.append('%s%s%s' % ( + esc(href), 'on' if active else '', esc(label), icon(ic), esc(label), '%d' % count if count else '')) + nav = '' % ''.join(links) + crumb = '%s %s' % (server, section) + (' · %s' % esc(title) if title != section else '') + + sizes = ''.join('' % ( + k, 'on' if k == size else '', t, l) for k, l, t in (('s', 'A-', 'Smaller text'), ('m', 'A', 'Normal text'), ('l', 'A+', 'Larger text'))) + # the game's Help window (BlizzardBrowser, 963 x 602) gets a compact layout + ingame = ' data-ingame="1"' if 'WorldOfWarcraft/' in (self.headers.get('User-Agent') or '') else '' + doc = ('' + '%s · %s %s' + '%s' + '
' + '
%s
%s
' + '
' + '
%s%s%s
') % ( + theme, size, esc(title), server, esc(section), head, '/' if s or section == 'Support' else '/armory', LOGO, server, esc(section), + nav, foot, crumb, sizes, icon('sun'), '

%s

' % esc(title) if heading else '', '

%s

' % lead if lead else '', body) + self.send(status, doc.encode('utf-8')) + + def csrf_field(self): + return '' % esc(self.session['csrf']) + + def current_character(self): + s = self.session + if not s or not s['char']: + return None + if 'char_row' not in s: + s['char_row'] = query_one(characters_db(s['realm']), 'SELECT guid, name, class FROM characters WHERE guid = %s AND account = %s', + (s['char'], s['account'])) + return s['char_row'] + + def characters(self): + return account_characters(self.session['realm'], self.session['account']) + + # ---- pages + + def sso(self): + token = self.query.get('token', '') + ref = self.query.get('ref', '') + row = query_one(auth_db(), 'SELECT * FROM battlenet_sso_tokens WHERE token = %s AND expires > UNIX_TIMESTAMP()', (token,)) if token else None + log('SSO', 'ok' if row else 'rejected', 'account', row['accountId'] if row else '-', 'ref', ref) + if not row: + self.session = None + return self.page('Support', alert('bad', 'Your support login has expired. Close this window and open Help again.'), status=403) + execute(auth_db(), 'DELETE FROM battlenet_sso_tokens WHERE token = %s', (token,)) + sid = start_session(row) + target = '/tickets' if 'ticket' in ref.lower() else '/' + self.redirect(target, [('Set-Cookie', 'fsid=%s; Path=/; HttpOnly; Secure; SameSite=Lax' % sid)]) + + def direct_entry(self, target): + """The Help window opens our URLs directly (the launcher points the client's Help URL at this site), without a token in the URL. + Who it is: a token this IP got a moment ago, else the character that is online from this IP. Several players behind one + address pick their character and type a code the server shows on that character's screen.""" + if self.session: + return self.redirect(target) + ip = self.client_address[0] + row = query_one(auth_db(), 'SELECT * FROM battlenet_sso_tokens WHERE ip = %s AND issued >= UNIX_TIMESTAMP() - %s ' + 'AND expires > UNIX_TIMESTAMP() ORDER BY issued DESC LIMIT 1', (ip, int(CFG.get('direct_entry_seconds', 30)))) + if row: + log('direct entry', ip, 'token, account', row['accountId']) + execute(auth_db(), 'DELETE FROM battlenet_sso_tokens WHERE token = %s', (row['token'],)) + return self.login(row, target) + + candidates = online_from_ip(ip) + log('direct entry', ip, '%d online character(s) from this address' % len(candidates)) + if len(candidates) == 1: + return self.login(candidates[0], target) + if not candidates: + return self.page('Support', alert('bad', 'We could not tell who you are. Log in to the game, then open Help again.'), status=403) + return self.verify_form(candidates, target) + + def login(self, row, target): + sid = start_session(row) + self.redirect(target, [('Set-Cookie', 'fsid=%s; Path=/; HttpOnly; Secure; SameSite=Lax' % sid)]) + + def verify_form(self, candidates, target, note=''): + options = ''.join('' % ( + i, ' checked' if i == 0 else '', esc(c['characterName']), esc(realm_name(c['realmId']))) for i, c in enumerate(candidates)) + one = same_player(candidates) + body = note + panel('Which character are you?', ( + '

%s

%s
' + '
') % ( + 'You have several characters online. Which one needs help?' if one else + 'Several players are connected from your network. Pick your character and we will show a code on its screen.', + options, esc(target), 'Continue' if one else 'Send me a code')) + self.page('Support', body) + + def verify(self): + ip = self.client_address[0] + candidates = online_from_ip(ip) + target = self.form.get('t', '/') if self.form.get('t', '/') in DIRECT_ENTRY.values() else '/' + pid = self.form.get('p', '') + if pid: + with PENDING_LOCK: + pend = PENDING.get(pid) + if pend: + pend['tries'] += 1 + if not pend or pend['expires'] < time.time() or pend['ip'] != ip or pend['tries'] > 5: + return self.verify_form(candidates, target, alert('bad', 'That code has expired. Please ask for a new one.')) if candidates else \ + self.page('Support', alert('bad', 'Log in to the game, then open Help again.'), status=403) + if not hmac.compare_digest(self.form.get('code', '').strip(), pend['code']): + return self.code_form(pid, pend, alert('bad', 'That code is not right. Check your game screen.')) + with PENDING_LOCK: + PENDING.pop(pid, None) + return self.login(pend['row'], pend['target']) + try: + choice = candidates[int(self.form.get('c', '-1'))] + except (ValueError, IndexError): + return self.verify_form(candidates, target) if candidates else self.redirect('/kb') + if same_player(candidates): # multiboxing on one battle.net account: one person, no code needed + return self.login(choice, target) + code = '%06d' % secrets.randbelow(1000000) + out = ra_command(choice['realmId'], 'send message %s Support website code: %s' % (choice['characterName'], code)) if ra_available(choice['realmId']) else None + if out is None: + return self.page('Support', alert('bad', 'We cannot send codes right now. Please try again later.'), status=503) + pid = secrets.token_urlsafe(18) + pend = {'row': choice, 'code': code, 'ip': ip, 'target': target, 'expires': time.time() + 300, 'tries': 0} + with PENDING_LOCK: + for old in [k for k, v in PENDING.items() if v['expires'] < time.time()]: + del PENDING[old] + PENDING[pid] = pend + log('verify code sent to', choice['characterName']) + self.code_form(pid, pend) + + def code_form(self, pid, pend, note=''): + self.page('Support', note + panel('Enter your code', ( + '

A 6-digit code is now shown on %s\'s screen.

' + '
' + '
') % (esc(pend['row']['characterName']), esc(pid)))) + + def home(self): + s = self.session + char = self.current_character() + tiles = [ + ('/unstuck', 'pin', 'Unstuck', 'Stuck in the world? Send a character to its inn or the nearest graveyard.'), + ('/ticket/new?category=bug', 'bug', 'Report a bug', 'Quests, creatures, spells or items that do not work as they should.'), + ('/ticket/new?category=stuck', 'alert', 'Still stuck', 'Unstuck did not help? A game master will move you.'), + ('/ticket/new', 'help', 'Get help', 'Account, character or player problems, and everything else.'), + ('/tickets', 'tickets', 'My tickets', 'Follow your reports and read replies from the staff.'), + ('/faq', 'book', 'FAQ', 'Answers to the most common questions.'), + ] + body = '' + if CFG.get('news_html'): + body += panel('News', CFG['news_html'], cls='accent') + body += '
%s
' % ''.join( + '%s%s%s' % (esc(h), icon(i), esc(t), esc(d)) + for h, i, t, d in tiles) + recent = query(auth_db(), 'SELECT id, category, subject, status, updated FROM support_tickets WHERE battlenetAccountId = %s ' + 'ORDER BY updated DESC LIMIT 5', (s['bnet'],)) + if recent: + body += panel('Your latest tickets', self.ticket_rows(recent, False), right='See all', flush=True) + lead = ('Hello %s. ' % char_name(char) if char else 'Hello. ') + 'What can we help you with?' + self.page('Support', '
%s
' % body, lead) + + def faq(self): + entries = CFG.get('faq') or [] + items = ''.join('
%s%s
%s
' % (esc(q), icon('chevron', 'i sm'), a) + for q, a in entries) + self.page('Frequently asked questions', panel('', items or '
Nothing here yet.
', flush=True), + 'Can\'t find your answer? Ask us.') + + # unstuck + + def unstuck_form(self, note=''): + s = self.session + chars = self.characters() + cooldown = int(CFG.get('unstuck_cooldown_minutes', 15)) + if chars: + rows = ''.join( + '%s%d' + '%s %s%s' % ( + c['guid'], ' checked' if c['guid'] == s['char'] or len(chars) == 1 else '', char_name(c), faction(c['race']), c['level'], + esc(RACES.get(c['race'], '')), c['class'], esc(CLASSES.get(c['class'], '')), '' if c['online'] else ' off', + 'Online' if c['online'] else 'Offline') for c in chars) + table = ('
' + '%s
CharacterH/ALevelClassStatus
') % rows + else: + table = '
No characters on this realm.
' + dest = ('
Send the character to
' + '' + '
' + '
' + 'Still stuck? Ask a game master
') % icon('pin', 'i sm') + form = '
%s%s
' % (self.csrf_field(), panel('Choose a character', table + dest, flush=True)) + self.page('Unstuck', note + form, + 'Moves a character that is stuck in the world. Works once every %d minutes per character, not in combat or on a flight path.' + % cooldown) + + def unstuck(self): + s = self.session + try: + guid = int(self.form.get('guid', '0')) + except ValueError: + guid = 0 + dest = self.form.get('dest', 'inn') + if dest not in ('inn', 'graveyard'): + dest = 'inn' + char = next((c for c in self.characters() if c['guid'] == guid), None) + if not char: + return self.unstuck_form(alert('bad', 'Please pick one of your characters.')) + + cooldown = int(CFG.get('unstuck_cooldown_minutes', 15)) * 60 + last = query_one(auth_db(), "SELECT MAX(time) AS t FROM support_unstuck_log WHERE realmId = %s AND characterGuid = %s AND result = 'ok'", + (s['realm'], guid))['t'] + if last and time.time() - last < cooldown: + wait = int((cooldown - (time.time() - last)) // 60) + 1 + return self.unstuck_form(alert('bad', '%s was moved recently. Try again in %d minute%s.' % (char_name(char), wait, '' if wait == 1 else 's'))) + + if ra_available(s['realm']): + out = ra_command(s['realm'], 'unstuck %s %s' % (char['name'], dest)) + ok = not out + elif not char['online']: + # no console access configured: do what the console command does for offline characters (inn only) + home = query_one(characters_db(s['realm']), 'SELECT mapId, zoneId, posX, posY, posZ, orientation FROM character_homebind WHERE guid = %s', (guid,)) + if home: + execute(characters_db(s['realm']), + "UPDATE characters SET position_x = %s, position_y = %s, position_z = %s, orientation = %s, map = %s, zone = %s, " + "trans_x = 0, trans_y = 0, trans_z = 0, transguid = 0, taxi_path = '', cinematic = 1 WHERE guid = %s AND online = 0", + (home['posX'], home['posY'], home['posZ'], home['orientation'], home['mapId'], home['zoneId'], guid)) + dest = 'inn' + ok, out = bool(home), '' if home else 'no hearthstone location' + else: + return self.unstuck_form(alert('bad', 'Online unstuck is not available right now. Log out to character select and try again.')) + + execute(auth_db(), 'INSERT INTO support_unstuck_log (accountId, realmId, characterGuid, destination, result, time) VALUES (%s, %s, %s, %s, %s, %s)', + (s['account'], s['realm'], guid, dest, 'ok' if ok else out[:255], int(time.time()))) + log('unstuck', char['name'], dest, 'ok' if ok else out) + if ok: + self.unstuck_form(alert('ok', '%s has been moved to %s.' % (char_name(char), 'its inn' if dest == 'inn' else 'the nearest graveyard'))) + else: + self.unstuck_form(alert('bad', 'That did not work: %s. Leave combat or finish your flight, then try again.' % esc(out or 'unknown error'))) + + # tickets + + def ticket_new_form(self, note='', values=None): + values = values or {} + category = values.get('category') or self.query.get('category', 'other') + if category not in CATEGORIES: + category = 'other' + hints = { + 'bug': 'What happened, what did you expect, and how can we make it happen again? Quest, creature or item names help a lot.', + 'stuck': 'Where are you stuck and what did you try? Your character\'s position is attached for us.', + 'player': 'Who, when, where and what happened.', + } + cats = ''.join('' % ( + k, k, ' checked' if k == category else '', k, esc(v)) for k, v in CATEGORIES.items()) + selected = int(values.get('guid') or self.session['char'] or 0) + chars = ''.join('' % ( + c['guid'], ' selected' if c['guid'] == selected else '', esc(c['name']), c['level'], esc(CLASSES.get(c['class'], ''))) + for c in self.characters()) + form = ('
%s' + '
Type
%s
' + '
Character
' + '
Subject
' + '
Details
' + '
' + 'We reply here and send you an in-game mail.
') % ( + self.csrf_field(), cats, chars, SUBJECT_MAX, esc(values.get('subject', '')), MESSAGE_MAX, + esc(hints.get(category, 'Tell us as much as you can.')), esc(values.get('message', '')), icon('send', 'i sm')) + title = 'Report a bug' if category == 'bug' else 'Get help' + lead = ('Thanks for helping us find problems. The more detail, the faster we can fix it.' if category == 'bug' + else 'Tell us what is going on and a game master will get back to you.') + self.page(title, note + panel('', form), lead) + + def ticket_create(self): + s = self.session + f = self.form + category = f.get('category', 'other') + subject = f.get('subject', '').strip()[:SUBJECT_MAX] + message = f.get('message', '').strip()[:MESSAGE_MAX] + if category not in CATEGORIES or not subject or not message: + return self.ticket_new_form(alert('bad', 'Please fill in a subject and the details.'), f) + open_count = query_one(auth_db(), "SELECT COUNT(*) AS n FROM support_tickets WHERE battlenetAccountId = %s AND status <> 'closed'", + (s['bnet'],))['n'] + if open_count >= MAX_OPEN_TICKETS: + return self.ticket_new_form(alert('bad', 'You already have %d open tickets. Please wait for a reply or close one.' % open_count), f) + try: + guid = int(f.get('guid', '0')) + except ValueError: + guid = 0 + char = next((c for c in self.characters() if c['guid'] == guid), None) + now = int(time.time()) + ticket_id = execute(auth_db(), + 'INSERT INTO support_tickets (battlenetAccountId, accountId, realmId, characterGuid, characterName, category, subject, message, ' + 'mapId, zoneId, posX, posY, posZ, status, created, updated) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', + (s['bnet'], s['account'], s['realm'], char['guid'] if char else 0, char['name'] if char else '', category, subject, + message, char['map'] if char else 0, char['zone'] if char else 0, char['position_x'] if char else 0, + char['position_y'] if char else 0, char['position_z'] if char else 0, 'open', now, now)) + log('ticket', ticket_id, category, 'by account', s['account']) + self.redirect('/ticket?id=%d&new=1' % ticket_id) + + def load_ticket(self, ticket_id): + try: + ticket_id = int(ticket_id) + except (TypeError, ValueError): + return None + ticket = query_one(auth_db(), 'SELECT * FROM support_tickets WHERE id = %s', (ticket_id,)) + if not ticket or (ticket['battlenetAccountId'] != self.session['bnet'] and not self.session['staff']): + return None + return ticket + + def ticket_list(self): + tickets = query(auth_db(), 'SELECT id, category, subject, status, updated FROM support_tickets WHERE battlenetAccountId = %s ' + 'ORDER BY status = \'closed\', updated DESC LIMIT 100', (self.session['bnet'],)) + new = '%sNew ticket' % icon('plus', 'i sm') + self.page('My tickets', panel('Tickets', self.ticket_rows(tickets, False), sub='· %d' % len(tickets), right=new, flush=True), + 'Everything you sent us, newest first. Tickets with a staff reply are marked green.') + + def ticket_rows(self, tickets, staff): + if not tickets: + return '
No tickets.
' + head = '#Subject%sTypeStatusUpdated' % ( + 'Character' if staff else '') + rows = ''.join('%d%s%s%s' + '%s%s' % ( + t['id'], t['id'], esc(t['subject']), '%s' % esc(t.get('characterName') or '-') if staff else '', + esc(CATEGORIES.get(t['category'], t['category'])), status_tag(t['status']), fmt_time(t['updated']), fmt_ago(t['updated'])) + for t in tickets) + return '
%s%s
' % (head, rows) + + def ticket_view(self): + ticket = self.load_ticket(self.query.get('id')) + if not ticket: + return self.page('Not found', '

That ticket does not exist.

', status=404) + s = self.session + replies = query(auth_db(), 'SELECT * FROM support_ticket_replies WHERE ticketId = %s ORDER BY id', (ticket['id'],)) + body = alert('ok', 'Thanks! Your ticket has been sent. Staff replies show up here.') if self.query.get('new') else '' + + author = esc(ticket['characterName'] or 'You') + events = ['
  • %s%s opened the ticket%s' + '
    %s
  • ' % (icon('user', 'i sm'), author, fmt_time(ticket['created']), esc(ticket['message']))] + for r in replies: + who = 'Staff' if r['isStaff'] else author + events.append('
  • %s%s replied%s' + '
    %s
  • ' % ('staff' if r['isStaff'] else 'muted', icon('shield' if r['isStaff'] else 'user', 'i sm'), + who, fmt_time(r['created']), esc(r['message']))) + conv = panel('Conversation', '
      %s
    ' % ''.join(events), right=status_tag(ticket['status']), flush=True) + if ticket['status'] != 'closed': + conv += panel('', ('
    %s' + '
    Reply
    ' + '
    ') % ( + self.csrf_field(), ticket['id'], MESSAGE_MAX, icon('send', 'i sm'))) + + details = [('Type', esc(CATEGORIES.get(ticket['category'], ticket['category']))), ('Status', status_tag(ticket['status'])), + ('Opened', fmt_time(ticket['created'])), ('Updated', fmt_ago(ticket['updated']))] + if ticket['characterName']: + details.append(('Character', esc(ticket['characterName']))) + if s['staff']: + details += [('Account', '%d (bnet %d)' % (ticket['accountId'], ticket['battlenetAccountId'])), ('Realm', esc(realm_name(ticket['realmId']))), + ('Position', 'map %d zone %d
    %.1f %.1f %.1f
    ' % ( + ticket['mapId'], ticket['zoneId'], ticket['posX'], ticket['posY'], ticket['posZ']))] + info = '
    %s
    ' % ''.join( + '%s%s' % (k, v) for k, v in details) + action = 'reopen' if ticket['status'] == 'closed' else 'close' + if action == 'close' or s['staff']: + info += ('
    %s' + '
    ') % ( + self.csrf_field(), ticket['id'], action, 'danger' if action == 'close' else '', icon('x' if action == 'close' else 'undo', 'i sm'), + action.title()) + body += '
    %s
    %s
    ' % (conv, panel('Details', info, flush=True)) + self.page('#%d %s' % (ticket['id'], ticket['subject']), body) + + def ticket_reply(self): + ticket = self.load_ticket(self.form.get('id')) + message = self.form.get('message', '').strip()[:MESSAGE_MAX] + if not ticket or ticket['status'] == 'closed' or not message: + return self.redirect('/ticket?id=%d' % ticket['id'] if ticket else '/tickets') + s = self.session + is_staff_reply = s['staff'] and ticket['battlenetAccountId'] != s['bnet'] + now = int(time.time()) + execute(auth_db(), 'INSERT INTO support_ticket_replies (ticketId, accountId, isStaff, message, created) VALUES (%s, %s, %s, %s, %s)', + (ticket['id'], s['account'], 1 if is_staff_reply else 0, message, now)) + execute(auth_db(), 'UPDATE support_tickets SET status = %s, updated = %s WHERE id = %s', + ('answered' if is_staff_reply else 'open', now, ticket['id'])) + if is_staff_reply: + self.notify_player(ticket) + self.redirect('/ticket?id=%d' % ticket['id']) + + def notify_player(self, ticket): + """Tells the player in game (by mail) that staff replied, when RA is configured.""" + if not CFG.get('notify_by_mail', True) or not ticket['characterName'] or not ra_available(ticket['realmId']): + return + try: + out = ra_command(ticket['realmId'], 'send mail %s "%s" "%s"' % ( + ticket['characterName'], ra_quote('Support ticket #%d answered' % ticket['id']), + ra_quote('A game master replied to your ticket "%s". Open Help (question mark) > My tickets to read it.' % ticket['subject']))) + log('notify', ticket['id'], out) + except Exception as e: + log('notify failed', ticket['id'], e) + + def ticket_status(self): + ticket = self.load_ticket(self.form.get('id')) + action = self.form.get('action') + if ticket and (action == 'close' or (action == 'reopen' and self.session['staff'])): + execute(auth_db(), 'UPDATE support_tickets SET status = %s, updated = %s WHERE id = %s', + ('closed' if action == 'close' else 'open', int(time.time()), ticket['id'])) + self.redirect('/ticket?id=%d' % ticket['id'] if ticket else '/tickets') + + # armory (public) + + def armory(self, path): + ip = self.client_address[0] + parts = [p for p in path.split('/') if p][1:] + bucket, limit = ('search', int(CFG.get('armory_search_per_minute', 20))) if not parts else ('page', int(CFG.get('armory_pages_per_minute', 60))) + if not rate_ok(ip, bucket, limit): + return self.page('Slow down', alert('bad', 'Too many requests. Please wait a minute and try again.'), status=429, section='Armory') + if not parts: + return self.armory_search() + if len(parts) == 2 and parts[0].isdigit(): + return self.armory_character(int(parts[0]), parts[1]) + return self.page('Not found', '

    That page does not exist.

    ', status=404, section='Armory') + + def armory_search(self): + q = ' '.join(self.query.get('q', '').split())[:60] + form = ('') % (esc(q), icon('search', 'i sm')) + if len(q) < 2: + return self.page('Armory', form, 'Look up any character on %s: type a name, a surname, or both.' % esc(CFG.get('server_name', 'Forever')), + section='Armory') + first, _, last = q.partition(' ') + like = lambda s: s.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + '%' + results = [] + for realm_id in CFG['realms']: + if last: + where, args = 'name LIKE %s AND surname LIKE %s', (like(first), like(last)) + else: + where, args = '(name LIKE %s OR surname LIKE %s)', (like(first), like(first)) + for c in query(characters_db(realm_id), 'SELECT name, surname, race, class, level, online FROM characters ' + 'WHERE deleteInfos_Account IS NULL AND ' + where + ' ORDER BY level DESC, name LIMIT 50', args): + c['realm'] = int(realm_id) + results.append(c) + results.sort(key=lambda c: (-c['level'], c['name'])) + races, classes = names('race'), names('class') + if results: + rows = ''.join( + '%s%s%s%d' + '%s %s%s' % ( + c['realm'], esc(c['name']), c['class'], esc(c['name']), ' %s' % esc(c['surname']) if c['surname'] else '', + faction(c['race']), c['level'], esc(races.get(c['race'], ('',))[0]), c['class'], esc(classes.get(c['class'], ('',))[0]), + esc(realm_name(c['realm']))) for c in results[:100]) + body = form + panel('Characters', '
    ' + '%s
    CharacterH/ALevelClassRealm
    ' % rows, + sub='· %d' % len(results), flush=True) + else: + body = form + panel('', '
    No character found for "%s".
    ' % esc(q), flush=True) + self.page('Armory', body, section='Armory') + + def armory_character(self, realm_id, name): + if str(realm_id) not in CFG['realms']: + return self.page('Not found', '

    That realm does not exist.

    ', status=404, section='Armory') + cdb = characters_db(realm_id) + c = query_one(cdb, 'SELECT guid, name, surname, race, class, gender, level, totalKills, todayKills, online FROM characters ' + 'WHERE name = %s AND deleteInfos_Account IS NULL', (name,)) + if not c: + return self.page('Not found', '

    No character called %s on %s.

    ' % (esc(name), esc(realm_name(realm_id))), + status=404, section='Armory') + guild = query_one(cdb, 'SELECT g.name FROM guild_member m JOIN guild g ON g.guildid = m.guildid WHERE m.guid = %s', (c['guid'],)) + gear = {r['slot']: r['itemEntry'] for r in query(cdb, 'SELECT ci.slot, ii.itemEntry FROM character_inventory ci JOIN item_instance ii ' + 'ON ii.guid = ci.item WHERE ci.guid = %s AND ci.bag = 0 AND ci.slot < 19', (c['guid'],))} + tips = item_tooltip_data(sorted(set(gear.values()))) + races, classes, skills = names('race'), names('class'), names('skill') + + def slot(s): + entry = gear.get(s) + tip = tips.get(entry) + if not tip: + return '
    ' % esc(SLOT_NAMES[s]) + return '
    %s
    ' % (tip['q'], entry, esc(tip['icon']), esc(tip['name'])) + + portrait = icon_url(CLASS_ICONS.get(c['class'])) + doll = ('
    %s
    %s
    %s' + '
    %s
    %s
    ') % ( + ''.join(slot(s) for s in DOLL_LEFT), esc(portrait), esc(races.get(c['race'], ('',))[0]), esc(classes.get(c['class'], ('',))[0]), + ''.join(slot(s) for s in DOLL_RIGHT), ''.join(slot(s) for s in DOLL_BOTTOM)) + + st = query_one(cdb, 'SELECT * FROM character_stats WHERE guid = %s', (c['guid'],)) + if st: + groups = [('Attributes', [('Strength', st['strength']), ('Agility', st['agility']), ('Stamina', st['stamina']), ('Intellect', st['intellect']), + ('Spirit', st['spirit'])]), + ('Melee', [('Attack power', st['attackPower']), ('Critical', '%.2f%%' % st['critPct']), ('Dodge', '%.2f%%' % st['dodgePct']), + ('Parry', '%.2f%%' % st['parryPct'])]), + ('Ranged & spell', [('Ranged power', st['rangedAttackPower']), ('Ranged critical', '%.2f%%' % st['rangedCritPct']), + ('Spell critical', '%.2f%%' % st['spellCritPct']), ('Spell power', st['spellPower'])]), + ('Defense', [('Armor', st['armor']), ('Health', st['maxhealth']), ('Block', '%.2f%%' % st['blockPct']), + ('Resilience', st['resilience'])]), + ('Resistances', [('Arcane', st['resArcane']), ('Fire', st['resFire']), ('Nature', st['resNature']), ('Frost', st['resFrost']), + ('Shadow', st['resShadow'])])] + stats = '
    %s
    ' % ''.join( + '

    %s

    %s
    ' % (g, ''.join('
    %s%s
    ' % (k, esc(v)) for k, v in rows)) + for g, rows in groups) + else: + stats = '
    Stats appear after the character logs out once.
    ' + + sk = query(cdb, 'SELECT skill, value, max FROM character_skills WHERE guid = %s', (c['guid'],)) + def skill_rows(category): + # Classic has a parent and a child skill line with the same name (Cooking 185 and 2939): one row per name, highest value; + # racial lines can carry the secondary-skill category + best = {} + for r in sk: + n = skills.get(r['skill']) + if not n or n[2] != category or 'Racial' in n[0]: + continue + if n[0] not in best or (r['value'], r['max']) > (best[n[0]][1]['value'], best[n[0]][1]['max']): + best[n[0]] = (n, r) + rows = list(best.values()) + return ''.join('
    %s%d / %d
    ' % ( + esc(icon_url(n[1], 'medium')), esc(n[0]), r['value'], r['max']) for n, r in sorted(rows, key=lambda x: x[0][0])) or \ + '
    None
    ' + + achs = names('achievement') + recent = query(cdb, 'SELECT achievement, date FROM character_achievement WHERE guid = %s ORDER BY date DESC LIMIT 6', (c['guid'],)) + recent_html = ''.join('
    %s%s
    ' % ( + esc(icon_url(achs.get(a['achievement'], ('', ''))[1], 'medium')), esc(achs.get(a['achievement'], ('Achievement %d' % a['achievement'],))[0]), + fmt_ago(a['date'])) for a in recent) or '
    Nothing yet
    ' + + side = ('
    %s%s%s%s
    ') % ( + panel('Professions', skill_rows(SKILL_PROFESSION)), panel('Secondary skills', skill_rows(SKILL_SECONDARY)), + panel('Player vs Player', '
    Honorable kills%d
    Kills today' + '%d
    ' % (c['totalKills'], c['todayKills'])), + panel('Recent achievements', recent_html)) + header = ('

    %s%s

    Level %d %s %s · %s%s

    ' + '
    %s%s
    ') % ( + c['class'], esc(c['name']), ' %s' % esc(c['surname']) if c['surname'] else '', c['level'], + esc(races.get(c['race'], ('',))[0]), c['class'], esc(classes.get(c['class'], ('',))[0]), esc(realm_name(realm_id)), + ' · <%s>' % esc(guild['name']) if guild else '', faction(c['race']), ' Online' if c['online'] else '') + body = header + '
    %s%s
    ' % ('
    %s%s
    ' % (panel('Equipment', doll), panel('Character stats', stats)), side) + data = '' % (json.dumps( + {str(k): v for k, v in tips.items()}).replace('That page does not exist.

    ', status=404) + status = self.query.get('status', 'open') + if status not in STATUS: + status = 'open' + counts = {r['status']: r['n'] for r in query(auth_db(), 'SELECT status, COUNT(*) AS n FROM support_tickets GROUP BY status')} + tickets = query(auth_db(), 'SELECT id, characterName, category, subject, status, updated FROM support_tickets WHERE status = %s ' + 'ORDER BY updated ' + ('ASC' if status == 'open' else 'DESC') + ' LIMIT 200', (status,)) + tabs = '
    %s
    ' % ''.join('%s%d' % ( + urlencode({'status': k}), 'on' if k == status else '', esc(label), counts.get(k, 0)) for k, (label, _) in STATUS.items()) + self.page('Staff', panel('Tickets', self.ticket_rows(tickets, True), right=tabs, flush=True), + 'Every ticket from every player. Oldest waiting first, so nobody is forgotten.') + + +# URLs the client itself opens (GlobalStrings VISITABLE_URL50/6/7 hotfix) -> page +DIRECT_ENTRY = { + '/kb': '/', + '/help/ticket': '/ticket/new', + '/help/tickets': '/tickets', +} + +ROUTES = { + ('GET', '/'): Handler.home, + ('GET', '/faq'): Handler.faq, + ('GET', '/unstuck'): Handler.unstuck_form, + ('POST', '/unstuck'): Handler.unstuck, + ('GET', '/ticket/new'): Handler.ticket_new_form, + ('POST', '/ticket/new'): Handler.ticket_create, + ('GET', '/tickets'): Handler.ticket_list, + ('GET', '/ticket'): Handler.ticket_view, + ('POST', '/ticket/reply'): Handler.ticket_reply, + ('POST', '/ticket/status'): Handler.ticket_status, + ('GET', '/staff'): Handler.staff, +} + + +def load_config(path): + global CFG + with open(path, encoding='utf-8') as f: + CFG = json.load(f) + + +def ensure_armory_export(): + """The armory needs world.armory_item/armory_name (".armory export" on a worldserver); run it through RA if they are empty.""" + try: + if query_one(world_db(), 'SELECT COUNT(*) AS n FROM armory_item')['n']: + return + for realm_id in CFG['realms']: + if ra_available(realm_id): + log('armory: tables empty, running "armory export" on realm', realm_id, '->', ra_command(realm_id, 'armory export')) + return + except Exception as e: + log('armory export failed:', e) + + +def make_token(bnet_account_id, realm_id): + account = query_one(auth_db(), 'SELECT id FROM account WHERE battlenet_account = %s ORDER BY battlenet_index LIMIT 1', (bnet_account_id,)) + if not account: + sys.exit('no game account for battle.net account %s' % bnet_account_id) + token = 'TUS-%s-%s' % (secrets.token_hex(16), bnet_account_id) + now = int(time.time()) + execute(auth_db(), 'INSERT INTO battlenet_sso_tokens (token, battlenetAccountId, accountId, realmId, characterGuid, issued, expires, ip) ' + 'VALUES (%s, %s, %s, %s, 0, %s, %s, %s)', (token, bnet_account_id, account['id'], realm_id, now, now + 3600, '127.0.0.1')) + print('https://%s:%d/s?%s' % (CFG.get('public_host', 'trinity.actual.battle.net'), int(CFG.get('port', 443)), + urlencode({'token': token, 'ref': 'test'}))) + + +def main(): + args = sys.argv[1:] + if args and args[0] == '--make-token': + load_config(args[3] if len(args) > 3 else os.path.join(HERE, 'support_site.json')) + return make_token(int(args[1]), int(args[2])) + load_config(args[0] if args else os.path.join(HERE, 'support_site.json')) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(CFG['cert'], CFG['key']) + threading.Thread(target=ensure_armory_export, daemon=True).start() + srv = ThreadingHTTPServer((CFG.get('listen', '0.0.0.0'), int(CFG.get('port', 443))), Handler) + srv.socket = ctx.wrap_socket(srv.socket, server_side=True) + log('support site on port', CFG.get('port', 443), '- RA', 'configured' if (CFG.get('ra') or {}).get('user') else 'not configured') + srv.serve_forever() + + +if __name__ == '__main__': + main() diff --git a/contrib/support_site/support_site.example.json b/contrib/support_site/support_site.example.json new file mode 100644 index 0000000000..b421c46a40 --- /dev/null +++ b/contrib/support_site/support_site.example.json @@ -0,0 +1,60 @@ +{ + "server_name": "Forever", + "listen": "0.0.0.0", + "port": 443, + "public_host": "trinity.actual.battle.net", + "cert": "F:/wow stuff/classic_re/certs/trinity_forever.cert.pem", + "key": "F:/wow stuff/classic_re/certs/trinity_forever.key.pem", + "db": { + "host": "127.0.0.1", + "port": 3307, + "user": "trinity", + "password": "trinity", + "auth": "auth", + "world": "world" + }, + "realms": { + "70": { + "characters": "characters", + "ra_port": 3443 + }, + "71": { + "characters": "characters_pvp", + "ra_port": 3444 + }, + "72": { + "characters": "characters_rp", + "ra_port": 3445 + }, + "73": { + "characters": "characters_hc", + "ra_port": 3446 + } + }, + "ra": { + "host": "127.0.0.1", + "user": "", + "password": "" + }, + "staff_min_level": 2, + "unstuck_cooldown_minutes": 15, + "notify_by_mail": true, + "news_html": "", + "faq": [ + [ + "My character is stuck, what can I do?", + "Use Unstuck. If that does not help, ask a game master." + ], + [ + "How do I report a bug?", + "Use Report a bug while logged in with the character that saw it; its position is attached for us." + ], + [ + "How do I know staff answered?", + "You get an in-game mail, and the ticket shows up as \"Staff replied\" under My tickets." + ] + ], + "icon_cdn": "https://wow.zamimg.com/images/wow/icons", + "armory_search_per_minute": 20, + "armory_pages_per_minute": 60 +} \ No newline at end of file diff --git a/sql/custom/auth/2026_10_03_00_auth_support.sql b/sql/custom/auth/2026_10_03_00_auth_support.sql new file mode 100644 index 0000000000..3d5909996a --- /dev/null +++ b/sql/custom/auth/2026_10_03_00_auth_support.sql @@ -0,0 +1,61 @@ +-- Classic 1.60: tokens handed to the in-game browser (Support window) by SMSG_GENERATE_SSO_TOKEN_RESPONSE. +-- The client opens ?token=&ref=; our support site looks the token up here to know the account and character. +CREATE TABLE IF NOT EXISTS `battlenet_sso_tokens` ( + `token` varchar(64) NOT NULL, + `battlenetAccountId` int unsigned NOT NULL, + `accountId` int unsigned NOT NULL COMMENT 'game account', + `realmId` int unsigned NOT NULL COMMENT 'realm (worldserver) that issued it', + `characterGuid` bigint unsigned NOT NULL DEFAULT '0' COMMENT 'character in world when issued, 0 = character select', + `issued` bigint NOT NULL, + `expires` bigint NOT NULL, + `ip` varchar(45) NOT NULL DEFAULT '', + PRIMARY KEY (`token`), + KEY `idx_expires` (`expires`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Support site (contrib/support_site): tickets, replies, unstuck history +CREATE TABLE IF NOT EXISTS `support_tickets` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `battlenetAccountId` int unsigned NOT NULL, + `accountId` int unsigned NOT NULL, + `realmId` int unsigned NOT NULL, + `characterGuid` bigint unsigned NOT NULL DEFAULT '0', + `characterName` varchar(12) NOT NULL DEFAULT '', + `category` enum('bug','stuck','account','player','other') NOT NULL, + `subject` varchar(120) NOT NULL, + `message` text NOT NULL, + `mapId` int unsigned NOT NULL DEFAULT '0', + `zoneId` int unsigned NOT NULL DEFAULT '0', + `posX` float NOT NULL DEFAULT '0', + `posY` float NOT NULL DEFAULT '0', + `posZ` float NOT NULL DEFAULT '0', + `status` enum('open','answered','closed') NOT NULL DEFAULT 'open', + `created` bigint NOT NULL, + `updated` bigint NOT NULL, + PRIMARY KEY (`id`), + KEY `idx_account` (`battlenetAccountId`), + KEY `idx_status` (`status`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `support_ticket_replies` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `ticketId` int unsigned NOT NULL, + `accountId` int unsigned NOT NULL, + `isStaff` tinyint unsigned NOT NULL DEFAULT '0', + `message` text NOT NULL, + `created` bigint NOT NULL, + PRIMARY KEY (`id`), + KEY `idx_ticket` (`ticketId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS `support_unstuck_log` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `accountId` int unsigned NOT NULL, + `realmId` int unsigned NOT NULL, + `characterGuid` bigint unsigned NOT NULL, + `destination` enum('inn','graveyard') NOT NULL, + `result` varchar(255) NOT NULL DEFAULT '', + `time` bigint NOT NULL, + PRIMARY KEY (`id`), + KEY `idx_character` (`realmId`,`characterGuid`,`time`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/sql/custom/world/2026_10_03_02_world_forever_stealth_bandits.sql b/sql/custom/world/2026_10_03_02_world_forever_stealth_bandits.sql new file mode 100644 index 0000000000..3a6b67df6d --- /dev/null +++ b/sql/custom/world/2026_10_03_02_world_forever_stealth_bandits.sql @@ -0,0 +1,5 @@ +-- Classic 1.60 (WoW Forever): Hungry Bandits (252802) are stealthed (official beta sniff 70170: they cast Sneak 22766 = stealth + +-- slower movement, and carry Sneak 7939, a dummy aura of the client). As addon auras they are applied at spawn and again after +-- evading. Safe to run again. +INSERT INTO `creature_template_addon` (`entry`, `auras`) VALUES (252802, '22766 7939') +ON DUPLICATE KEY UPDATE `auras` = '22766 7939'; diff --git a/sql/custom/world/2026_10_03_03_world_forever_energizing_vortex.sql b/sql/custom/world/2026_10_03_03_world_forever_energizing_vortex.sql new file mode 100644 index 0000000000..de20af2cf4 --- /dev/null +++ b/sql/custom/world/2026_10_03_03_world_forever_energizing_vortex.sql @@ -0,0 +1,18 @@ +-- Classic 1.60 (WoW Forever): the Energizing Vortex (267599) tornadoes on Zephras Isle carry Energizing Winds (1299003, aura 395 = +-- area trigger, create properties 43253). Touching one gives Blessing of Zephras (1258510: run speed +40% for 5 min, ends on +-- hostile action), seen on the player in the official beta sniff (70170); the player casts it on himself +-- (classic_at_energizing_vortex), so leaving the moving trigger does not remove it. The shape is not in the client data: a 5 yd +-- sphere, about the size of the tornado model. Safe to run again. +DELETE FROM `areatrigger_template` WHERE `Id` = 43253 AND `IsCustom` = 1; +INSERT INTO `areatrigger_template` (`Id`, `IsCustom`, `Flags`, `ActionSetId`, `ActionSetFlags`, `VerifiedBuild`) VALUES +(43253, 1, 0, 0, 0, 0); + +DELETE FROM `areatrigger_template_actions` WHERE `AreaTriggerId` = 43253 AND `IsCustom` = 1; + +DELETE FROM `areatrigger_create_properties` WHERE `Id` = 43253 AND `IsCustom` = 0; +INSERT INTO `areatrigger_create_properties` (`Id`, `IsCustom`, `AreaTriggerId`, `IsAreatriggerCustom`, `Flags`, `MoveCurveId`, +`ScaleCurveId`, `MorphCurveId`, `FacingCurveId`, `AnimId`, `AnimKitId`, `DecalPropertiesId`, `SpellForVisuals`, `PositionalSoundKitId`, +`TimeToTargetScale`, `Speed`, `SpeedIsTime`, `Shape`, `ShapeData0`, `ShapeData1`, `ShapeData2`, `ShapeData3`, `ShapeData4`, +`ShapeData5`, `ShapeData6`, `ShapeData7`, `Roll`, `Pitch`, `Yaw`, `TargetRoll`, `TargetPitch`, `TargetYaw`, `ScriptName`, +`VerifiedBuild`) VALUES +(43253, 0, 43253, 1, 0, 0, 0, 0, 0, -1, -1, 0, NULL, 0, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'classic_at_energizing_vortex', 0); diff --git a/sql/custom/world/2026_10_03_04_world_forever_skycutter_announcements.sql b/sql/custom/world/2026_10_03_04_world_forever_skycutter_announcements.sql new file mode 100644 index 0000000000..e7ce21993c --- /dev/null +++ b/sql/custom/world/2026_10_03_04_world_forever_skycutter_announcements.sql @@ -0,0 +1,6 @@ +-- Classic 1.60 (WoW Forever): dockmaster announcements when a Skycutter docks (classic_event_skycutter_arrival; arrival events of +-- the dock nodes of taxi paths 11398 / 11457, official beta sniff 70170). Safe to run again. +DELETE FROM `event_script_names` WHERE `Id` IN (105988, 103315); +INSERT INTO `event_script_names` (`Id`, `ScriptName`) VALUES +(105988, 'classic_event_skycutter_arrival'), -- Zephras Isle dock (Dalaran Skycutter) +(103315, 'classic_event_skycutter_arrival'); -- Dalaran / Lordamere Lake dock diff --git a/sql/custom/world/2026_10_03_05_world_tauren_plainsrunning.sql b/sql/custom/world/2026_10_03_05_world_tauren_plainsrunning.sql new file mode 100644 index 0000000000..6527d0a560 --- /dev/null +++ b/sql/custom/world/2026_10_03_05_world_tauren_plainsrunning.sql @@ -0,0 +1,4 @@ +-- Classic 1.60: Tauren racial Plainsrunning (1259918) stacks Plainsrunning speed (1299038) while moving (classic_spell_plainsrunning). +-- Safe to run again. +DELETE FROM `spell_script_names` WHERE `spell_id` = 1259918; +INSERT INTO `spell_script_names` (`spell_id`, `ScriptName`) VALUES (1259918, 'classic_spell_plainsrunning'); diff --git a/sql/custom/world/2026_10_03_06_world_forever_orchard_bandits.sql b/sql/custom/world/2026_10_03_06_world_forever_orchard_bandits.sql new file mode 100644 index 0000000000..ea9b862110 --- /dev/null +++ b/sql/custom/world/2026_10_03_06_world_forever_orchard_bandits.sql @@ -0,0 +1,11 @@ +-- Classic 1.60 (WoW Forever), Zephras Isle orchard: Ferauu the Bludgeon (252863) and his Bandit Henchmen (252875) are summoned by +-- the Malfunctioning Cyclone Construct's event (classic_npc_malfunctioning_cyclone_construct, official beta sniff 70170). The sniff +-- import placed them as fixed spawns at both ends of their walk: removed. The construct wanders by its post between the events. +-- Safe to run again. +DELETE FROM `creature_addon` WHERE `guid` IN (SELECT `guid` FROM `creature` WHERE `id` IN (252863, 252875) AND `map` = 2991); +DELETE FROM `creature` WHERE `id` IN (252863, 252875) AND `map` = 2991; + +UPDATE `creature_template` SET `AIName` = '', `ScriptName` = 'classic_npc_malfunctioning_cyclone_construct' WHERE `entry` = 250929; +DELETE FROM `smart_scripts` WHERE `entryorguid` = 250929 AND `source_type` = 0; +DELETE FROM `creature_addon` WHERE `guid` = 21100144; +UPDATE `creature` SET `MovementType` = 1, `wander_distance` = 15 WHERE `guid` = 21100144; diff --git a/sql/custom/world/2026_10_03_10_world_armory_item.sql b/sql/custom/world/2026_10_03_10_world_armory_item.sql new file mode 100644 index 0000000000..6283a76f5f --- /dev/null +++ b/sql/custom/world/2026_10_03_10_world_armory_item.sql @@ -0,0 +1,47 @@ +-- Classic 1.60: data for the website armory (contrib/support_site), written by the console command ".armory export" +-- (scripts/Custom/Classic/world/classic_armory_commands.cpp) from the server's item templates (DB2 + hotfixes). +-- stats = "statType:value,..." (ItemModType), effects = "triggerType:spellId:spellName|...", icon = file name from the listfile. +CREATE TABLE IF NOT EXISTS `armory_item` ( + `id` int unsigned NOT NULL, + `name` varchar(255) NOT NULL DEFAULT '', + `quality` tinyint unsigned NOT NULL DEFAULT '0', + `itemLevel` smallint unsigned NOT NULL DEFAULT '0', + `requiredLevel` smallint NOT NULL DEFAULT '0', + `class` tinyint unsigned NOT NULL DEFAULT '0', + `subclass` tinyint unsigned NOT NULL DEFAULT '0', + `inventoryType` tinyint unsigned NOT NULL DEFAULT '0', + `bonding` tinyint unsigned NOT NULL DEFAULT '0', + `armor` int unsigned NOT NULL DEFAULT '0', + `dmgMin` float NOT NULL DEFAULT '0', + `dmgMax` float NOT NULL DEFAULT '0', + `delay` int unsigned NOT NULL DEFAULT '0', + `stats` varchar(255) NOT NULL DEFAULT '', + `effects` varchar(2048) NOT NULL DEFAULT '', + `description` varchar(1024) NOT NULL DEFAULT '', + `iconFileDataId` int NOT NULL DEFAULT '0', + `sellPrice` int unsigned NOT NULL DEFAULT '0', + `allowableClass` int NOT NULL DEFAULT '-1', + `itemSet` smallint unsigned NOT NULL DEFAULT '0', + `requiredSkill` smallint unsigned NOT NULL DEFAULT '0', + `requiredSkillRank` smallint unsigned NOT NULL DEFAULT '0', + `flags` int unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `idx_name` (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- names and icons the armory shows: kind = race, class, skill, achievement (extra = skill category / achievement points) +CREATE TABLE IF NOT EXISTS `armory_name` ( + `kind` varchar(16) NOT NULL, + `id` int unsigned NOT NULL, + `name` varchar(255) NOT NULL DEFAULT '', + `iconFileDataId` int NOT NULL DEFAULT '0', + `extra` int NOT NULL DEFAULT '0', + PRIMARY KEY (`kind`,`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- icon file names (interface/icons/.blp) for the file data ids above, from the community listfile (contrib/support_site/armory_icons.py) +CREATE TABLE IF NOT EXISTS `armory_icon` ( + `fileDataId` int NOT NULL, + `name` varchar(128) NOT NULL, + PRIMARY KEY (`fileDataId`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/src/server/database/Database/Implementation/LoginDatabase.cpp b/src/server/database/Database/Implementation/LoginDatabase.cpp index fa4894d361..0a542b3747 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.cpp +++ b/src/server/database/Database/Implementation/LoginDatabase.cpp @@ -205,6 +205,9 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_SEL_BNET_PLAYER_DATA_FLAGS_ACCOUNT, "SELECT storageIndex, mask FROM battlenet_account_player_data_flag WHERE battlenetAccountId = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_DEL_BNET_PLAYER_DATA_FLAGS_ACCOUNT, "DELETE FROM battlenet_account_player_data_flag WHERE battlenetAccountId = ? AND storageIndex = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_INS_BNET_PLAYER_DATA_FLAGS_ACCOUNT, "INSERT INTO battlenet_account_player_data_flag (battlenetAccountId, storageIndex, mask) VALUES (?, ?, ?)", CONNECTION_ASYNC); + + PrepareStatement(LOGIN_DEL_BNET_SSO_TOKENS_EXPIRED, "DELETE FROM battlenet_sso_tokens WHERE expires < UNIX_TIMESTAMP()", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_BNET_SSO_TOKEN, "INSERT INTO battlenet_sso_tokens (token, battlenetAccountId, accountId, realmId, characterGuid, issued, expires, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); } LoginDatabaseConnection::LoginDatabaseConnection(MySQLConnectionInfo& connInfo, ConnectionFlags connectionFlags) : MySQLConnection(connInfo, connectionFlags) diff --git a/src/server/database/Database/Implementation/LoginDatabase.h b/src/server/database/Database/Implementation/LoginDatabase.h index 53d1d7a769..8d2841adba 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.h +++ b/src/server/database/Database/Implementation/LoginDatabase.h @@ -190,6 +190,9 @@ enum LoginDatabaseStatements : uint32 LOGIN_DEL_BNET_PLAYER_DATA_FLAGS_ACCOUNT, LOGIN_INS_BNET_PLAYER_DATA_FLAGS_ACCOUNT, + LOGIN_DEL_BNET_SSO_TOKENS_EXPIRED, + LOGIN_INS_BNET_SSO_TOKEN, + MAX_LOGINDATABASE_STATEMENTS }; diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index fb487bb0d8..94a5e5d82f 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -444,13 +444,14 @@ Item* AuctionHouseMgr::GetAItem(ObjectGuid itemGuid) uint64 AuctionHouseMgr::GetCommodityAuctionDeposit(ItemTemplate const* item, Minutes time, uint32 quantity) { uint32 sellPrice = item->GetSellPrice(); - return uint64(std::ceil(std::floor(fmax(0.15 * quantity * sellPrice, 100.0)) / int64(SILVER)) * int64(SILVER)) * (time.count() / (MIN_AUCTION_TIME / MINUTE)); + // Classic 1.60: deposit 5% of the vendor price per 2 hours (AuctionHouse.db2 DepositRate 5), at least 1 copper, no silver rounding + return uint64(std::max(1.0, std::floor(0.05 * quantity * sellPrice))) * (time.count() / (MIN_AUCTION_TIME / MINUTE)); } uint64 AuctionHouseMgr::GetItemAuctionDeposit(Player const* player, Item const* item, Minutes time) { uint32 sellPrice = item->GetSellPrice(player); - return uint64(std::ceil(std::floor(fmax(sellPrice * 0.15, 100.0)) / int64(SILVER)) * int64(SILVER)) * (time.count() / (MIN_AUCTION_TIME / MINUTE)); + return uint64(std::max(1.0, std::floor(sellPrice * 0.05))) * (time.count() / (MIN_AUCTION_TIME / MINUTE)); } std::string AuctionHouseMgr::BuildItemAuctionMailSubject(AuctionMailType type, AuctionPosting const* auction) diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.h b/src/server/game/AuctionHouse/AuctionHouseMgr.h index 2d84fa3f5e..6903bc7ede 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.h +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.h @@ -49,7 +49,7 @@ namespace WorldPackets } } -uint32 constexpr MIN_AUCTION_TIME = 12 * HOUR; +uint32 constexpr MIN_AUCTION_TIME = 2 * HOUR; // Classic 1.60: auctions run 2, 8 or 24 hours (retail 12/24/48) enum class AuctionResult : int8 { diff --git a/src/server/game/DataStores/DB2Stores.cpp b/src/server/game/DataStores/DB2Stores.cpp index 879c0fa739..7c54723caa 100644 --- a/src/server/game/DataStores/DB2Stores.cpp +++ b/src/server/game/DataStores/DB2Stores.cpp @@ -1718,11 +1718,9 @@ void DB2Manager::IndexLoadedStores() if (node->GetFlags().HasFlag(TaxiNodeFlags::ShowOnAllianceMap)) sAllianceTaxiNodesMask[field] |= submask; - uint32 uiMapId = uint32(-1); - if (!GetUiMapPosition(node->Pos.X, node->Pos.Y, node->Pos.Z, node->ContinentID, 0, 0, 0, UI_MAP_SYSTEM_ADVENTURE, false, &uiMapId)) - GetUiMapPosition(node->Pos.X, node->Pos.Y, node->Pos.Z, node->ContinentID, 0, 0, 0, UI_MAP_SYSTEM_TAXI, false, &uiMapId); - - if (uiMapId == 985 || uiMapId == 986) + // Classic 1.60: the old continents are simply Eastern Kingdoms (map 0) and Kalimdor (map 1); retail looked them up by the + // Cataclysm world map ids 985/986, which the Classic UiMap data does not use (the mask stayed empty) + if (node->ContinentID == 0 || node->ContinentID == 1) sOldContinentsNodesMask[field] |= submask; } @@ -1963,7 +1961,11 @@ std::vector const* DB2Manager::GetHotfixOptional uint32 DB2Manager::GetEmptyAnimStateID() const { - return sAnimationDataStore.GetNumRows(); + // "no state animation" = one past the last AnimationData row OF THE CLIENT. Classic 1.60.1.70170 expects 1866 (official beta + // sniff: every gameobject create carries 1866); our extracted DB2s are older (1806), and the client then plays animation 1806 as + // a state: fishing bobbers never splash, NPC/object animations break. Remove when the DB2s are re-extracted from 70170 or newer. + static constexpr uint32 CLASSIC_EMPTY_ANIM_STATE_ID = 1866; + return std::max(sAnimationDataStore.GetNumRows(), CLASSIC_EMPTY_ANIM_STATE_ID); } void DB2Manager::InsertNewHotfix(uint32 tableHash, uint32 recordId) diff --git a/src/server/game/Entities/Object/Updates/UpdateFields.cpp b/src/server/game/Entities/Object/Updates/UpdateFields.cpp index e23864cb60..b233f1912b 100644 --- a/src/server/game/Entities/Object/Updates/UpdateFields.cpp +++ b/src/server/game/Entities/Object/Updates/UpdateFields.cpp @@ -7366,7 +7366,9 @@ void GameObjectData::WriteCreate(EnumFlag fieldVisibilityFlags, data << float(ParentRotation->z); data << float(ParentRotation->w); data << int32(FactionTemplate); - data << int32(0); // Classic 1.60.1.70009: unknown int32 (client GameObjectData reader rva 0x4506180, +0x74) + data << int32(Level); // Classic 1.60 int32 (client GameObjectData reader rva 0x4506180, +0x74): the level of + // the player who created the object (official beta sniff 70170: bobbers, campfires, + // camp features carry their owner's level, world objects 0) data << int8(ViewerDependentValue::GetValue(this, receiver, owner)); data << int8(TypeID); data << uint8(PercentHealth); diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 409766ffbe..df64c3278b 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -2314,6 +2314,25 @@ void Player::GiveLevel(uint8 level) sScriptMgr->OnPlayerLevelChanged(this, oldLevel); } +// Classic 1.60 (WoW Forever): the first character bank tab is free (BankTab.db2: BankType 0, OrderIndex 0, Cost 0) and every character +// has it without buying it (official beta sniff 70170: items stored in bank bag 63 slot 0 with no tab purchase). Without a tab the +// bank has no slots ("bank is full"). +void Player::GrantClassicFreeBankTab() +{ + if (GetCharacterBankTabCount() > 0) + return; + + uint16 pos = 0; + if (CanEquipNewItem(BANK_SLOT_BAG_START, pos, ITEM_CHARACTER_BANK_TAB_BAG, false) != EQUIP_ERR_OK) + return; + + if (!EquipNewItem(pos, ITEM_CHARACTER_BANK_TAB_BAG, ItemContext::NONE, true)) + return; + + SetCharacterBankTabCount(1); + SetCharacterBankTabSettings(0, ChatHandler(GetSession()).PGetParseString(LANG_BANK_TAB_NAME, 1), "", "", BagSlotFlags::None); +} + void Player::UpdateClassicLegacyUnlock() { // Classic 1.60: the Legacy system (micro menu "Legacy", LegacyMicroButtonMixin:IsLegacySystemUnlocked) opens with renown level 1 @@ -14138,6 +14157,10 @@ void Player::SendNewItem(Item* item, uint32 quantity, bool pushed, bool created, /*** GOSSIP SYSTEM ***/ /*********************************************************/ +// Classic 1.60: gossip option ids of the trainer / vendor options added to menus that lack them (never used by DB options) +static constexpr int32 CLASSIC_GOSSIP_OPTION_AUTO_TRAINER = 2146000001; +static constexpr int32 CLASSIC_GOSSIP_OPTION_AUTO_VENDOR = 2146000002; + void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId, bool showQuests /*= false*/) { PlayerTalkClass->ClearMenus(); @@ -14245,6 +14268,28 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId, bool showQues if (canTalk) PlayerTalkClass->GetGossipMenu().AddMenuItem(gossipMenuItem, gossipMenuItem.MenuID, gossipMenuItem.OrderIndex); } + + // Classic 1.60: the client opens trainers and vendors only through a gossip option. NPCs whose menu (vanilla data, sniffed + // menus) lacks the option for a service they have get it added here. + if (Creature* creature = source->ToCreature()) + { + GossipMenu& menu = PlayerTalkClass->GetGossipMenu(); + auto hasOption = [&](GossipOptionNpc optionNpc) + { + for (GossipMenuItem const& item : menu.GetMenuItems()) + if (item.OptionNpc == optionNpc) + return true; + return false; + }; + + if (creature->HasNpcFlag(UNIT_NPC_FLAG_TRAINER) && creature->GetTrainerId() && !hasOption(GossipOptionNpc::Trainer)) + menu.AddMenuItem(CLASSIC_GOSSIP_OPTION_AUTO_TRAINER, menu.GetMenuItemCount(), GossipOptionNpc::Trainer, "Train me.", 0, + GossipOptionFlags::None, {}, 0, 0, false, 0, "", {}, {}, menuId, menu.GetMenuItemCount()); + + if (creature->HasNpcFlag(UNIT_NPC_FLAG_VENDOR) && creature->GetVendorItems() && !hasOption(GossipOptionNpc::Vendor)) + menu.AddMenuItem(CLASSIC_GOSSIP_OPTION_AUTO_VENDOR, menu.GetMenuItemCount(), GossipOptionNpc::Vendor, "Let me browse your goods.", 0, + GossipOptionFlags::None, {}, 0, 0, false, 0, "", {}, {}, menuId, menu.GetMenuItemCount()); + } } void Player::SendPreparedGossip(WorldObject* source) @@ -14335,8 +14380,16 @@ void Player::OnGossipSelect(WorldObject* source, int32 gossipOptionId, uint32 me GetSession()->SendTaxiMenu(source->ToCreature()); break; case GossipOptionNpc::Trainer: - GetSession()->SendTrainerList(source->ToCreature(), sObjectMgr->GetCreatureTrainerForGossipOption(source->GetEntry(), menuId, item->OrderIndex)); + { + // Classic 1.60: vanilla menus point at sniffed trainers (and the added "Train me." option has no creature_trainer + // row): fall back to the creature's trainer + uint32 trainerId = sObjectMgr->GetCreatureTrainerForGossipOption(source->GetEntry(), menuId, item->OrderIndex); + if (!trainerId) + if (Creature* trainerCreature = source->ToCreature()) + trainerId = trainerCreature->GetTrainerId(); + GetSession()->SendTrainerList(source->ToCreature(), trainerId); break; + } case GossipOptionNpc::SpiritHealer: source->CastSpell(source->ToCreature(), 17251, CastSpellExtraArgs(TRIGGERED_FULL_MASK).SetOriginalCaster(GetGUID())); handled = false; diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index 1eee9c5c03..28deb353c9 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -2402,6 +2402,7 @@ class TC_GAME_API Player final : public Unit, public GridObject static uint32 GetClassicProfessionSkill(uint32 skill); void SyncClassicProfessionChildSkills(uint32 skill); void UpdateClassicLegacyUnlock(); + void GrantClassicFreeBankTab(); bool HasSkill(uint32 skill) const; void LearnSkillRewardedSpells(uint32 skillId, uint32 skillValue, Races race); int32 GetProfessionSlotFor(uint32 skillId) const; diff --git a/src/server/game/Entities/Player/PlayerTaxi.cpp b/src/server/game/Entities/Player/PlayerTaxi.cpp index ba0ab55c98..6615b4f4d2 100644 --- a/src/server/game/Entities/Player/PlayerTaxi.cpp +++ b/src/server/game/Entities/Player/PlayerTaxi.cpp @@ -32,17 +32,14 @@ PlayerTaxi::~PlayerTaxi() = default; void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level) { - // class specific initial known nodes + // Classic 1.60 (WoW Forever): every character knows all flight points of its faction on Kalimdor and the Eastern Kingdoms + // (official beta sniff, build 70170: a level 15 Skyborne opening the Thunder Bluff flight master already knew Orgrimmar, + // Crossroads, Gadgetzan, Everlook, ... and in the Eastern Kingdoms Undercity, Tarren Mill, Booty Bay, Stonard, ...). + // Retail gives this only to death knights. + (void)chrClass; TaxiMask const& factionMask = Player::TeamForRace(race) == HORDE ? sHordeTaxiNodesMask : sAllianceTaxiNodesMask; - switch (chrClass) - { - case CLASS_DEATH_KNIGHT: - { - for (std::size_t i = 0; i < m_taximask.size(); ++i) - m_taximask[i] |= sOldContinentsNodesMask[i] & factionMask[i]; - break; - } - } + for (std::size_t i = 0; i < m_taximask.size(); ++i) + m_taximask[i] |= sOldContinentsNodesMask[i] & factionMask[i]; // race specific initial known nodes: capital and taxi hub masks switch (race) diff --git a/src/server/game/Globals/ObjectMgr.h b/src/server/game/Globals/ObjectMgr.h index ffbc324506..b939166e2f 100644 --- a/src/server/game/Globals/ObjectMgr.h +++ b/src/server/game/Globals/ObjectMgr.h @@ -1550,7 +1550,16 @@ class TC_GAME_API ObjectMgr Trainer::Trainer const* GetTrainer(uint32 trainerId) const; uint32 GetCreatureDefaultTrainer(uint32 creatureId) const { - return GetCreatureTrainerForGossipOption(creatureId, 0, 0); + if (uint32 trainerId = GetCreatureTrainerForGossipOption(creatureId, 0, 0)) + return trainerId; + + // Classic 1.60: the client opens trainers without gossip (CMSG_TRAINER_LIST) also for creatures whose only + // creature_trainer row is tied to a gossip option (sniffed trainers): use that trainer + auto itr = _creatureDefaultTrainers.lower_bound(std::make_tuple(creatureId, 0u, 0u)); + if (itr != _creatureDefaultTrainers.end() && std::get<0>(itr->first) == creatureId) + return itr->second; + + return 0; } uint32 GetCreatureTrainerForGossipOption(uint32 creatureId, uint32 gossipMenuId, uint32 gossipOptionId) const; diff --git a/src/server/game/Handlers/AuctionHouseHandler.cpp b/src/server/game/Handlers/AuctionHouseHandler.cpp index 4193652851..2cca363553 100644 --- a/src/server/game/Handlers/AuctionHouseHandler.cpp +++ b/src/server/game/Handlers/AuctionHouseHandler.cpp @@ -363,12 +363,6 @@ void WorldSession::HandleAuctionPlaceBid(WorldPackets::AuctionHouse::AuctionPlac return; } - // auction house does not deal with copper - if (placeBid.BidAmount % SILVER) - { - SendAuctionCommandResult(placeBid.AuctionID, AuctionCommand::PlaceBid, AuctionResult::BidIncrement, throttle.DelayUntilNext); - return; - } // remove fake death if (GetPlayer()->HasUnitState(UNIT_STATE_DIED)) @@ -617,12 +611,6 @@ void WorldSession::HandleAuctionSellCommodity(WorldPackets::AuctionHouse::Auctio return; } - // auction house does not deal with copper - if (sellCommodity.UnitPrice % SILVER) - { - SendAuctionCommandResult(0, AuctionCommand::SellItem, AuctionResult::DatabaseError, throttle.DelayUntilNext); - return; - } Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(sellCommodity.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER, UNIT_NPC_FLAG_2_NONE); if (!creature) @@ -641,9 +629,9 @@ void WorldSession::HandleAuctionSellCommodity(WorldPackets::AuctionHouse::Auctio switch (sellCommodity.RunTime) { - case 1 * MIN_AUCTION_TIME / MINUTE: - case 2 * MIN_AUCTION_TIME / MINUTE: + case 1 * MIN_AUCTION_TIME / MINUTE: // Classic 1.60: 2, 8 and 24 hours case 4 * MIN_AUCTION_TIME / MINUTE: + case 12 * MIN_AUCTION_TIME / MINUTE: break; default: SendAuctionCommandResult(0, AuctionCommand::SellItem, AuctionResult::AuctionHouseBusy, throttle.DelayUntilNext); @@ -841,12 +829,6 @@ void WorldSession::HandleAuctionSellItem(WorldPackets::AuctionHouse::AuctionSell return; } - // auction house does not deal with copper - if (sellItem.MinBid % SILVER || sellItem.BuyoutPrice % SILVER) - { - SendAuctionCommandResult(0, AuctionCommand::SellItem, AuctionResult::DatabaseError, throttle.DelayUntilNext); - return; - } Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(sellItem.Auctioneer, UNIT_NPC_FLAG_AUCTIONEER, UNIT_NPC_FLAG_2_NONE); if (!creature) @@ -865,9 +847,9 @@ void WorldSession::HandleAuctionSellItem(WorldPackets::AuctionHouse::AuctionSell switch (sellItem.RunTime) { - case 1 * MIN_AUCTION_TIME / MINUTE: - case 2 * MIN_AUCTION_TIME / MINUTE: + case 1 * MIN_AUCTION_TIME / MINUTE: // Classic 1.60: 2, 8 and 24 hours case 4 * MIN_AUCTION_TIME / MINUTE: + case 12 * MIN_AUCTION_TIME / MINUTE: break; default: SendAuctionCommandResult(0, AuctionCommand::SellItem, AuctionResult::AuctionHouseBusy, throttle.DelayUntilNext); diff --git a/src/server/game/Handlers/BattlenetHandler.cpp b/src/server/game/Handlers/BattlenetHandler.cpp index e9c3810d53..fb3d555688 100644 --- a/src/server/game/Handlers/BattlenetHandler.cpp +++ b/src/server/game/Handlers/BattlenetHandler.cpp @@ -17,6 +17,13 @@ #include "WorldSession.h" #include "BattlenetPackets.h" +#include "CryptoRandom.h" +#include "DatabaseEnv.h" +#include "GameTime.h" +#include "Player.h" +#include "RealmList.h" +#include "StringFormat.h" +#include "Util.h" #include "WorldserverServiceDispatcher.h" #include "ObjectDefines.h" @@ -37,6 +44,43 @@ void WorldSession::HandleBattlenetRequest(WorldPackets::Battlenet::Request& requ sServiceDispatcher.Dispatch(this, request.Method.GetServiceHash(), request.Method.Token, request.Method.GetMethodId(), std::move(request.Data)); } +// Classic 1.60: tokens for the in-game browser (Support window), stored in battlenet_sso_tokens so our support site can tell who opened it. +// Same shape as the official ones: "TUS-" + 32 lowercase hex + "-" + battle.net account id, valid for 4 hours. +std::string WorldSession::CreateSsoToken(time_t issued, time_t expires) +{ + std::string secret = ByteArrayToHexStr(Trinity::Crypto::GetRandomBytes<16>()); + strToLower(secret); + std::string token = Trinity::StringFormat("TUS-{}-{}", secret, GetBattlenetAccountId()); + + LoginDatabaseTransaction trans = LoginDatabase.BeginTransaction(); + trans->Append(LoginDatabase.GetPreparedStatement(LOGIN_DEL_BNET_SSO_TOKENS_EXPIRED)); + + LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_BNET_SSO_TOKEN); + stmt->setString(0, token); + stmt->setUInt32(1, GetBattlenetAccountId()); + stmt->setUInt32(2, GetAccountId()); + stmt->setUInt32(3, sRealmList->GetCurrentRealmId().Realm); + stmt->setUInt64(4, _player ? _player->GetGUID().GetCounter() : 0); + stmt->setInt64(5, issued); + stmt->setInt64(6, expires); + stmt->setString(7, GetRemoteAddress()); + trans->Append(stmt); + LoginDatabase.CommitTransaction(trans); + + return token; +} + +void WorldSession::HandleGenerateSsoToken(WorldPackets::Battlenet::GenerateSsoToken& generateSsoToken) +{ + WorldPackets::Battlenet::GenerateSsoTokenResponse response; + response.RequestID = generateSsoToken.RequestID; + response.Issued = GameTime::GetGameTime(); + response.Expires = response.Issued + SsoTokenDuration; + response.Token = CreateSsoToken(response.Issued, response.Expires); + + SendPacket(response.Write()); +} + void WorldSession::SendBattlenetResponse(uint32 serviceHash, uint32 methodId, uint32 token, pb::Message const* response) { WorldPackets::Battlenet::Response bnetResponse; diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index 88ff46dfaa..1508326ac8 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -1359,6 +1359,10 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder const& holder) // Classic 1.60: characters that were already level 25+ get the Legacy unlock on login pCurrChar->UpdateClassicLegacyUnlock(); + // Classic 1.60: every character has the free first bank tab. DISABLED: sending a bank tab (ActivePlayerData + // CharacterBankTabSettings) crashes the 70170 client at login (assert n < N, 354 vs 257): its Classic layout is not verified yet. + // pCurrChar->GrantClassicFreeBankTab(); + CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ONLINE); stmt->setUInt64(0, pCurrChar->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/Handlers/SkillHandler.cpp b/src/server/game/Handlers/SkillHandler.cpp index 2aeaace305..2355ddad6b 100644 --- a/src/server/game/Handlers/SkillHandler.cpp +++ b/src/server/game/Handlers/SkillHandler.cpp @@ -23,6 +23,7 @@ #include "ObjectAccessor.h" #include "Pet.h" #include "Player.h" +#include "SpellMgr.h" #include "SpellPackets.h" #include "TalentPackets.h" @@ -129,3 +130,50 @@ void WorldSession::HandleTradeSkillSetFavorite(WorldPackets::Spells::TradeSkillS _player->SetSpellFavorite(tradeSkillSetFavorite.RecipeID, tradeSkillSetFavorite.IsFavorite); } + +// Classic 1.60: a click on another player's profession link in chat. The answer lists that player's profession line and its +// Classic child line (e.g. Enchanting 333 + 2940), their ranks and every recipe known on them (official beta sniff, build 70170). +void WorldSession::HandleShowTradeSkill(WorldPackets::Spells::ShowTradeSkill& packet) +{ + Player* target = ObjectAccessor::FindConnectedPlayer(packet.PlayerGUID); + if (!target) + return; + + uint32 skill = Player::GetClassicProfessionSkill(uint32(packet.SkillLineID)); + if (!target->HasSkill(skill)) + return; + + std::vector lines = { skill }; + if (std::vector const* children = sDB2Manager.GetSkillLinesForParentSkill(skill)) + for (SkillLineEntry const* child : *children) + if (target->HasSkill(child->ID)) + lines.push_back(child->ID); + + WorldPackets::Spells::ShowTradeSkillResponse response; + response.PlayerGUID = packet.PlayerGUID; + response.SpellID = packet.SpellID; + for (uint32 line : lines) + { + response.SkillLineIDs.push_back(int32(line)); + response.SkillRanks.push_back(int32(target->GetSkillValue(line))); + response.SkillMaxRanks.push_back(int32(target->GetMaxSkillValue(line))); + } + + for (auto const& [spellId, spell] : target->GetSpellMap()) + { + if (spell.state == PLAYERSPELL_REMOVED || !spell.active || spell.disabled) + continue; + + SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellId); + for (auto itr = bounds.first; itr != bounds.second; ++itr) + { + if (std::find(lines.begin(), lines.end(), uint32(itr->second->SkillLine)) != lines.end()) + { + response.KnownAbilitySpellIDs.push_back(int32(spellId)); + break; + } + } + } + + SendPacket(response.Write()); +} diff --git a/src/server/game/Handlers/TicketHandler.cpp b/src/server/game/Handlers/TicketHandler.cpp index 56eaac4623..01f99c194e 100644 --- a/src/server/game/Handlers/TicketHandler.cpp +++ b/src/server/game/Handlers/TicketHandler.cpp @@ -18,6 +18,7 @@ #include "WorldSession.h" #include "Common.h" #include "DatabaseEnv.h" +#include "GameTime.h" #include "SupportMgr.h" #include "TicketPackets.h" @@ -35,6 +36,11 @@ void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPackets::Ticket::GMTick WorldPackets::Ticket::GMTicketSystemStatus response; response.Status = sSupportMgr->GetSupportSystemStatus() ? GMTICKET_QUEUE_STATUS_ENABLED : GMTICKET_QUEUE_STATUS_DISABLED; SendPacket(response.Write()); + + // Classic 1.60: sent when the Help window opens, which then loads our support site without a token in the URL. A token issued now + // tells the site which session (account, character) opened it, also when several accounts play from one address. + time_t now = GameTime::GetGameTime(); + CreateSsoToken(now, now + SsoTokenDuration); } void WorldSession::HandleSubmitUserFeedback(WorldPackets::Ticket::SubmitUserFeedback& userFeedback) diff --git a/src/server/game/Server/Packets/BattlenetPackets.cpp b/src/server/game/Server/Packets/BattlenetPackets.cpp index 8a1ecc366d..0db9ad2382 100644 --- a/src/server/game/Server/Packets/BattlenetPackets.cpp +++ b/src/server/game/Server/Packets/BattlenetPackets.cpp @@ -98,4 +98,21 @@ void ChangeRealmTicket::Read() _worldPacket >> Token; _worldPacket.read(Secret.data(), Secret.size()); } + +void GenerateSsoToken::Read() +{ + _worldPacket >> RequestID; + _worldPacket >> Usage; +} + +WorldPacket const* GenerateSsoTokenResponse::Write() +{ + _worldPacket << uint32(RequestID); + _worldPacket << uint32(Result); + _worldPacket << Issued; + _worldPacket << Expires; + _worldPacket.append(reinterpret_cast(Token.data()), Token.size()); + + return &_worldPacket; +} } diff --git a/src/server/game/Server/Packets/BattlenetPackets.h b/src/server/game/Server/Packets/BattlenetPackets.h index dcde6acec4..014f834aa7 100644 --- a/src/server/game/Server/Packets/BattlenetPackets.h +++ b/src/server/game/Server/Packets/BattlenetPackets.h @@ -21,6 +21,7 @@ #include "Packet.h" #include "BattlenetRpcErrorCodes.h" #include "MessageBuffer.h" +#include "PacketUtilities.h" #include namespace WorldPackets @@ -104,6 +105,32 @@ namespace WorldPackets uint32 Token = 0; std::array Secret = { }; }; + + // Classic 1.60: the in-game browser (Support window) opens ?token=&ref= + class GenerateSsoToken final : public ClientPacket + { + public: + explicit GenerateSsoToken(WorldPacket&& packet) : ClientPacket(CMSG_GENERATE_SSO_TOKEN, std::move(packet)) { } + + void Read() override; + + uint32 RequestID = 0; + uint32 Usage = 0; // 0x00417070 ("ppA") in every request seen + }; + + class GenerateSsoTokenResponse final : public ServerPacket + { + public: + explicit GenerateSsoTokenResponse() : ServerPacket(SMSG_GENERATE_SSO_TOKEN_RESPONSE, 4 + 4 + 8 + 8 + 64) { } + + WorldPacket const* Write() override; + + uint32 RequestID = 0; + uint32 Result = 0; + Timestamp<> Issued; + Timestamp<> Expires; + std::string Token; // no length prefix, the rest of the packet + }; } } diff --git a/src/server/game/Server/Packets/SpellPackets.cpp b/src/server/game/Server/Packets/SpellPackets.cpp index 230b33458a..c1522d3387 100644 --- a/src/server/game/Server/Packets/SpellPackets.cpp +++ b/src/server/game/Server/Packets/SpellPackets.cpp @@ -1186,6 +1186,36 @@ void TradeSkillSetFavorite::Read() _worldPacket >> Bits<1>(IsFavorite); } +void ShowTradeSkill::Read() +{ + _worldPacket >> PlayerGUID; + _worldPacket >> SpellID; + _worldPacket >> SkillLineID; +} + +WorldPacket const* ShowTradeSkillResponse::Write() +{ + _worldPacket << PlayerGUID; + _worldPacket << int32(SpellID); + _worldPacket << Size(SkillLineIDs); + _worldPacket << Size(SkillRanks); + _worldPacket << Size(SkillMaxRanks); + _worldPacket << Size(KnownAbilitySpellIDs); + _worldPacket << uint32(0); // three more counts in Classic, 0 in every sniffed response + _worldPacket << uint32(0); + _worldPacket << uint32(0); + for (int32 id : SkillLineIDs) + _worldPacket << int32(id); + for (int32 rank : SkillRanks) + _worldPacket << int32(rank); + for (int32 rank : SkillMaxRanks) + _worldPacket << int32(rank); + for (int32 spellId : KnownAbilitySpellIDs) + _worldPacket << int32(spellId); + + return &_worldPacket; +} + void KeyboundOverride::Read() { _worldPacket >> OverrideID; diff --git a/src/server/game/Server/Packets/SpellPackets.h b/src/server/game/Server/Packets/SpellPackets.h index 9d46a7a4ca..8a252b8cb8 100644 --- a/src/server/game/Server/Packets/SpellPackets.h +++ b/src/server/game/Server/Packets/SpellPackets.h @@ -1205,6 +1205,34 @@ namespace WorldPackets bool IsFavorite = false; }; + // Classic 1.60: clicking another player's profession link (layouts from a sniff of the official beta, build 70170) + class ShowTradeSkill final : public ClientPacket + { + public: + explicit ShowTradeSkill(WorldPacket&& packet) : ClientPacket(CMSG_SHOW_TRADE_SKILL, std::move(packet)) { } + + void Read() override; + + ObjectGuid PlayerGUID; + int32 SpellID = 0; + int32 SkillLineID = 0; + }; + + class ShowTradeSkillResponse final : public ServerPacket + { + public: + explicit ShowTradeSkillResponse() : ServerPacket(SMSG_SHOW_TRADE_SKILL_RESPONSE) { } + + WorldPacket const* Write() override; + + ObjectGuid PlayerGUID; + int32 SpellID = 0; + std::vector SkillLineIDs; + std::vector SkillRanks; + std::vector SkillMaxRanks; + std::vector KnownAbilitySpellIDs; + }; + class KeyboundOverride final : public ClientPacket { public: diff --git a/src/server/game/Server/Protocol/ClassicClientOpcodes.inc b/src/server/game/Server/Protocol/ClassicClientOpcodes.inc index bf4c437af0..b7b99fd853 100644 --- a/src/server/game/Server/Protocol/ClassicClientOpcodes.inc +++ b/src/server/game/Server/Protocol/ClassicClientOpcodes.inc @@ -155,9 +155,12 @@ { 0x3E0146, 0x3D0144 }, // CMSG_QUERY_QUEST_INFO (0.0) { 0x3E0147, 0x3D0145 }, // CMSG_QUERY_PAGE_TEXT (0.0) { 0x3E0148, 0x3D0146 }, // CMSG_QUERY_PET_NAME (3.8) - { 0x3E0149, 0x3D0148 }, // CMSG_QUERY_GARRISON_PET_NAME (0.0) - { 0x3E014A, 0x3D0149 }, // CMSG_QUERY_PETITION (0.0) - { 0x3E014B, 0x3D014C }, // CMSG_REQUEST_PLAYED_TIME (0.0) + // retail + 2 from QUERY_PET_NAME on (sniff 70170: Classic 0x3E014B carries u32 PetitionID + charter item guid = QUERY_PETITION, + // sent before PETITION_SHOW_SIGNATURES; Classic 0x3E014E is a 1-byte message = REQUEST_PLAYED_TIME's bool) + { 0x3E0149, 0x3D0147 }, // CMSG_QUERY_BATTLE_PET_NAME + { 0x3E014A, 0x3D0148 }, // CMSG_QUERY_GARRISON_PET_NAME + { 0x3E014B, 0x3D0149 }, // CMSG_QUERY_PETITION (sniff) + { 0x3E014E, 0x3D014C }, // CMSG_REQUEST_PLAYED_TIME (sniff: 1 byte) { 0x3E0154, 0x3D0152 }, // CMSG_SET_TITLE (3.8) { 0x3E0155, 0x3D0153 }, // CMSG_CANCEL_MOUNT_AURA (0.0) { 0x3E0156, 0x3D0154 }, // CMSG_MOUNT_SPECIAL_ANIM (1.0) @@ -366,6 +369,7 @@ { 0x3F008B, 0x3E0089 }, // CMSG_GAME_OBJ_USE (0.0) { 0x3F008C, 0x3E008A }, // CMSG_GAME_OBJ_REPORT_USE (0.0) { 0x3F0091, 0x3E008F }, // CMSG_REPORT_PVP_PLAYER_AFK (3.8) + { 0x3F0092, 0x3E0090 }, // CMSG_ALTER_APPEARANCE (sniff 70170: barber "accept", 155 bytes = TC layout, 18 customizations) { 0x3F0096, 0x3E0093 }, // CMSG_TOTEM_DESTROYED (4.6) { 0x3F0097, 0x3E0094 }, // CMSG_DISMISS_CRITTER (3.8) { 0x3F009E, 0x3E009B }, // CMSG_QUERY_INSPECT_ACHIEVEMENTS (3.8) diff --git a/src/server/game/Server/Protocol/Opcodes.cpp b/src/server/game/Server/Protocol/Opcodes.cpp index 6a0b3b0a64..d8199d6098 100644 --- a/src/server/game/Server/Protocol/Opcodes.cpp +++ b/src/server/game/Server/Protocol/Opcodes.cpp @@ -226,7 +226,7 @@ void OpcodeTable::InitializeClientOpcodes() DEFINE_HANDLER(CMSG_BATTLE_PAY_DISTRIBUTION_ASSIGN_VAS, STATUS_IGNORED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); DEFINE_HANDLER(CMSG_BATTLE_PAY_GET_PRODUCT_LIST, STATUS_IGNORED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); DEFINE_HANDLER(CMSG_BATTLE_PAY_GET_PURCHASE_LIST, STATUS_IGNORED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); - DEFINE_HANDLER(CMSG_BATTLE_PAY_OPEN_CHECKOUT, STATUS_IGNORED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); + DEFINE_HANDLER(CMSG_GENERATE_SSO_TOKEN, STATUS_AUTHED, PROCESS_THREADUNSAFE, &WorldSession::HandleGenerateSsoToken); DEFINE_HANDLER(CMSG_BATTLE_PAY_REQUEST_PRICE_INFO, STATUS_IGNORED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); DEFINE_HANDLER(CMSG_BATTLE_PAY_START_PURCHASE, STATUS_IGNORED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); DEFINE_HANDLER(CMSG_BATTLE_PAY_START_VAS_PURCHASE, STATUS_IGNORED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); @@ -1072,7 +1072,7 @@ void OpcodeTable::InitializeClientOpcodes() DEFINE_HANDLER(CMSG_SET_USING_PARTY_GARRISON, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); DEFINE_HANDLER(CMSG_SET_WAR_MODE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleSetWarMode); DEFINE_HANDLER(CMSG_SET_WATCHED_FACTION, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleSetWatchedFactionOpcode); - DEFINE_HANDLER(CMSG_SHOW_TRADE_SKILL, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::Handle_NULL); + DEFINE_HANDLER(CMSG_SHOW_TRADE_SKILL, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleShowTradeSkill); DEFINE_HANDLER(CMSG_SIGN_PETITION, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleSignPetition); DEFINE_HANDLER(CMSG_SILENCE_PARTY_TALKER, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL); DEFINE_HANDLER(CMSG_SOCIAL_CONTRACT_REQUEST, STATUS_AUTHED, PROCESS_THREADUNSAFE, &WorldSession::HandleSocialContractRequest); @@ -1651,7 +1651,7 @@ void OpcodeTable::InitializeServerOpcodes() DEFINE_SERVER_OPCODE_HANDLER(SMSG_GARRISON_UPGRADE_RESULT, STATUS_UNHANDLED, CONNECTION_TYPE_INSTANCE); DEFINE_SERVER_OPCODE_HANDLER(SMSG_GARRISON_USE_RECALL_PORTAL_RESULT, STATUS_UNHANDLED, CONNECTION_TYPE_INSTANCE); DEFINE_SERVER_OPCODE_HANDLER(SMSG_GENERATE_RANDOM_CHARACTER_NAME_RESULT, STATUS_NEVER, CONNECTION_TYPE_REALM); - DEFINE_SERVER_OPCODE_HANDLER(SMSG_GENERATE_SSO_TOKEN_RESPONSE, STATUS_UNHANDLED, CONNECTION_TYPE_REALM); + DEFINE_SERVER_OPCODE_HANDLER(SMSG_GENERATE_SSO_TOKEN_RESPONSE, STATUS_NEVER, CONNECTION_TYPE_REALM); DEFINE_SERVER_OPCODE_HANDLER(SMSG_GET_ACCOUNT_CHARACTER_LIST_RESULT, STATUS_UNHANDLED, CONNECTION_TYPE_REALM); DEFINE_SERVER_OPCODE_HANDLER(SMSG_GET_ALL_LICENSED_DECOR_QUANTITIES_RESPONSE, STATUS_UNHANDLED, CONNECTION_TYPE_REALM); DEFINE_SERVER_OPCODE_HANDLER(SMSG_GET_DECOR_REFUND_LIST_RESPONSE, STATUS_UNHANDLED, CONNECTION_TYPE_REALM); @@ -2420,7 +2420,7 @@ void OpcodeTable::InitializeServerOpcodes() DEFINE_SERVER_OPCODE_HANDLER(SMSG_SHOW_NEUTRAL_PLAYER_FACTION_SELECT_UI, STATUS_UNHANDLED, CONNECTION_TYPE_REALM); DEFINE_SERVER_OPCODE_HANDLER(SMSG_SHOW_QUEST_COMPLETION_TEXT, STATUS_UNHANDLED, CONNECTION_TYPE_REALM); DEFINE_SERVER_OPCODE_HANDLER(SMSG_SHOW_TAXI_NODES, STATUS_NEVER, CONNECTION_TYPE_REALM); - DEFINE_SERVER_OPCODE_HANDLER(SMSG_SHOW_TRADE_SKILL_RESPONSE, STATUS_UNHANDLED, CONNECTION_TYPE_REALM); + DEFINE_SERVER_OPCODE_HANDLER(SMSG_SHOW_TRADE_SKILL_RESPONSE, STATUS_NEVER, CONNECTION_TYPE_REALM); DEFINE_SERVER_OPCODE_HANDLER(SMSG_SOCIAL_CONTRACT_REQUEST_RESPONSE, STATUS_NEVER, CONNECTION_TYPE_REALM); DEFINE_SERVER_OPCODE_HANDLER(SMSG_SOCKET_GEMS_FAILURE, STATUS_UNHANDLED, CONNECTION_TYPE_INSTANCE); DEFINE_SERVER_OPCODE_HANDLER(SMSG_SOCKET_GEMS_SUCCESS, STATUS_NEVER, CONNECTION_TYPE_INSTANCE); diff --git a/src/server/game/Server/Protocol/Opcodes.h b/src/server/game/Server/Protocol/Opcodes.h index 1578ff53d2..feb80e2dbc 100644 --- a/src/server/game/Server/Protocol/Opcodes.h +++ b/src/server/game/Server/Protocol/Opcodes.h @@ -1065,6 +1065,9 @@ enum OpcodeClient : uint32 CMSG_BATTLE_PET_DELETE_PET_CHEAT = CMSG_BATTLE_PET_DELETE_PET + 1, CMSG_PET_BATTLE_WILD_LOCATION_FAIL = CMSG_PET_BATTLE_REQUEST_WILD + 1, + // Classic 1.60: Classic 0x44013A (u32 request id, u32 tag) lands on retail BATTLE_PAY_OPEN_CHECKOUT, it is the SSO token request + CMSG_GENERATE_SSO_TOKEN = CMSG_BATTLE_PAY_OPEN_CHECKOUT, + // Deleted opcodes, here only to allow compile CMSG_TRANSMOGRIFY_ITEMS = CMSG_REQUEST_SCHEDULED_PVP_INFO + 1, }; diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index 34ae796daf..dbc0afe911 100644 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -196,6 +196,7 @@ namespace WorldPackets namespace Battlenet { class ChangeRealmTicket; + class GenerateSsoToken; class Request; } @@ -750,6 +751,7 @@ namespace WorldPackets class UpdateMissileTrajectory; class UpdateAuraVisual; class TradeSkillSetFavorite; + class ShowTradeSkill; class KeyboundOverride; class SetEmpowerMinHoldStagePercent; class SpellEmpowerRelease; @@ -1605,6 +1607,7 @@ class TC_GAME_API WorldSession void HandleConfirmRespecWipeOpcode(WorldPackets::Talent::ConfirmRespecWipe& confirmRespecWipe); void HandleUnlearnSkillOpcode(WorldPackets::Spells::UnlearnSkill& packet); void HandleTradeSkillSetFavorite(WorldPackets::Spells::TradeSkillSetFavorite const& tradeSkillSetFavorite); + void HandleShowTradeSkill(WorldPackets::Spells::ShowTradeSkill& packet); void HandleTraitsCommitConfig(WorldPackets::Traits::TraitsCommitConfig const& traitsCommitConfig); void HandleClassTalentsRequestNewConfig(WorldPackets::Traits::ClassTalentsRequestNewConfig& classTalentsRequestNewConfig); @@ -1890,6 +1893,9 @@ class TC_GAME_API WorldSession // Battlenet void HandleBattlenetChangeRealmTicket(WorldPackets::Battlenet::ChangeRealmTicket& changeRealmTicket); void HandleBattlenetRequest(WorldPackets::Battlenet::Request& request); + void HandleGenerateSsoToken(WorldPackets::Battlenet::GenerateSsoToken& generateSsoToken); + static constexpr time_t SsoTokenDuration = 4 * HOUR; + std::string CreateSsoToken(time_t issued, time_t expires); void SendBattlenetResponse(uint32 serviceHash, uint32 methodId, uint32 token, pb::Message const* response); void SendBattlenetResponse(uint32 serviceHash, uint32 methodId, uint32 token, uint32 status); diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index b6a3e4dd80..63b5586dda 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -4529,13 +4529,9 @@ void Spell::EffectTransmitted() // end time of range when possible catch fish (FISHING_BOBBER_READY_TIME..GetDuration(m_spellInfo)) // start time == fish-FISHING_BOBBER_READY_TIME (0..GetDuration(m_spellInfo)-FISHING_BOBBER_READY_TIME) - int32 lastSec = 0; - switch (urand(0, 2)) - { - case 0: lastSec = 3; break; - case 1: lastSec = 7; break; - case 2: lastSec = 13; break; - } + // Classic 1.60 (official beta sniff): the fish bites anywhere from a few seconds after the cast to near the end of + // the 30 s channel (8-25 s seen), not only at TC's three fixed times (17/23/25 s) + int32 lastSec = irand(3, std::max(3, duration / IN_MILLISECONDS - 5)); // Duration of the fishing bobber can't be higher than the Fishing channeling duration duration = std::min(duration, duration - lastSec*IN_MILLISECONDS + FISHING_BOBBER_READY_TIME*IN_MILLISECONDS); @@ -4563,7 +4559,7 @@ void Spell::EffectTransmitted() go->SetOwnerGUID(unitCaster->GetGUID()); - //go->SetLevel(unitCaster->getLevel()); + go->SetLevel(unitCaster->GetLevel()); // Classic 1.60: objects placed by players carry the owner's level (official sniff) go->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effectInfo->Effect, go); diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index aca2ae0090..5fbdabb8b0 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -991,8 +991,10 @@ public: if (!spellInfo) return false; - if (Player* caster = handler->GetSession()->GetPlayer()) + if (Player* caster = handler->GetSession() ? handler->GetSession()->GetPlayer() : nullptr) caster->SendDirectMessage(WorldPackets::Misc::DisplayGameError(GameError::ERR_CLIENT_LOCKED_OUT).Write()); + else + handler->SendSysMessage("Player is in combat or in flight."); return false; } diff --git a/src/server/scripts/Custom/Classic/classic_script_loader.cpp b/src/server/scripts/Custom/Classic/classic_script_loader.cpp index 526645ef22..f754a8cf8f 100644 --- a/src/server/scripts/Custom/Classic/classic_script_loader.cpp +++ b/src/server/scripts/Custom/Classic/classic_script_loader.cpp @@ -193,6 +193,7 @@ void AddSC_classic_silithus(); void AddSC_classic_world_event_wareffort(); void AddSC_classic_npcs_special(); void AddSC_classic_go_scripts(); +void AddSC_classic_armory_commands(); void AddSC_classic_wetlands(); void AddSC_classic_westfall(); void AddSC_classic_western_plaguelands(); @@ -382,6 +383,7 @@ void AddClassicScripts() AddSC_classic_world_event_wareffort(); AddSC_classic_npcs_special(); AddSC_classic_go_scripts(); + AddSC_classic_armory_commands(); AddSC_classic_wetlands(); AddSC_classic_westfall(); AddSC_classic_western_plaguelands(); diff --git a/src/server/scripts/Custom/Classic/world/classic_armory_commands.cpp b/src/server/scripts/Custom/Classic/world/classic_armory_commands.cpp new file mode 100644 index 0000000000..f529361493 --- /dev/null +++ b/src/server/scripts/Custom/Classic/world/classic_armory_commands.cpp @@ -0,0 +1,205 @@ +/* + * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +// Classic 1.60: data for the website armory (contrib/support_site). ".armory export" writes every item the server knows, with the +// values the game shows (DB2 + hotfixes; stats from StatPercentEditor and the random property points, like Item::GetItemStatValue), +// into world.armory_item, and the race, class, skill and achievement names into world.armory_name. Run it after data changes; the +// site runs it through RA when the tables are empty. + +#include "Chat.h" +#include "ChatCommand.h" +#include "DatabaseEnv.h" +#include "DB2Stores.h" +#include "GameTables.h" +#include "ItemEnchantmentMgr.h" +#include "ItemTemplate.h" +#include "ObjectMgr.h" +#include "RBAC.h" +#include "ScriptMgr.h" +#include "StringFormat.h" +#include "Timer.h" +#include + +using namespace Trinity::ChatCommands; + +namespace +{ +std::string Quote(std::string text) +{ + WorldDatabase.EscapeString(text); + return "'" + text + "'"; +} + +// icon of the item's default appearance (lowest OrderIndex of modifier 0), else the item's own icon +std::unordered_map BuildIconMap() +{ + std::unordered_map> best; // item -> (order, appearance) + for (ItemModifiedAppearanceEntry const* ima : sItemModifiedAppearanceStore) + { + if (ima->ItemAppearanceModifierID != 0) + continue; + auto itr = best.find(ima->ItemID); + if (itr == best.end() || ima->OrderIndex < itr->second.first) + best[ima->ItemID] = { ima->OrderIndex, ima->ItemAppearanceID }; + } + + std::unordered_map icons; + for (auto const& [itemId, appearance] : best) + if (ItemAppearanceEntry const* entry = sItemAppearanceStore.LookupEntry(appearance.second)) + icons[itemId] = entry->DefaultIconFileDataID; + return icons; +} +} + +class classic_armory_commandscript : public CommandScript +{ +public: + classic_armory_commandscript() : CommandScript("classic_armory_commandscript") { } + + std::span GetCommands() const override + { + static ChatCommandTable armoryCommandTable = + { + { "export", HandleExportCommand, rbac::RBAC_PERM_COMMAND_RELOAD, Console::Yes }, + }; + static ChatCommandTable commandTable = + { + { "armory", armoryCommandTable }, + }; + return commandTable; + } + + static bool HandleExportCommand(ChatHandler* handler) + { + uint32 oldMSTime = getMSTime(); + uint32 items = ExportItems(); + uint32 names = ExportNames(); + handler->PSendSysMessage("Armory: exported %u items and %u names in %u ms.", items, names, GetMSTimeDiffToNow(oldMSTime)); + return true; + } + + static uint32 ExportNames() + { + WorldDatabaseTransaction trans = WorldDatabase.BeginTransaction(); + trans->Append("DELETE FROM armory_name"); + std::string values; + uint32 rows = 0; + auto add = [&](char const* kind, uint32 id, char const* name, int32 icon, int32 extra) + { + if (!name || !*name) + return; + values += Trinity::StringFormat("{}('{}',{},{},{},{})", values.empty() ? "" : ",", kind, id, Quote(name), icon, extra); + ++rows; + if (values.size() > 60000) + { + trans->Append(("INSERT INTO armory_name (kind, id, name, iconFileDataId, extra) VALUES " + values).c_str()); + values.clear(); + } + }; + + for (ChrRacesEntry const* race : sChrRacesStore) + add("race", race->ID, race->Name[LOCALE_enUS], 0, race->Alliance); // 0 Alliance, 1 Horde, 2 neutral + for (ChrClassesEntry const* cls : sChrClassesStore) + add("class", cls->ID, cls->Name[LOCALE_enUS], 0, 0); + for (SkillLineEntry const* skill : sSkillLineStore) + add("skill", skill->ID, skill->DisplayName[LOCALE_enUS], skill->SpellIconFileID, skill->CategoryID); + for (AchievementEntry const* achievement : sAchievementStore) + add("achievement", achievement->ID, achievement->Title[LOCALE_enUS], achievement->IconFileID, achievement->Points); + + if (!values.empty()) + trans->Append(("INSERT INTO armory_name (kind, id, name, iconFileDataId, extra) VALUES " + values).c_str()); + WorldDatabase.DirectCommitTransaction(trans); + return rows; + } + + static uint32 ExportItems() + { + std::unordered_map icons = BuildIconMap(); + + WorldDatabaseTransaction trans = WorldDatabase.BeginTransaction(); + trans->Append("DELETE FROM armory_item"); + + std::string values; + uint32 rows = 0, inBatch = 0; + auto flush = [&]() + { + if (values.empty()) + return; + trans->Append(("INSERT INTO armory_item (id, name, quality, itemLevel, requiredLevel, class, subclass, inventoryType, bonding, " + "armor, dmgMin, dmgMax, delay, stats, effects, description, iconFileDataId, sellPrice, allowableClass, itemSet, requiredSkill, " + "requiredSkillRank, flags) VALUES " + values).c_str()); + values.clear(); + inBatch = 0; + }; + + for (auto const& [itemId, proto] : sObjectMgr->GetItemTemplateStore()) + { + uint32 itemLevel = proto.GetBaseItemLevel(); + + std::string stats; + float points = GetRandomPropertyPoints(itemLevel, proto.GetQuality(), proto.GetInventoryType(), proto.GetSubClass()); + for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i) + { + int32 type = proto.GetStatModifierBonusStat(i); + if (type < 0 || !proto.GetStatPercentEditor(i)) + continue; + float value = float(proto.GetStatPercentEditor(i) * points) * 0.0001f; + if (GtItemSocketCostPerLevelEntry const* gtCost = sItemSocketCostPerLevelGameTable.GetRow(itemLevel)) + value -= proto.GetStatPercentageOfSocket(i) * gtCost->SocketCost; + if (int32 rounded = int32(value + (value >= 0 ? 0.5f : -0.5f))) + stats += Trinity::StringFormat("{}{}:{}", stats.empty() ? "" : ",", type, rounded); + } + + std::string effects; + for (ItemEffectEntry const* effect : proto.Effects) + { + SpellNameEntry const* spellName = sSpellNameStore.LookupEntry(effect->SpellID); + std::string name = spellName ? spellName->Name[LOCALE_enUS] : ""; + std::erase_if(name, [](char c) { return c == '|' || c == ':'; }); + effects += Trinity::StringFormat("{}{}:{}:{}", effects.empty() ? "" : "|", effect->TriggerType, effect->SpellID, name); + } + + // ItemTemplate::GetDPS asserts when the damage tables have no row for the item level (some weapons in the data do) + float dmgMin = 0.0f, dmgMax = 0.0f; + if (proto.GetClass() == ITEM_CLASS_WEAPON && sItemDamageOneHandStore.LookupEntry(itemLevel) && sItemDamageOneHandCasterStore.LookupEntry(itemLevel) + && sItemDamageTwoHandStore.LookupEntry(itemLevel) && sItemDamageTwoHandCasterStore.LookupEntry(itemLevel) + && sItemDamageAmmoStore.LookupEntry(itemLevel)) + proto.GetDamage(itemLevel, dmgMin, dmgMax); + + auto icon = icons.find(itemId); + int32 iconFileDataId = icon != icons.end() && icon->second ? icon->second : proto.BasicData->IconFileDataID; + + values += Trinity::StringFormat("{}({},{},{},{},{},{},{},{},{},{},{:.1f},{:.1f},{},{},{},{},{},{},{},{},{},{},{})", + values.empty() ? "" : ",", itemId, Quote(proto.GetName(LOCALE_enUS)), proto.GetQuality(), itemLevel, proto.GetBaseRequiredLevel(), + proto.GetClass(), proto.GetSubClass(), uint32(proto.GetInventoryType()), uint32(proto.GetBonding()), proto.GetArmor(itemLevel), + dmgMin, dmgMax, proto.GetDelay(), Quote(stats), Quote(effects), Quote(proto.ExtendedData->Description[LOCALE_enUS]), iconFileDataId, + proto.GetSellPrice(), proto.GetAllowableClass(), proto.GetItemSet(), proto.GetRequiredSkill(), proto.GetRequiredSkillRank(), + proto.ExtendedData->Flags[0]); + ++rows; + if (++inBatch == 500) + flush(); + } + flush(); + WorldDatabase.DirectCommitTransaction(trans); + return rows; + } +}; + +void AddSC_classic_armory_commands() +{ + new classic_armory_commandscript(); +} diff --git a/src/server/scripts/Custom/Classic/world/classic_go_scripts.cpp b/src/server/scripts/Custom/Classic/world/classic_go_scripts.cpp index b20b19b42e..503e69dbec 100644 --- a/src/server/scripts/Custom/Classic/world/classic_go_scripts.cpp +++ b/src/server/scripts/Custom/Classic/world/classic_go_scripts.cpp @@ -19,6 +19,8 @@ // Field Repair Bot 74A schematic: teaches spell 22704 to engineers (skill >= 300) #include "ScriptMgr.h" +#include "AreaTrigger.h" +#include "AreaTriggerAI.h" #include "GameObject.h" #include "GameObjectAI.h" #include "Player.h" @@ -259,8 +261,153 @@ struct classic_go_camp_chair : public GameObjectAI } }; +/*###### +## classic_spell_plainsrunning (1259918) +######*/ + +// Classic 1.60 Tauren racial: "Gain 1% increased movement speed every 5 sec spent moving, up to a maximum of 30% increase. Taking +// damage or standing still will reduce this effect." The racial is a 1 s periodic dummy (effect 0) with the step seconds and the +// maximum in effects 1 and 2; the speed is the stacking aura Plainsrunning (1299038, +1% per stack). How fast it decays is not in +// the spell data: here one stack per second standing still and five stacks when hit. +enum Plainsrunning +{ + SPELL_PLAINSRUNNING_SPEED = 1299038, + PLAINSRUNNING_STACKS_LOST_ON_HIT = 5 +}; + +class classic_spell_plainsrunning : public AuraScript +{ + bool Validate(SpellInfo const* spellInfo) override + { + return ValidateSpellInfo({ SPELL_PLAINSRUNNING_SPEED }) && ValidateSpellEffect({ { spellInfo->Id, EFFECT_2 } }); + } + + void RemoveStacks(Unit* target, int32 count) + { + Aura* speed = target->GetAura(SPELL_PLAINSRUNNING_SPEED); + if (!speed) + return; + + if (speed->GetStackAmount() <= count) + speed->Remove(); + else + speed->ModStackAmount(-count); + } + + void HandlePeriodic(AuraEffect const* /*aurEff*/) + { + Unit* target = GetTarget(); + int32 secondsPerStack = std::max(1, int32(GetEffect(EFFECT_1)->GetAmount())); + int32 maxStacks = std::max(1, int32(GetEffect(EFFECT_2)->GetAmount())); + + uint64 health = target->GetHealth(); + bool hit = health < _lastHealth; + _lastHealth = health; + if (hit) + { + _movingSeconds = 0; + RemoveStacks(target, PLAINSRUNNING_STACKS_LOST_ON_HIT); + return; + } + + if (!target->isMoving()) + { + _movingSeconds = 0; + RemoveStacks(target, 1); + return; + } + + if (++_movingSeconds < secondsPerStack) + return; + + _movingSeconds = 0; + if (Aura* speed = target->GetAura(SPELL_PLAINSRUNNING_SPEED)) + { + if (speed->GetStackAmount() < maxStacks) + speed->ModStackAmount(1); + else + speed->RefreshDuration(); + } + else + target->CastSpell(target, SPELL_PLAINSRUNNING_SPEED, true); + } + + void Register() override + { + OnEffectPeriodic += AuraEffectPeriodicFn(classic_spell_plainsrunning::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); + } + + uint32 _movingSeconds = 0; + uint64 _lastHealth = 0; +}; + +/*###### +## classic_at_energizing_vortex (area trigger of Energizing Winds 1299003, create properties 43253) +######*/ + +// Classic 1.60 (WoW Forever): touching an Energizing Vortex gives Blessing of Zephras (run speed +40% for 5 min). The player casts +// it on himself: an area trigger action would cast it as the vortex, and TC removes such auras when the unit leaves the (moving) +// trigger, a second later. +enum EnergizingVortex +{ + SPELL_BLESSING_OF_ZEPHRAS = 1258510 +}; + +struct classic_at_energizing_vortex : AreaTriggerAI +{ + explicit classic_at_energizing_vortex(AreaTrigger* areaTrigger) : AreaTriggerAI(areaTrigger) { } + + void OnUnitEnter(Unit* unit) override + { + if (Player* player = unit->ToPlayer()) + if (!player->IsInCombat()) + player->CastSpell(player, SPELL_BLESSING_OF_ZEPHRAS, true); + } +}; + +/*###### +## classic_event_skycutter_arrival (taxi path arrival events of the Skycutters) +######*/ + +// Classic 1.60 (WoW Forever): when a Skycutter docks, the dockmaster there announces it (official beta sniff, build 70170). The +// events are the ArrivalEventIDs of the dock nodes in TaxiPathNode.db2; the Mulgore Skycutter's docks (105969 Zephras Isle, +// 105967 Mulgore) were not heard in the sniffs yet. +struct SkycutterAnnouncement +{ + uint32 EventId; + uint32 Creature; + char const* Text; +}; + +static constexpr SkycutterAnnouncement SkycutterAnnouncements[] = +{ + { 105988, 275269, "The skycutter bound for Dalaran City has just arrived. All aboard for Dalaran City!" }, // Zephras Isle dock, High Order Dockmaster + { 103315, 256306, "The skycutter to Zephras Isle has just arrived. Please watch your step when boarding the vessel." }, // Dalaran (Lordamere Lake) dock, Arcanist Laurain +}; + +class classic_event_skycutter_arrival : public EventScript +{ +public: + classic_event_skycutter_arrival() : EventScript("classic_event_skycutter_arrival") { } + + void OnTrigger(WorldObject* object, WorldObject* invoker, uint32 eventId) override + { + WorldObject* transport = object ? object : invoker; + if (!transport) + return; + + for (SkycutterAnnouncement const& announcement : SkycutterAnnouncements) + if (announcement.EventId == eventId) + if (Creature* dockmaster = transport->FindNearestCreature(announcement.Creature, 100.0f)) + dockmaster->Say(announcement.Text, LANG_UNIVERSAL); + } +}; + void AddSC_classic_go_scripts() { + new classic_event_skycutter_arrival(); + RegisterSpellScript(classic_spell_plainsrunning); + RegisterAreaTriggerAI(classic_at_energizing_vortex); RegisterGameObjectAI(classic_go_field_repair_bot_74A); RegisterGameObjectAI(classic_go_camp_chair); RegisterSpellScript(classic_spell_campfire_rest); diff --git a/src/server/scripts/Custom/Classic/world/classic_npcs_special.cpp b/src/server/scripts/Custom/Classic/world/classic_npcs_special.cpp index f7747023a1..ac21118acc 100644 --- a/src/server/scripts/Custom/Classic/world/classic_npcs_special.cpp +++ b/src/server/scripts/Custom/Classic/world/classic_npcs_special.cpp @@ -24,6 +24,8 @@ #include "MotionMaster.h" #include "ObjectAccessor.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "Player.h" #include "SpellInfo.h" @@ -136,7 +138,140 @@ private: ObjectGuid _playerGUID; }; +/*###### +## classic_npc_malfunctioning_cyclone_construct (250929) +######*/ + +// Classic 1.60 (WoW Forever), Zephras Isle orchard event (official beta sniff, build 70170): every ~114 s Ferauu the Bludgeon and +// six Bandit Henchmen appear on the road, Ferauu yells and they walk down to the orchard. ~44 s after they appeared the construct, +// which wanders by its post otherwise, walks over, yells, kills them with Chain Lightning, yells again and walks back. +enum CycloneConstructEvent +{ + NPC_FERAUU_THE_BLUDGEON = 252863, + NPC_BANDIT_HENCHMAN = 252875, + SPELL_CONSTRUCT_CHAIN_LIGHTNING = 1257106, + + EVENT_BANDITS_APPEAR = 1, + EVENT_CONSTRUCT_GO, + EVENT_CONSTRUCT_STRIKE, + EVENT_CONSTRUCT_DONE, + + POINT_CONSTRUCT_STRIKE = 1, + POINT_CONSTRUCT_HOME = 2 +}; + +static constexpr Milliseconds CycloneEventPeriod = 114s; +static constexpr Milliseconds CycloneStrikeDelay = 44s; +static constexpr float CycloneWanderDistance = 15.0f; + +static Position const FerauuStart = { 2110.0f, 1543.5f, 664.7f, 3.6f }; +static Position const FerauuEnd = { 2071.0f, 1571.1f, 655.7f, 3.6f }; +static Position const ConstructStrikeAt = { 2069.0f, 1557.4f, 655.2f, 1.6f }; + +// start (on the road) -> end (in the orchard) of each henchman +static std::pair const HenchmanPaths[] = +{ + { { 2115.7f, 1548.3f, 665.8f, 3.6f }, { 2078.6f, 1573.9f, 657.0f, 3.6f } }, + { { 2117.1f, 1550.8f, 666.7f, 3.6f }, { 2075.6f, 1575.6f, 656.5f, 3.6f } }, + { { 2114.5f, 1550.3f, 666.0f, 3.6f }, { 2074.4f, 1572.8f, 656.0f, 3.6f } }, + { { 2106.5f, 1535.5f, 664.9f, 3.6f }, { 2073.2f, 1559.9f, 656.2f, 3.6f } }, + { { 2108.4f, 1537.7f, 665.1f, 3.6f }, { 2070.3f, 1562.3f, 655.9f, 3.6f } }, + { { 2105.8f, 1537.8f, 664.6f, 3.6f }, { 2068.4f, 1560.0f, 654.7f, 3.6f } }, +}; + +struct classic_npc_malfunctioning_cyclone_construct : public ScriptedAI +{ + classic_npc_malfunctioning_cyclone_construct(Creature* creature) : ScriptedAI(creature), _summons(creature) { } + + void JustAppeared() override + { + _events.Reset(); + _events.ScheduleEvent(EVENT_BANDITS_APPEAR, 30s); + me->GetMotionMaster()->MoveRandom(CycloneWanderDistance); + } + + void JustSummoned(Creature* summon) override + { + _summons.Summon(summon); + } + + void SummonedCreatureDespawn(Creature* summon) override + { + _summons.Despawn(summon); + } + + void MovementInform(uint32 type, uint32 id) override + { + if (type != POINT_MOTION_TYPE) + return; + + if (id == POINT_CONSTRUCT_STRIKE) + { + me->Yell("THREAT DETECTED. ADMINISTERING VIOLENCE.", LANG_UNIVERSAL); + _events.ScheduleEvent(EVENT_CONSTRUCT_STRIKE, 3s); + } + else if (id == POINT_CONSTRUCT_HOME) + me->GetMotionMaster()->MoveRandom(CycloneWanderDistance); + } + + void UpdateAI(uint32 diff) override + { + _events.Update(diff); + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_BANDITS_APPEAR: + { + _summons.DespawnAll(); + if (Creature* ferauu = me->SummonCreature(NPC_FERAUU_THE_BLUDGEON, FerauuStart, TEMPSUMMON_MANUAL_DESPAWN)) + { + ferauu->Yell("Little apple farmers! Ferauu is here to collect what is owed!", LANG_UNIVERSAL); + ferauu->GetMotionMaster()->MovePoint(0, FerauuEnd); + } + for (auto const& [start, end] : HenchmanPaths) + if (Creature* henchman = me->SummonCreature(NPC_BANDIT_HENCHMAN, start, TEMPSUMMON_MANUAL_DESPAWN)) + henchman->GetMotionMaster()->MovePoint(0, end); + _events.ScheduleEvent(EVENT_CONSTRUCT_GO, CycloneStrikeDelay); + _events.ScheduleEvent(EVENT_BANDITS_APPEAR, CycloneEventPeriod); + break; + } + case EVENT_CONSTRUCT_GO: + me->GetMotionMaster()->Clear(); + me->GetMotionMaster()->MovePoint(POINT_CONSTRUCT_STRIKE, ConstructStrikeAt); + break; + case EVENT_CONSTRUCT_STRIKE: + { + if (Creature* ferauu = me->FindNearestCreature(NPC_FERAUU_THE_BLUDGEON, 40.0f)) + me->CastSpell(ferauu, SPELL_CONSTRUCT_CHAIN_LIGHTNING, true); + for (ObjectGuid const& guid : _summons) + if (Creature* bandit = ObjectAccessor::GetCreature(*me, guid)) + if (bandit->IsAlive()) + { + bandit->KillSelf(); + bandit->DespawnOrUnsummon(10s); + } + _events.ScheduleEvent(EVENT_CONSTRUCT_DONE, 3s); + break; + } + case EVENT_CONSTRUCT_DONE: + me->Yell("FUNCTION FULFILLED. RESUMING REST MODE.", LANG_UNIVERSAL); + me->GetMotionMaster()->MovePoint(POINT_CONSTRUCT_HOME, me->GetHomePosition()); + break; + default: + break; + } + } + } + +private: + EventMap _events; + SummonList _summons; +}; + void AddSC_classic_npcs_special() { RegisterCreatureAI(classic_npc_sickly_critter); + RegisterCreatureAI(classic_npc_malfunctioning_cyclone_construct); }