Compare commits

...

5 commits

Author SHA1 Message Date
Lukas Brübach
e36b59c2f5 [Client] Alt tab filters and unified user timeline
TabAlts gains client-side match filters (Email / Client ID / IP toggles plus a hide-IPs-shared-by-more-than-N-users threshold for VPN noise) with a shown/hidden status count, and a Selected user panel that loads the row account's counts, admin notes, warning history, and ban history in one place. Detail requests are guarded against stale selections.
2026-10-13 20:50:33 +02:00
Lukas Brübach
3823dfa087 [Client] Alt investigation entry points and in-tab navigation
TabModeration gains an Open alt graph button plus alts-table double-click, both routing to the User Alts tab. UserContextMenu gains an Investigate alts action. TabAlts gains row double-click navigation with a Back history stack so moderators can walk the alt graph without retyping names.
2026-10-13 20:50:33 +02:00
Lukas Brübach
f468315826 [Client] Transient User Alts investigation tab
New TabAlts tab with user search, depth selector (1-3), and an alt table showing per-row match evidence (Via, Depth, Shared fan-out) alongside the account data. Sends Command_GetUserAlts with the requested depth and degrades gracefully against old servers (missing evidence fields render as dashes). Wired as a transient single-reuse tab via TabSupervisor::openTabAlts with no menu action or persisted setting; closed on disconnect like the other staff tabs.
2026-10-13 20:50:33 +02:00
Lukas Brübach
3113289dbe [Server] Recursive alt search with match evidence
getUserAlts() now walks a breadth-first graph to the requested depth (clamped 1-3): each level expands frontier accounts over registration email, current client id, recent session IPs (6-month window), and historic session client ids, so identifier changes no longer hide older alts. Every row carries match_reason (email / clientid:<id> / ip:<addr>), depth, and shared_count fan-out so moderators can distinguish real alts from VPN/shared-network overlap. Command_GetUserAlts depth is plumbed through; unset depth defaults to 1, preserving previous single-hop behavior for old clients.
2026-10-13 20:50:29 +02:00
Lukas Brübach
a7fa3f0852 [Protocol] Add alt match evidence and search depth
ServerInfo_UserAlt gains match_reason, depth, and shared_count so moderators can see why an account was flagged and how far it sits from the investigated user. Command_GetUserAlts gains a depth parameter (default 1) for transitive alt-of-alt searches. No behavior change: server still answers depth 1 and leaves the new fields empty until the follow-up server/client layers land.
2026-10-13 20:01:41 +02:00
14 changed files with 975 additions and 53 deletions

View file

