Initial commit
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/db';
|
||||
import { users, blocks, follows } from '@/db/schema';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { requireAuth } from '@/lib/auth';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
// GET - Check if blocked
|
||||
export async function GET(req: NextRequest, context: RouteContext) {
|
||||
try {
|
||||
const currentUser = await requireAuth();
|
||||
const { handle } = await context.params;
|
||||
|
||||
const targetUser = await db.query.users.findFirst({
|
||||
where: eq(users.handle, handle),
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const block = await db.query.blocks.findFirst({
|
||||
where: and(
|
||||
eq(blocks.userId, currentUser.id),
|
||||
eq(blocks.blockedUserId, targetUser.id)
|
||||
),
|
||||
});
|
||||
|
||||
return NextResponse.json({ blocked: !!block });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'Unauthorized') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
console.error('Check block error:', error);
|
||||
return NextResponse.json({ error: 'Failed to check block status' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST - Block user
|
||||
export async function POST(req: NextRequest, context: RouteContext) {
|
||||
try {
|
||||
const currentUser = await requireAuth();
|
||||
const { handle } = await context.params;
|
||||
|
||||
const targetUser = await db.query.users.findFirst({
|
||||
where: eq(users.handle, handle),
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (targetUser.id === currentUser.id) {
|
||||
return NextResponse.json({ error: 'Cannot block yourself' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if already blocked
|
||||
const existing = await db.query.blocks.findFirst({
|
||||
where: and(
|
||||
eq(blocks.userId, currentUser.id),
|
||||
eq(blocks.blockedUserId, targetUser.id)
|
||||
),
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return NextResponse.json({ blocked: true });
|
||||
}
|
||||
|
||||
// Create block
|
||||
await db.insert(blocks).values({
|
||||
userId: currentUser.id,
|
||||
blockedUserId: targetUser.id,
|
||||
});
|
||||
|
||||
// Remove any follows between the users
|
||||
await db.delete(follows).where(
|
||||
and(
|
||||
eq(follows.followerId, currentUser.id),
|
||||
eq(follows.followingId, targetUser.id)
|
||||
)
|
||||
);
|
||||
await db.delete(follows).where(
|
||||
and(
|
||||
eq(follows.followerId, targetUser.id),
|
||||
eq(follows.followingId, currentUser.id)
|
||||
)
|
||||
);
|
||||
|
||||
return NextResponse.json({ blocked: true });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'Unauthorized') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
console.error('Block user error:', error);
|
||||
return NextResponse.json({ error: 'Failed to block user' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE - Unblock user
|
||||
export async function DELETE(req: NextRequest, context: RouteContext) {
|
||||
try {
|
||||
const currentUser = await requireAuth();
|
||||
const { handle } = await context.params;
|
||||
|
||||
const targetUser = await db.query.users.findFirst({
|
||||
where: eq(users.handle, handle),
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
await db.delete(blocks).where(
|
||||
and(
|
||||
eq(blocks.userId, currentUser.id),
|
||||
eq(blocks.blockedUserId, targetUser.id)
|
||||
)
|
||||
);
|
||||
|
||||
return NextResponse.json({ blocked: false });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'Unauthorized') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
console.error('Unblock user error:', error);
|
||||
return NextResponse.json({ error: 'Failed to unblock user' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import crypto from 'crypto';
|
||||
import { db, follows, users, notifications, remoteFollows } from '@/db';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { requireAuth } from '@/lib/auth';
|
||||
import { resolveRemoteUser } from '@/lib/activitypub/fetch';
|
||||
import { createFollowActivity, createUndoActivity } from '@/lib/activitypub/activities';
|
||||
import { deliverActivity } from '@/lib/activitypub/outbox';
|
||||
import { cacheRemoteUserPosts } from '@/lib/activitypub/cache';
|
||||
import { isSwarmNode, deliverSwarmFollow, deliverSwarmUnfollow } from '@/lib/swarm/interactions';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
const parseRemoteHandle = (handle: string) => {
|
||||
const clean = handle.toLowerCase().replace(/^@/, '');
|
||||
const parts = clean.split('@').filter(Boolean);
|
||||
if (parts.length === 2) {
|
||||
return { handle: parts[0], domain: parts[1] };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Strip HTML tags from a string (for Mastodon bios that come as HTML)
|
||||
const stripHtml = (html: string | null | undefined): string | null => {
|
||||
if (!html) return null;
|
||||
return html.replace(/<[^>]*>/g, '').trim() || null;
|
||||
};
|
||||
|
||||
// Check follow status
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const currentUser = await requireAuth();
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const remote = parseRemoteHandle(handle);
|
||||
|
||||
if (currentUser.isSuspended || currentUser.isSilenced) {
|
||||
return NextResponse.json({ error: 'Account restricted' }, { status: 403 });
|
||||
}
|
||||
|
||||
if (remote) {
|
||||
if (!db) {
|
||||
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
|
||||
}
|
||||
const targetHandle = `${remote.handle}@${remote.domain}`;
|
||||
const existingRemoteFollow = await db.query.remoteFollows.findFirst({
|
||||
where: and(
|
||||
eq(remoteFollows.followerId, currentUser.id),
|
||||
eq(remoteFollows.targetHandle, targetHandle)
|
||||
),
|
||||
});
|
||||
return NextResponse.json({ following: !!existingRemoteFollow, remote: true });
|
||||
}
|
||||
|
||||
if (!db) {
|
||||
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
|
||||
}
|
||||
|
||||
const targetUser = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
if (targetUser.isSuspended) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (targetUser.id === currentUser.id) {
|
||||
return NextResponse.json({ following: false, self: true });
|
||||
}
|
||||
|
||||
const existingFollow = await db.query.follows.findFirst({
|
||||
where: and(
|
||||
eq(follows.followerId, currentUser.id),
|
||||
eq(follows.followingId, targetUser.id)
|
||||
),
|
||||
});
|
||||
|
||||
return NextResponse.json({ following: !!existingFollow });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'Authentication required') {
|
||||
return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
console.error('Follow status error:', error);
|
||||
return NextResponse.json({ error: 'Failed to get follow status' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// Follow a user
|
||||
export async function POST(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const currentUser = await requireAuth();
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const remote = parseRemoteHandle(handle);
|
||||
const nodeDomain = process.env.NEXT_PUBLIC_NODE_DOMAIN || 'localhost:3000';
|
||||
|
||||
if (currentUser.isSuspended || currentUser.isSilenced) {
|
||||
return NextResponse.json({ error: 'Account restricted' }, { status: 403 });
|
||||
}
|
||||
|
||||
if (remote) {
|
||||
const targetHandle = `${remote.handle}@${remote.domain}`;
|
||||
|
||||
// Check if already following
|
||||
const existingRemoteFollow = await db.query.remoteFollows.findFirst({
|
||||
where: and(
|
||||
eq(remoteFollows.followerId, currentUser.id),
|
||||
eq(remoteFollows.targetHandle, targetHandle)
|
||||
),
|
||||
});
|
||||
if (existingRemoteFollow) {
|
||||
return NextResponse.json({ error: 'Already following' }, { status: 400 });
|
||||
}
|
||||
|
||||
// SWARM-FIRST: Check if this is a Synapsis swarm node
|
||||
const isSwarm = await isSwarmNode(remote.domain);
|
||||
|
||||
if (isSwarm) {
|
||||
// Use swarm protocol for Synapsis nodes
|
||||
const activityId = crypto.randomUUID();
|
||||
|
||||
const result = await deliverSwarmFollow(remote.domain, {
|
||||
targetHandle: remote.handle,
|
||||
follow: {
|
||||
followerHandle: currentUser.handle,
|
||||
followerDisplayName: currentUser.displayName || currentUser.handle,
|
||||
followerAvatarUrl: currentUser.avatarUrl || undefined,
|
||||
followerBio: currentUser.bio || undefined,
|
||||
followerNodeDomain: nodeDomain,
|
||||
interactionId: activityId,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
console.warn(`[Swarm] Follow delivery failed, falling back to ActivityPub: ${result.error}`);
|
||||
// Fall through to ActivityPub below
|
||||
} else {
|
||||
// Swarm follow succeeded - store the follow locally
|
||||
await db.insert(remoteFollows).values({
|
||||
followerId: currentUser.id,
|
||||
targetHandle,
|
||||
targetActorUrl: `swarm://${remote.domain}/${remote.handle}`,
|
||||
inboxUrl: `https://${remote.domain}/api/swarm/interactions/inbox`,
|
||||
activityId,
|
||||
displayName: null, // Will be fetched later
|
||||
bio: null,
|
||||
avatarUrl: null,
|
||||
});
|
||||
|
||||
// Update the user's following count
|
||||
await db.update(users)
|
||||
.set({ followingCount: currentUser.followingCount + 1 })
|
||||
.where(eq(users.id, currentUser.id));
|
||||
|
||||
console.log(`[Swarm] Follow delivered to ${remote.domain} for @${remote.handle}`);
|
||||
return NextResponse.json({ success: true, following: true, remote: true, swarm: true });
|
||||
}
|
||||
}
|
||||
|
||||
// FALLBACK: Use ActivityPub for non-swarm nodes or if swarm failed
|
||||
const remoteProfile = await resolveRemoteUser(remote.handle, remote.domain);
|
||||
if (!remoteProfile) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
const targetInbox = remoteProfile.endpoints?.sharedInbox || remoteProfile.inbox;
|
||||
if (!targetInbox) {
|
||||
return NextResponse.json({ error: 'Remote inbox not available' }, { status: 400 });
|
||||
}
|
||||
|
||||
const activityId = crypto.randomUUID();
|
||||
const followActivity = createFollowActivity(currentUser, remoteProfile.id, nodeDomain, activityId);
|
||||
const keyId = `https://${nodeDomain}/users/${currentUser.handle}#main-key`;
|
||||
const privateKey = currentUser.privateKeyEncrypted;
|
||||
if (!privateKey) {
|
||||
return NextResponse.json({ error: 'Missing signing key' }, { status: 500 });
|
||||
}
|
||||
const result = await deliverActivity(followActivity, targetInbox, privateKey, keyId);
|
||||
if (!result.success) {
|
||||
return NextResponse.json({ error: result.error || 'Failed to follow remote user' }, { status: 502 });
|
||||
}
|
||||
|
||||
// Extract avatar URL from remote profile
|
||||
let avatarUrl: string | null = null;
|
||||
if (remoteProfile.icon) {
|
||||
if (typeof remoteProfile.icon === 'string') {
|
||||
avatarUrl = remoteProfile.icon;
|
||||
} else if (typeof remoteProfile.icon === 'object' && remoteProfile.icon.url) {
|
||||
avatarUrl = remoteProfile.icon.url;
|
||||
}
|
||||
}
|
||||
|
||||
await db.insert(remoteFollows).values({
|
||||
followerId: currentUser.id,
|
||||
targetHandle,
|
||||
targetActorUrl: remoteProfile.id,
|
||||
inboxUrl: targetInbox,
|
||||
activityId,
|
||||
displayName: remoteProfile.name || null,
|
||||
bio: stripHtml(remoteProfile.summary),
|
||||
avatarUrl,
|
||||
});
|
||||
|
||||
// Update the user's following count
|
||||
await db.update(users)
|
||||
.set({ followingCount: currentUser.followingCount + 1 })
|
||||
.where(eq(users.id, currentUser.id));
|
||||
|
||||
// Cache the remote user's recent posts in the background
|
||||
const origin = new URL(request.url).origin;
|
||||
cacheRemoteUserPosts(remoteProfile, targetHandle, origin, 20)
|
||||
.then(result => console.log(`Cached ${result.cached} posts for ${targetHandle}`))
|
||||
.catch(err => console.error('Error caching remote posts:', err));
|
||||
|
||||
return NextResponse.json({ success: true, following: true, remote: true });
|
||||
}
|
||||
|
||||
if (!db) {
|
||||
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
|
||||
}
|
||||
|
||||
// Find target user
|
||||
const targetUser = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
if (targetUser.isSuspended) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Can't follow yourself
|
||||
if (targetUser.id === currentUser.id) {
|
||||
return NextResponse.json({ error: 'Cannot follow yourself' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if already following
|
||||
const existingFollow = await db.query.follows.findFirst({
|
||||
where: and(
|
||||
eq(follows.followerId, currentUser.id),
|
||||
eq(follows.followingId, targetUser.id)
|
||||
),
|
||||
});
|
||||
|
||||
if (existingFollow) {
|
||||
return NextResponse.json({ error: 'Already following' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Create follow
|
||||
await db.insert(follows).values({
|
||||
followerId: currentUser.id,
|
||||
followingId: targetUser.id,
|
||||
});
|
||||
|
||||
if (currentUser.id !== targetUser.id) {
|
||||
await db.insert(notifications).values({
|
||||
userId: targetUser.id,
|
||||
actorId: currentUser.id,
|
||||
type: 'follow',
|
||||
});
|
||||
}
|
||||
|
||||
// Update counts
|
||||
await db.update(users)
|
||||
.set({ followingCount: currentUser.followingCount + 1 })
|
||||
.where(eq(users.id, currentUser.id));
|
||||
|
||||
await db.update(users)
|
||||
.set({ followersCount: targetUser.followersCount + 1 })
|
||||
.where(eq(users.id, targetUser.id));
|
||||
|
||||
// TODO: Send ActivityPub Follow activity
|
||||
|
||||
return NextResponse.json({ success: true, following: true });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'Authentication required') {
|
||||
return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
console.error('Follow error:', error);
|
||||
return NextResponse.json({ error: 'Failed to follow' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// Unfollow a user
|
||||
export async function DELETE(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const currentUser = await requireAuth();
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const remote = parseRemoteHandle(handle);
|
||||
const nodeDomain = process.env.NEXT_PUBLIC_NODE_DOMAIN || 'localhost:3000';
|
||||
|
||||
if (remote) {
|
||||
if (!db) {
|
||||
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
|
||||
}
|
||||
const targetHandle = `${remote.handle}@${remote.domain}`;
|
||||
const existingRemoteFollow = await db.query.remoteFollows.findFirst({
|
||||
where: and(
|
||||
eq(remoteFollows.followerId, currentUser.id),
|
||||
eq(remoteFollows.targetHandle, targetHandle)
|
||||
),
|
||||
});
|
||||
if (!existingRemoteFollow) {
|
||||
return NextResponse.json({ error: 'Not following' }, { status: 400 });
|
||||
}
|
||||
|
||||
// SWARM-FIRST: Check if this is a swarm follow (swarm:// actor URL)
|
||||
const isSwarmFollow = existingRemoteFollow.targetActorUrl.startsWith('swarm://');
|
||||
|
||||
if (isSwarmFollow) {
|
||||
// Use swarm protocol for unfollow
|
||||
const result = await deliverSwarmUnfollow(remote.domain, {
|
||||
targetHandle: remote.handle,
|
||||
unfollow: {
|
||||
followerHandle: currentUser.handle,
|
||||
followerNodeDomain: nodeDomain,
|
||||
interactionId: crypto.randomUUID(),
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
console.warn(`[Swarm] Unfollow delivery failed: ${result.error}`);
|
||||
// Continue anyway - remove local record
|
||||
}
|
||||
|
||||
// Remove the follow record
|
||||
await db.delete(remoteFollows).where(eq(remoteFollows.id, existingRemoteFollow.id));
|
||||
|
||||
// Update the user's following count
|
||||
await db.update(users)
|
||||
.set({ followingCount: Math.max(0, currentUser.followingCount - 1) })
|
||||
.where(eq(users.id, currentUser.id));
|
||||
|
||||
console.log(`[Swarm] Unfollow delivered to ${remote.domain}`);
|
||||
return NextResponse.json({ success: true, following: false, remote: true, swarm: true });
|
||||
}
|
||||
|
||||
// FALLBACK: Use ActivityPub for non-swarm follows
|
||||
const originalFollow = createFollowActivity(
|
||||
currentUser,
|
||||
existingRemoteFollow.targetActorUrl,
|
||||
nodeDomain,
|
||||
existingRemoteFollow.activityId
|
||||
);
|
||||
const undoActivity = createUndoActivity(currentUser, originalFollow, nodeDomain, crypto.randomUUID());
|
||||
const keyId = `https://${nodeDomain}/users/${currentUser.handle}#main-key`;
|
||||
const privateKey = currentUser.privateKeyEncrypted;
|
||||
if (!privateKey) {
|
||||
return NextResponse.json({ error: 'Missing signing key' }, { status: 500 });
|
||||
}
|
||||
const result = await deliverActivity(undoActivity, existingRemoteFollow.inboxUrl, privateKey, keyId);
|
||||
if (!result.success) {
|
||||
return NextResponse.json({ error: result.error || 'Failed to unfollow remote user' }, { status: 502 });
|
||||
}
|
||||
await db.delete(remoteFollows).where(eq(remoteFollows.id, existingRemoteFollow.id));
|
||||
|
||||
// Update the user's following count
|
||||
await db.update(users)
|
||||
.set({ followingCount: Math.max(0, currentUser.followingCount - 1) })
|
||||
.where(eq(users.id, currentUser.id));
|
||||
|
||||
return NextResponse.json({ success: true, following: false, remote: true });
|
||||
}
|
||||
|
||||
if (!db) {
|
||||
return NextResponse.json({ error: 'Database not available' }, { status: 503 });
|
||||
}
|
||||
|
||||
// Find target user
|
||||
const targetUser = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
if (targetUser.isSuspended) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Find existing follow
|
||||
const existingFollow = await db.query.follows.findFirst({
|
||||
where: and(
|
||||
eq(follows.followerId, currentUser.id),
|
||||
eq(follows.followingId, targetUser.id)
|
||||
),
|
||||
});
|
||||
|
||||
if (!existingFollow) {
|
||||
return NextResponse.json({ error: 'Not following' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Remove follow
|
||||
await db.delete(follows).where(eq(follows.id, existingFollow.id));
|
||||
|
||||
// Update counts
|
||||
await db.update(users)
|
||||
.set({ followingCount: Math.max(0, currentUser.followingCount - 1) })
|
||||
.where(eq(users.id, currentUser.id));
|
||||
|
||||
await db.update(users)
|
||||
.set({ followersCount: Math.max(0, targetUser.followersCount - 1) })
|
||||
.where(eq(users.id, targetUser.id));
|
||||
|
||||
// TODO: Send ActivityPub Undo Follow activity
|
||||
|
||||
return NextResponse.json({ success: true, following: false });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === 'Authentication required') {
|
||||
return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
console.error('Unfollow error:', error);
|
||||
return NextResponse.json({ error: 'Failed to unfollow' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, follows, users } from '@/db';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '20'), 50);
|
||||
|
||||
// Return empty if no database
|
||||
if (!db) {
|
||||
return NextResponse.json({ followers: [], nextCursor: null });
|
||||
}
|
||||
|
||||
// Find the user
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
if (user.isSuspended) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Get followers
|
||||
const userFollowers = await db
|
||||
.select({
|
||||
id: follows.id,
|
||||
follower: users,
|
||||
})
|
||||
.from(follows)
|
||||
.innerJoin(users, eq(follows.followerId, users.id))
|
||||
.where(eq(follows.followingId, user.id))
|
||||
.limit(limit);
|
||||
|
||||
return NextResponse.json({
|
||||
followers: userFollowers.map(f => ({
|
||||
id: f.follower.id,
|
||||
handle: f.follower.handle,
|
||||
displayName: f.follower.displayName,
|
||||
avatarUrl: f.follower.avatarUrl,
|
||||
bio: f.follower.bio,
|
||||
isBot: f.follower.isBot,
|
||||
})),
|
||||
nextCursor: userFollowers.length === limit ? userFollowers[userFollowers.length - 1]?.id : null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Get followers error:', error);
|
||||
return NextResponse.json({ error: 'Failed to get followers' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, follows, users, remoteFollows } from '@/db';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '20'), 50);
|
||||
|
||||
// Return empty if no database
|
||||
if (!db) {
|
||||
return NextResponse.json({ following: [], nextCursor: null });
|
||||
}
|
||||
|
||||
// Find the user
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
if (user.isSuspended) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Get local following
|
||||
const userFollowing = await db
|
||||
.select({
|
||||
id: follows.id,
|
||||
following: users,
|
||||
})
|
||||
.from(follows)
|
||||
.innerJoin(users, eq(follows.followingId, users.id))
|
||||
.where(eq(follows.followerId, user.id))
|
||||
.limit(limit);
|
||||
|
||||
const localFollowing = userFollowing.map(f => ({
|
||||
id: f.following.id,
|
||||
handle: f.following.handle,
|
||||
displayName: f.following.displayName,
|
||||
avatarUrl: f.following.avatarUrl,
|
||||
bio: f.following.bio,
|
||||
isRemote: false,
|
||||
isBot: f.following.isBot,
|
||||
}));
|
||||
|
||||
// Get remote following
|
||||
const userRemoteFollowing = await db.query.remoteFollows.findMany({
|
||||
where: eq(remoteFollows.followerId, user.id),
|
||||
limit,
|
||||
});
|
||||
|
||||
const remoteFollowing = userRemoteFollowing.map(f => ({
|
||||
id: f.targetActorUrl,
|
||||
handle: f.targetHandle,
|
||||
displayName: f.displayName || f.targetHandle.split('@')[0], // Use stored display name or username part
|
||||
avatarUrl: f.avatarUrl,
|
||||
bio: f.bio,
|
||||
isRemote: true,
|
||||
}));
|
||||
|
||||
// Merge and return
|
||||
const allFollowing = [...localFollowing, ...remoteFollowing].slice(0, limit);
|
||||
|
||||
return NextResponse.json({
|
||||
following: allFollowing,
|
||||
nextCursor: allFollowing.length === limit ? allFollowing[allFollowing.length - 1]?.id : null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Get following error:', error);
|
||||
return NextResponse.json({ error: 'Failed to get following' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* ActivityPub User Inbox Endpoint
|
||||
*
|
||||
* Receives incoming activities from remote servers for a specific user.
|
||||
* POST /users/{handle}/inbox
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, users } from '@/db';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { processIncomingActivity, type IncomingActivity } from '@/lib/activitypub/inbox';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
export async function POST(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
|
||||
// Verify the target user exists
|
||||
if (!db) {
|
||||
console.error('[Inbox] Database not available');
|
||||
return NextResponse.json({ error: 'Service unavailable' }, { status: 503 });
|
||||
}
|
||||
|
||||
const targetUser = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!targetUser) {
|
||||
console.error(`[Inbox] User not found: ${cleanHandle}`);
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Parse the activity
|
||||
let activity: IncomingActivity;
|
||||
try {
|
||||
activity = await request.json();
|
||||
} catch (e) {
|
||||
console.error('[Inbox] Invalid JSON body:', e);
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
|
||||
}
|
||||
|
||||
console.log(`[Inbox] Received ${activity.type} activity for @${cleanHandle} from ${activity.actor}`);
|
||||
|
||||
// Extract headers for signature verification
|
||||
const headers: Record<string, string> = {};
|
||||
request.headers.forEach((value, key) => {
|
||||
headers[key] = value;
|
||||
});
|
||||
|
||||
// Get the request path
|
||||
const url = new URL(request.url);
|
||||
const path = url.pathname;
|
||||
|
||||
// Process the activity
|
||||
const result = await processIncomingActivity(activity, headers, path, targetUser);
|
||||
|
||||
if (!result.success) {
|
||||
console.error(`[Inbox] Activity processing failed: ${result.error}`);
|
||||
return NextResponse.json({ error: result.error }, { status: 400 });
|
||||
}
|
||||
|
||||
// Return 202 Accepted (standard for ActivityPub)
|
||||
return new NextResponse(null, { status: 202 });
|
||||
} catch (error) {
|
||||
console.error('[Inbox] Error processing activity:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// ActivityPub requires the inbox to be discoverable
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
const { handle } = await context.params;
|
||||
return NextResponse.json(
|
||||
{
|
||||
'@context': 'https://www.w3.org/ns/activitystreams',
|
||||
summary: `Inbox for @${handle}`,
|
||||
type: 'OrderedCollection',
|
||||
totalItems: 0,
|
||||
orderedItems: [],
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/activity+json',
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, likes, posts, users } from '@/db';
|
||||
import { eq, desc, and, inArray } from 'drizzle-orm';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '25'), 50);
|
||||
|
||||
// Find the user
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Don't show likes for bot accounts
|
||||
if (user.isBot) {
|
||||
return NextResponse.json({ posts: [] });
|
||||
}
|
||||
|
||||
// Get user's liked posts
|
||||
const userLikes = await db.query.likes.findMany({
|
||||
where: eq(likes.userId, user.id),
|
||||
with: {
|
||||
post: {
|
||||
with: {
|
||||
author: true,
|
||||
media: true,
|
||||
bot: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [desc(likes.createdAt)],
|
||||
limit,
|
||||
});
|
||||
|
||||
// Filter out any likes where the post was removed and format response
|
||||
let likedPosts = userLikes
|
||||
.filter(like => like.post && !like.post.isRemoved)
|
||||
.map(like => like.post);
|
||||
|
||||
// Populate isLiked and isReposted for authenticated users
|
||||
try {
|
||||
const { getSession } = await import('@/lib/auth');
|
||||
const session = await getSession();
|
||||
|
||||
if (session?.user && likedPosts.length > 0) {
|
||||
const viewer = session.user;
|
||||
const postIds = likedPosts.map(p => p!.id).filter(Boolean);
|
||||
|
||||
if (postIds.length > 0) {
|
||||
const viewerLikes = await db.query.likes.findMany({
|
||||
where: and(
|
||||
eq(likes.userId, viewer.id),
|
||||
inArray(likes.postId, postIds)
|
||||
),
|
||||
});
|
||||
const likedPostIds = new Set(viewerLikes.map(l => l.postId));
|
||||
|
||||
const viewerReposts = await db.query.posts.findMany({
|
||||
where: and(
|
||||
eq(posts.userId, viewer.id),
|
||||
inArray(posts.repostOfId, postIds)
|
||||
),
|
||||
});
|
||||
const repostedPostIds = new Set(viewerReposts.map(r => r.repostOfId));
|
||||
|
||||
likedPosts = likedPosts.map(p => ({
|
||||
...p!,
|
||||
isLiked: likedPostIds.has(p!.id),
|
||||
isReposted: repostedPostIds.has(p!.id),
|
||||
})) as any;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error populating interaction flags:', error);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
posts: likedPosts,
|
||||
nextCursor: likedPosts.length === limit ? likedPosts[likedPosts.length - 1]?.id : null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Get user likes error:', error);
|
||||
return NextResponse.json({ error: 'Failed to get likes' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, posts, users, likes } from '@/db';
|
||||
import { eq, desc, and, inArray } from 'drizzle-orm';
|
||||
import { resolveRemoteUser } from '@/lib/activitypub/fetch';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
const decodeEntities = (value: string) =>
|
||||
value
|
||||
.replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
|
||||
.replace(/&#(\d+);/g, (_, num) => String.fromCharCode(Number(num)))
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'");
|
||||
|
||||
const sanitizeText = (value?: string | null) => {
|
||||
if (!value) return null;
|
||||
const withoutTags = value.replace(/<[^>]*>/g, ' ');
|
||||
const decoded = decodeEntities(withoutTags);
|
||||
return decoded.replace(/\s+/g, ' ').trim() || null;
|
||||
};
|
||||
|
||||
const extractTextAndUrls = (value?: string | null) => {
|
||||
if (!value) return { text: '', urls: [] as string[] };
|
||||
let html = value;
|
||||
// Replace <br> with spaces to avoid words running together.
|
||||
html = html.replace(/<br\s*\/?>/gi, ' ');
|
||||
// Replace anchor tags with their hrefs (preferred) or inner text.
|
||||
html = html.replace(/<a[^>]*href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gi, (_, href, text) => {
|
||||
const cleanedHref = decodeEntities(String(href));
|
||||
const cleanedText = decodeEntities(String(text)).replace(/<[^>]*>/g, ' ').trim();
|
||||
return cleanedHref || cleanedText;
|
||||
});
|
||||
const withoutTags = html.replace(/<[^>]*>/g, ' ');
|
||||
const decoded = decodeEntities(withoutTags);
|
||||
const text = decoded.replace(/\s+/g, ' ').trim();
|
||||
const urls = Array.from(text.matchAll(/https?:\/\/[^\s]+/gi)).map((match) => match[0]);
|
||||
return { text, urls };
|
||||
};
|
||||
|
||||
const normalizeUrl = (value: string) => value.replace(/[)\].,!?]+$/, '');
|
||||
|
||||
const fetchLinkPreview = async (url: string, origin: string) => {
|
||||
try {
|
||||
const previewUrl = new URL('/api/media/preview', origin);
|
||||
previewUrl.searchParams.set('url', url);
|
||||
const res = await fetch(previewUrl.toString(), {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
signal: AbortSignal.timeout(4000),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
return {
|
||||
url: data?.url || url,
|
||||
title: data?.title || null,
|
||||
description: data?.description || null,
|
||||
image: data?.image || null,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const stripFirstUrl = (text: string, url: string) => {
|
||||
const idx = text.indexOf(url);
|
||||
if (idx === -1) return text;
|
||||
const before = text.slice(0, idx).trimEnd();
|
||||
const after = text.slice(idx + url.length).trimStart();
|
||||
return `${before} ${after}`.trim();
|
||||
};
|
||||
|
||||
// Normalize content for deduplication (strip HTML entities, URLs, whitespace, category suffixes)
|
||||
const normalizeForDedup = (content: string): string => {
|
||||
return content
|
||||
.replace(/Posted into [\w\s-]+/gi, '') // Remove "Posted into [Category]" patterns
|
||||
.replace(/&[a-z]+;/gi, '') // Remove HTML entities like ‘
|
||||
.replace(/&#\d+;/g, '') // Remove numeric entities
|
||||
.replace(/https?:\/\/[^\s]+/gi, '') // Remove URLs
|
||||
.replace(/[^\w\s]/g, '') // Remove punctuation
|
||||
.replace(/\s+/g, ' ') // Normalize whitespace
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.slice(0, 50); // Compare first 50 chars (article title)
|
||||
};
|
||||
|
||||
const parseRemoteHandle = (handle: string) => {
|
||||
const clean = handle.toLowerCase().replace(/^@/, '');
|
||||
const parts = clean.split('@').filter(Boolean);
|
||||
if (parts.length === 2) {
|
||||
return { handle: parts[0], domain: parts[1] };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch remote user posts via Swarm API (preferred for Synapsis nodes)
|
||||
*/
|
||||
const fetchSwarmUserPosts = async (handle: string, domain: string, limit: number) => {
|
||||
try {
|
||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||
const url = `${protocol}://${domain}/api/swarm/users/${handle}?limit=${limit}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
if (!data.profile || !data.posts) return null;
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const fetchOutboxItems = async (outboxUrl: string, limit: number) => {
|
||||
const res = await fetch(outboxUrl, {
|
||||
headers: {
|
||||
'Accept': 'application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
|
||||
},
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json();
|
||||
const first = data?.first;
|
||||
if (first) {
|
||||
if (typeof first === 'string') {
|
||||
const pageRes = await fetch(first, {
|
||||
headers: {
|
||||
'Accept': 'application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
|
||||
},
|
||||
});
|
||||
if (!pageRes.ok) return [];
|
||||
const page = await pageRes.json();
|
||||
return page?.orderedItems || page?.items || [];
|
||||
}
|
||||
return first?.orderedItems || first?.items || [];
|
||||
}
|
||||
const items = data?.orderedItems || data?.items || [];
|
||||
return items.slice(0, limit);
|
||||
};
|
||||
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '25'), 50);
|
||||
|
||||
const remote = parseRemoteHandle(handle);
|
||||
|
||||
if (!db) {
|
||||
if (!remote) {
|
||||
return NextResponse.json({ posts: [], nextCursor: null });
|
||||
}
|
||||
|
||||
// Try Swarm API first (for Synapsis nodes)
|
||||
const swarmData = await fetchSwarmUserPosts(remote.handle, remote.domain, limit);
|
||||
if (swarmData?.posts) {
|
||||
const profile = swarmData.profile;
|
||||
const authorHandle = `${profile.handle}@${remote.domain}`;
|
||||
const author = {
|
||||
id: `swarm:${remote.domain}:${profile.handle}`,
|
||||
handle: authorHandle,
|
||||
displayName: profile.displayName || profile.handle,
|
||||
avatarUrl: profile.avatarUrl,
|
||||
};
|
||||
|
||||
const posts = swarmData.posts.map((post: any) => ({
|
||||
id: post.id,
|
||||
content: post.content,
|
||||
createdAt: post.createdAt,
|
||||
likesCount: post.likesCount || 0,
|
||||
repostsCount: post.repostsCount || 0,
|
||||
repliesCount: post.repliesCount || 0,
|
||||
author,
|
||||
media: post.media || [],
|
||||
linkPreviewUrl: post.linkPreviewUrl || null,
|
||||
linkPreviewTitle: post.linkPreviewTitle || null,
|
||||
linkPreviewDescription: post.linkPreviewDescription || null,
|
||||
linkPreviewImage: post.linkPreviewImage || null,
|
||||
isSwarm: true,
|
||||
nodeDomain: remote.domain,
|
||||
originalPostId: post.id,
|
||||
}));
|
||||
|
||||
return NextResponse.json({ posts, nextCursor: null });
|
||||
}
|
||||
|
||||
// Fall back to ActivityPub for non-Synapsis nodes
|
||||
const remoteProfile = await resolveRemoteUser(remote.handle, remote.domain);
|
||||
if (!remoteProfile?.outbox) {
|
||||
return NextResponse.json({ posts: [] });
|
||||
}
|
||||
const outboxItems = await fetchOutboxItems(remoteProfile.outbox, limit);
|
||||
const authorHandle = `${remoteProfile.preferredUsername || remote.handle}@${remote.domain}`;
|
||||
const author = {
|
||||
id: remoteProfile.id || `remote:${authorHandle}`,
|
||||
handle: authorHandle,
|
||||
displayName: sanitizeText(remoteProfile.name) || remoteProfile.preferredUsername || remote.handle,
|
||||
avatarUrl: typeof remoteProfile.icon === 'string' ? remoteProfile.icon : remoteProfile.icon?.url,
|
||||
bio: sanitizeText(remoteProfile.summary),
|
||||
};
|
||||
const posts = [];
|
||||
const seenIds = new Set<string>();
|
||||
const seenContentKeys = new Set<string>(); // For content-based dedup
|
||||
const origin = new URL(request.url).origin;
|
||||
for (const item of outboxItems) {
|
||||
const activity = item?.type === 'Create' ? item : null;
|
||||
const object = activity?.object;
|
||||
if (!object || typeof object === 'string' || object.type !== 'Note') {
|
||||
continue;
|
||||
}
|
||||
// Deduplicate by object ID
|
||||
const postId = object.id || activity.id;
|
||||
if (seenIds.has(postId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Content-based dedup: similar content = skip
|
||||
const contentKey = normalizeForDedup(object.content || '');
|
||||
if (seenContentKeys.has(contentKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seenIds.add(postId);
|
||||
seenContentKeys.add(contentKey);
|
||||
|
||||
const attachments = Array.isArray(object.attachment) ? object.attachment : [];
|
||||
const { text, urls } = extractTextAndUrls(object.content);
|
||||
const normalizedUrl = urls.length > 0 ? normalizeUrl(urls[0]) : null;
|
||||
const linkPreview = normalizedUrl ? await fetchLinkPreview(normalizedUrl, origin) : null;
|
||||
const contentText = linkPreview && normalizedUrl ? stripFirstUrl(text, normalizedUrl) : text;
|
||||
posts.push({
|
||||
id: postId,
|
||||
content: contentText || '',
|
||||
createdAt: object.published || activity.published || new Date().toISOString(),
|
||||
likesCount: 0,
|
||||
repostsCount: 0,
|
||||
repliesCount: 0,
|
||||
author,
|
||||
media: attachments
|
||||
.filter((attachment: any) => attachment?.url)
|
||||
.map((attachment: any, index: number) => ({
|
||||
id: `${postId || 'media'}-${index}`,
|
||||
url: attachment.url,
|
||||
altText: sanitizeText(attachment.name) || null,
|
||||
})),
|
||||
linkPreviewUrl: linkPreview?.url || normalizedUrl,
|
||||
linkPreviewTitle: linkPreview?.title || null,
|
||||
linkPreviewDescription: linkPreview?.description || null,
|
||||
linkPreviewImage: linkPreview?.image || null,
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ posts, nextCursor: null });
|
||||
}
|
||||
|
||||
// Find the user
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
if (!remote) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Try Swarm API first (for Synapsis nodes)
|
||||
const swarmData = await fetchSwarmUserPosts(remote.handle, remote.domain, limit);
|
||||
if (swarmData?.posts) {
|
||||
const profile = swarmData.profile;
|
||||
const authorHandle = `${profile.handle}@${remote.domain}`;
|
||||
const author = {
|
||||
id: `swarm:${remote.domain}:${profile.handle}`,
|
||||
handle: authorHandle,
|
||||
displayName: profile.displayName || profile.handle,
|
||||
avatarUrl: profile.avatarUrl,
|
||||
};
|
||||
|
||||
const posts = swarmData.posts.map((post: any) => ({
|
||||
id: post.id,
|
||||
content: post.content,
|
||||
createdAt: post.createdAt,
|
||||
likesCount: post.likesCount || 0,
|
||||
repostsCount: post.repostsCount || 0,
|
||||
repliesCount: post.repliesCount || 0,
|
||||
author,
|
||||
media: post.media || [],
|
||||
linkPreviewUrl: post.linkPreviewUrl || null,
|
||||
linkPreviewTitle: post.linkPreviewTitle || null,
|
||||
linkPreviewDescription: post.linkPreviewDescription || null,
|
||||
linkPreviewImage: post.linkPreviewImage || null,
|
||||
isSwarm: true,
|
||||
nodeDomain: remote.domain,
|
||||
originalPostId: post.id,
|
||||
}));
|
||||
|
||||
return NextResponse.json({ posts, nextCursor: null });
|
||||
}
|
||||
|
||||
// Fall back to ActivityPub for non-Synapsis nodes
|
||||
const remoteProfile = await resolveRemoteUser(remote.handle, remote.domain);
|
||||
if (!remoteProfile?.outbox) {
|
||||
return NextResponse.json({ posts: [] });
|
||||
}
|
||||
|
||||
const outboxItems = await fetchOutboxItems(remoteProfile.outbox, limit);
|
||||
const authorHandle = `${remoteProfile.preferredUsername || remote.handle}@${remote.domain}`;
|
||||
const author = {
|
||||
id: remoteProfile.id || `remote:${authorHandle}`,
|
||||
handle: authorHandle,
|
||||
displayName: sanitizeText(remoteProfile.name) || remoteProfile.preferredUsername || remote.handle,
|
||||
avatarUrl: typeof remoteProfile.icon === 'string' ? remoteProfile.icon : remoteProfile.icon?.url,
|
||||
bio: sanitizeText(remoteProfile.summary),
|
||||
};
|
||||
const posts = [];
|
||||
const seenIds = new Set<string>();
|
||||
const seenContentKeys = new Set<string>(); // For content-based dedup
|
||||
const origin = new URL(request.url).origin;
|
||||
for (const item of outboxItems) {
|
||||
const activity = item?.type === 'Create' ? item : null;
|
||||
const object = activity?.object;
|
||||
if (!object || typeof object === 'string' || object.type !== 'Note') {
|
||||
continue;
|
||||
}
|
||||
// Deduplicate by object ID
|
||||
const postId = object.id || activity.id;
|
||||
if (seenIds.has(postId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Content-based dedup: similar content = skip
|
||||
const contentKey = normalizeForDedup(object.content || '');
|
||||
if (seenContentKeys.has(contentKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seenIds.add(postId);
|
||||
seenContentKeys.add(contentKey);
|
||||
|
||||
const attachments = Array.isArray(object.attachment) ? object.attachment : [];
|
||||
const { text, urls } = extractTextAndUrls(object.content);
|
||||
const normalizedUrl = urls.length > 0 ? normalizeUrl(urls[0]) : null;
|
||||
const linkPreview = normalizedUrl ? await fetchLinkPreview(normalizedUrl, origin) : null;
|
||||
const contentText = linkPreview && normalizedUrl ? stripFirstUrl(text, normalizedUrl) : text;
|
||||
posts.push({
|
||||
id: postId,
|
||||
content: contentText || '',
|
||||
createdAt: object.published || activity.published || new Date().toISOString(),
|
||||
likesCount: 0,
|
||||
repostsCount: 0,
|
||||
repliesCount: 0,
|
||||
author,
|
||||
media: attachments
|
||||
.filter((attachment: any) => attachment?.url)
|
||||
.map((attachment: any, index: number) => ({
|
||||
id: `${postId || 'media'}-${index}`,
|
||||
url: attachment.url,
|
||||
altText: sanitizeText(attachment.name) || null,
|
||||
})),
|
||||
linkPreviewUrl: linkPreview?.url || normalizedUrl,
|
||||
linkPreviewTitle: linkPreview?.title || null,
|
||||
linkPreviewDescription: linkPreview?.description || null,
|
||||
linkPreviewImage: linkPreview?.image || null,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
posts,
|
||||
nextCursor: null,
|
||||
});
|
||||
}
|
||||
if (user.isSuspended) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Get user's posts
|
||||
let userPosts: any[] = await db.query.posts.findMany({
|
||||
where: and(eq(posts.userId, user.id), eq(posts.isRemoved, false)),
|
||||
with: {
|
||||
author: true,
|
||||
media: true,
|
||||
bot: true,
|
||||
replyTo: {
|
||||
with: { author: true },
|
||||
},
|
||||
},
|
||||
orderBy: [desc(posts.createdAt)],
|
||||
limit,
|
||||
});
|
||||
|
||||
// Populate isLiked and isReposted for authenticated users
|
||||
try {
|
||||
const { getSession } = await import('@/lib/auth');
|
||||
const session = await getSession();
|
||||
|
||||
if (session?.user && userPosts.length > 0) {
|
||||
const viewer = session.user;
|
||||
const postIds = userPosts.map(p => p.id).filter(Boolean);
|
||||
|
||||
if (postIds.length > 0) {
|
||||
const viewerLikes = await db.query.likes.findMany({
|
||||
where: and(
|
||||
eq(likes.userId, viewer.id),
|
||||
inArray(likes.postId, postIds)
|
||||
),
|
||||
});
|
||||
const likedPostIds = new Set(viewerLikes.map(l => l.postId));
|
||||
|
||||
const viewerReposts = await db.query.posts.findMany({
|
||||
where: and(
|
||||
eq(posts.userId, viewer.id),
|
||||
inArray(posts.repostOfId, postIds)
|
||||
),
|
||||
});
|
||||
const repostedPostIds = new Set(viewerReposts.map(r => r.repostOfId));
|
||||
|
||||
userPosts = userPosts.map(p => ({
|
||||
...p,
|
||||
isLiked: likedPostIds.has(p.id),
|
||||
isReposted: repostedPostIds.has(p.id),
|
||||
}));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error populating interaction flags:', error);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
posts: userPosts,
|
||||
nextCursor: userPosts.length === limit ? userPosts[userPosts.length - 1]?.id : null,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Get user posts error:', error);
|
||||
return NextResponse.json({ error: 'Failed to get posts' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db, users } from '@/db';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { userToActor } from '@/lib/activitypub/actor';
|
||||
import { resolveRemoteUser } from '@/lib/activitypub/fetch';
|
||||
|
||||
type RouteContext = { params: Promise<{ handle: string }> };
|
||||
|
||||
const decodeEntities = (value: string) =>
|
||||
value
|
||||
.replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
|
||||
.replace(/&#(\d+);/g, (_, num) => String.fromCharCode(Number(num)))
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'");
|
||||
|
||||
const sanitizeText = (value?: string | null) => {
|
||||
if (!value) return null;
|
||||
const withoutTags = value.replace(/<[^>]*>/g, ' ');
|
||||
const decoded = decodeEntities(withoutTags);
|
||||
return decoded.replace(/\s+/g, ' ').trim() || null;
|
||||
};
|
||||
|
||||
const fetchCollectionCount = async (url?: string | null) => {
|
||||
if (!url) return 0;
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
'Accept': 'application/activity+json, application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
|
||||
},
|
||||
});
|
||||
if (!res.ok) return 0;
|
||||
const data = await res.json();
|
||||
if (typeof data?.totalItems === 'number') return data.totalItems;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch remote user profile via Swarm API (preferred for Synapsis nodes)
|
||||
*/
|
||||
const fetchSwarmProfile = async (handle: string, domain: string) => {
|
||||
try {
|
||||
const protocol = domain.includes('localhost') ? 'http' : 'https';
|
||||
const url = `${protocol}://${domain}/api/swarm/users/${handle}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { 'Accept': 'application/json' },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
if (!data.profile) return null;
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { handle } = await context.params;
|
||||
const cleanHandle = handle.toLowerCase().replace(/^@/, '');
|
||||
const [remoteHandle, remoteDomain] = cleanHandle.split('@');
|
||||
|
||||
// Return mock user if no database
|
||||
if (!db) {
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
id: 'demo-user',
|
||||
handle: cleanHandle,
|
||||
displayName: cleanHandle,
|
||||
bio: 'This is a demo profile.',
|
||||
avatarUrl: null,
|
||||
headerUrl: null,
|
||||
followersCount: 0,
|
||||
followingCount: 0,
|
||||
postsCount: 0,
|
||||
createdAt: new Date().toISOString(),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.handle, cleanHandle),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
if (remoteHandle && remoteDomain) {
|
||||
// Try Swarm API first (for Synapsis nodes)
|
||||
const swarmData = await fetchSwarmProfile(remoteHandle, remoteDomain);
|
||||
if (swarmData?.profile) {
|
||||
const profile = swarmData.profile;
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
id: `swarm:${remoteDomain}:${profile.handle}`,
|
||||
handle: `${profile.handle}@${remoteDomain}`,
|
||||
displayName: profile.displayName,
|
||||
bio: profile.bio || null,
|
||||
avatarUrl: profile.avatarUrl || null,
|
||||
headerUrl: profile.headerUrl || null,
|
||||
followersCount: profile.followersCount,
|
||||
followingCount: profile.followingCount,
|
||||
postsCount: profile.postsCount,
|
||||
website: profile.website || null,
|
||||
createdAt: profile.createdAt,
|
||||
isRemote: true,
|
||||
isSwarm: true,
|
||||
nodeDomain: remoteDomain,
|
||||
isBot: profile.isBot || false,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Fall back to ActivityPub for non-Synapsis nodes
|
||||
const remoteProfile = await resolveRemoteUser(remoteHandle, remoteDomain);
|
||||
if (remoteProfile) {
|
||||
const displayName = sanitizeText(remoteProfile.name) || sanitizeText(remoteProfile.preferredUsername) || remoteHandle;
|
||||
const iconUrl = typeof remoteProfile.icon === 'string' ? remoteProfile.icon : remoteProfile.icon?.url;
|
||||
const headerUrl = typeof remoteProfile.image === 'string' ? remoteProfile.image : remoteProfile.image?.url;
|
||||
const profileUrl = typeof remoteProfile.url === 'string' ? remoteProfile.url : remoteProfile.id;
|
||||
const [followersCount, followingCount, postsCount] = await Promise.all([
|
||||
fetchCollectionCount(remoteProfile.followers),
|
||||
fetchCollectionCount(remoteProfile.following),
|
||||
fetchCollectionCount(remoteProfile.outbox),
|
||||
]);
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
id: remoteProfile.id || profileUrl || `remote:${cleanHandle}`,
|
||||
handle: `${remoteProfile.preferredUsername || remoteHandle}@${remoteDomain}`,
|
||||
displayName,
|
||||
bio: sanitizeText(remoteProfile.summary),
|
||||
avatarUrl: iconUrl ?? null,
|
||||
headerUrl: headerUrl ?? null,
|
||||
followersCount,
|
||||
followingCount,
|
||||
postsCount,
|
||||
website: profileUrl ?? null,
|
||||
createdAt: new Date().toISOString(),
|
||||
isRemote: true,
|
||||
profileUrl: profileUrl ?? null,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
if (user.isSuspended) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Check if ActivityPub request
|
||||
const accept = request.headers.get('accept') || '';
|
||||
if (accept.includes('application/activity+json') || accept.includes('application/ld+json')) {
|
||||
const nodeDomain = process.env.NEXT_PUBLIC_NODE_DOMAIN || 'localhost:3000';
|
||||
const actor = userToActor(user, nodeDomain);
|
||||
return NextResponse.json(actor, {
|
||||
headers: {
|
||||
'Content-Type': 'application/activity+json',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Return user profile (without sensitive data)
|
||||
// Include bot info if this is a bot account
|
||||
const userResponse: Record<string, unknown> = {
|
||||
id: user.id,
|
||||
handle: user.handle,
|
||||
displayName: user.displayName,
|
||||
bio: user.bio,
|
||||
avatarUrl: user.avatarUrl,
|
||||
headerUrl: user.headerUrl,
|
||||
followersCount: user.followersCount,
|
||||
followingCount: user.followingCount,
|
||||
postsCount: user.postsCount,
|
||||
createdAt: user.createdAt,
|
||||
website: user.website,
|
||||
movedTo: user.movedTo,
|
||||
isBot: user.isBot,
|
||||
};
|
||||
|
||||
// If this is a bot, include owner info
|
||||
if (user.isBot && user.botOwnerId) {
|
||||
const owner = await db.query.users.findFirst({
|
||||
where: eq(users.id, user.botOwnerId),
|
||||
});
|
||||
if (owner) {
|
||||
userResponse.botOwner = {
|
||||
id: owner.id,
|
||||
handle: owner.handle,
|
||||
displayName: owner.displayName,
|
||||
avatarUrl: owner.avatarUrl,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ user: userResponse });
|
||||
} catch (error) {
|
||||
console.error('Get user error:', error);
|
||||
return NextResponse.json({ error: 'Failed to get user' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user