fix: DM avatar color and reactions in federation + explore/server discovery
- Fix DM welcome header avatar using home identity for correct gradient color - Register DM channel IDs in channelOriginMap so federated DM operations (reactions, messages, typing) route to the correct instance - Pass origin when creating DM channels from friends list and WS events - Add server discovery/explore page with public server listings - Add server visibility and description fields
This commit is contained in:
@@ -68,7 +68,15 @@ export function runMigrations(db: Database.Database): void {
|
|||||||
name: 'instance_settings',
|
name: 'instance_settings',
|
||||||
columns: [
|
columns: [
|
||||||
{ name: 'instance_name', type: "TEXT DEFAULT 'Backspace'" },
|
{ name: 'instance_name', type: "TEXT DEFAULT 'Backspace'" },
|
||||||
{ name: 'worker_id', type: 'INTEGER' }
|
{ name: 'worker_id', type: 'INTEGER' },
|
||||||
|
{ name: 'discovery_enabled', type: 'INTEGER NOT NULL DEFAULT 1' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'servers',
|
||||||
|
columns: [
|
||||||
|
{ name: 'visibility', type: "TEXT DEFAULT 'private'" },
|
||||||
|
{ name: 'description', type: 'TEXT' }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
@@ -101,6 +109,20 @@ export function runMigrations(db: Database.Database): void {
|
|||||||
);
|
);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
|
// Ensure join_requests table exists (idempotent)
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS join_requests (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
server_id TEXT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
message TEXT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending',
|
||||||
|
decided_by TEXT REFERENCES users(id),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
decided_at INTEGER
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
// ─── RBAC Migration: Ensure @everyone roles exist for all servers ─────────
|
// ─── RBAC Migration: Ensure @everyone roles exist for all servers ─────────
|
||||||
migrateEveryoneRoles(db);
|
migrateEveryoneRoles(db);
|
||||||
|
|
||||||
@@ -110,6 +132,9 @@ export function runMigrations(db: Database.Database): void {
|
|||||||
// ─── Worker ID: ensure a unique Snowflake worker ID is persisted ───────────
|
// ─── Worker ID: ensure a unique Snowflake worker ID is persisted ───────────
|
||||||
migrateWorkerId(db);
|
migrateWorkerId(db);
|
||||||
|
|
||||||
|
// ─── Namespace replicated users: ensure all federated users use user@domain ─
|
||||||
|
migrateReplicatedUsernames(db);
|
||||||
|
|
||||||
// ─── Admin flag: ensure at least one admin exists (first registered user) ──
|
// ─── Admin flag: ensure at least one admin exists (first registered user) ──
|
||||||
migrateFirstAdmin(db);
|
migrateFirstAdmin(db);
|
||||||
|
|
||||||
@@ -210,3 +235,23 @@ function migrateEveryoneRoles(db: Database.Database): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rename non-namespaced replicated users: e.g. "test" → "test@nova.ddns.net"
|
||||||
|
* Frees plain usernames for native user creation and makes all federated users
|
||||||
|
* visually consistent. Safe because JWTs validate by userId, not username.
|
||||||
|
*/
|
||||||
|
function migrateReplicatedUsernames(db: Database.Database): void {
|
||||||
|
const rows = db.prepare(
|
||||||
|
"SELECT id, username, home_instance FROM users WHERE home_instance IS NOT NULL AND username NOT LIKE '%@%'"
|
||||||
|
).all() as { id: string; username: string; home_instance: string }[];
|
||||||
|
|
||||||
|
if (rows.length === 0) return;
|
||||||
|
|
||||||
|
const update = db.prepare('UPDATE users SET username = ? WHERE id = ?');
|
||||||
|
for (const row of rows) {
|
||||||
|
const newUsername = `${row.username}@${row.home_instance}`;
|
||||||
|
update.run(newUsername, row.id);
|
||||||
|
console.log(`Migrating: Renamed replicated user "${row.username}" → "${newUsername}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ export const servers = sqliteTable('servers', {
|
|||||||
icon: text('icon'),
|
icon: text('icon'),
|
||||||
ownerId: text('owner_id').notNull().references(() => users.id),
|
ownerId: text('owner_id').notNull().references(() => users.id),
|
||||||
inviteCode: text('invite_code').unique(),
|
inviteCode: text('invite_code').unique(),
|
||||||
|
visibility: text('visibility').default('private'),
|
||||||
|
description: text('description'),
|
||||||
createdAt: integer('created_at').notNull(),
|
createdAt: integer('created_at').notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -182,6 +184,7 @@ export const instanceSettings = sqliteTable('instance_settings', {
|
|||||||
id: integer('id').primaryKey().default(1),
|
id: integer('id').primaryKey().default(1),
|
||||||
instanceName: text('instance_name').default('Backspace'),
|
instanceName: text('instance_name').default('Backspace'),
|
||||||
workerId: integer('worker_id'),
|
workerId: integer('worker_id'),
|
||||||
|
discoveryEnabled: integer('discovery_enabled').notNull().default(1),
|
||||||
maxBitrateKbps: integer('max_bitrate_kbps').notNull().default(20000),
|
maxBitrateKbps: integer('max_bitrate_kbps').notNull().default(20000),
|
||||||
minBitrateKbps: integer('min_bitrate_kbps').notNull().default(500),
|
minBitrateKbps: integer('min_bitrate_kbps').notNull().default(500),
|
||||||
bitrateStepKbps: integer('bitrate_step_kbps').notNull().default(500),
|
bitrateStepKbps: integer('bitrate_step_kbps').notNull().default(500),
|
||||||
@@ -191,3 +194,14 @@ export const instanceSettings = sqliteTable('instance_settings', {
|
|||||||
maxFramerate: integer('max_framerate').notNull().default(60),
|
maxFramerate: integer('max_framerate').notNull().default(60),
|
||||||
updatedAt: integer('updated_at').notNull(),
|
updatedAt: integer('updated_at').notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const joinRequests = sqliteTable('join_requests', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
serverId: text('server_id').notNull().references(() => servers.id, { onDelete: 'cascade' }),
|
||||||
|
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||||
|
message: text('message'),
|
||||||
|
status: text('status').notNull().default('pending'),
|
||||||
|
decidedBy: text('decided_by').references(() => users.id),
|
||||||
|
createdAt: integer('created_at').notNull(),
|
||||||
|
decidedAt: integer('decided_at'),
|
||||||
|
});
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { socialRoutes } from './routes/social.js';
|
|||||||
import { settingsRoutes } from './routes/settings.js';
|
import { settingsRoutes } from './routes/settings.js';
|
||||||
import { utilRoutes } from './routes/utils.js';
|
import { utilRoutes } from './routes/utils.js';
|
||||||
import { instanceRoutes } from './routes/instance.js';
|
import { instanceRoutes } from './routes/instance.js';
|
||||||
|
import { exploreRoutes } from './routes/explore.js';
|
||||||
import { registerWebSocket } from './ws/handler.js';
|
import { registerWebSocket } from './ws/handler.js';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
@@ -77,6 +78,7 @@ async function main(): Promise<void> {
|
|||||||
await app.register(settingsRoutes);
|
await app.register(settingsRoutes);
|
||||||
await app.register(utilRoutes);
|
await app.register(utilRoutes);
|
||||||
await app.register(instanceRoutes);
|
await app.register(instanceRoutes);
|
||||||
|
await app.register(exploreRoutes);
|
||||||
await app.register(registerWebSocket);
|
await app.register(registerWebSocket);
|
||||||
|
|
||||||
app.get('/api/health', async () => {
|
app.get('/api/health', async () => {
|
||||||
|
|||||||
@@ -53,13 +53,9 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
return reply.code(400).send({ error: 'Username must be 100 characters or less', statusCode: 400 });
|
return reply.code(400).send({ error: 'Username must be 100 characters or less', statusCode: 400 });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Plain username from a replicated registration — same rules as local
|
// Replicated users MUST use username@domain format — plain usernames
|
||||||
if (trimmedUsername.length < 3 || trimmedUsername.length > 32) {
|
// are reserved exclusively for native users of this instance
|
||||||
return reply.code(400).send({ error: 'Username must be between 3 and 32 characters', statusCode: 400 });
|
return reply.code(400).send({ error: 'Replicated users must use username@domain format', statusCode: 400 });
|
||||||
}
|
|
||||||
if (!/^[a-zA-Z0-9_]+$/.test(trimmedUsername)) {
|
|
||||||
return reply.code(400).send({ error: 'Username can only contain letters, numbers, and underscores', statusCode: 400 });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Local registration — strict validation
|
// Local registration — strict validation
|
||||||
|
|||||||
@@ -0,0 +1,539 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import { eq, and, sql, inArray } from 'drizzle-orm';
|
||||||
|
import { getDb, schema } from '../db/index.js';
|
||||||
|
import { authenticate } from '../utils/auth.js';
|
||||||
|
import { generateSnowflake } from '../utils/snowflake.js';
|
||||||
|
import { isMember, isServerOwner, hasPermission, computePermissions, PermissionBits, permissionsToString } from '../utils/permissions.js';
|
||||||
|
import { connectionManager } from '../ws/handler.js';
|
||||||
|
import { sanitizeUser } from '../utils/sanitize.js';
|
||||||
|
import type {
|
||||||
|
ExploreServer,
|
||||||
|
JoinRequest,
|
||||||
|
MemberWithUser,
|
||||||
|
ServerWithChannelsAndMembers,
|
||||||
|
Channel,
|
||||||
|
} from '@backspace/shared';
|
||||||
|
|
||||||
|
function rowToJoinRequest(
|
||||||
|
row: typeof schema.joinRequests.$inferSelect,
|
||||||
|
user?: ReturnType<typeof sanitizeUser>,
|
||||||
|
): JoinRequest {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
serverId: row.serverId,
|
||||||
|
userId: row.userId,
|
||||||
|
message: row.message,
|
||||||
|
status: row.status as JoinRequest['status'],
|
||||||
|
decidedBy: row.decidedBy,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
decidedAt: row.decidedAt,
|
||||||
|
user: user ?? undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find all online users for a server who have MANAGE_SERVER or are the owner.
|
||||||
|
* Used to route join_request_received events.
|
||||||
|
*/
|
||||||
|
function getServerManagers(serverId: string): string[] {
|
||||||
|
const db = getDb();
|
||||||
|
const server = db.select().from(schema.servers).where(eq(schema.servers.id, serverId)).get();
|
||||||
|
if (!server) return [];
|
||||||
|
|
||||||
|
const memberRows = db.select()
|
||||||
|
.from(schema.serverMembers)
|
||||||
|
.where(eq(schema.serverMembers.serverId, serverId))
|
||||||
|
.all();
|
||||||
|
|
||||||
|
const managers: string[] = [];
|
||||||
|
for (const member of memberRows) {
|
||||||
|
if (member.userId === server.ownerId || hasPermission(member.userId, serverId, PermissionBits.MANAGE_SERVER)) {
|
||||||
|
managers.push(member.userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return managers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a full ServerWithChannelsAndMembers for a newly joined user.
|
||||||
|
* Used after accepting a join request or public join.
|
||||||
|
*/
|
||||||
|
function buildFullServer(serverId: string, forUserId: string): ServerWithChannelsAndMembers | null {
|
||||||
|
const db = getDb();
|
||||||
|
const server = db.select().from(schema.servers).where(eq(schema.servers.id, serverId)).get();
|
||||||
|
if (!server) return null;
|
||||||
|
|
||||||
|
const channels = db.select()
|
||||||
|
.from(schema.channels)
|
||||||
|
.where(eq(schema.channels.serverId, serverId))
|
||||||
|
.all();
|
||||||
|
|
||||||
|
const roles = db.select()
|
||||||
|
.from(schema.roles)
|
||||||
|
.where(eq(schema.roles.serverId, serverId))
|
||||||
|
.orderBy(schema.roles.position)
|
||||||
|
.all();
|
||||||
|
|
||||||
|
const memberRows = db.select()
|
||||||
|
.from(schema.serverMembers)
|
||||||
|
.where(eq(schema.serverMembers.serverId, serverId))
|
||||||
|
.all();
|
||||||
|
|
||||||
|
const memberUserIds = memberRows.map(m => m.userId);
|
||||||
|
const users = memberUserIds.length > 0
|
||||||
|
? db.select().from(schema.users).where(inArray(schema.users.id, memberUserIds)).all()
|
||||||
|
: [];
|
||||||
|
const userMap = new Map(users.map(u => [u.id, u]));
|
||||||
|
|
||||||
|
const memberRoleRows = db.select()
|
||||||
|
.from(schema.memberRoles)
|
||||||
|
.where(eq(schema.memberRoles.serverId, serverId))
|
||||||
|
.all();
|
||||||
|
|
||||||
|
const members: MemberWithUser[] = memberRows
|
||||||
|
.map(m => {
|
||||||
|
const u = userMap.get(m.userId);
|
||||||
|
if (!u) return null;
|
||||||
|
|
||||||
|
const assignedRoleIds = memberRoleRows
|
||||||
|
.filter(mr => mr.userId === m.userId)
|
||||||
|
.map(mr => mr.roleId);
|
||||||
|
|
||||||
|
const memberRoles = roles
|
||||||
|
.filter(r => assignedRoleIds.includes(r.id))
|
||||||
|
.map(r => ({
|
||||||
|
id: r.id,
|
||||||
|
serverId: r.serverId,
|
||||||
|
name: r.name,
|
||||||
|
color: r.color ?? '#b9bbbe',
|
||||||
|
position: r.position ?? 0,
|
||||||
|
createdAt: r.createdAt,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
serverId: m.serverId,
|
||||||
|
userId: m.userId,
|
||||||
|
nickname: m.nickname,
|
||||||
|
joinedAt: m.joinedAt,
|
||||||
|
user: sanitizeUser(u),
|
||||||
|
roles: memberRoles,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((m): m is MemberWithUser => m !== null);
|
||||||
|
|
||||||
|
const serverPerms = computePermissions(forUserId, serverId);
|
||||||
|
|
||||||
|
const visibleChannels: Channel[] = [];
|
||||||
|
for (const ch of channels) {
|
||||||
|
const chPerms = computePermissions(forUserId, serverId, ch.id);
|
||||||
|
const hasView = (chPerms & PermissionBits.VIEW_CHANNEL) !== 0n || (chPerms & PermissionBits.ADMINISTRATOR) !== 0n;
|
||||||
|
if (hasView) {
|
||||||
|
visibleChannels.push({
|
||||||
|
id: ch.id,
|
||||||
|
serverId: ch.serverId,
|
||||||
|
name: ch.name,
|
||||||
|
type: ch.type as Channel['type'],
|
||||||
|
topic: ch.topic,
|
||||||
|
position: ch.position ?? 0,
|
||||||
|
createdAt: ch.createdAt,
|
||||||
|
myPermissions: permissionsToString(chPerms),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: server.id,
|
||||||
|
name: server.name,
|
||||||
|
icon: server.icon,
|
||||||
|
ownerId: server.ownerId,
|
||||||
|
inviteCode: server.inviteCode,
|
||||||
|
visibility: (server.visibility ?? 'private') as ServerWithChannelsAndMembers['visibility'],
|
||||||
|
description: server.description ?? null,
|
||||||
|
createdAt: server.createdAt,
|
||||||
|
channels: visibleChannels,
|
||||||
|
members,
|
||||||
|
roles: roles.map(r => ({
|
||||||
|
id: r.id,
|
||||||
|
serverId: r.serverId,
|
||||||
|
name: r.name,
|
||||||
|
color: r.color ?? '#b9bbbe',
|
||||||
|
position: r.position ?? 0,
|
||||||
|
permissions: r.permissions ?? undefined,
|
||||||
|
isEveryone: r.id === serverId,
|
||||||
|
createdAt: r.createdAt,
|
||||||
|
})),
|
||||||
|
myPermissions: permissionsToString(serverPerms),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exploreRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
|
||||||
|
// GET /api/servers/explore — list discoverable servers
|
||||||
|
app.get<{ Querystring: { q?: string; limit?: string; offset?: string } }>('/api/servers/explore', {
|
||||||
|
preHandler: authenticate,
|
||||||
|
}, async (request, reply) => {
|
||||||
|
const db = getDb();
|
||||||
|
|
||||||
|
// Check instance-level discovery toggle
|
||||||
|
const settings = db.select().from(schema.instanceSettings).where(eq(schema.instanceSettings.id, 1)).get();
|
||||||
|
if (!settings || settings.discoveryEnabled === 0) {
|
||||||
|
return reply.code(200).send({ servers: [], total: 0, discoveryEnabled: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
const q = request.query.q?.trim() ?? '';
|
||||||
|
const limit = Math.min(Math.max(parseInt(request.query.limit ?? '50', 10) || 50, 1), 100);
|
||||||
|
const offset = Math.max(parseInt(request.query.offset ?? '0', 10) || 0, 0);
|
||||||
|
|
||||||
|
// Get user's current server memberships to exclude
|
||||||
|
const myMemberships = db.select({ serverId: schema.serverMembers.serverId })
|
||||||
|
.from(schema.serverMembers)
|
||||||
|
.where(eq(schema.serverMembers.userId, request.userId))
|
||||||
|
.all();
|
||||||
|
const myServerIds = new Set(myMemberships.map(m => m.serverId));
|
||||||
|
|
||||||
|
// Build raw SQL query for explore — we need a LEFT JOIN for member count
|
||||||
|
// which is more efficient to do with raw SQL
|
||||||
|
const rawDb = (db as any).$client as import('better-sqlite3').Database;
|
||||||
|
|
||||||
|
let countSql = `SELECT COUNT(DISTINCT s.id) as total FROM servers s WHERE s.visibility IN ('public', 'request')`;
|
||||||
|
let querySql = `
|
||||||
|
SELECT s.id, s.name, s.icon, s.description, s.visibility, s.created_at,
|
||||||
|
COUNT(sm.user_id) as member_count
|
||||||
|
FROM servers s
|
||||||
|
LEFT JOIN server_members sm ON sm.server_id = s.id
|
||||||
|
WHERE s.visibility IN ('public', 'request')
|
||||||
|
`;
|
||||||
|
|
||||||
|
const params: string[] = [];
|
||||||
|
|
||||||
|
if (q) {
|
||||||
|
const likePattern = `%${q}%`;
|
||||||
|
querySql += ` AND (s.name LIKE ? COLLATE NOCASE OR s.description LIKE ? COLLATE NOCASE)`;
|
||||||
|
countSql += ` AND (s.name LIKE ? COLLATE NOCASE OR s.description LIKE ? COLLATE NOCASE)`;
|
||||||
|
params.push(likePattern, likePattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
querySql += ` GROUP BY s.id ORDER BY member_count DESC, s.created_at DESC LIMIT ? OFFSET ?`;
|
||||||
|
|
||||||
|
const totalRow = rawDb.prepare(countSql).get(...params) as { total: number };
|
||||||
|
const rows = rawDb.prepare(querySql).all(...params, limit, offset) as {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
icon: string | null;
|
||||||
|
description: string | null;
|
||||||
|
visibility: string;
|
||||||
|
created_at: number;
|
||||||
|
member_count: number;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
// Filter out servers the user is already a member of
|
||||||
|
const servers: ExploreServer[] = rows
|
||||||
|
.filter(r => !myServerIds.has(r.id))
|
||||||
|
.map(r => ({
|
||||||
|
id: r.id,
|
||||||
|
name: r.name,
|
||||||
|
icon: r.icon,
|
||||||
|
description: r.description,
|
||||||
|
visibility: r.visibility as ExploreServer['visibility'],
|
||||||
|
memberCount: r.member_count,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return reply.code(200).send({ servers, total: totalRow.total, discoveryEnabled: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/servers/:id/public-join — join a public server without invite
|
||||||
|
app.post<{ Params: { id: string } }>('/api/servers/:id/public-join', {
|
||||||
|
preHandler: authenticate,
|
||||||
|
}, async (request, reply) => {
|
||||||
|
const { id } = request.params;
|
||||||
|
const db = getDb();
|
||||||
|
|
||||||
|
const server = db.select().from(schema.servers).where(eq(schema.servers.id, id)).get();
|
||||||
|
if (!server) {
|
||||||
|
return reply.code(404).send({ error: 'Server not found', statusCode: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (server.visibility !== 'public') {
|
||||||
|
return reply.code(403).send({ error: 'This server does not allow public joins', statusCode: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isMember(id, request.userId)) {
|
||||||
|
return reply.code(409).send({ error: 'You are already a member of this server', statusCode: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
db.insert(schema.serverMembers).values({
|
||||||
|
serverId: id,
|
||||||
|
userId: request.userId,
|
||||||
|
joinedAt: now,
|
||||||
|
}).run();
|
||||||
|
|
||||||
|
// Register in connectionManager for WS broadcasts
|
||||||
|
connectionManager.addUserServer(request.userId, id);
|
||||||
|
|
||||||
|
// Broadcast member_joined to existing server members
|
||||||
|
const joiningUser = db.select().from(schema.users).where(eq(schema.users.id, request.userId)).get();
|
||||||
|
if (joiningUser) {
|
||||||
|
const memberPayload: MemberWithUser = {
|
||||||
|
serverId: id,
|
||||||
|
userId: request.userId,
|
||||||
|
nickname: null,
|
||||||
|
joinedAt: now,
|
||||||
|
user: sanitizeUser(joiningUser),
|
||||||
|
roles: [],
|
||||||
|
};
|
||||||
|
connectionManager.sendToServer(id, {
|
||||||
|
type: 'member_joined',
|
||||||
|
serverId: id,
|
||||||
|
member: memberPayload,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return full server data
|
||||||
|
const fullServer = buildFullServer(id, request.userId);
|
||||||
|
if (!fullServer) {
|
||||||
|
return reply.code(500).send({ error: 'Failed to load server', statusCode: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.code(200).send(fullServer);
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/servers/:id/request-join — request to join a request-only server
|
||||||
|
app.post<{ Params: { id: string }; Body: { message?: string } }>('/api/servers/:id/request-join', {
|
||||||
|
preHandler: authenticate,
|
||||||
|
config: {
|
||||||
|
rateLimit: {
|
||||||
|
max: 5,
|
||||||
|
timeWindow: '1 minute',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, async (request, reply) => {
|
||||||
|
const { id } = request.params;
|
||||||
|
const db = getDb();
|
||||||
|
|
||||||
|
const server = db.select().from(schema.servers).where(eq(schema.servers.id, id)).get();
|
||||||
|
if (!server) {
|
||||||
|
return reply.code(404).send({ error: 'Server not found', statusCode: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (server.visibility !== 'request') {
|
||||||
|
return reply.code(403).send({ error: 'This server does not accept join requests', statusCode: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isMember(id, request.userId)) {
|
||||||
|
return reply.code(409).send({ error: 'You are already a member of this server', statusCode: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for existing pending request
|
||||||
|
const existingRequest = db.select().from(schema.joinRequests)
|
||||||
|
.where(and(
|
||||||
|
eq(schema.joinRequests.serverId, id),
|
||||||
|
eq(schema.joinRequests.userId, request.userId),
|
||||||
|
eq(schema.joinRequests.status, 'pending'),
|
||||||
|
))
|
||||||
|
.get();
|
||||||
|
|
||||||
|
if (existingRequest) {
|
||||||
|
return reply.code(409).send({ error: 'You already have a pending request for this server', statusCode: 409 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestId = generateSnowflake();
|
||||||
|
const now = Date.now();
|
||||||
|
const msgText = request.body?.message?.trim().slice(0, 500) ?? null;
|
||||||
|
|
||||||
|
db.insert(schema.joinRequests).values({
|
||||||
|
id: requestId,
|
||||||
|
serverId: id,
|
||||||
|
userId: request.userId,
|
||||||
|
message: msgText,
|
||||||
|
status: 'pending',
|
||||||
|
createdAt: now,
|
||||||
|
}).run();
|
||||||
|
|
||||||
|
const joiningUser = db.select().from(schema.users).where(eq(schema.users.id, request.userId)).get();
|
||||||
|
const joinRequest = rowToJoinRequest(
|
||||||
|
db.select().from(schema.joinRequests).where(eq(schema.joinRequests.id, requestId)).get()!,
|
||||||
|
joiningUser ? sanitizeUser(joiningUser) : undefined,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Send WS event to server managers (owner + MANAGE_SERVER users)
|
||||||
|
const managers = getServerManagers(id);
|
||||||
|
for (const managerId of managers) {
|
||||||
|
connectionManager.sendToUser(managerId, {
|
||||||
|
type: 'join_request_received',
|
||||||
|
request: joinRequest,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.code(201).send(joinRequest);
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/servers/:id/join-requests — list join requests for a server
|
||||||
|
app.get<{ Params: { id: string }; Querystring: { status?: string } }>('/api/servers/:id/join-requests', {
|
||||||
|
preHandler: authenticate,
|
||||||
|
}, async (request, reply) => {
|
||||||
|
const { id } = request.params;
|
||||||
|
const db = getDb();
|
||||||
|
|
||||||
|
const server = db.select().from(schema.servers).where(eq(schema.servers.id, id)).get();
|
||||||
|
if (!server) {
|
||||||
|
return reply.code(404).send({ error: 'Server not found', statusCode: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isServerOwner(id, request.userId) && !hasPermission(request.userId, id, PermissionBits.MANAGE_SERVER)) {
|
||||||
|
return reply.code(403).send({ error: 'Missing MANAGE_SERVER permission', statusCode: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusFilter = request.query.status ?? 'pending';
|
||||||
|
const rows = db.select().from(schema.joinRequests)
|
||||||
|
.where(and(
|
||||||
|
eq(schema.joinRequests.serverId, id),
|
||||||
|
eq(schema.joinRequests.status, statusFilter),
|
||||||
|
))
|
||||||
|
.all();
|
||||||
|
|
||||||
|
// Populate user data
|
||||||
|
const userIds = rows.map(r => r.userId);
|
||||||
|
const users = userIds.length > 0
|
||||||
|
? db.select().from(schema.users).where(inArray(schema.users.id, userIds)).all()
|
||||||
|
: [];
|
||||||
|
const userMap = new Map(users.map(u => [u.id, sanitizeUser(u)]));
|
||||||
|
|
||||||
|
const requests: JoinRequest[] = rows.map(r => rowToJoinRequest(r, userMap.get(r.userId)));
|
||||||
|
|
||||||
|
return reply.code(200).send({ requests });
|
||||||
|
});
|
||||||
|
|
||||||
|
// PATCH /api/servers/:id/join-requests/:requestId — accept or decline
|
||||||
|
app.patch<{ Params: { id: string; requestId: string }; Body: { action: 'accept' | 'decline' } }>('/api/servers/:id/join-requests/:requestId', {
|
||||||
|
preHandler: authenticate,
|
||||||
|
}, async (request, reply) => {
|
||||||
|
const { id, requestId } = request.params;
|
||||||
|
const { action } = request.body;
|
||||||
|
const db = getDb();
|
||||||
|
|
||||||
|
if (!action || (action !== 'accept' && action !== 'decline')) {
|
||||||
|
return reply.code(400).send({ error: 'Action must be "accept" or "decline"', statusCode: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const server = db.select().from(schema.servers).where(eq(schema.servers.id, id)).get();
|
||||||
|
if (!server) {
|
||||||
|
return reply.code(404).send({ error: 'Server not found', statusCode: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isServerOwner(id, request.userId) && !hasPermission(request.userId, id, PermissionBits.MANAGE_SERVER)) {
|
||||||
|
return reply.code(403).send({ error: 'Missing MANAGE_SERVER permission', statusCode: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const joinReq = db.select().from(schema.joinRequests).where(eq(schema.joinRequests.id, requestId)).get();
|
||||||
|
if (!joinReq || joinReq.serverId !== id) {
|
||||||
|
return reply.code(404).send({ error: 'Join request not found', statusCode: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (joinReq.status !== 'pending') {
|
||||||
|
return reply.code(400).send({ error: 'This request has already been decided', statusCode: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
if (action === 'accept') {
|
||||||
|
// Insert member and update request atomically
|
||||||
|
db.transaction((tx) => {
|
||||||
|
tx.insert(schema.serverMembers).values({
|
||||||
|
serverId: id,
|
||||||
|
userId: joinReq.userId,
|
||||||
|
joinedAt: now,
|
||||||
|
}).run();
|
||||||
|
|
||||||
|
tx.update(schema.joinRequests).set({
|
||||||
|
status: 'accepted',
|
||||||
|
decidedBy: request.userId,
|
||||||
|
decidedAt: now,
|
||||||
|
}).where(eq(schema.joinRequests.id, requestId)).run();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Register in connectionManager
|
||||||
|
connectionManager.addUserServer(joinReq.userId, id);
|
||||||
|
|
||||||
|
// Broadcast member_joined to server
|
||||||
|
const joiningUser = db.select().from(schema.users).where(eq(schema.users.id, joinReq.userId)).get();
|
||||||
|
if (joiningUser) {
|
||||||
|
const memberPayload: MemberWithUser = {
|
||||||
|
serverId: id,
|
||||||
|
userId: joinReq.userId,
|
||||||
|
nickname: null,
|
||||||
|
joinedAt: now,
|
||||||
|
user: sanitizeUser(joiningUser),
|
||||||
|
roles: [],
|
||||||
|
};
|
||||||
|
connectionManager.sendToServer(id, {
|
||||||
|
type: 'member_joined',
|
||||||
|
serverId: id,
|
||||||
|
member: memberPayload,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build full server for the accepted user
|
||||||
|
const fullServer = buildFullServer(id, joinReq.userId);
|
||||||
|
|
||||||
|
const updatedRow = db.select().from(schema.joinRequests).where(eq(schema.joinRequests.id, requestId)).get()!;
|
||||||
|
const updatedRequest = rowToJoinRequest(updatedRow, joiningUser ? sanitizeUser(joiningUser) : undefined);
|
||||||
|
|
||||||
|
// Send join_request_accepted to the requesting user
|
||||||
|
if (fullServer) {
|
||||||
|
connectionManager.sendToUser(joinReq.userId, {
|
||||||
|
type: 'join_request_accepted',
|
||||||
|
request: updatedRequest,
|
||||||
|
server: fullServer,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.code(200).send(updatedRequest);
|
||||||
|
} else {
|
||||||
|
// Decline
|
||||||
|
db.update(schema.joinRequests).set({
|
||||||
|
status: 'declined',
|
||||||
|
decidedBy: request.userId,
|
||||||
|
decidedAt: now,
|
||||||
|
}).where(eq(schema.joinRequests.id, requestId)).run();
|
||||||
|
|
||||||
|
const updatedRow = db.select().from(schema.joinRequests).where(eq(schema.joinRequests.id, requestId)).get()!;
|
||||||
|
const updatedRequest = rowToJoinRequest(updatedRow);
|
||||||
|
|
||||||
|
// Send join_request_declined to the requesting user
|
||||||
|
connectionManager.sendToUser(joinReq.userId, {
|
||||||
|
type: 'join_request_declined',
|
||||||
|
request: updatedRequest,
|
||||||
|
});
|
||||||
|
|
||||||
|
return reply.code(200).send(updatedRequest);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/users/@me/join-requests — list the current user's join requests
|
||||||
|
app.get<{ Querystring: { status?: string } }>('/api/users/@me/join-requests', {
|
||||||
|
preHandler: authenticate,
|
||||||
|
}, async (request, reply) => {
|
||||||
|
const db = getDb();
|
||||||
|
const statusFilter = request.query.status;
|
||||||
|
|
||||||
|
let rows;
|
||||||
|
if (statusFilter) {
|
||||||
|
rows = db.select().from(schema.joinRequests)
|
||||||
|
.where(and(
|
||||||
|
eq(schema.joinRequests.userId, request.userId),
|
||||||
|
eq(schema.joinRequests.status, statusFilter),
|
||||||
|
))
|
||||||
|
.all();
|
||||||
|
} else {
|
||||||
|
rows = db.select().from(schema.joinRequests)
|
||||||
|
.where(eq(schema.joinRequests.userId, request.userId))
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
const requests: JoinRequest[] = rows.map(r => rowToJoinRequest(r));
|
||||||
|
|
||||||
|
return reply.code(200).send({ requests });
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -27,6 +27,8 @@ function rowToServer(row: typeof schema.servers.$inferSelect): Server {
|
|||||||
icon: row.icon,
|
icon: row.icon,
|
||||||
ownerId: row.ownerId,
|
ownerId: row.ownerId,
|
||||||
inviteCode: row.inviteCode,
|
inviteCode: row.inviteCode,
|
||||||
|
visibility: (row.visibility ?? 'private') as Server['visibility'],
|
||||||
|
description: row.description ?? null,
|
||||||
createdAt: row.createdAt,
|
createdAt: row.createdAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -242,7 +244,7 @@ export async function serverRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
preHandler: authenticate,
|
preHandler: authenticate,
|
||||||
}, async (request, reply) => {
|
}, async (request, reply) => {
|
||||||
const { id } = request.params;
|
const { id } = request.params;
|
||||||
const { name, icon } = request.body;
|
const { name, icon, visibility, description } = request.body;
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
|
|
||||||
const server = db.select().from(schema.servers).where(eq(schema.servers.id, id)).get();
|
const server = db.select().from(schema.servers).where(eq(schema.servers.id, id)).get();
|
||||||
@@ -268,6 +270,19 @@ export async function serverRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
updates.icon = icon;
|
updates.icon = icon;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (visibility !== undefined) {
|
||||||
|
const validVisibilities = ['public', 'request', 'private'];
|
||||||
|
if (!validVisibilities.includes(visibility)) {
|
||||||
|
return reply.code(400).send({ error: 'Visibility must be "public", "request", or "private"', statusCode: 400 });
|
||||||
|
}
|
||||||
|
updates.visibility = visibility;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (description !== undefined) {
|
||||||
|
const trimmed = description.trim().slice(0, 200);
|
||||||
|
updates.description = trimmed || null;
|
||||||
|
}
|
||||||
|
|
||||||
if (Object.keys(updates).length === 0) {
|
if (Object.keys(updates).length === 0) {
|
||||||
return reply.code(400).send({ error: 'No fields to update', statusCode: 400 });
|
return reply.code(400).send({ error: 'No fields to update', statusCode: 400 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ function rowToLimits(row: typeof schema.instanceSettings.$inferSelect): Instance
|
|||||||
allowedFramerates: row.allowedFramerates.split(',').map(Number).filter((n) => VALID_FRAMERATES.includes(n)),
|
allowedFramerates: row.allowedFramerates.split(',').map(Number).filter((n) => VALID_FRAMERATES.includes(n)),
|
||||||
maxResolution: row.maxResolution,
|
maxResolution: row.maxResolution,
|
||||||
maxFramerate: row.maxFramerate,
|
maxFramerate: row.maxFramerate,
|
||||||
|
discoveryEnabled: row.discoveryEnabled === 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,6 +101,10 @@ export async function settingsRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
updateData.maxFramerate = body.maxFramerate;
|
updateData.maxFramerate = body.maxFramerate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (body.discoveryEnabled !== undefined) {
|
||||||
|
updateData.discoveryEnabled = body.discoveryEnabled ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
// Cross-field validation: min < max
|
// Cross-field validation: min < max
|
||||||
const currentRow = db.select().from(schema.instanceSettings).where(eq(schema.instanceSettings.id, 1)).get();
|
const currentRow = db.select().from(schema.instanceSettings).where(eq(schema.instanceSettings.id, 1)).get();
|
||||||
if (!currentRow) {
|
if (!currentRow) {
|
||||||
|
|||||||
@@ -677,6 +677,8 @@ function buildReadyPayload(userId: string): {
|
|||||||
icon: serverRow.icon,
|
icon: serverRow.icon,
|
||||||
ownerId: serverRow.ownerId,
|
ownerId: serverRow.ownerId,
|
||||||
inviteCode: serverRow.inviteCode,
|
inviteCode: serverRow.inviteCode,
|
||||||
|
visibility: (serverRow.visibility ?? 'private') as ServerWithChannelsAndMembers['visibility'],
|
||||||
|
description: serverRow.description ?? null,
|
||||||
createdAt: serverRow.createdAt,
|
createdAt: serverRow.createdAt,
|
||||||
channels: visibleChannels,
|
channels: visibleChannels,
|
||||||
members,
|
members,
|
||||||
|
|||||||
@@ -28,15 +28,41 @@ export interface UserWithPassword extends User {
|
|||||||
|
|
||||||
// ─── Server (Guild) Types ───────────────────────────────────────────────────
|
// ─── Server (Guild) Types ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export type ServerVisibility = 'public' | 'request' | 'private';
|
||||||
|
|
||||||
export interface Server {
|
export interface Server {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
icon: string | null;
|
icon: string | null;
|
||||||
ownerId: string;
|
ownerId: string;
|
||||||
inviteCode: string | null;
|
inviteCode: string | null;
|
||||||
|
visibility: ServerVisibility;
|
||||||
|
description: string | null;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ExploreServer {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
icon: string | null;
|
||||||
|
description: string | null;
|
||||||
|
visibility: ServerVisibility;
|
||||||
|
memberCount: number;
|
||||||
|
createdAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JoinRequest {
|
||||||
|
id: string;
|
||||||
|
serverId: string;
|
||||||
|
userId: string;
|
||||||
|
message: string | null;
|
||||||
|
status: 'pending' | 'accepted' | 'declined';
|
||||||
|
decidedBy: string | null;
|
||||||
|
createdAt: number;
|
||||||
|
decidedAt: number | null;
|
||||||
|
user?: User;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ServerWithChannelsAndMembers extends Server {
|
export interface ServerWithChannelsAndMembers extends Server {
|
||||||
channels: Channel[];
|
channels: Channel[];
|
||||||
members: MemberWithUser[];
|
members: MemberWithUser[];
|
||||||
@@ -244,6 +270,9 @@ export type ServerEvent =
|
|||||||
| { type: 'channel_updated'; channel: Channel; serverId: string }
|
| { type: 'channel_updated'; channel: Channel; serverId: string }
|
||||||
| { type: 'channel_deleted'; channelId: string; serverId: string }
|
| { type: 'channel_deleted'; channelId: string; serverId: string }
|
||||||
| { type: 'server_updated'; server: Server }
|
| { type: 'server_updated'; server: Server }
|
||||||
|
| { type: 'join_request_received'; request: JoinRequest }
|
||||||
|
| { type: 'join_request_accepted'; request: JoinRequest; server: ServerWithChannelsAndMembers }
|
||||||
|
| { type: 'join_request_declined'; request: JoinRequest }
|
||||||
| { type: 'pong' }
|
| { type: 'pong' }
|
||||||
| { type: 'error'; message: string };
|
| { type: 'error'; message: string };
|
||||||
|
|
||||||
@@ -287,6 +316,8 @@ export interface UpdateChannelRequest {
|
|||||||
export interface UpdateServerRequest {
|
export interface UpdateServerRequest {
|
||||||
name?: string;
|
name?: string;
|
||||||
icon?: string;
|
icon?: string;
|
||||||
|
visibility?: ServerVisibility;
|
||||||
|
description?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UpdateUserRequest {
|
export interface UpdateUserRequest {
|
||||||
@@ -360,6 +391,8 @@ export interface Friend {
|
|||||||
customStatus: string | null;
|
customStatus: string | null;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
addedAt: number;
|
addedAt: number;
|
||||||
|
homeUserId: string | null;
|
||||||
|
homeInstance: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type FriendRequestStatus = 'pending' | 'accepted' | 'declined';
|
export type FriendRequestStatus = 'pending' | 'accepted' | 'declined';
|
||||||
@@ -391,6 +424,7 @@ export interface InstanceStreamingLimits {
|
|||||||
allowedFramerates: number[];
|
allowedFramerates: number[];
|
||||||
maxResolution: number;
|
maxResolution: number;
|
||||||
maxFramerate: number;
|
maxFramerate: number;
|
||||||
|
discoveryEnabled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Federation Types ──────────────────────────────────────────────────────
|
// ─── Federation Types ──────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ import type {
|
|||||||
InstanceStreamingLimits,
|
InstanceStreamingLimits,
|
||||||
InstanceInfoResponse,
|
InstanceInfoResponse,
|
||||||
VerifyPasswordResponse,
|
VerifyPasswordResponse,
|
||||||
|
ExploreServer,
|
||||||
|
JoinRequest,
|
||||||
} from '@backspace/shared';
|
} from '@backspace/shared';
|
||||||
|
|
||||||
export class BackspaceApiClient {
|
export class BackspaceApiClient {
|
||||||
@@ -115,6 +117,15 @@ export class BackspaceApiClient {
|
|||||||
info: () => Promise<InstanceInfoResponse>;
|
info: () => Promise<InstanceInfoResponse>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
readonly explore: {
|
||||||
|
list: (q?: string, limit?: number, offset?: number) => Promise<{ servers: ExploreServer[]; total: number; discoveryEnabled: boolean }>;
|
||||||
|
publicJoin: (serverId: string) => Promise<ServerWithChannelsAndMembers>;
|
||||||
|
requestJoin: (serverId: string, message?: string) => Promise<JoinRequest>;
|
||||||
|
getJoinRequests: (serverId: string, status?: string) => Promise<{ requests: JoinRequest[] }>;
|
||||||
|
decideJoinRequest: (serverId: string, requestId: string, action: 'accept' | 'decline') => Promise<JoinRequest>;
|
||||||
|
myJoinRequests: (status?: string) => Promise<{ requests: JoinRequest[] }>;
|
||||||
|
};
|
||||||
|
|
||||||
constructor(baseUrl: string, getToken: () => string | null) {
|
constructor(baseUrl: string, getToken: () => string | null) {
|
||||||
async function request<T>(
|
async function request<T>(
|
||||||
method: string,
|
method: string,
|
||||||
@@ -287,6 +298,34 @@ export class BackspaceApiClient {
|
|||||||
this.instance = {
|
this.instance = {
|
||||||
info: () => request<InstanceInfoResponse>('GET', '/instance/info', undefined, false),
|
info: () => request<InstanceInfoResponse>('GET', '/instance/info', undefined, false),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
this.explore = {
|
||||||
|
list: (q?: string, limit = 50, offset = 0) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (q) params.set('q', q);
|
||||||
|
params.set('limit', String(limit));
|
||||||
|
params.set('offset', String(offset));
|
||||||
|
return request<{ servers: ExploreServer[]; total: number; discoveryEnabled: boolean }>(
|
||||||
|
'GET', `/servers/explore?${params}`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
publicJoin: (serverId: string) =>
|
||||||
|
request<ServerWithChannelsAndMembers>('POST', `/servers/${serverId}/public-join`),
|
||||||
|
requestJoin: (serverId: string, message?: string) =>
|
||||||
|
request<JoinRequest>('POST', `/servers/${serverId}/request-join`, message ? { message } : {}),
|
||||||
|
getJoinRequests: (serverId: string, status?: string) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (status) params.set('status', status);
|
||||||
|
return request<{ requests: JoinRequest[] }>('GET', `/servers/${serverId}/join-requests?${params}`);
|
||||||
|
},
|
||||||
|
decideJoinRequest: (serverId: string, requestId: string, action: 'accept' | 'decline') =>
|
||||||
|
request<JoinRequest>('PATCH', `/servers/${serverId}/join-requests/${requestId}`, { action }),
|
||||||
|
myJoinRequests: (status?: string) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (status) params.set('status', status);
|
||||||
|
return request<{ requests: JoinRequest[] }>('GET', `/users/@me/join-requests?${params}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,300 @@
|
|||||||
|
import React, { useEffect, useRef, useState, useCallback } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useExploreStore, type TaggedExploreServer } from '../../stores/exploreStore';
|
||||||
|
import { useServerStore } from '../../stores/serverStore';
|
||||||
|
import { useUIStore } from '../../stores/uiStore';
|
||||||
|
import { LoadingSpinner } from '../ui/LoadingSpinner';
|
||||||
|
import { getServerGradient } from '../../utils/gradients';
|
||||||
|
|
||||||
|
export function ExplorePage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const setCurrentServer = useServerStore((s) => s.setCurrentServer);
|
||||||
|
const setShowExplore = useUIStore((s) => s.setShowExplore);
|
||||||
|
|
||||||
|
const servers = useExploreStore((s) => s.servers);
|
||||||
|
const myRequests = useExploreStore((s) => s.myRequests);
|
||||||
|
const isLoading = useExploreStore((s) => s.isLoading);
|
||||||
|
const discoveryEnabled = useExploreStore((s) => s.discoveryEnabled);
|
||||||
|
const error = useExploreStore((s) => s.error);
|
||||||
|
const searchQuery = useExploreStore((s) => s.searchQuery);
|
||||||
|
const setSearchQuery = useExploreStore((s) => s.setSearchQuery);
|
||||||
|
const fetchServers = useExploreStore((s) => s.fetchServers);
|
||||||
|
const fetchMyRequests = useExploreStore((s) => s.fetchMyRequests);
|
||||||
|
|
||||||
|
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
// Fetch on mount
|
||||||
|
useEffect(() => {
|
||||||
|
fetchServers();
|
||||||
|
fetchMyRequests();
|
||||||
|
}, [fetchServers, fetchMyRequests]);
|
||||||
|
|
||||||
|
// Debounced search
|
||||||
|
const handleSearchChange = useCallback((value: string) => {
|
||||||
|
setSearchQuery(value);
|
||||||
|
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||||
|
debounceRef.current = setTimeout(() => {
|
||||||
|
fetchServers(value || undefined);
|
||||||
|
}, 300);
|
||||||
|
}, [setSearchQuery, fetchServers]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleJoinSuccess = (serverId: string) => {
|
||||||
|
setShowExplore(false);
|
||||||
|
setCurrentServer(serverId);
|
||||||
|
navigate(`/channels/${serverId}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex-1 flex flex-col bg-surface-chat h-full">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="h-12 px-4 flex items-center shadow-header flex-shrink-0 z-10 bg-surface-chat">
|
||||||
|
<div className="flex items-center gap-2 mr-4">
|
||||||
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor" className="text-txt-tertiary">
|
||||||
|
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-5.5-2.5l7.51-3.49L17.5 6.5 9.99 9.99 6.5 17.5zm5.5-6.6c.61 0 1.1.49 1.1 1.1s-.49 1.1-1.1 1.1-1.1-.49-1.1-1.1.49-1.1 1.1-1.1z" />
|
||||||
|
</svg>
|
||||||
|
<span className="font-bold text-txt-primary">Explore</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-[1px] h-6 bg-surface-elevated mx-2" />
|
||||||
|
|
||||||
|
<div className="relative flex-1 max-w-xs ml-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search servers..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => handleSearchChange(e.target.value)}
|
||||||
|
className="w-full bg-surface-base text-txt-primary text-sm px-3 py-1.5 rounded-[4px] outline-none placeholder:text-txt-tertiary/50 focus:ring-1 focus:ring-accent-primary transition-all"
|
||||||
|
/>
|
||||||
|
{searchQuery && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleSearchChange('')}
|
||||||
|
className="absolute right-2 top-1/2 -translate-y-1/2 text-txt-tertiary hover:text-txt-secondary"
|
||||||
|
>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 overflow-y-auto">
|
||||||
|
{!discoveryEnabled && (
|
||||||
|
<div className="mx-6 mt-4 p-2.5 bg-accent-amber/10 border border-accent-amber/30 rounded text-[13px] text-accent-amber">
|
||||||
|
Server discovery is disabled by the instance administrator.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isLoading && servers.length === 0 ? (
|
||||||
|
<div className="flex-1 flex items-center justify-center h-64">
|
||||||
|
<LoadingSpinner />
|
||||||
|
</div>
|
||||||
|
) : error ? (
|
||||||
|
<div className="mx-6 mt-4 p-3 bg-accent-rose/10 border border-accent-rose/30 rounded text-sm text-txt-danger">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
) : servers.length === 0 ? (
|
||||||
|
<div className="flex flex-col items-center justify-center h-64 opacity-60">
|
||||||
|
<svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor" className="text-txt-tertiary mb-3">
|
||||||
|
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-5.5-2.5l7.51-3.49L17.5 6.5 9.99 9.99 6.5 17.5zm5.5-6.6c.61 0 1.1.49 1.1 1.1s-.49 1.1-1.1 1.1-1.1-.49-1.1-1.1.49-1.1 1.1-1.1z" />
|
||||||
|
</svg>
|
||||||
|
<p className="text-txt-tertiary text-sm">
|
||||||
|
{searchQuery ? 'No servers match your search.' : 'No discoverable servers found.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 p-6">
|
||||||
|
{servers.map((server) => (
|
||||||
|
<ServerCard
|
||||||
|
key={`${server.id}:${server._instanceOrigin}`}
|
||||||
|
server={server}
|
||||||
|
isPending={myRequests.some(r => r.serverId === server.id && r.status === 'pending')}
|
||||||
|
onJoinSuccess={handleJoinSuccess}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ServerCard({
|
||||||
|
server,
|
||||||
|
isPending,
|
||||||
|
onJoinSuccess,
|
||||||
|
}: {
|
||||||
|
server: TaggedExploreServer;
|
||||||
|
isPending: boolean;
|
||||||
|
onJoinSuccess: (serverId: string) => void;
|
||||||
|
}) {
|
||||||
|
const publicJoin = useExploreStore((s) => s.publicJoin);
|
||||||
|
const requestJoin = useExploreStore((s) => s.requestJoin);
|
||||||
|
|
||||||
|
const [joining, setJoining] = useState(false);
|
||||||
|
const [showRequestForm, setShowRequestForm] = useState(false);
|
||||||
|
const [requestMessage, setRequestMessage] = useState('');
|
||||||
|
const [requestSent, setRequestSent] = useState(isPending);
|
||||||
|
const [joinError, setJoinError] = useState('');
|
||||||
|
|
||||||
|
const gradient = getServerGradient(server.id, server.name);
|
||||||
|
const isPublic = server.visibility === 'public';
|
||||||
|
const originLabel = server._instanceOrigin
|
||||||
|
? (() => { try { return new URL(server._instanceOrigin).host; } catch { return server._instanceOrigin; } })()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const handlePublicJoin = async () => {
|
||||||
|
setJoining(true);
|
||||||
|
setJoinError('');
|
||||||
|
try {
|
||||||
|
const fullServer = await publicJoin(server);
|
||||||
|
onJoinSuccess(fullServer.id);
|
||||||
|
} catch (err) {
|
||||||
|
setJoinError(err instanceof Error ? err.message : 'Failed to join');
|
||||||
|
setJoining(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRequestJoin = async () => {
|
||||||
|
setJoining(true);
|
||||||
|
setJoinError('');
|
||||||
|
try {
|
||||||
|
await requestJoin(server, requestMessage.trim() || undefined);
|
||||||
|
setRequestSent(true);
|
||||||
|
setShowRequestForm(false);
|
||||||
|
} catch (err) {
|
||||||
|
setJoinError(err instanceof Error ? err.message : 'Failed to send request');
|
||||||
|
} finally {
|
||||||
|
setJoining(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-surface-sidebar rounded-lg border border-border-soft overflow-hidden flex flex-col transition-colors hover:border-border-hard">
|
||||||
|
{/* Banner / Icon area */}
|
||||||
|
<div className="h-32 relative flex items-center justify-center" style={{ background: gradient.gradient }}>
|
||||||
|
{server.icon ? (
|
||||||
|
<img
|
||||||
|
src={server.icon.startsWith('http') ? server.icon : `/api/uploads/${server.icon}`}
|
||||||
|
alt={server.name}
|
||||||
|
className="w-16 h-16 rounded-2xl object-cover shadow-lg"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<span className="text-3xl font-bold text-white/90 drop-shadow-md">
|
||||||
|
{server.name.charAt(0).toUpperCase()}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Visibility badge */}
|
||||||
|
<div className="absolute top-2 right-2">
|
||||||
|
<span className={`px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wider ${
|
||||||
|
isPublic
|
||||||
|
? 'bg-accent-mint/20 text-accent-mint'
|
||||||
|
: 'bg-accent-amber/20 text-accent-amber'
|
||||||
|
}`}>
|
||||||
|
{isPublic ? 'Public' : 'Request'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Instance origin */}
|
||||||
|
{originLabel && (
|
||||||
|
<div className="absolute bottom-2 left-2">
|
||||||
|
<span className="px-1.5 py-0.5 rounded bg-black/40 text-[10px] text-white/80 font-medium backdrop-blur-sm">
|
||||||
|
{originLabel}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="p-4 flex flex-col flex-1">
|
||||||
|
<h3 className="text-[15px] font-bold text-txt-primary truncate mb-1">{server.name}</h3>
|
||||||
|
|
||||||
|
{server.description ? (
|
||||||
|
<p className="text-[13px] text-txt-secondary line-clamp-2 mb-3 flex-1">
|
||||||
|
{server.description}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-[13px] text-txt-tertiary italic mb-3 flex-1">No description</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 text-[12px] text-txt-tertiary mb-3">
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" className="opacity-60">
|
||||||
|
<path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" />
|
||||||
|
</svg>
|
||||||
|
{server.memberCount} {server.memberCount === 1 ? 'member' : 'members'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Action area */}
|
||||||
|
{joinError && (
|
||||||
|
<div className="text-[12px] text-txt-danger mb-2">{joinError}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isPublic ? (
|
||||||
|
<button
|
||||||
|
onClick={handlePublicJoin}
|
||||||
|
disabled={joining}
|
||||||
|
className="w-full py-2 bg-accent-primary hover:bg-accent-primary-hover text-white text-sm font-medium rounded transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{joining ? (
|
||||||
|
<span className="flex items-center justify-center gap-2">
|
||||||
|
<LoadingSpinner />
|
||||||
|
Joining...
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
'Join Server'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
) : requestSent ? (
|
||||||
|
<button
|
||||||
|
disabled
|
||||||
|
className="w-full py-2 bg-interactive-muted text-txt-tertiary text-sm font-medium rounded cursor-default"
|
||||||
|
>
|
||||||
|
Request Pending
|
||||||
|
</button>
|
||||||
|
) : showRequestForm ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<textarea
|
||||||
|
value={requestMessage}
|
||||||
|
onChange={(e) => setRequestMessage(e.target.value.slice(0, 200))}
|
||||||
|
placeholder="Why do you want to join? (optional)"
|
||||||
|
rows={2}
|
||||||
|
className="w-full px-3 py-2 bg-surface-input rounded text-sm text-txt-primary outline-none focus:ring-1 focus:ring-accent-primary resize-none placeholder:text-txt-tertiary"
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={handleRequestJoin}
|
||||||
|
disabled={joining}
|
||||||
|
className="flex-1 py-1.5 bg-accent-amber hover:bg-accent-amber/80 text-[#13131a] text-sm font-medium rounded transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{joining ? 'Sending...' : 'Send Request'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowRequestForm(false)}
|
||||||
|
className="px-3 py-1.5 text-sm text-txt-tertiary hover:text-txt-secondary transition-colors"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => setShowRequestForm(true)}
|
||||||
|
className="w-full py-2 bg-accent-amber/20 hover:bg-accent-amber/30 text-accent-amber text-sm font-medium rounded transition-colors"
|
||||||
|
>
|
||||||
|
Request to Join
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -59,7 +59,7 @@ export function FriendsPage() {
|
|||||||
if (instance?.api) client = instance.api;
|
if (instance?.api) client = instance.api;
|
||||||
}
|
}
|
||||||
const dmChannel = await client.dm.create({ userId: friendId });
|
const dmChannel = await client.dm.create({ userId: friendId });
|
||||||
addDmChannel(dmChannel);
|
addDmChannel(dmChannel, instanceOrigin);
|
||||||
navigate(`/channels/@me/${dmChannel.id}`);
|
navigate(`/channels/@me/${dmChannel.id}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to open DM:', err);
|
console.error('Failed to open DM:', err);
|
||||||
|
|||||||
@@ -185,7 +185,7 @@ function WelcomeHeader({ channelId }: { channelId: string }) {
|
|||||||
return (
|
return (
|
||||||
<div className="px-4 pt-8 pb-4">
|
<div className="px-4 pt-8 pb-4">
|
||||||
<div className="mb-2">
|
<div className="mb-2">
|
||||||
<Avatar src={otherUser?.avatar} name={displayName} size={80} userId={otherUser?.id} />
|
<Avatar src={otherUser?.avatar} name={displayName} size={80} user={otherUser ?? undefined} />
|
||||||
</div>
|
</div>
|
||||||
<h3 className="text-[32px] leading-10 font-bold text-txt-primary">{displayName}</h3>
|
<h3 className="text-[32px] leading-10 font-bold text-txt-primary">{displayName}</h3>
|
||||||
<p className="text-txt-secondary text-[14px] mt-1">
|
<p className="text-txt-secondary text-[14px] mt-1">
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ import React, { useEffect, useMemo } from 'react';
|
|||||||
import { useSocialStore } from '../../stores/socialStore';
|
import { useSocialStore } from '../../stores/socialStore';
|
||||||
import { useUIStore } from '../../stores/uiStore';
|
import { useUIStore } from '../../stores/uiStore';
|
||||||
import { Avatar } from '../ui/Avatar';
|
import { Avatar } from '../ui/Avatar';
|
||||||
|
import { Username } from '../ui/Username';
|
||||||
import type { Friend } from '@backspace/shared';
|
import type { Friend } from '@backspace/shared';
|
||||||
|
import { parseFederatedUsername } from '../../utils/identity';
|
||||||
|
|
||||||
export function ActivityPanel() {
|
export function ActivityPanel() {
|
||||||
const friends = useSocialStore((s) => s.friends);
|
const friends = useSocialStore((s) => s.friends);
|
||||||
@@ -34,7 +36,11 @@ export function ActivityPanel() {
|
|||||||
status: friend.status,
|
status: friend.status,
|
||||||
customStatus: friend.customStatus,
|
customStatus: friend.customStatus,
|
||||||
createdAt: friend.createdAt,
|
createdAt: friend.createdAt,
|
||||||
} as any,
|
homeUserId: friend.homeUserId,
|
||||||
|
homeInstance: friend.homeInstance,
|
||||||
|
isAdmin: false,
|
||||||
|
replicatedInstances: [],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
top: Math.min(rect.top, window.innerHeight - 450),
|
top: Math.min(rect.top, window.innerHeight - 450),
|
||||||
left: rect.left - 316,
|
left: rect.left - 316,
|
||||||
@@ -42,30 +48,38 @@ export function ActivityPanel() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderFriend = (friend: Friend, isOffline = false) => (
|
const renderFriend = (friend: Friend, isOffline = false) => {
|
||||||
<div
|
const { baseName, domain } = parseFederatedUsername(friend.username);
|
||||||
key={friend.id}
|
const friendDisplayName = friend.displayName ?? baseName;
|
||||||
onClick={(e) => handleFriendClick(e, friend)}
|
return (
|
||||||
className="flex items-center gap-2.5 px-2 py-1.5 rounded-[4px] hover:bg-interactive-hover cursor-pointer group transition-colors"
|
<div
|
||||||
>
|
key={friend.id}
|
||||||
<Avatar
|
onClick={(e) => handleFriendClick(e, friend)}
|
||||||
src={friend.avatar}
|
className="flex items-center gap-2.5 px-2 py-1.5 rounded-[4px] hover:bg-interactive-hover cursor-pointer group transition-colors"
|
||||||
name={friend.displayName ?? friend.username}
|
>
|
||||||
size={32}
|
<Avatar
|
||||||
status={isOffline ? 'offline' : friend.status}
|
src={friend.avatar}
|
||||||
className={isOffline ? 'opacity-60' : undefined}
|
name={friendDisplayName}
|
||||||
userId={friend.id}
|
size={32}
|
||||||
/>
|
status={isOffline ? 'offline' : friend.status}
|
||||||
<div className="flex-1 min-w-0">
|
className={isOffline ? 'opacity-60' : undefined}
|
||||||
<div className={`text-[13.5px] leading-[1.2] font-medium truncate ${isOffline ? 'text-txt-tertiary' : 'text-txt-primary'}`}>
|
userId={friend.homeUserId ?? friend.id}
|
||||||
{friend.displayName ?? friend.username}
|
/>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<Username
|
||||||
|
username={friendDisplayName}
|
||||||
|
className={`text-[13.5px] leading-[1.2] font-medium truncate ${isOffline ? 'text-txt-tertiary' : 'text-txt-primary'}`}
|
||||||
|
/>
|
||||||
|
{domain && !isOffline && (
|
||||||
|
<div className="text-[10px] leading-[1.3] text-txt-tertiary truncate opacity-60">@{domain}</div>
|
||||||
|
)}
|
||||||
|
{!isOffline && friend.customStatus && (
|
||||||
|
<div className="text-[11px] leading-[1.3] text-txt-tertiary truncate">{friend.customStatus}</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{!isOffline && friend.customStatus && (
|
|
||||||
<div className="text-[11px] leading-[1.3] text-txt-tertiary truncate">{friend.customStatus}</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
);
|
||||||
);
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-60 bg-surface-channel flex-shrink-0 overflow-y-auto select-none no-scrollbar hidden md:block border-l border-border-hard">
|
<div className="w-60 bg-surface-channel flex-shrink-0 overflow-y-auto select-none no-scrollbar hidden md:block border-l border-border-hard">
|
||||||
|
|||||||
@@ -9,10 +9,12 @@ import { VoiceChannel } from '../voice/VoiceChannel';
|
|||||||
import { VoiceControls } from '../voice/VoiceControls';
|
import { VoiceControls } from '../voice/VoiceControls';
|
||||||
import { useVoiceStore } from '../../stores/voiceStore';
|
import { useVoiceStore } from '../../stores/voiceStore';
|
||||||
import { Avatar } from '../ui/Avatar';
|
import { Avatar } from '../ui/Avatar';
|
||||||
|
import { Username } from '../ui/Username';
|
||||||
import { wsSend } from '../../hooks/useWebSocket';
|
import { wsSend } from '../../hooks/useWebSocket';
|
||||||
import { getActiveRoom } from '../../hooks/useLiveKit';
|
import { getActiveRoom } from '../../hooks/useLiveKit';
|
||||||
import { AudioManager } from '../../audio/AudioManager';
|
import { AudioManager } from '../../audio/AudioManager';
|
||||||
import { hasPermissionBit, PermissionBits } from '../../utils/permissions';
|
import { hasPermissionBit, PermissionBits } from '../../utils/permissions';
|
||||||
|
import { parseFederatedUsername } from '../../utils/identity';
|
||||||
|
|
||||||
export function ChannelSidebar() {
|
export function ChannelSidebar() {
|
||||||
const servers = useServerStore((s) => s.servers);
|
const servers = useServerStore((s) => s.servers);
|
||||||
@@ -193,7 +195,7 @@ export function ChannelSidebar() {
|
|||||||
const isDmUnread = unreadChannels.has(dm.id) && currentChannelId !== dm.id;
|
const isDmUnread = unreadChannels.has(dm.id) && currentChannelId !== dm.id;
|
||||||
|
|
||||||
const dmDisplayName = isGroup
|
const dmDisplayName = isGroup
|
||||||
? otherMembers.map(m => m.displayName ?? m.username).join(', ')
|
? otherMembers.map(m => m.displayName ?? parseFederatedUsername(m.username).baseName).join(', ')
|
||||||
: otherMembers[0]?.displayName ?? otherMembers[0]?.username;
|
: otherMembers[0]?.displayName ?? otherMembers[0]?.username;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -224,21 +226,22 @@ export function ChannelSidebar() {
|
|||||||
zIndex: 2 - i,
|
zIndex: 2 - i,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Avatar src={m.avatar} name={m.displayName ?? m.username} size={22} userId={m.id} />
|
<Avatar src={m.avatar} name={m.displayName ?? parseFederatedUsername(m.username).baseName} size={22} userId={m.homeUserId ?? m.id} />
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<Avatar src={otherMembers[0]?.avatar} name={otherMembers[0]?.displayName ?? otherMembers[0]?.username ?? ''} size={32} status={otherMembers[0]?.status as any} userId={otherMembers[0]?.id} />
|
<Avatar src={otherMembers[0]?.avatar} name={otherMembers[0]?.displayName ?? parseFederatedUsername(otherMembers[0]?.username ?? '').baseName} size={32} status={otherMembers[0]?.status as any} userId={otherMembers[0]?.homeUserId ?? otherMembers[0]?.id} />
|
||||||
)}
|
)}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className={`text-[15px] truncate leading-tight ${
|
<Username
|
||||||
currentChannelId === dm.id ? 'text-white font-medium'
|
username={dmDisplayName ?? ''}
|
||||||
: isDmUnread ? 'text-white font-bold'
|
className={`text-[15px] truncate leading-tight block ${
|
||||||
: 'text-txt-tertiary group-hover:text-txt-secondary font-medium'
|
currentChannelId === dm.id ? 'text-white font-medium'
|
||||||
}`}>
|
: isDmUnread ? 'text-white font-bold'
|
||||||
{dmDisplayName}
|
: 'text-txt-tertiary group-hover:text-txt-secondary font-medium'
|
||||||
</div>
|
}`}
|
||||||
|
/>
|
||||||
{isGroup ? (
|
{isGroup ? (
|
||||||
<div className="text-[12px] text-txt-tertiary truncate leading-tight mt-0.5">
|
<div className="text-[12px] text-txt-tertiary truncate leading-tight mt-0.5">
|
||||||
{dm.members.length} Members
|
{dm.members.length} Members
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { VoiceGrid } from '../voice/VoiceGrid';
|
|||||||
import { VoiceControlBar } from '../voice/VoiceControlBar';
|
import { VoiceControlBar } from '../voice/VoiceControlBar';
|
||||||
import { VoiceChatPanel } from '../voice/VoiceChatPanel';
|
import { VoiceChatPanel } from '../voice/VoiceChatPanel';
|
||||||
import { FriendsPage } from '../chat/FriendsPage';
|
import { FriendsPage } from '../chat/FriendsPage';
|
||||||
|
import { ExplorePage } from '../chat/ExplorePage';
|
||||||
import { Avatar } from '../ui/Avatar';
|
import { Avatar } from '../ui/Avatar';
|
||||||
import { useVoiceStore } from '../../stores/voiceStore';
|
import { useVoiceStore } from '../../stores/voiceStore';
|
||||||
import { wsSend } from '../../hooks/useWebSocket';
|
import { wsSend } from '../../hooks/useWebSocket';
|
||||||
@@ -27,6 +28,7 @@ export function MainContent() {
|
|||||||
const isLiveKitConnected = useVoiceStore((s) => s.isLiveKitConnected);
|
const isLiveKitConnected = useVoiceStore((s) => s.isLiveKitConnected);
|
||||||
const connectionError = useVoiceStore((s) => s.connectionError);
|
const connectionError = useVoiceStore((s) => s.connectionError);
|
||||||
const showDms = useUIStore((s) => s.showDms);
|
const showDms = useUIStore((s) => s.showDms);
|
||||||
|
const showExplore = useUIStore((s) => s.showExplore);
|
||||||
const activeDmCall = useVoiceStore((s) => s.activeDmCall);
|
const activeDmCall = useVoiceStore((s) => s.activeDmCall);
|
||||||
const outgoingCall = useVoiceStore((s) => s.outgoingCall);
|
const outgoingCall = useVoiceStore((s) => s.outgoingCall);
|
||||||
const dmChannels = useServerStore((s) => s.dmChannels);
|
const dmChannels = useServerStore((s) => s.dmChannels);
|
||||||
@@ -58,8 +60,9 @@ export function MainContent() {
|
|||||||
const channel = channels.find(c => c.id === currentChannelId);
|
const channel = channels.find(c => c.id === currentChannelId);
|
||||||
const isVoiceChannel = channel?.type === 'voice' || channel?.type === 'video';
|
const isVoiceChannel = channel?.type === 'voice' || channel?.type === 'video';
|
||||||
|
|
||||||
if (showDms || !currentServerId) {
|
if (showDms || showExplore || !currentServerId) {
|
||||||
if (!currentChannelId) {
|
if (!currentChannelId) {
|
||||||
|
if (showExplore) return <ExplorePage />;
|
||||||
return <FriendsPage />;
|
return <FriendsPage />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useServerStore } from '../../stores/serverStore';
|
|||||||
import { useUIStore } from '../../stores/uiStore';
|
import { useUIStore } from '../../stores/uiStore';
|
||||||
import { Avatar } from '../ui/Avatar';
|
import { Avatar } from '../ui/Avatar';
|
||||||
import { Username } from '../ui/Username';
|
import { Username } from '../ui/Username';
|
||||||
|
import { parseFederatedUsername } from '../../utils/identity';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Derives the display group for a member based on their highest-positioned role
|
* Derives the display group for a member based on their highest-positioned role
|
||||||
@@ -95,7 +96,8 @@ export function MemberSidebar() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const renderMember = (member: MemberWithUser, isOffline = false) => {
|
const renderMember = (member: MemberWithUser, isOffline = false) => {
|
||||||
const displayName = member.user.displayName ?? member.user.username;
|
const { baseName, domain } = parseFederatedUsername(member.user.username);
|
||||||
|
const displayName = member.user.displayName ?? baseName;
|
||||||
const colorStyle = isOffline ? undefined : getMemberColor(member);
|
const colorStyle = isOffline ? undefined : getMemberColor(member);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -117,6 +119,9 @@ export function MemberSidebar() {
|
|||||||
className={`text-[13.5px] leading-[1.2] font-medium truncate ${isOffline ? 'text-txt-tertiary' : (!colorStyle ? 'text-txt-primary' : '')}`}
|
className={`text-[13.5px] leading-[1.2] font-medium truncate ${isOffline ? 'text-txt-tertiary' : (!colorStyle ? 'text-txt-primary' : '')}`}
|
||||||
style={colorStyle}
|
style={colorStyle}
|
||||||
/>
|
/>
|
||||||
|
{domain && !isOffline && (
|
||||||
|
<div className="text-[10px] leading-[1.3] text-txt-tertiary truncate opacity-60">@{domain}</div>
|
||||||
|
)}
|
||||||
{!isOffline && member.user.customStatus && (
|
{!isOffline && member.user.customStatus && (
|
||||||
<div className="text-[11px] leading-[1.3] text-txt-tertiary truncate">{member.user.customStatus}</div>
|
<div className="text-[11px] leading-[1.3] text-txt-tertiary truncate">{member.user.customStatus}</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ interface SidebarItemProps {
|
|||||||
active: boolean;
|
active: boolean;
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
type?: 'server' | 'dm' | 'action';
|
type?: 'server' | 'dm' | 'action';
|
||||||
actionType?: 'add' | 'join';
|
actionType?: 'add' | 'join' | 'explore';
|
||||||
hasUnread?: boolean;
|
hasUnread?: boolean;
|
||||||
dimmed?: boolean;
|
dimmed?: boolean;
|
||||||
}
|
}
|
||||||
@@ -89,6 +89,10 @@ function SidebarItem({ id, name, icon, active, onClick, type = 'server', actionT
|
|||||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||||
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z" />
|
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z" />
|
||||||
</svg>
|
</svg>
|
||||||
|
) : actionType === 'explore' ? (
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-5.5-2.5l7.51-3.49L17.5 6.5 9.99 9.99 6.5 17.5zm5.5-6.6c.61 0 1.1.49 1.1 1.1s-.49 1.1-1.1 1.1-1.1-.49-1.1-1.1.49-1.1 1.1-1.1z" />
|
||||||
|
</svg>
|
||||||
) : (
|
) : (
|
||||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||||
<path d="M12 2L4.5 20.29l.71.71L12 18l6.79 3 .71-.71z" />
|
<path d="M12 2L4.5 20.29l.71.71L12 18l6.79 3 .71-.71z" />
|
||||||
@@ -116,6 +120,8 @@ export function ServerSidebar() {
|
|||||||
const dmChannels = useServerStore((s) => s.dmChannels);
|
const dmChannels = useServerStore((s) => s.dmChannels);
|
||||||
const showDms = useUIStore((s) => s.showDms);
|
const showDms = useUIStore((s) => s.showDms);
|
||||||
const setShowDms = useUIStore((s) => s.setShowDms);
|
const setShowDms = useUIStore((s) => s.setShowDms);
|
||||||
|
const showExplore = useUIStore((s) => s.showExplore);
|
||||||
|
const setShowExplore = useUIStore((s) => s.setShowExplore);
|
||||||
const openModal = useUIStore((s) => s.openModal);
|
const openModal = useUIStore((s) => s.openModal);
|
||||||
const addToast = useUIStore((s) => s.addToast);
|
const addToast = useUIStore((s) => s.addToast);
|
||||||
const unreadChannels = useChatStore((s) => s.unreadChannels);
|
const unreadChannels = useChatStore((s) => s.unreadChannels);
|
||||||
@@ -175,6 +181,7 @@ export function ServerSidebar() {
|
|||||||
}
|
}
|
||||||
setCurrentServer(serverId);
|
setCurrentServer(serverId);
|
||||||
setShowDms(false);
|
setShowDms(false);
|
||||||
|
setShowExplore(false);
|
||||||
navigate(`/channels/${serverId}`);
|
navigate(`/channels/${serverId}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -184,6 +191,12 @@ export function ServerSidebar() {
|
|||||||
navigate('/channels/@me');
|
navigate('/channels/@me');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleExploreClick = () => {
|
||||||
|
setShowExplore(true);
|
||||||
|
setCurrentServer(null);
|
||||||
|
navigate('/channels/@me');
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav data-pip-obstacle="left" className="w-[72px] bg-surface-base flex flex-col items-center py-3 overflow-y-auto flex-shrink-0 no-scrollbar select-none md:fixed md:inset-y-0 md:left-0 md:z-[100] md:glass-strip">
|
<nav data-pip-obstacle="left" className="w-[72px] bg-surface-base flex flex-col items-center py-3 overflow-y-auto flex-shrink-0 no-scrollbar select-none md:fixed md:inset-y-0 md:left-0 md:z-[100] md:glass-strip">
|
||||||
<SidebarItem
|
<SidebarItem
|
||||||
@@ -257,6 +270,15 @@ export function ServerSidebar() {
|
|||||||
actionType="join"
|
actionType="join"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<SidebarItem
|
||||||
|
id="explore"
|
||||||
|
name="Explore Servers"
|
||||||
|
active={showExplore}
|
||||||
|
onClick={handleExploreClick}
|
||||||
|
type="action"
|
||||||
|
actionType="explore"
|
||||||
|
/>
|
||||||
|
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { Avatar } from '../ui/Avatar';
|
|||||||
import { api } from '../../api/client';
|
import { api } from '../../api/client';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { hasPermissionBit, PermissionBits } from '../../utils/permissions';
|
import { hasPermissionBit, PermissionBits } from '../../utils/permissions';
|
||||||
import type { InstanceStreamingLimits } from '@backspace/shared';
|
import type { InstanceStreamingLimits, ServerVisibility, JoinRequest } from '@backspace/shared';
|
||||||
|
|
||||||
const VALID_RESOLUTIONS = [540, 720, 1080] as const;
|
const VALID_RESOLUTIONS = [540, 720, 1080] as const;
|
||||||
const VALID_FRAMERATES = [30, 45, 60] as const;
|
const VALID_FRAMERATES = [30, 45, 60] as const;
|
||||||
@@ -215,6 +215,250 @@ function StreamingLimitsPanel() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DiscoveryPanel({ serverId }: { serverId: string }) {
|
||||||
|
const servers = useServerStore((s) => s.servers);
|
||||||
|
const updateServer = useServerStore((s) => s.updateServer);
|
||||||
|
const discoveryEnabled = useSettingsStore((s) => s.streamingLimits?.discoveryEnabled ?? true);
|
||||||
|
|
||||||
|
const server = servers.find(s => s.id === serverId);
|
||||||
|
|
||||||
|
const [visibility, setVisibility] = useState<ServerVisibility>(
|
||||||
|
(server?.visibility as ServerVisibility) ?? 'private'
|
||||||
|
);
|
||||||
|
const [description, setDescription] = useState(server?.description ?? '');
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [saveError, setSaveError] = useState('');
|
||||||
|
const [saveSuccess, setSaveSuccess] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (server) {
|
||||||
|
setVisibility((server.visibility as ServerVisibility) ?? 'private');
|
||||||
|
setDescription(server.description ?? '');
|
||||||
|
}
|
||||||
|
}, [server]);
|
||||||
|
|
||||||
|
if (!server) return null;
|
||||||
|
|
||||||
|
const hasChanges =
|
||||||
|
visibility !== ((server.visibility as ServerVisibility) ?? 'private') ||
|
||||||
|
description !== (server.description ?? '');
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
setSaving(true);
|
||||||
|
setSaveError('');
|
||||||
|
setSaveSuccess(false);
|
||||||
|
try {
|
||||||
|
await api.servers.update(serverId, { visibility, description: description.trim() });
|
||||||
|
setSaveSuccess(true);
|
||||||
|
setTimeout(() => setSaveSuccess(false), 2000);
|
||||||
|
} catch (err) {
|
||||||
|
setSaveError(err instanceof Error ? err.message : 'Failed to save');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleReset = () => {
|
||||||
|
setVisibility((server.visibility as ServerVisibility) ?? 'private');
|
||||||
|
setDescription(server.description ?? '');
|
||||||
|
setSaveError('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const visibilityOptions: { value: ServerVisibility; label: string; desc: string }[] = [
|
||||||
|
{ value: 'private', label: 'Private', desc: 'Only people with an invite link can join' },
|
||||||
|
{ value: 'request', label: 'Request to Join', desc: 'Visible in Explore — people can request to join' },
|
||||||
|
{ value: 'public', label: 'Public', desc: 'Visible in Explore — anyone can join instantly' },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{!discoveryEnabled && (
|
||||||
|
<div className="p-2.5 bg-accent-amber/10 border border-accent-amber/30 rounded text-[13px] text-accent-amber">
|
||||||
|
Server discovery is disabled by the instance administrator. Changing visibility will have no effect until discovery is re-enabled.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="text-[11px] text-txt-tertiary font-semibold uppercase tracking-wider mb-2">
|
||||||
|
Visibility
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{visibilityOptions.map((opt) => (
|
||||||
|
<label
|
||||||
|
key={opt.value}
|
||||||
|
className={`flex items-start gap-3 p-2.5 rounded cursor-pointer transition-colors ${
|
||||||
|
visibility === opt.value
|
||||||
|
? 'bg-interactive-selected'
|
||||||
|
: 'hover:bg-interactive-hover'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="visibility"
|
||||||
|
value={opt.value}
|
||||||
|
checked={visibility === opt.value}
|
||||||
|
onChange={() => setVisibility(opt.value)}
|
||||||
|
className="mt-0.5 accent-accent-primary"
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-medium text-txt-primary">{opt.label}</div>
|
||||||
|
<div className="text-xs text-txt-tertiary">{opt.desc}</div>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="text-[11px] text-txt-tertiary font-semibold uppercase tracking-wider mb-1.5">
|
||||||
|
Description
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value.slice(0, 200))}
|
||||||
|
placeholder="A short description for the Explore page..."
|
||||||
|
rows={3}
|
||||||
|
className="w-full px-3 py-2 bg-surface-input rounded text-sm text-txt-primary outline-none focus:ring-1 focus:ring-accent-primary resize-none placeholder:text-txt-tertiary"
|
||||||
|
/>
|
||||||
|
<div className="text-[11px] text-txt-tertiary text-right">{description.length}/200</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{saveError && (
|
||||||
|
<div className="p-2 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-sm">{saveError}</div>
|
||||||
|
)}
|
||||||
|
{saveSuccess && (
|
||||||
|
<div className="p-2 bg-status-online/10 border border-status-online/30 rounded text-status-online text-sm">Settings saved</div>
|
||||||
|
)}
|
||||||
|
{hasChanges && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={saving}
|
||||||
|
className="px-4 py-1.5 bg-accent-primary hover:bg-accent-primary/80 text-white text-sm font-medium rounded transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{saving ? 'Saving...' : 'Save'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleReset}
|
||||||
|
className="px-4 py-1.5 text-sm text-txt-tertiary hover:text-txt-secondary transition-colors"
|
||||||
|
>
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Pending Join Requests — only shown when visibility is 'request' */}
|
||||||
|
{(visibility === 'request' || (server.visibility as ServerVisibility) === 'request') && (
|
||||||
|
<JoinRequestsSection serverId={serverId} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function JoinRequestsSection({ serverId }: { serverId: string }) {
|
||||||
|
const [requests, setRequests] = useState<JoinRequest[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [actionError, setActionError] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
setLoading(true);
|
||||||
|
api.explore.getJoinRequests(serverId, 'pending')
|
||||||
|
.then(({ requests: reqs }) => {
|
||||||
|
if (!cancelled) {
|
||||||
|
setRequests(reqs);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [serverId]);
|
||||||
|
|
||||||
|
const handleDecide = async (requestId: string, action: 'accept' | 'decline') => {
|
||||||
|
setActionError('');
|
||||||
|
try {
|
||||||
|
await api.explore.decideJoinRequest(serverId, requestId, action);
|
||||||
|
setRequests(prev => prev.filter(r => r.id !== requestId));
|
||||||
|
} catch (err) {
|
||||||
|
setActionError(err instanceof Error ? err.message : 'Action failed');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-4 border-t border-border-soft">
|
||||||
|
<div className="text-[11px] text-txt-tertiary font-semibold uppercase tracking-wider mb-2">
|
||||||
|
Pending Join Requests
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{actionError && (
|
||||||
|
<div className="mb-2 p-2 bg-accent-rose/10 border border-accent-rose/30 rounded text-txt-danger text-xs">
|
||||||
|
{actionError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="text-sm text-txt-tertiary">Loading...</div>
|
||||||
|
) : requests.length === 0 ? (
|
||||||
|
<div className="text-sm text-txt-tertiary">No pending join requests</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2 max-h-[240px] overflow-y-auto scrollbar-thin">
|
||||||
|
{requests.map((req) => {
|
||||||
|
const user = req.user;
|
||||||
|
const displayName = user?.displayName ?? user?.username ?? 'Unknown';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={req.id} className="flex items-start gap-3 p-2.5 rounded bg-surface-base">
|
||||||
|
<Avatar
|
||||||
|
src={user?.avatar}
|
||||||
|
name={displayName}
|
||||||
|
size={32}
|
||||||
|
userId={user?.id}
|
||||||
|
/>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className="text-sm font-medium text-txt-primary truncate">{displayName}</span>
|
||||||
|
{user?.username && (
|
||||||
|
<span className="text-xs text-txt-tertiary">@{user.username}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{req.message && (
|
||||||
|
<p className="text-xs text-txt-secondary mt-0.5 line-clamp-2">{req.message}</p>
|
||||||
|
)}
|
||||||
|
<span className="text-[10px] text-txt-tertiary">
|
||||||
|
{new Date(req.createdAt).toLocaleDateString()}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1 flex-shrink-0">
|
||||||
|
<button
|
||||||
|
onClick={() => handleDecide(req.id, 'accept')}
|
||||||
|
className="p-1.5 rounded text-status-online hover:bg-status-online/20 transition-colors"
|
||||||
|
title="Accept"
|
||||||
|
>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDecide(req.id, 'decline')}
|
||||||
|
className="p-1.5 rounded text-txt-danger hover:bg-accent-rose/20 transition-colors"
|
||||||
|
title="Decline"
|
||||||
|
>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function ServerSettingsModal() {
|
export function ServerSettingsModal() {
|
||||||
const activeModal = useUIStore((s) => s.activeModal);
|
const activeModal = useUIStore((s) => s.activeModal);
|
||||||
const closeModal = useUIStore((s) => s.closeModal);
|
const closeModal = useUIStore((s) => s.closeModal);
|
||||||
@@ -229,7 +473,7 @@ export function ServerSettingsModal() {
|
|||||||
const isAdmin = useSettingsStore((s) => s.isAdmin);
|
const isAdmin = useSettingsStore((s) => s.isAdmin);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const [tab, setTab] = useState<'overview' | 'members' | 'streaming'>('overview');
|
const [tab, setTab] = useState<'overview' | 'discovery' | 'members' | 'streaming'>('overview');
|
||||||
const [serverName, setServerName] = useState('');
|
const [serverName, setServerName] = useState('');
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
@@ -346,6 +590,16 @@ export function ServerSettingsModal() {
|
|||||||
>
|
>
|
||||||
Overview
|
Overview
|
||||||
</button>
|
</button>
|
||||||
|
{canManageServer && (
|
||||||
|
<button
|
||||||
|
onClick={() => setTab('discovery')}
|
||||||
|
className={`w-full text-left px-3 py-1.5 rounded text-sm transition-colors ${
|
||||||
|
tab === 'discovery' ? 'bg-interactive-selected text-txt-primary' : 'text-txt-tertiary hover:text-txt-secondary hover:bg-interactive-hover'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Discovery
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() => setTab('members')}
|
onClick={() => setTab('members')}
|
||||||
className={`w-full text-left px-3 py-1.5 rounded text-sm transition-colors ${
|
className={`w-full text-left px-3 py-1.5 rounded text-sm transition-colors ${
|
||||||
@@ -411,6 +665,10 @@ export function ServerSettingsModal() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{tab === 'discovery' && canManageServer && currentServerId && (
|
||||||
|
<DiscoveryPanel serverId={currentServerId} />
|
||||||
|
)}
|
||||||
|
|
||||||
{tab === 'members' && (
|
{tab === 'members' && (
|
||||||
<div className="space-y-2 max-h-[400px] overflow-y-auto scrollbar-thin">
|
<div className="space-y-2 max-h-[400px] overflow-y-auto scrollbar-thin">
|
||||||
{members.map((member) => {
|
{members.map((member) => {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { api } from '../../api/client';
|
|||||||
import { useServerStore } from '../../stores/serverStore';
|
import { useServerStore } from '../../stores/serverStore';
|
||||||
import { useUIStore } from '../../stores/uiStore';
|
import { useUIStore } from '../../stores/uiStore';
|
||||||
import { getAvatarGradient } from '../../utils/gradients';
|
import { getAvatarGradient } from '../../utils/gradients';
|
||||||
|
import { parseFederatedUsername } from '../../utils/identity';
|
||||||
|
|
||||||
interface UserProfilePopoutProps {
|
interface UserProfilePopoutProps {
|
||||||
user: User;
|
user: User;
|
||||||
@@ -17,7 +18,8 @@ interface UserProfilePopoutProps {
|
|||||||
export function UserProfilePopout({ user, onClose, position }: UserProfilePopoutProps) {
|
export function UserProfilePopout({ user, onClose, position }: UserProfilePopoutProps) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const addDmChannel = useServerStore((s) => s.addDmChannel);
|
const addDmChannel = useServerStore((s) => s.addDmChannel);
|
||||||
const displayName = user.displayName ?? user.username;
|
const { baseName, domain } = parseFederatedUsername(user.username);
|
||||||
|
const displayName = user.displayName ?? baseName;
|
||||||
|
|
||||||
const top = position
|
const top = position
|
||||||
? Math.min(Math.max(8, position.top), window.innerHeight - 360)
|
? Math.min(Math.max(8, position.top), window.innerHeight - 360)
|
||||||
@@ -72,21 +74,23 @@ export function UserProfilePopout({ user, onClose, position }: UserProfilePopout
|
|||||||
name={displayName}
|
name={displayName}
|
||||||
size={56}
|
size={56}
|
||||||
status={user.status as 'online' | 'idle' | 'dnd' | 'offline' | null}
|
status={user.status as 'online' | 'idle' | 'dnd' | 'offline' | null}
|
||||||
userId={user.id}
|
userId={user.homeUserId ?? user.id}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Name & info — flows naturally after avatar */}
|
{/* Name & info — flows naturally after avatar */}
|
||||||
<div>
|
<div>
|
||||||
<Username
|
<Username
|
||||||
username={displayName}
|
username={user.displayName ?? baseName}
|
||||||
className="text-[16px] font-semibold text-txt-primary leading-tight"
|
className="text-[16px] font-semibold text-txt-primary leading-tight"
|
||||||
/>
|
/>
|
||||||
{user.username.includes('@') ? (
|
<div className="text-[13px] text-txt-tertiary">
|
||||||
<Username username={user.username} className="text-[13px] text-txt-tertiary" />
|
{domain ? (
|
||||||
) : (
|
<Username username={user.username} className="text-[13px] text-txt-tertiary" />
|
||||||
<div className="text-[13px] text-txt-tertiary">@{user.username}</div>
|
) : (
|
||||||
)}
|
<span>@{baseName}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
{user.customStatus && (
|
{user.customStatus && (
|
||||||
<div className="text-[13px] text-txt-secondary italic mt-1">
|
<div className="text-[13px] text-txt-secondary italic mt-1">
|
||||||
{user.customStatus}
|
{user.customStatus}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import React, { useEffect, useRef } from 'react';
|
import React, { useEffect, useRef } from 'react';
|
||||||
import { useVoiceStore } from '../../stores/voiceStore';
|
import { useVoiceStore } from '../../stores/voiceStore';
|
||||||
|
import { useServerStore } from '../../stores/serverStore';
|
||||||
import { wsSend } from '../../hooks/useWebSocket';
|
import { wsSend } from '../../hooks/useWebSocket';
|
||||||
import { getAvatarGradient } from '../../utils/gradients';
|
import { getAvatarGradient } from '../../utils/gradients';
|
||||||
|
import { parseFederatedUsername } from '../../utils/identity';
|
||||||
|
|
||||||
export function IncomingCallModal() {
|
export function IncomingCallModal() {
|
||||||
const incomingCall = useVoiceStore((s) => s.incomingCall);
|
const incomingCall = useVoiceStore((s) => s.incomingCall);
|
||||||
@@ -25,8 +27,16 @@ export function IncomingCallModal() {
|
|||||||
};
|
};
|
||||||
}, [incomingCall, setIncomingCall]);
|
}, [incomingCall, setIncomingCall]);
|
||||||
|
|
||||||
|
const dmChannels = useServerStore((s) => s.dmChannels);
|
||||||
|
|
||||||
if (!incomingCall) return null;
|
if (!incomingCall) return null;
|
||||||
|
|
||||||
|
// Look up the caller in DM channel members for homeUserId
|
||||||
|
const dmChannel = dmChannels.find(d => d.id === incomingCall.dmChannelId);
|
||||||
|
const callerMember = dmChannel?.members.find(m => m.id === incomingCall.callerId);
|
||||||
|
const callerAvatarId = callerMember?.homeUserId ?? incomingCall.callerId;
|
||||||
|
const { baseName: callerBaseName } = parseFederatedUsername(incomingCall.callerName);
|
||||||
|
|
||||||
const handleAccept = () => {
|
const handleAccept = () => {
|
||||||
if (timerRef.current) clearTimeout(timerRef.current);
|
if (timerRef.current) clearTimeout(timerRef.current);
|
||||||
wsSend({ type: 'dm_call_accept', dmChannelId: incomingCall.dmChannelId });
|
wsSend({ type: 'dm_call_accept', dmChannelId: incomingCall.dmChannelId });
|
||||||
@@ -55,8 +65,8 @@ export function IncomingCallModal() {
|
|||||||
<div className="relative p-8 flex flex-col items-center gap-4">
|
<div className="relative p-8 flex flex-col items-center gap-4">
|
||||||
{/* Caller avatar */}
|
{/* Caller avatar */}
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="w-20 h-20 rounded-full flex items-center justify-center text-white text-3xl font-bold" style={{ background: getAvatarGradient(incomingCall.callerId, incomingCall.callerName).gradient }}>
|
<div className="w-20 h-20 rounded-full flex items-center justify-center text-white text-3xl font-bold" style={{ background: getAvatarGradient(callerAvatarId, callerBaseName).gradient }}>
|
||||||
{incomingCall.callerName.charAt(0).toUpperCase()}
|
{callerBaseName.charAt(0).toUpperCase()}
|
||||||
</div>
|
</div>
|
||||||
{/* Ringing phone icon */}
|
{/* Ringing phone icon */}
|
||||||
<div className="absolute -bottom-1 -right-1 w-7 h-7 rounded-full bg-status-online flex items-center justify-center">
|
<div className="absolute -bottom-1 -right-1 w-7 h-7 rounded-full bg-status-online flex items-center justify-center">
|
||||||
@@ -68,7 +78,7 @@ export function IncomingCallModal() {
|
|||||||
|
|
||||||
{/* Caller info */}
|
{/* Caller info */}
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<h3 className="text-[20px] font-bold text-txt-primary">{incomingCall.callerName}</h3>
|
<h3 className="text-[20px] font-bold text-txt-primary">{callerBaseName}</h3>
|
||||||
<p className="text-[14px] text-txt-tertiary mt-1">Incoming Voice Call...</p>
|
<p className="text-[14px] text-txt-tertiary mt-1">Incoming Voice Call...</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -351,7 +351,7 @@ export function PictureInPicture() {
|
|||||||
<Avatar
|
<Avatar
|
||||||
name={displayParticipant.username}
|
name={displayParticipant.username}
|
||||||
size={64}
|
size={64}
|
||||||
userId={displayParticipant.userId}
|
userId={displayParticipant.homeUserId ?? displayParticipant.userId}
|
||||||
/>
|
/>
|
||||||
{speakingParticipantIds.has(displayParticipant.identity) && (
|
{speakingParticipantIds.has(displayParticipant.identity) && (
|
||||||
<div className="absolute -inset-1 rounded-full ring-2 ring-status-online animate-pulse" />
|
<div className="absolute -inset-1 rounded-full ring-2 ring-status-online animate-pulse" />
|
||||||
|
|||||||
@@ -268,7 +268,7 @@ function handleEvent(origin: string, event: ServerEvent): void {
|
|||||||
createdAt: event.message.createdAt,
|
createdAt: event.message.createdAt,
|
||||||
members: event.message.user ? [event.message.user] : [],
|
members: event.message.user ? [event.message.user] : [],
|
||||||
lastMessage: event.message,
|
lastMessage: event.message,
|
||||||
});
|
}, origin);
|
||||||
} else {
|
} else {
|
||||||
const updatedDms = currentDmChannels.map(dm =>
|
const updatedDms = currentDmChannels.map(dm =>
|
||||||
dm.id === event.message.dmChannelId
|
dm.id === event.message.dmChannelId
|
||||||
@@ -388,7 +388,7 @@ function handleEvent(origin: string, event: ServerEvent): void {
|
|||||||
|
|
||||||
case 'dm_channel_created':
|
case 'dm_channel_created':
|
||||||
if (!isHome) break;
|
if (!isHome) break;
|
||||||
addDmChannel(event.dmChannel);
|
addDmChannel(event.dmChannel, origin);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'dm_channel_closed':
|
case 'dm_channel_closed':
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import { create } from 'zustand';
|
||||||
|
import type { ExploreServer, JoinRequest, ServerWithChannelsAndMembers } from '@backspace/shared';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import { useInstanceStore } from './instanceStore';
|
||||||
|
import { useServerStore } from './serverStore';
|
||||||
|
|
||||||
|
// ─── Types ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface TaggedExploreServer extends ExploreServer {
|
||||||
|
_instanceOrigin: string; // '' = home instance
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ExploreState {
|
||||||
|
servers: TaggedExploreServer[];
|
||||||
|
myRequests: JoinRequest[];
|
||||||
|
searchQuery: string;
|
||||||
|
isLoading: boolean;
|
||||||
|
discoveryEnabled: boolean;
|
||||||
|
error: string | null;
|
||||||
|
|
||||||
|
fetchServers: (query?: string) => Promise<void>;
|
||||||
|
fetchMyRequests: () => Promise<void>;
|
||||||
|
publicJoin: (server: TaggedExploreServer) => Promise<ServerWithChannelsAndMembers>;
|
||||||
|
requestJoin: (server: TaggedExploreServer, message?: string) => Promise<JoinRequest>;
|
||||||
|
setSearchQuery: (q: string) => void;
|
||||||
|
reset: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function getApiForOrigin(origin: string) {
|
||||||
|
if (!origin) return api;
|
||||||
|
const instance = useInstanceStore.getState().instances.find(i => i.origin === origin);
|
||||||
|
return instance?.api ?? api;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Store ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const useExploreStore = create<ExploreState>((set, get) => ({
|
||||||
|
servers: [],
|
||||||
|
myRequests: [],
|
||||||
|
searchQuery: '',
|
||||||
|
isLoading: false,
|
||||||
|
discoveryEnabled: true,
|
||||||
|
error: null,
|
||||||
|
|
||||||
|
fetchServers: async (query?: string) => {
|
||||||
|
set({ isLoading: true, error: null });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const instances = useInstanceStore.getState().instances;
|
||||||
|
const connectedInstances = instances.filter(i => i.status === 'connected');
|
||||||
|
|
||||||
|
// Fetch from home + all connected remote instances in parallel
|
||||||
|
const results = await Promise.allSettled([
|
||||||
|
api.explore.list(query).then(res => ({ ...res, origin: '' })),
|
||||||
|
...connectedInstances.map(inst =>
|
||||||
|
inst.api.explore.list(query).then(res => ({ ...res, origin: inst.origin }))
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const allServers: TaggedExploreServer[] = [];
|
||||||
|
const seen = new Set<string>(); // dedup by serverId+origin
|
||||||
|
let homeDiscoveryEnabled = true;
|
||||||
|
|
||||||
|
for (const result of results) {
|
||||||
|
if (result.status !== 'fulfilled') continue;
|
||||||
|
|
||||||
|
const { servers, discoveryEnabled, origin } = result.value;
|
||||||
|
|
||||||
|
// Track home instance discovery state
|
||||||
|
if (!origin) {
|
||||||
|
homeDiscoveryEnabled = discoveryEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const server of servers) {
|
||||||
|
const key = `${server.id}:${origin}`;
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
allServers.push({ ...server, _instanceOrigin: origin });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
set({
|
||||||
|
servers: allServers,
|
||||||
|
discoveryEnabled: homeDiscoveryEnabled,
|
||||||
|
isLoading: false,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
set({
|
||||||
|
isLoading: false,
|
||||||
|
error: err instanceof Error ? err.message : 'Failed to fetch servers',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
fetchMyRequests: async () => {
|
||||||
|
try {
|
||||||
|
const { requests } = await api.explore.myJoinRequests('pending');
|
||||||
|
set({ myRequests: requests });
|
||||||
|
} catch {
|
||||||
|
// Non-critical — silently fail
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
publicJoin: async (server: TaggedExploreServer) => {
|
||||||
|
const client = getApiForOrigin(server._instanceOrigin);
|
||||||
|
const fullServer = await client.explore.publicJoin(server.id);
|
||||||
|
|
||||||
|
// Add to server store
|
||||||
|
useServerStore.getState().addServerFromReady(server._instanceOrigin, fullServer);
|
||||||
|
|
||||||
|
// Remove from explore list
|
||||||
|
set((state) => ({
|
||||||
|
servers: state.servers.filter(s =>
|
||||||
|
!(s.id === server.id && s._instanceOrigin === server._instanceOrigin)
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return fullServer;
|
||||||
|
},
|
||||||
|
|
||||||
|
requestJoin: async (server: TaggedExploreServer, message?: string) => {
|
||||||
|
const client = getApiForOrigin(server._instanceOrigin);
|
||||||
|
const request = await client.explore.requestJoin(server.id, message);
|
||||||
|
|
||||||
|
set((state) => ({
|
||||||
|
myRequests: [...state.myRequests, request],
|
||||||
|
}));
|
||||||
|
|
||||||
|
return request;
|
||||||
|
},
|
||||||
|
|
||||||
|
setSearchQuery: (q: string) => set({ searchQuery: q }),
|
||||||
|
|
||||||
|
reset: () => set({
|
||||||
|
servers: [],
|
||||||
|
myRequests: [],
|
||||||
|
searchQuery: '',
|
||||||
|
isLoading: false,
|
||||||
|
discoveryEnabled: true,
|
||||||
|
error: null,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
@@ -140,13 +140,12 @@ export const useInstanceStore = create<InstanceState>((set, get) => ({
|
|||||||
const tempClient = createApiClient(origin, () => null);
|
const tempClient = createApiClient(origin, () => null);
|
||||||
|
|
||||||
let response: AuthResponse | null = null;
|
let response: AuthResponse | null = null;
|
||||||
let finalUsername = currentUser.username;
|
const finalUsername = `${currentUser.username}@${homeInstance}`;
|
||||||
let needsLogin = false;
|
|
||||||
|
|
||||||
// 2a: Attempt registration with plain username
|
// 2a: Attempt registration with namespaced username
|
||||||
try {
|
try {
|
||||||
response = await tempClient.auth.register({
|
response = await tempClient.auth.register({
|
||||||
username: currentUser.username,
|
username: finalUsername,
|
||||||
password,
|
password,
|
||||||
displayName: displayName || currentUser.displayName || undefined,
|
displayName: displayName || currentUser.displayName || undefined,
|
||||||
homeInstance,
|
homeInstance,
|
||||||
@@ -154,52 +153,29 @@ export const useInstanceStore = create<InstanceState>((set, get) => ({
|
|||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = (err as Error).message;
|
const message = (err as Error).message;
|
||||||
if (message.includes('already taken') || message.includes('409')) {
|
if (message.includes('already taken') || message.includes('409') ||
|
||||||
// Username collision — try domain-qualified username
|
message.includes('Registration is currently closed') || message.includes('403')) {
|
||||||
try {
|
// Already registered or registration closed — fall through to login
|
||||||
finalUsername = `${currentUser.username}@${homeInstance}`;
|
|
||||||
response = await tempClient.auth.register({
|
|
||||||
username: finalUsername,
|
|
||||||
password,
|
|
||||||
displayName: displayName || currentUser.displayName || undefined,
|
|
||||||
homeInstance,
|
|
||||||
homeUserId: currentUser.id,
|
|
||||||
});
|
|
||||||
} catch (err2) {
|
|
||||||
const msg2 = (err2 as Error).message;
|
|
||||||
if (msg2.includes('already taken') || msg2.includes('409')) {
|
|
||||||
// Both usernames exist on remote — fall through to login
|
|
||||||
needsLogin = true;
|
|
||||||
} else {
|
|
||||||
throw err2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (message.includes('Registration is currently closed') || message.includes('403')) {
|
|
||||||
// Registration closed on remote — fall through to login
|
|
||||||
needsLogin = true;
|
|
||||||
} else {
|
} else {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2b: If registration didn't work, try login with the same password
|
// 2b: If registration didn't work, try login
|
||||||
if (needsLogin) {
|
if (!response) {
|
||||||
// Try plain username first, then domain-qualified
|
|
||||||
try {
|
try {
|
||||||
response = await tempClient.auth.login({
|
response = await tempClient.auth.login({
|
||||||
username: currentUser.username,
|
username: finalUsername,
|
||||||
password,
|
password,
|
||||||
});
|
});
|
||||||
finalUsername = currentUser.username;
|
|
||||||
} catch {
|
} catch {
|
||||||
|
// Namespaced login failed — try legacy plain username as fallback
|
||||||
try {
|
try {
|
||||||
finalUsername = `${currentUser.username}@${homeInstance}`;
|
|
||||||
response = await tempClient.auth.login({
|
response = await tempClient.auth.login({
|
||||||
username: finalUsername,
|
username: currentUser.username,
|
||||||
password,
|
password,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
// Both login attempts failed — different password scenario
|
|
||||||
throw new DifferentPasswordError(currentUser.username);
|
throw new DifferentPasswordError(currentUser.username);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -390,6 +366,12 @@ export const useInstanceStore = create<InstanceState>((set, get) => ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Backfill cached username if stale after server-side migration
|
||||||
|
// (e.g. "test" was renamed to "test@nova.ddns.net")
|
||||||
|
if (user.username !== cachedEntry.username) {
|
||||||
|
cachedEntry.username = user.username;
|
||||||
|
}
|
||||||
|
|
||||||
const connectedInstance: ConnectedInstance = {
|
const connectedInstance: ConnectedInstance = {
|
||||||
origin,
|
origin,
|
||||||
label,
|
label,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { create } from 'zustand';
|
import { create } from 'zustand';
|
||||||
import type { Server, Channel, MemberWithUser, ServerWithChannelsAndMembers, Role, ServerFolder, DmChannel, User } from '@backspace/shared';
|
import type { Server, Channel, MemberWithUser, ServerWithChannelsAndMembers, Role, ServerFolder, DmChannel, User, UpdateServerRequest } from '@backspace/shared';
|
||||||
import { api, BackspaceApiClient } from '../api/client';
|
import { api, BackspaceApiClient } from '../api/client';
|
||||||
import { resolveAssetUrl, normalizeUserAssets } from '../utils/assetUrls';
|
import { resolveAssetUrl, normalizeUserAssets } from '../utils/assetUrls';
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ interface ServerState {
|
|||||||
setMembers: (members: MemberWithUser[]) => void;
|
setMembers: (members: MemberWithUser[]) => void;
|
||||||
setRoles: (roles: Role[]) => void;
|
setRoles: (roles: Role[]) => void;
|
||||||
setDmChannels: (channels: DmChannel[]) => void;
|
setDmChannels: (channels: DmChannel[]) => void;
|
||||||
addDmChannel: (channel: DmChannel) => void;
|
addDmChannel: (channel: DmChannel, origin?: string) => void;
|
||||||
removeDmChannel: (id: string) => void;
|
removeDmChannel: (id: string) => void;
|
||||||
addDmMember: (dmChannelId: string, user: User) => void;
|
addDmMember: (dmChannelId: string, user: User) => void;
|
||||||
removeDmMember: (dmChannelId: string, userId: string) => void;
|
removeDmMember: (dmChannelId: string, userId: string) => void;
|
||||||
@@ -48,7 +48,7 @@ interface ServerState {
|
|||||||
loadServerDetail: (serverId: string) => Promise<void>;
|
loadServerDetail: (serverId: string) => Promise<void>;
|
||||||
loadDmChannels: () => Promise<void>;
|
loadDmChannels: () => Promise<void>;
|
||||||
createServer: (name: string, icon?: string) => Promise<Server>;
|
createServer: (name: string, icon?: string) => Promise<Server>;
|
||||||
updateServer: (serverId: string, data: { name?: string; icon?: string }) => Promise<void>;
|
updateServer: (serverId: string, data: UpdateServerRequest) => Promise<void>;
|
||||||
deleteServer: (serverId: string) => Promise<void>;
|
deleteServer: (serverId: string) => Promise<void>;
|
||||||
joinServer: (serverId: string, inviteCode: string) => Promise<void>;
|
joinServer: (serverId: string, inviteCode: string) => Promise<void>;
|
||||||
joinByCode: (inviteCode: string, origin?: string) => Promise<Server>;
|
joinByCode: (inviteCode: string, origin?: string) => Promise<Server>;
|
||||||
@@ -61,6 +61,7 @@ interface ServerState {
|
|||||||
addMember: (member: MemberWithUser) => void;
|
addMember: (member: MemberWithUser) => void;
|
||||||
removeMember: (userId: string) => void;
|
removeMember: (userId: string) => void;
|
||||||
populateFromReady: (origin: string, servers: ServerWithChannelsAndMembers[], folders?: ServerFolder[], dmChannels?: DmChannel[]) => void;
|
populateFromReady: (origin: string, servers: ServerWithChannelsAndMembers[], folders?: ServerFolder[], dmChannels?: DmChannel[]) => void;
|
||||||
|
addServerFromReady: (origin: string, server: ServerWithChannelsAndMembers) => void;
|
||||||
removeInstanceServers: (origin: string) => void;
|
removeInstanceServers: (origin: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,9 +86,16 @@ export const useServerStore = create<ServerState>((set, get) => ({
|
|||||||
setRoles: (roles) => set({ roles }),
|
setRoles: (roles) => set({ roles }),
|
||||||
setDmChannels: (dmChannels) => set({ dmChannels }),
|
setDmChannels: (dmChannels) => set({ dmChannels }),
|
||||||
|
|
||||||
addDmChannel: (channel) => set((state) => ({
|
addDmChannel: (channel, origin?: string) => set((state) => {
|
||||||
dmChannels: [channel, ...state.dmChannels.filter(c => c.id !== channel.id)]
|
const channelOriginMap = new Map(state.channelOriginMap);
|
||||||
})),
|
if (origin !== undefined) {
|
||||||
|
channelOriginMap.set(channel.id, origin);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
dmChannels: [channel, ...state.dmChannels.filter(c => c.id !== channel.id)],
|
||||||
|
channelOriginMap,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
|
||||||
removeDmChannel: (id) => set((state) => ({
|
removeDmChannel: (id) => set((state) => ({
|
||||||
dmChannels: state.dmChannels.filter(c => c.id !== id)
|
dmChannels: state.dmChannels.filter(c => c.id !== id)
|
||||||
@@ -169,7 +177,7 @@ export const useServerStore = create<ServerState>((set, get) => ({
|
|||||||
return server;
|
return server;
|
||||||
},
|
},
|
||||||
|
|
||||||
updateServer: async (serverId: string, data: { name?: string; icon?: string }) => {
|
updateServer: async (serverId: string, data: UpdateServerRequest) => {
|
||||||
const updated = await api.servers.update(serverId, data);
|
const updated = await api.servers.update(serverId, data);
|
||||||
set((state) => ({
|
set((state) => ({
|
||||||
servers: state.servers.map(s => s.id === serverId ? { ...s, ...updated } : s),
|
servers: state.servers.map(s => s.id === serverId ? { ...s, ...updated } : s),
|
||||||
@@ -284,6 +292,8 @@ export const useServerStore = create<ServerState>((set, get) => ({
|
|||||||
icon: s.icon,
|
icon: s.icon,
|
||||||
ownerId: s.ownerId,
|
ownerId: s.ownerId,
|
||||||
inviteCode: s.inviteCode,
|
inviteCode: s.inviteCode,
|
||||||
|
visibility: s.visibility ?? 'private' as const,
|
||||||
|
description: s.description ?? null,
|
||||||
createdAt: s.createdAt,
|
createdAt: s.createdAt,
|
||||||
_instanceOrigin: origin,
|
_instanceOrigin: origin,
|
||||||
}));
|
}));
|
||||||
@@ -353,6 +363,7 @@ export const useServerStore = create<ServerState>((set, get) => ({
|
|||||||
const dms = isHome ? (dmChannels || []) : get().dmChannels;
|
const dms = isHome ? (dmChannels || []) : get().dmChannels;
|
||||||
if (isHome) {
|
if (isHome) {
|
||||||
for (const dm of dms) {
|
for (const dm of dms) {
|
||||||
|
channelOriginMap.set(dm.id, origin);
|
||||||
if (dm.lastMessage?.id) {
|
if (dm.lastMessage?.id) {
|
||||||
channelLastMessageIds.set(dm.id, dm.lastMessage.id);
|
channelLastMessageIds.set(dm.id, dm.lastMessage.id);
|
||||||
}
|
}
|
||||||
@@ -377,6 +388,49 @@ export const useServerStore = create<ServerState>((set, get) => ({
|
|||||||
set(update as any);
|
set(update as any);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
addServerFromReady: (origin: string, server: ServerWithChannelsAndMembers) => {
|
||||||
|
const tagged: TaggedServer = {
|
||||||
|
id: server.id,
|
||||||
|
name: server.name,
|
||||||
|
icon: server.icon,
|
||||||
|
ownerId: server.ownerId,
|
||||||
|
inviteCode: server.inviteCode,
|
||||||
|
visibility: server.visibility,
|
||||||
|
description: server.description,
|
||||||
|
createdAt: server.createdAt,
|
||||||
|
_instanceOrigin: origin,
|
||||||
|
};
|
||||||
|
|
||||||
|
const channelToServerMap = new Map(get().channelToServerMap);
|
||||||
|
const channelLastMessageIds = new Map(get().channelLastMessageIds);
|
||||||
|
const serverPermissions = new Map(get().serverPermissions);
|
||||||
|
const channelPermissions = new Map(get().channelPermissions);
|
||||||
|
const channelOriginMap = new Map(get().channelOriginMap);
|
||||||
|
|
||||||
|
if (server.myPermissions) {
|
||||||
|
serverPermissions.set(server.id, server.myPermissions);
|
||||||
|
}
|
||||||
|
for (const ch of server.channels) {
|
||||||
|
channelToServerMap.set(ch.id, server.id);
|
||||||
|
channelOriginMap.set(ch.id, origin);
|
||||||
|
if (ch.lastMessageId) {
|
||||||
|
channelLastMessageIds.set(ch.id, ch.lastMessageId);
|
||||||
|
}
|
||||||
|
if (ch.myPermissions) {
|
||||||
|
channelPermissions.set(ch.id, ch.myPermissions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
set((state) => ({
|
||||||
|
servers: [...state.servers.filter(s => s.id !== server.id), tagged],
|
||||||
|
channelToServerMap,
|
||||||
|
channelLastMessageIds,
|
||||||
|
serverPermissions,
|
||||||
|
channelPermissions,
|
||||||
|
channelOriginMap,
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
|
||||||
removeInstanceServers: (origin: string) => {
|
removeInstanceServers: (origin: string) => {
|
||||||
set((state) => {
|
set((state) => {
|
||||||
const remainingServers = state.servers.filter(s => s._instanceOrigin !== origin);
|
const remainingServers = state.servers.filter(s => s._instanceOrigin !== origin);
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ const DEFAULT_LIMITS: InstanceStreamingLimits = {
|
|||||||
allowedFramerates: [30, 45, 60],
|
allowedFramerates: [30, 45, 60],
|
||||||
maxResolution: 1080,
|
maxResolution: 1080,
|
||||||
maxFramerate: 60,
|
maxFramerate: 60,
|
||||||
|
discoveryEnabled: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getStreamingLimits(): InstanceStreamingLimits {
|
export function getStreamingLimits(): InstanceStreamingLimits {
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ interface UIState {
|
|||||||
modalData: Record<string, unknown>;
|
modalData: Record<string, unknown>;
|
||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
showDms: boolean;
|
showDms: boolean;
|
||||||
|
showExplore: boolean;
|
||||||
imagePreviewUrl: string | null;
|
imagePreviewUrl: string | null;
|
||||||
userProfilePopout: {
|
userProfilePopout: {
|
||||||
user: User | null;
|
user: User | null;
|
||||||
@@ -40,6 +41,7 @@ interface UIState {
|
|||||||
closeModal: () => void;
|
closeModal: () => void;
|
||||||
setIsMobile: (isMobile: boolean) => void;
|
setIsMobile: (isMobile: boolean) => void;
|
||||||
setShowDms: (show: boolean) => void;
|
setShowDms: (show: boolean) => void;
|
||||||
|
setShowExplore: (show: boolean) => void;
|
||||||
openImagePreview: (url: string) => void;
|
openImagePreview: (url: string) => void;
|
||||||
closeImagePreview: () => void;
|
closeImagePreview: () => void;
|
||||||
openUserProfile: (user: User, position: { top: number; left: number }) => void;
|
openUserProfile: (user: User, position: { top: number; left: number }) => void;
|
||||||
@@ -64,6 +66,7 @@ export const useUIStore = create<UIState>()(
|
|||||||
modalData: {},
|
modalData: {},
|
||||||
isMobile: false,
|
isMobile: false,
|
||||||
showDms: false,
|
showDms: false,
|
||||||
|
showExplore: false,
|
||||||
imagePreviewUrl: null,
|
imagePreviewUrl: null,
|
||||||
userProfilePopout: {
|
userProfilePopout: {
|
||||||
user: null,
|
user: null,
|
||||||
@@ -89,7 +92,8 @@ export const useUIStore = create<UIState>()(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
setShowDms: (show) => set({ showDms: show }),
|
setShowDms: (show) => set({ showDms: show, ...(show ? { showExplore: false } : {}) }),
|
||||||
|
setShowExplore: (show) => set({ showExplore: show, ...(show ? { showDms: false } : {}) }),
|
||||||
|
|
||||||
openImagePreview: (url) => set({ activeModal: 'imagePreview', imagePreviewUrl: url }),
|
openImagePreview: (url) => set({ activeModal: 'imagePreview', imagePreviewUrl: url }),
|
||||||
closeImagePreview: () => set({ activeModal: null, imagePreviewUrl: null }),
|
closeImagePreview: () => set({ activeModal: null, imagePreviewUrl: null }),
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
import type { User } from '@backspace/shared';
|
import type { User } from '@backspace/shared';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits a potentially federated username into base name and domain.
|
||||||
|
* "youruser@nova.ddns.net" → { baseName: "youruser", domain: "nova.ddns.net" }
|
||||||
|
* "youruser" → { baseName: "youruser", domain: null }
|
||||||
|
*/
|
||||||
|
export function parseFederatedUsername(username: string): { baseName: string; domain: string | null } {
|
||||||
|
const atIndex = username.indexOf('@');
|
||||||
|
if (atIndex === -1) return { baseName: username, domain: null };
|
||||||
|
return { baseName: username.slice(0, atIndex), domain: username.slice(atIndex + 1) };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stateless check: is `user` a replicated alias of `homeUser`?
|
* Stateless check: is `user` a replicated alias of `homeUser`?
|
||||||
* Uses the immutable (username, homeInstance) composite key —
|
* Uses the immutable (username, homeInstance) composite key —
|
||||||
@@ -16,8 +27,8 @@ export function isSelf(
|
|||||||
if (!user.homeInstance) return false;
|
if (!user.homeInstance) return false;
|
||||||
if (user.homeInstance !== window.location.host) return false;
|
if (user.homeInstance !== window.location.host) return false;
|
||||||
// Username: "youruser" or "youruser@nova.ddns.net" → base must match
|
// Username: "youruser" or "youruser@nova.ddns.net" → base must match
|
||||||
const baseUsername = user.username.split('@')[0];
|
const { baseName } = parseFederatedUsername(user.username);
|
||||||
return baseUsername === homeUser.username;
|
return baseName === homeUser.username;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user