@ -393,6 +393,7 @@ set(cockatrice_SOURCES
src/interface/widgets/tabs/tab.cpp
src/interface/widgets/tabs/tab_account.cpp
src/interface/widgets/tabs/tab_admin.cpp
src/interface/widgets/tabs/tab_alts.cpp
src/interface/widgets/tabs/tab_card_art_rules.cpp
src/interface/widgets/tabs/tab_deck_editor.cpp
src/interface/widgets/tabs/tab_deck_storage.cpp

View file

@ -82,6 +82,7 @@ UserContextMenu::UserContextMenu(TabSupervisor *_tabSupervisor, QWidget *parent,
aDemoteFromDeveloper = new QAction(QString(), this);
aGetAdminNotes = new QAction(QString(), this);
aInvestigateUser = new QAction(QString(), this);
aInvestigateAlts = new QAction(QString(), this);
retranslateUi();
}
@ -110,6 +111,7 @@ void UserContextMenu::retranslateUi()
aDemoteFromDeveloper->setText(tr("Demote user from de&veloper"));
aGetAdminNotes->setText(tr("View admin notes"));
aInvestigateUser->setText(tr("Investigate user"));
aInvestigateAlts->setText(tr("Investigate &alts"));
}
void UserContextMenu::gamesOfUserReceived(const Response &resp, const CommandContainer &commandContainer)
@ -453,6 +455,7 @@ void UserContextMenu::showContextMenu(const QPoint &pos,
menu->addSeparator();
menu->addAction(aGetAdminNotes);
menu->addAction(aInvestigateUser);
menu->addAction(aInvestigateAlts);
menu->addSeparator();
if (userLevel.testFlag(ServerInfo_User::IsModerator) &&
@ -498,6 +501,7 @@ void UserContextMenu::showContextMenu(const QPoint &pos,
aBanHistory->setEnabled(anotherUser);
aGetAdminNotes->setEnabled(anotherUser);
aInvestigateUser->setEnabled(anotherUser);
aInvestigateAlts->setEnabled(anotherUser);
aPromoteToMod->setEnabled(anotherUser);
aDemoteFromMod->setEnabled(anotherUser);
aPromoteToJudge->setEnabled(anotherUser);
@ -552,6 +556,8 @@ void UserContextMenu::showContextMenu(const QPoint &pos,
execAdminNotes(userName);
} else if (actionClicked == aInvestigateUser) {
execInvestigateUser(userName);
} else if (actionClicked == aInvestigateAlts) {
execInvestigateAlts(userName);
} else if (actionClicked == aCopyToClipBoard) {
QClipboard *clipboard = QGuiApplication::clipboard();
clipboard->setText(deckHash);
@ -746,6 +752,11 @@ void UserContextMenu::execInvestigateUser(const QString &userName)
tabSupervisor->openTabModeration(userName);
}
void UserContextMenu::execInvestigateAlts(const QString &userName)
{
tabSupervisor->openTabAlts(userName);
}
void UserContextMenu::execAdjustMod(const QString &userName, bool shouldBeMod)
{
Command_AdjustMod cmd;

View file

@ -54,6 +54,7 @@ private:
QAction *aGetAdminNotes;
std::function<QList<GameInviteOption>()> gameInviteLinkProvider;
QAction *aInvestigateUser;
QAction *aInvestigateAlts;
signals:
void openMessageDialog(const QString &userName, bool focus);
private slots:
@ -127,6 +128,7 @@ public:
void execWarnHistory(const QString &userName);
void execAdminNotes(const QString &userName);
void execInvestigateUser(const QString &userName);
void execInvestigateAlts(const QString &userName);
void execAdjustMod(const QString &userName, bool shouldBeMod);
void execAdjustJudge(const QString &userName, bool shouldBeJudge);
void execAdjustDeveloper(const QString &userName, bool shouldBeDeveloper);

View file

@ -0,0 +1,471 @@
#include "tab_alts.h"
#include "abstract_client.h"
#include "libcockatrice/protocol/pb/response.pb.h"
#include "libcockatrice/protocol/pb/response_user_alts.pb.h"
#include <QAbstractItemView>
#include <QCheckBox>
#include <QDateTime>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QList>
#include <QPushButton>
#include <QSpinBox>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QWidget>
#include <libcockatrice/protocol/pb/command_report_user_info.pb.h>
#include <libcockatrice/protocol/pb/moderator_commands.pb.h>
#include <libcockatrice/protocol/pb/response_ban_history.pb.h>
#include <libcockatrice/protocol/pb/response_report_user_info.pb.h>
#include <libcockatrice/protocol/pb/response_warn_history.pb.h>
#include <libcockatrice/protocol/pb/serverinfo_ban.pb.h>
#include <libcockatrice/protocol/pb/serverinfo_warning.pb.h>
#include <libcockatrice/protocol/pending_command.h>
#include <string>
namespace
{
constexpr int COL_ALTS_USER = 0;
constexpr int COL_ALTS_VIA = 1;
constexpr int COL_ALTS_DEPTH = 2;
constexpr int COL_ALTS_SHARED = 3;
constexpr int COL_ALTS_EMAIL = 4;
constexpr int COL_ALTS_CLIENTID = 5;
constexpr int COL_ALTS_REGISTERED = 6;
constexpr int COL_ALTS_LAST_LOGIN = 7;
constexpr int COL_ALTS_WARNS = 8;
constexpr int COL_ALTS_BANS = 9;
constexpr int COL_ALTS_ACTIVE = 10;
constexpr int COL_ALTS_COUNT = 11;
constexpr int MAX_ALT_DEPTH = 3;
// Starting default only (adjustable 1-100000): shared VPN exits routinely
// cover dozens of users, so 10 hides the obvious VPN noise but keeps
// small shared networks visible.
constexpr int DEFAULT_VPN_THRESHOLD = 10;
void configureAltTable(QTableWidget *table)
{
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::SingleSelection);
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
table->verticalHeader()->setVisible(false);
table->setAlternatingRowColors(true);
table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
table->horizontalHeader()->setStretchLastSection(true);
}
} // namespace
TabAlts::TabAlts(TabSupervisor *_tabSupervisor, AbstractClient *_client, const QString &initialUser)
: Tab(_tabSupervisor), client(_client)
{
auto *centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
searchEdit = new QLineEdit;
searchEdit->setClearButtonEnabled(true);
connect(searchEdit, &QLineEdit::returnPressed, this, &TabAlts::investigateUser);
depthSpin = new QSpinBox;
depthSpin->setMinimum(1);
depthSpin->setMaximum(MAX_ALT_DEPTH);
depthSpin->setValue(1);
investigateButton = new QPushButton;
connect(investigateButton, &QPushButton::clicked, this, &TabAlts::investigateUser);
backButton = new QPushButton;
backButton->setEnabled(false);
connect(backButton, &QPushButton::clicked, this, &TabAlts::goBack);
statusLabel = new QLabel;
auto *topBar = new QHBoxLayout;
topBar->addWidget(backButton);
topBar->addWidget(searchEdit);
topBar->addWidget(depthSpin);
topBar->addWidget(investigateButton);
emailCheck = new QCheckBox;
emailCheck->setChecked(true);
connect(emailCheck, &QCheckBox::toggled, this, &TabAlts::onFilterChanged);
clientIdCheck = new QCheckBox;
clientIdCheck->setChecked(true);
connect(clientIdCheck, &QCheckBox::toggled, this, &TabAlts::onFilterChanged);
ipCheck = new QCheckBox;
ipCheck->setChecked(true);
connect(ipCheck, &QCheckBox::toggled, this, &TabAlts::onFilterChanged);
vpnLabel = new QLabel;
vpnSpin = new QSpinBox;
vpnSpin->setMinimum(1);
vpnSpin->setMaximum(100000);
vpnSpin->setValue(DEFAULT_VPN_THRESHOLD);
connect(vpnSpin, &QSpinBox::valueChanged, this, &TabAlts::onFilterChanged);
auto *filterBar = new QHBoxLayout;
filterBar->addWidget(emailCheck);
filterBar->addWidget(clientIdCheck);
filterBar->addWidget(ipCheck);
filterBar->addWidget(vpnLabel);
filterBar->addWidget(vpnSpin);
filterBar->addStretch();
altsTable = new QTableWidget(0, COL_ALTS_COUNT);
configureAltTable(altsTable);
connect(altsTable, &QTableWidget::cellDoubleClicked, this, [this](int row, int) {
auto *userItem = altsTable->item(row, COL_ALTS_USER);
if (userItem != nullptr && !userItem->text().isEmpty() && userItem->text() != currentUser) {
investigate(userItem->text());
}
});
connect(altsTable, &QTableWidget::itemSelectionChanged, this, &TabAlts::onAltSelected);
detailNameValue = new QLabel;
detailCountsValue = new QLabel;
detailNotesEdit = new QTextEdit;
detailNotesEdit->setReadOnly(true);
// Compact cap so the warn/ban tables stay visible without scrolling the tab.
detailNotesEdit->setMaximumHeight(60);
warnsTable = new QTableWidget(0, 3);
configureAltTable(warnsTable);
bansTable = new QTableWidget(0, 4);
configureAltTable(bansTable);
auto *detailGrid = new QGridLayout;
detailNameLabel = new QLabel;
detailCountsLabel = new QLabel;
detailNotesLabel = new QLabel;
detailGrid->addWidget(detailNameLabel, 0, 0);
detailGrid->addWidget(detailNameValue, 0, 1);
detailGrid->addWidget(detailCountsLabel, 0, 2);
detailGrid->addWidget(detailCountsValue, 0, 3);
detailGrid->addWidget(detailNotesLabel, 1, 0);
detailGrid->addWidget(detailNotesEdit, 1, 1, 1, 3);
auto *detailTables = new QHBoxLayout;
detailTables->addWidget(warnsTable);
detailTables->addWidget(bansTable);
detailsGroup = new QGroupBox;
auto *detailsLayout = new QVBoxLayout(detailsGroup);
detailsLayout->addLayout(detailGrid);
detailsLayout->addLayout(detailTables);
auto *mainLayout = new QVBoxLayout(centralWidget);
mainLayout->addLayout(topBar);
mainLayout->addLayout(filterBar);
mainLayout->addWidget(statusLabel);
mainLayout->addWidget(altsTable, 3);
mainLayout->addWidget(detailsGroup, 2);
retranslateUi();
clearDetails();
investigate(initialUser);
}
void TabAlts::retranslateUi()
{
searchEdit->setPlaceholderText(tr("User name"));
depthSpin->setPrefix(tr("Depth: "));
depthSpin->setToolTip(tr("Search depth: 1 finds direct matches, higher values follow alts of alts."));
investigateButton->setText(tr("Investigate"));
backButton->setText(tr("Back"));
backButton->setToolTip(tr("Back to the previously investigated user"));
if (currentUser.isEmpty()) {
statusLabel->setText(tr("Enter a user name to investigate."));
}
emailCheck->setText(tr("Email"));
clientIdCheck->setText(tr("Client ID"));
ipCheck->setText(tr("IP"));
vpnLabel->setText(tr("Hide IPs shared by more than"));
vpnSpin->setSuffix(tr(" users"));
altsTable->setHorizontalHeaderLabels({tr("User"), tr("Via"), tr("Depth"), tr("Shared"), tr("eMail"),
tr("Client ID"), tr("Registered"), tr("Last login"), tr("Warns"), tr("Bans"),
tr("Active")});
warnsTable->setHorizontalHeaderLabels({tr("Warning time"), tr("Moderator"), tr("Reason")});
bansTable->setHorizontalHeaderLabels({tr("Ban time"), tr("Moderator"), tr("Length"), tr("Reason")});
detailsGroup->setTitle(tr("Selected user"));
detailNameLabel->setText(tr("Name:"));
detailCountsLabel->setText(tr("Counts:"));
detailNotesLabel->setText(tr("Admin notes:"));
}
QString TabAlts::formatEpoch(quint64 ts) const
{
if (ts == 0) {
return tr("Unknown");
}
return QDateTime::fromSecsSinceEpoch(ts).toLocalTime().toString("yyyy-MM-dd HH:mm");
}
void TabAlts::investigate(const QString &userName)
{
if (userName.isEmpty() || userName == currentUser) {
return;
}
if (!currentUser.isEmpty()) {
backStack << currentUser;
backButton->setEnabled(true);
}
loadUser(userName);
}
void TabAlts::goBack()
{
if (backStack.isEmpty()) {
return;
}
const QString previousUser = backStack.takeLast();
backButton->setEnabled(!backStack.isEmpty());
loadUser(previousUser);
}
void TabAlts::loadUser(const QString &userName)
{
currentUser = userName;
searchEdit->setText(userName);
investigateUser();
}
void TabAlts::investigateUser()
{
const QString userName = searchEdit->text().simplified();
if (userName.isEmpty()) {
return;
}
currentUser = userName;
lastAlts.clear();
selectedUser.clear();
clearDetails();
altsTable->setRowCount(0);
statusLabel->setText(tr("Loading alts for %1...").arg(currentUser));
requestAlts(userName, depthSpin->value());
}
void TabAlts::requestAlts(const QString &userName, int depth)
{
Command_GetUserAlts cmd;
cmd.set_user_name(userName.toStdString());
cmd.set_depth(static_cast<google::protobuf::uint32>(depth));
PendingCommand *pend = client->prepareModeratorCommand(cmd);
connect(pend, &PendingCommand::finished, this, &TabAlts::altsResponse);
client->sendCommand(pend);
}
void TabAlts::altsResponse(const Response &response)
{
lastAlts.clear();
if (response.response_code() != Response::RespOk) {
renderTable();
statusLabel->setText(tr("User %1 not found.").arg(currentUser));
return;
}
const Response_UserAlts &resp = response.GetExtension(Response_UserAlts::ext);
for (int i = 0; i < resp.alts_size(); ++i) {
lastAlts << resp.alts(i);
}
renderTable();
}
bool TabAlts::rowVisible(const ServerInfo_UserAlt &alt) const
{
const QString name = QString::fromStdString(alt.user_name());
if (name == currentUser) {
return true;
}
if (!alt.has_match_reason() || alt.match_reason().empty()) {
return true;
}
const QString reason = QString::fromStdString(alt.match_reason());
if (reason == QStringLiteral("email")) {
return emailCheck->isChecked();
}
if (reason.startsWith(QStringLiteral("clientid:"))) {
return clientIdCheck->isChecked();
}
if (reason.startsWith(QStringLiteral("ip:"))) {
return ipCheck->isChecked() &&
(!alt.has_shared_count() || alt.shared_count() <= static_cast<unsigned>(vpnSpin->value()));
}
return true;
}
void TabAlts::renderTable()
{
altsTable->setRowCount(0);
int hidden = 0;
int row = 0;
for (const ServerInfo_UserAlt &alt : lastAlts) {
if (!rowVisible(alt)) {
++hidden;
continue;
}
altsTable->insertRow(row);
altsTable->setItem(row, COL_ALTS_USER, new QTableWidgetItem(QString::fromStdString(alt.user_name())));
altsTable->setItem(row, COL_ALTS_VIA,
new QTableWidgetItem(alt.has_match_reason() && !alt.match_reason().empty()
? QString::fromStdString(alt.match_reason())
: QStringLiteral("-")));
altsTable->setItem(row, COL_ALTS_DEPTH,
new QTableWidgetItem(alt.has_depth() ? QString::number(alt.depth()) : QStringLiteral("-")));
altsTable->setItem(
row, COL_ALTS_SHARED,
new QTableWidgetItem(alt.has_shared_count() ? QString::number(alt.shared_count()) : QStringLiteral("-")));
altsTable->setItem(row, COL_ALTS_EMAIL, new QTableWidgetItem(QString::fromStdString(alt.email())));
altsTable->setItem(row, COL_ALTS_CLIENTID, new QTableWidgetItem(QString::fromStdString(alt.clientid())));
altsTable->setItem(row, COL_ALTS_REGISTERED, new QTableWidgetItem(formatEpoch(alt.registration_time())));
altsTable->setItem(row, COL_ALTS_LAST_LOGIN, new QTableWidgetItem(formatEpoch(alt.last_login())));
altsTable->setItem(row, COL_ALTS_WARNS, new QTableWidgetItem(QString::number(alt.warn_count())));
altsTable->setItem(row, COL_ALTS_BANS, new QTableWidgetItem(QString::number(alt.ban_count())));
altsTable->setItem(row, COL_ALTS_ACTIVE, new QTableWidgetItem(alt.is_active() ? tr("yes") : tr("no")));
++row;
}
if (hidden == 0) {
statusLabel->setText(tr("%1 account(s) related to %2.").arg(lastAlts.size()).arg(currentUser));
} else {
statusLabel->setText(tr("%1 shown, %2 hidden by filters (%3 total) related to %4.")
.arg(row)
.arg(hidden)
.arg(lastAlts.size())
.arg(currentUser));
}
}
void TabAlts::onFilterChanged()
{
if (lastAlts.isEmpty()) {
return;
}
renderTable();
}
void TabAlts::onAltSelected()
{
const auto selected = altsTable->selectedItems();
if (selected.isEmpty()) {
selectedUser.clear();
clearDetails();
return;
}
auto *userItem = altsTable->item(selected.first()->row(), COL_ALTS_USER);
if (userItem == nullptr || userItem->text().isEmpty() || userItem->text() == selectedUser) {
return;
}
selectedUser = userItem->text();
requestDetails(selectedUser);
}
void TabAlts::requestDetails(const QString &userName)
{
detailNameValue->setText(userName);
detailCountsValue->setText(tr("Loading..."));
detailNotesEdit->clear();
warnsTable->setRowCount(0);
bansTable->setRowCount(0);
Command_ReportUserInfo infoCmd;
infoCmd.set_user_name(userName.toStdString());
PendingCommand *infoPend = client->prepareModeratorCommand(infoCmd);
connect(infoPend, &PendingCommand::finished, this, [this, userName](const Response &response) {
if (userName == selectedUser) {
userDetailsResponse(response);
}
});
client->sendCommand(infoPend);
Command_GetWarnHistory warnCmd;
warnCmd.set_user_name(userName.toStdString());
PendingCommand *warnPend = client->prepareModeratorCommand(warnCmd);
connect(warnPend, &PendingCommand::finished, this, [this, userName](const Response &response) {
if (userName == selectedUser) {
warnHistoryResponse(response);
}
});
client->sendCommand(warnPend);
Command_GetBanHistory banCmd;
banCmd.set_user_name(userName.toStdString());
PendingCommand *banPend = client->prepareModeratorCommand(banCmd);
connect(banPend, &PendingCommand::finished, this, [this, userName](const Response &response) {
if (userName == selectedUser) {
banHistoryResponse(response);
}
});
client->sendCommand(banPend);
}
void TabAlts::clearDetails()
{
detailNameValue->clear();
detailCountsValue->clear();
detailNotesEdit->clear();
warnsTable->setRowCount(0);
bansTable->setRowCount(0);
}
void TabAlts::userDetailsResponse(const Response &response)
{
if (response.response_code() != Response::RespOk) {
detailCountsValue->setText(tr("Error loading user info."));
return;
}
const Response_ReportUserInfo &resp = response.GetExtension(Response_ReportUserInfo::ext);
detailCountsValue->setText(tr("Reports: %1 Bans: %2 Warnings: %3")
.arg(resp.total_reports())
.arg(resp.total_bans())
.arg(resp.total_warns()));
if (resp.has_admin_notes() && !resp.admin_notes().empty()) {
detailNotesEdit->setPlainText(QString::fromStdString(resp.admin_notes()));
} else {
detailNotesEdit->setPlainText(tr("(none)"));
}
}
void TabAlts::warnHistoryResponse(const Response &response)
{
warnsTable->setRowCount(0);
if (response.response_code() != Response::RespOk) {
return;
}
const Response_WarnHistory &resp = response.GetExtension(Response_WarnHistory::ext);
warnsTable->setRowCount(resp.warn_list_size());
for (int i = 0; i < resp.warn_list_size(); ++i) {
const ServerInfo_Warning &warn = resp.warn_list(i);
warnsTable->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(warn.time_of())));
warnsTable->setItem(i, 1, new QTableWidgetItem(QString::fromStdString(warn.admin_name())));
warnsTable->setItem(i, 2, new QTableWidgetItem(QString::fromStdString(warn.reason())));
}
}
void TabAlts::banHistoryResponse(const Response &response)
{
bansTable->setRowCount(0);
if (response.response_code() != Response::RespOk) {
return;
}
const Response_BanHistory &resp = response.GetExtension(Response_BanHistory::ext);
bansTable->setRowCount(resp.ban_list_size());
for (int i = 0; i < resp.ban_list_size(); ++i) {
const ServerInfo_Ban &ban = resp.ban_list(i);
bansTable->setItem(i, 0, new QTableWidgetItem(QString::fromStdString(ban.ban_time())));
bansTable->setItem(i, 1, new QTableWidgetItem(QString::fromStdString(ban.admin_name())));
bansTable->setItem(i, 2, new QTableWidgetItem(QString::fromStdString(ban.ban_length())));
bansTable->setItem(i, 3, new QTableWidgetItem(QString::fromStdString(ban.ban_reason())));
}
}

View file

@ -0,0 +1,91 @@
#ifndef TAB_ALTS_H
#define TAB_ALTS_H
#include "tab.h"
#include <QList>
#include <QString>
#include <QtGlobal>
#include <libcockatrice/protocol/pb/serverinfo_user_alt.pb.h>
#include <qtmetamacros.h>
class AbstractClient;
class QCheckBox;
class QLabel;
class QLineEdit;
class QPushButton;
class QSpinBox;
class QTableWidget;
class QTextEdit;
class Response;
class TabSupervisor;
/**
* Staff alt-graph investigation tool. Shows accounts related to the
* investigated user (shared email, client id, or recent IP address),
* including transitive alts-of-alts, with per-row match evidence.
* Selecting a row loads that account's warnings, bans, and admin notes.
*/
class TabAlts : public Tab
{
Q_OBJECT
public:
explicit TabAlts(TabSupervisor *_tabSupervisor, AbstractClient *_client, const QString &initialUser = {});
void retranslateUi() override;
[[nodiscard]] QString getTabText() const override
{
return tr("User Alts");
}
void investigate(const QString &userName);
private slots:
void investigateUser();
void goBack();
void altsResponse(const Response &response);
void onFilterChanged();
void onAltSelected();
void userDetailsResponse(const Response &response);
void warnHistoryResponse(const Response &response);
void banHistoryResponse(const Response &response);
private:
void loadUser(const QString &userName);
void requestAlts(const QString &userName, int depth);
void requestDetails(const QString &userName);
void clearDetails();
void renderTable();
[[nodiscard]] bool rowVisible(const ServerInfo_UserAlt &alt) const;
[[nodiscard]] QString formatEpoch(quint64 ts) const;
AbstractClient *client;
QString currentUser;
QString selectedUser;
QList<QString> backStack;
QList<ServerInfo_UserAlt> lastAlts;
QLineEdit *searchEdit;
QSpinBox *depthSpin;
QPushButton *investigateButton;
QPushButton *backButton;
QLabel *statusLabel;
QTableWidget *altsTable;
QCheckBox *emailCheck;
QCheckBox *clientIdCheck;
QCheckBox *ipCheck;
QLabel *vpnLabel;
QSpinBox *vpnSpin;
QLabel *detailNameValue;
QLabel *detailCountsValue;
QTextEdit *detailNotesEdit;
QTableWidget *warnsTable;
QTableWidget *bansTable;
QGroupBox *detailsGroup;
QLabel *detailNameLabel;
QLabel *detailCountsLabel;
QLabel *detailNotesLabel;
};
#endif // TAB_ALTS_H

View file

@ -6,6 +6,7 @@
#include "libcockatrice/protocol/pb/serverinfo_moderator_login.pb.h"
#include "libcockatrice/protocol/pb/serverinfo_user_alt.pb.h"
#include "libcockatrice/protocol/pb/serverinfo_user_session.pb.h"
#include "tab_supervisor.h"
#include <QAbstractItemView>
#include <QDateTime>
@ -139,7 +140,19 @@ TabModeration::TabModeration(TabSupervisor *_tabSupervisor, AbstractClient *_cli
altsGroup = new QGroupBox;
altsTable = new QTableWidget(0, COL_ALTS_COUNT);
configureTable(altsTable);
connect(altsTable, &QTableWidget::cellDoubleClicked, this, [this](int row, int) {
auto *userItem = altsTable->item(row, COL_ALTS_USER);
if (userItem != nullptr && !userItem->text().isEmpty()) {
getTabSupervisor()->openTabAlts(userItem->text());
}
});
openAltsButton = new QPushButton;
connect(openAltsButton, &QPushButton::clicked, this, &TabModeration::openAltsGraph);
auto *altsHeader = new QHBoxLayout;
altsHeader->addStretch();
altsHeader->addWidget(openAltsButton);
auto *altsLayout = new QVBoxLayout(altsGroup);
altsLayout->addLayout(altsHeader);
altsLayout->addWidget(altsTable);
sessionsGroup = new QGroupBox;
@ -197,6 +210,8 @@ void TabModeration::retranslateUi()
userInfoNotesLabel->setText(tr("Admin notes:"));
altsGroup->setTitle(tr("Alts"));
openAltsButton->setText(tr("Open alt graph"));
openAltsButton->setToolTip(tr("Open this user in the User Alts tab"));
sessionsGroup->setTitle(tr("Sessions"));
staffGroup->setTitle(tr("Staff Last Logins"));
@ -227,6 +242,7 @@ void TabModeration::clearUserData()
sessionsTable->setRowCount(0);
resetPasswordButton->setEnabled(false);
removeAvatarButton->setEnabled(false);
openAltsButton->setEnabled(false);
}
void TabModeration::investigate(const QString &userName)
@ -247,6 +263,7 @@ void TabModeration::investigateUser()
currentUser = userName;
resetPasswordButton->setEnabled(true);
removeAvatarButton->setEnabled(true);
openAltsButton->setEnabled(true);
altsTable->setRowCount(0);
sessionsTable->setRowCount(0);
requestUserInfo(userName);
@ -254,6 +271,14 @@ void TabModeration::investigateUser()
requestAlts(userName);
}
void TabModeration::openAltsGraph()
{
if (currentUser.isEmpty()) {
return;
}
getTabSupervisor()->openTabAlts(currentUser);
}
void TabModeration::requestUserInfo(const QString &userName)
{
userInfoNameValue->setText(userName);

View file

@ -36,6 +36,7 @@ public:
private slots:
void investigateUser();
void openAltsGraph();
void userInfoResponse(const Response &response);
void sessionsResponse(const Response &response);
void altsResponse(const Response &response);
@ -77,6 +78,7 @@ private:
QGroupBox *altsGroup;
QTableWidget *altsTable;
QPushButton *openAltsButton;
QGroupBox *sessionsGroup;
QTableWidget *sessionsTable;
QGroupBox *staffGroup;

View file

@ -25,6 +25,7 @@
#include "tab.h"
#include "tab_account.h"
#include "tab_admin.h"
#include "tab_alts.h"
#include "tab_card_art_rules.h"
#include "tab_deck_editor.h"
#include "tab_deck_storage.h"
@ -156,7 +157,7 @@ TabSupervisor::TabSupervisor(AbstractClient *_client, QMenu *tabsMenu, QWidget *
: QTabWidget(parent), userInfo(nullptr), client(_client), tabsMenu(tabsMenu), tabHome(nullptr),
tabVisualDeckStorage(nullptr), tabServer(nullptr), tabAccount(nullptr), tabDeckStorage(nullptr),
tabReplays(nullptr), tabAdmin(nullptr), tabCardArtRules(nullptr), tabLog(nullptr), tabReport(nullptr),
tabModeration(nullptr), tabDeveloper(nullptr), isLocalGame(false)
tabModeration(nullptr), tabAlts(nullptr), tabDeveloper(nullptr), isLocalGame(false)
{
setElideMode(Qt::ElideRight);
setMovable(true);
@ -300,6 +301,7 @@ void TabSupervisor::retranslateUi()
tabs.append(tabLog);
tabs.append(tabReport);
tabs.append(tabModeration);
tabs.append(tabAlts);
tabs.append(tabCardArtRules);
tabs.append(tabDeveloper);
QMapIterator<int, TabRoom *> roomIterator(roomTabs);
@ -600,6 +602,7 @@ void TabSupervisor::startLocal(const QList<AbstractClient *> &_clients)
tabLog = nullptr;
tabReport = nullptr;
tabModeration = nullptr;
tabAlts = nullptr;
tabDeveloper = nullptr;
isLocalGame = true;
userInfo = new ServerInfo_User;
@ -648,6 +651,9 @@ void TabSupervisor::stop()
if (tabModeration) {
tabModeration->close();
}
if (tabAlts) {
tabAlts->close();
}
if (tabCardArtRules) {
tabCardArtRules->close();
}
@ -956,6 +962,20 @@ void TabSupervisor::openTabModeration(const QString &userName)
aTabModeration->setChecked(true);
}
void TabSupervisor::openTabAlts(const QString &userName)
{
if (tabAlts) {
setCurrentWidget(tabAlts);
if (!userName.isEmpty()) {
tabAlts->investigate(userName);
}
return;
}
tabAlts = new TabAlts(this, client, userName);
myAddTab(tabAlts);
connect(tabAlts, &QObject::destroyed, this, [this] { tabAlts = nullptr; });
}
void TabSupervisor::actTabDeveloper(bool checked)
{
if (checked && !tabDeveloper) {

View file

@ -50,6 +50,7 @@ class TabAdmin;
class TabMessage;
class TabReport;
class TabModeration;
class TabAlts;
class TabAccount;
class TabDeckEditor;
class TabDeveloper;
@ -116,6 +117,7 @@ private:
TabLog *tabLog;
TabReport *tabReport;
TabModeration *tabModeration;
TabAlts *tabAlts;
TabDeveloper *tabDeveloper;
QMap<int, TabRoom *> roomTabs;
QMap<int, TabGame *> gameTabs;
@ -209,6 +211,7 @@ public slots:
/** Joins or spectates a game listed on a user's profile hover card. */
void joinGameFromUserCard(int gameId, int roomId, bool asSpectator);
void openTabModeration(const QString &userName = {});
void openTabAlts(const QString &userName = {});
void switchToFirstAvailableNetworkTab();
void maximizeMainWindow();
void actTabVisualDeckStorage(bool checked);

View file

@ -165,6 +165,7 @@ message Command_GetUserAlts {
optional Command_GetUserAlts ext = 1014;
}
optional string user_name = 1;
optional uint32 depth = 2 [default = 1]; // BFS depth: 1 = direct matches only, up to 3 for transitive alts-of-alts
}
message Command_GetModeratorLastLogins {

View file

@ -13,4 +13,8 @@ message ServerInfo_UserAlt {
optional uint32 warn_count = 6; // number of warnings on record
optional uint32 ban_count = 7; // number of bans on record
optional bool is_active = 8; // account is not deactivated/banned
optional string match_reason = 9; // why flagged, e.g. "email", "clientid:abc", "ip:1.2.3.4"; empty = seed/legacy
optional uint32 depth = 10; // BFS distance from investigated account; 1 = direct, 2+ = alt-of-alt
optional uint32 shared_count =
11; // distinct users sharing the matched identifier; high values suggest VPN/shared network
}

View file

@ -33,6 +33,7 @@
#include <QStringList>
#include <QVariant>
#include <QVariantList>
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <libcockatrice/deck_list/deck_list.h>
#include <libcockatrice/protocol/pb/game_replay.pb.h>
@ -1621,7 +1622,58 @@ QList<ServerInfo_UserSession> Servatrice_DatabaseInterface::getUserSessions(cons
return results;
}
QList<ServerInfo_UserAlt> Servatrice_DatabaseInterface::getUserAlts(const QString &userName)
namespace
{
constexpr int MAX_USER_ALT_DEPTH = 3;
constexpr int MAX_USER_ALTS_PER_LEVEL = 200;
// Bounds per-level work and the prepared-statement cache (keyed by query text,
// so every distinct IN-list size is a new entry on the long-lived server).
// Identifier-heavy frontiers, e.g. VPN users with hundreds of recent IPs, are
// truncated: this tool is deliberately a first-pass sweep, not an audit.
constexpr int MAX_USER_ALT_IDENTIFIERS = 200;
QString altInClause(const QString &prefix, const QList<QString> &values)
{
QStringList placeholders;
placeholders.reserve(values.size());
for (int i = 0; i < values.size(); ++i) {
placeholders << prefix + QString::number(i);
}
return QStringLiteral("(") + placeholders.join(QStringLiteral(",")) + QStringLiteral(")");
}
void altBindValues(QSqlQuery *query, const QString &prefix, const QList<QString> &values)
{
for (int i = 0; i < values.size(); ++i) {
query->bindValue(prefix + QString::number(i), values.at(i));
}
}
struct AltCandidate
{
QString name;
QString email;
QString clientId;
qint64 registrationTime = 0;
qint64 lastLogin = 0;
bool hasLastLogin = false;
int warnCount = 0;
int banCount = 0;
bool isActive = false;
};
QList<QString> cappedIdentifiers(QSet<QString> values)
{
QList<QString> list = values.values();
std::sort(list.begin(), list.end());
if (list.size() > MAX_USER_ALT_IDENTIFIERS) {
list.erase(list.begin() + MAX_USER_ALT_IDENTIFIERS, list.end());
}
return list;
}
} // namespace
QList<ServerInfo_UserAlt> Servatrice_DatabaseInterface::getUserAlts(const QString &userName, int depth)
{
QList<ServerInfo_UserAlt> results;
@ -1629,63 +1681,301 @@ QList<ServerInfo_UserAlt> Servatrice_DatabaseInterface::getUserAlts(const QStrin
return results;
}
// Seed account identifiers used to find related accounts
QSqlQuery *seedQuery = prepareQuery("SELECT email, clientid FROM {prefix}_users WHERE name = :user_name");
if (depth < 1) {
depth = 1;
} else if (depth > MAX_USER_ALT_DEPTH) {
depth = MAX_USER_ALT_DEPTH;
}
// Seed must exist; its row anchors the result at depth 0.
QSqlQuery *seedQuery = prepareQuery("SELECT u.name, u.email, u.clientid, UNIX_TIMESTAMP(u.registrationDate), "
"UNIX_TIMESTAMP(a.last_login), "
"(SELECT COUNT(*) FROM {prefix}_warnings w WHERE w.user_id = u.id), "
"(SELECT COUNT(*) FROM {prefix}_bans b WHERE b.user_name = u.name), "
"u.active "
"FROM {prefix}_users u "
"LEFT JOIN {prefix}_user_analytics a ON a.id = u.id "
"WHERE u.name = :user_name");
seedQuery->bindValue(":user_name", userName);
if (!execSqlQuery(seedQuery) || !seedQuery->next()) {
return results;
}
const QString seedEmail = seedQuery->value(0).toString();
const QString seedClientId = seedQuery->value(1).toString();
QString queryString = "SELECT u.name, u.email, u.clientid, UNIX_TIMESTAMP(u.registrationDate), "
"UNIX_TIMESTAMP(a.last_login), "
"(SELECT COUNT(*) FROM {prefix}_warnings w WHERE w.user_id = u.id), "
"(SELECT COUNT(*) FROM {prefix}_bans b WHERE b.user_name = u.name), "
"u.active "
"FROM {prefix}_users u "
"LEFT JOIN {prefix}_user_analytics a ON a.id = u.id "
"WHERE u.name = :user_name";
if (!seedEmail.isEmpty()) {
queryString.append(" OR u.email = :seed_email");
}
if (!seedClientId.isEmpty()) {
queryString.append(" OR u.clientid = :seed_clientid");
}
queryString.append(" OR u.name IN (SELECT DISTINCT s.user_name FROM {prefix}_sessions s "
"WHERE s.ip_address IN (SELECT DISTINCT s2.ip_address FROM {prefix}_sessions s2 "
"WHERE s2.user_name = :user_name"
" AND s2.start_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH))"
" AND s.start_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH)) "
"ORDER BY u.name LIMIT 200");
QSqlQuery *query = prepareQuery(queryString);
query->bindValue(":user_name", userName);
if (!seedEmail.isEmpty()) {
query->bindValue(":seed_email", seedEmail);
}
if (!seedClientId.isEmpty()) {
query->bindValue(":seed_clientid", seedClientId);
}
if (!execSqlQuery(query)) {
qCWarning(DatabaseInterfaceLog) << "Failed to collect user alt information: SQL Error";
return results;
}
while (query->next()) {
auto appendAlt = [&results](const AltCandidate &candidate, const QString &matchReason, int matchDepth,
int sharedCount) {
ServerInfo_UserAlt altDetails;
altDetails.set_user_name(query->value(0).toString().toStdString());
altDetails.set_email(query->value(1).toString().toStdString());
altDetails.set_clientid(query->value(2).toString().toStdString());
altDetails.set_registration_time(query->value(3).toLongLong());
if (!query->value(4).isNull()) {
altDetails.set_last_login(query->value(4).toLongLong());
altDetails.set_user_name(candidate.name.toStdString());
altDetails.set_email(candidate.email.toStdString());
altDetails.set_clientid(candidate.clientId.toStdString());
altDetails.set_registration_time(candidate.registrationTime);
if (candidate.hasLastLogin) {
altDetails.set_last_login(candidate.lastLogin);
}
altDetails.set_warn_count(query->value(5).toInt());
altDetails.set_ban_count(query->value(6).toInt());
altDetails.set_is_active(query->value(7).toBool());
altDetails.set_warn_count(candidate.warnCount);
altDetails.set_ban_count(candidate.banCount);
altDetails.set_is_active(candidate.isActive);
altDetails.set_match_reason(matchReason.toStdString());
altDetails.set_depth(static_cast<google::protobuf::uint32>(matchDepth));
altDetails.set_shared_count(static_cast<google::protobuf::uint32>(sharedCount));
results << altDetails;
};
AltCandidate seed{.name = seedQuery->value(0).toString(),
.email = seedQuery->value(1).toString(),
.clientId = seedQuery->value(2).toString(),
.registrationTime = seedQuery->value(3).toLongLong(),
.lastLogin = seedQuery->value(4).toLongLong(),
.hasLastLogin = !seedQuery->value(4).isNull(),
.warnCount = seedQuery->value(5).toInt(),
.banCount = seedQuery->value(6).toInt(),
.isActive = seedQuery->value(7).toBool()};
appendAlt(seed, QStringLiteral("self"), 0, 1);
QSet<QString> visited{userName};
QList<QString> frontier{userName};
for (int level = 1; level <= depth && !frontier.isEmpty(); ++level) {
const QString frontierClause = altInClause(QStringLiteral(":alt_name"), frontier);
// Current identifiers of the frontier: registration email + client id.
QSet<QString> emails;
QSet<QString> clientIds;
QSet<QString> ips;
QSqlQuery *frontierQuery =
prepareQuery(QStringLiteral("SELECT email, clientid FROM {prefix}_users WHERE name IN ") + frontierClause);
altBindValues(frontierQuery, QStringLiteral(":alt_name"), frontier);
if (execSqlQuery(frontierQuery)) {
while (frontierQuery->next()) {
const QString email = frontierQuery->value(0).toString();
const QString clientId = frontierQuery->value(1).toString();
if (!email.isEmpty()) {
emails << email;
}
if (!clientId.isEmpty()) {
clientIds << clientId;
}
}
}
// Recent session identifiers: IPs plus historic client ids.
QSqlQuery *sessionQuery = prepareQuery(
QStringLiteral("SELECT DISTINCT ip_address, clientid FROM {prefix}_sessions WHERE user_name IN ") +
frontierClause + QStringLiteral(" AND start_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH)"));
altBindValues(sessionQuery, QStringLiteral(":alt_name"), frontier);
if (execSqlQuery(sessionQuery)) {
while (sessionQuery->next()) {
const QString ip = sessionQuery->value(0).toString();
const QString clientId = sessionQuery->value(1).toString();
if (!ip.isEmpty()) {
ips << ip;
}
if (!clientId.isEmpty()) {
clientIds << clientId;
}
}
}
if (emails.isEmpty() && clientIds.isEmpty() && ips.isEmpty()) {
break;
}
// Accounts sharing any frontier identifier. Historic client ids are matched
// through past sessions so identifier changes do not hide older alts.
QString candidateString =
QStringLiteral("SELECT u.name, u.email, u.clientid, UNIX_TIMESTAMP(u.registrationDate), "
"UNIX_TIMESTAMP(a.last_login), "
"(SELECT COUNT(*) FROM {prefix}_warnings w WHERE w.user_id = u.id), "
"(SELECT COUNT(*) FROM {prefix}_bans b WHERE b.user_name = u.name), "
"u.active "
"FROM {prefix}_users u "
"LEFT JOIN {prefix}_user_analytics a ON a.id = u.id "
"WHERE ");
QStringList conditions;
QList<QString> emailList = cappedIdentifiers(emails);
QList<QString> clientIdList = cappedIdentifiers(clientIds);
QList<QString> ipList = cappedIdentifiers(ips);
if (!emailList.isEmpty()) {
conditions << QStringLiteral("u.email IN ") + altInClause(QStringLiteral(":alt_email"), emailList);
}
if (!clientIdList.isEmpty()) {
conditions << QStringLiteral("u.clientid IN ") + altInClause(QStringLiteral(":alt_cid"), clientIdList);
}
if (!ipList.isEmpty()) {
conditions << QStringLiteral("u.name IN (SELECT DISTINCT s.user_name FROM {prefix}_sessions s WHERE "
"s.ip_address IN ") +
altInClause(QStringLiteral(":alt_ip"), ipList) +
QStringLiteral(" AND s.start_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH))");
}
if (!clientIdList.isEmpty()) {
conditions << QStringLiteral("u.name IN (SELECT DISTINCT s.user_name FROM {prefix}_sessions s WHERE "
"s.clientid IN ") +
altInClause(QStringLiteral(":alt_hcid"), clientIdList) +
QStringLiteral(" AND s.start_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH))");
}
candidateString += conditions.join(QStringLiteral(" OR "));
candidateString += QStringLiteral(" ORDER BY u.name LIMIT ") + QString::number(MAX_USER_ALTS_PER_LEVEL);
QSqlQuery *candidateQuery = prepareQuery(candidateString);
altBindValues(candidateQuery, QStringLiteral(":alt_email"), emailList);
altBindValues(candidateQuery, QStringLiteral(":alt_cid"), clientIdList);
altBindValues(candidateQuery, QStringLiteral(":alt_ip"), ipList);
altBindValues(candidateQuery, QStringLiteral(":alt_hcid"), clientIdList);
if (!execSqlQuery(candidateQuery)) {
qCWarning(DatabaseInterfaceLog) << "Failed to collect user alt information: SQL Error";
return results;
}
QList<AltCandidate> candidates;
while (candidateQuery->next()) {
AltCandidate candidate;
candidate.name = candidateQuery->value(0).toString();
if (visited.contains(candidate.name)) {
continue;
}
candidate.email = candidateQuery->value(1).toString();
candidate.clientId = candidateQuery->value(2).toString();
candidate.registrationTime = candidateQuery->value(3).toLongLong();
candidate.hasLastLogin = !candidateQuery->value(4).isNull();
candidate.lastLogin = candidateQuery->value(4).toLongLong();
candidate.warnCount = candidateQuery->value(5).toInt();
candidate.banCount = candidateQuery->value(6).toInt();
candidate.isActive = candidateQuery->value(7).toBool();
candidates << candidate;
}
// Resolve session-level evidence (shared IP or historic client id) for
// candidates that do not match on current email or client id.
QMap<QString, QString> candidateIp;
QMap<QString, QString> candidateHistoricClientId;
QList<QString> unexplained;
for (const AltCandidate &candidate : candidates) {
const bool emailMatch = !candidate.email.isEmpty() && emails.contains(candidate.email);
const bool clientIdMatch = !candidate.clientId.isEmpty() && clientIds.contains(candidate.clientId);
if (!emailMatch && !clientIdMatch) {
unexplained << candidate.name;
}
}
if (!unexplained.isEmpty() && (!ips.isEmpty() || !clientIds.isEmpty())) {
QString evidenceString =
QStringLiteral("SELECT DISTINCT user_name, ip_address, clientid FROM {prefix}_sessions WHERE "
"user_name IN ") +
altInClause(QStringLiteral(":alt_ev"), unexplained) + QStringLiteral(" AND (");
QStringList evidenceConditions;
if (!ipList.isEmpty()) {
evidenceConditions << QStringLiteral("ip_address IN ") +
altInClause(QStringLiteral(":alt_eip"), ipList);
}
if (!clientIdList.isEmpty()) {
evidenceConditions << QStringLiteral("clientid IN ") +
altInClause(QStringLiteral(":alt_ecid"), clientIdList);
}
evidenceString += evidenceConditions.join(QStringLiteral(" OR "));
evidenceString += QStringLiteral(") AND start_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH)");
QSqlQuery *evidenceQuery = prepareQuery(evidenceString);
altBindValues(evidenceQuery, QStringLiteral(":alt_ev"), unexplained);
altBindValues(evidenceQuery, QStringLiteral(":alt_eip"), ipList);
altBindValues(evidenceQuery, QStringLiteral(":alt_ecid"), clientIdList);
if (execSqlQuery(evidenceQuery)) {
while (evidenceQuery->next()) {
const QString name = evidenceQuery->value(0).toString();
const QString ip = evidenceQuery->value(1).toString();
const QString clientId = evidenceQuery->value(2).toString();
if (!ip.isEmpty() && ips.contains(ip) && !candidateIp.contains(name)) {
candidateIp.insert(name, ip);
}
if (!clientId.isEmpty() && clientIds.contains(clientId) &&
!candidateHistoricClientId.contains(name)) {
candidateHistoricClientId.insert(name, clientId);
}
}
}
}
// Fan-out counts so moderators can spot VPN/shared-network false positives.
QMap<QString, int> emailCounts;
QMap<QString, int> clientIdCounts;
QMap<QString, int> ipCounts;
QSet<QString> neededEmails;
QSet<QString> neededClientIds;
QSet<QString> neededIps;
for (const AltCandidate &candidate : candidates) {
if (!candidate.email.isEmpty() && emails.contains(candidate.email)) {
neededEmails << candidate.email;
} else if (!candidate.clientId.isEmpty() && clientIds.contains(candidate.clientId)) {
neededClientIds << candidate.clientId;
} else if (candidateHistoricClientId.contains(candidate.name)) {
neededClientIds << candidateHistoricClientId.value(candidate.name);
} else if (candidateIp.contains(candidate.name)) {
neededIps << candidateIp.value(candidate.name);
}
}
if (!neededEmails.isEmpty()) {
const QList<QString> neededEmailList = neededEmails.values();
QSqlQuery *countQuery = prepareQuery(QStringLiteral("SELECT email, COUNT(*) FROM {prefix}_users WHERE "
"email IN ") +
altInClause(QStringLiteral(":alt_ce"), neededEmailList) +
QStringLiteral(" GROUP BY email"));
altBindValues(countQuery, QStringLiteral(":alt_ce"), neededEmailList);
if (execSqlQuery(countQuery)) {
while (countQuery->next()) {
emailCounts.insert(countQuery->value(0).toString(), countQuery->value(1).toInt());
}
}
}
if (!neededClientIds.isEmpty()) {
const QList<QString> neededClientIdList = neededClientIds.values();
QSqlQuery *countQuery = prepareQuery(QStringLiteral("SELECT clientid, COUNT(*) FROM {prefix}_users WHERE "
"clientid IN ") +
altInClause(QStringLiteral(":alt_cc"), neededClientIdList) +
QStringLiteral(" GROUP BY clientid"));
altBindValues(countQuery, QStringLiteral(":alt_cc"), neededClientIdList);
if (execSqlQuery(countQuery)) {
while (countQuery->next()) {
clientIdCounts.insert(countQuery->value(0).toString(), countQuery->value(1).toInt());
}
}
}
if (!neededIps.isEmpty()) {
const QList<QString> neededIpList = neededIps.values();
QSqlQuery *countQuery = prepareQuery(
QStringLiteral("SELECT ip_address, COUNT(DISTINCT user_name) FROM {prefix}_sessions WHERE "
"ip_address IN ") +
altInClause(QStringLiteral(":alt_ci"), neededIpList) +
QStringLiteral(" AND start_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH) GROUP BY ip_address"));
altBindValues(countQuery, QStringLiteral(":alt_ci"), neededIpList);
if (execSqlQuery(countQuery)) {
while (countQuery->next()) {
ipCounts.insert(countQuery->value(0).toString(), countQuery->value(1).toInt());
}
}
}
QList<QString> nextFrontier;
for (const AltCandidate &candidate : candidates) {
QString matchReason;
int sharedCount = 1;
if (!candidate.email.isEmpty() && emails.contains(candidate.email)) {
matchReason = QStringLiteral("email");
sharedCount = qMax(1, emailCounts.value(candidate.email, 1));
} else if (!candidate.clientId.isEmpty() && clientIds.contains(candidate.clientId)) {
matchReason = QStringLiteral("clientid:") + candidate.clientId;
sharedCount = qMax(1, clientIdCounts.value(candidate.clientId, 1));
} else if (candidateHistoricClientId.contains(candidate.name)) {
const QString historicId = candidateHistoricClientId.value(candidate.name);
matchReason = QStringLiteral("clientid:") + historicId;
sharedCount = qMax(1, clientIdCounts.value(historicId, 1));
} else if (candidateIp.contains(candidate.name)) {
const QString ip = candidateIp.value(candidate.name);
matchReason = QStringLiteral("ip:") + ip;
sharedCount = qMax(1, ipCounts.value(ip, 1));
} else {
continue;
}
appendAlt(candidate, matchReason, level, sharedCount);
visited.insert(candidate.name);
nextFrontier << candidate.name;
}
frontier = nextFrontier;
}
return results;

View file

@ -200,7 +200,7 @@ public:
int &range,
int &maxresults);
QList<ServerInfo_UserSession> getUserSessions(const QString &userName, int limit);
QList<ServerInfo_UserAlt> getUserAlts(const QString &userName);
QList<ServerInfo_UserAlt> getUserAlts(const QString &userName, int depth = 1);
QList<ServerInfo_ModeratorLogin> getModeratorLastLogins();
// Uptime snapshot as recorded by Servatrice::statusUpdate() into the

View file

@ -2565,7 +2565,8 @@ Response::ResponseCode AbstractServerSocketInterface::cmdGetUserAlts(const Comma
}
Response_UserAlts *re = new Response_UserAlts;
const QList<ServerInfo_UserAlt> alts = sqlInterface->getUserAlts(userName);
const int depth = cmd.has_depth() ? static_cast<int>(cmd.depth()) : 1;
const QList<ServerInfo_UserAlt> alts = sqlInterface->getUserAlts(userName, depth);
for (const ServerInfo_UserAlt &alt : alts) {
re->add_alts()->CopyFrom(alt);
}