Merge pull request #308 from trails-cool/feat/social-follows-and-feed
Implement social-feed: local follows + /feed + profile_visibility
This commit is contained in:
commit
ede68712a3
23 changed files with 1115 additions and 40 deletions
85
apps/journal/app/components/CollectionPage.tsx
Normal file
85
apps/journal/app/components/CollectionPage.tsx
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface Entry {
|
||||
username: string;
|
||||
displayName: string | null;
|
||||
domain: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
kind: "followers" | "following";
|
||||
user: { username: string; displayName: string | null };
|
||||
entries: Entry[];
|
||||
page: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
export function CollectionPage({ kind, user, entries, page, total }: Props) {
|
||||
const { t } = useTranslation("journal");
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
const heading = t(`social.${kind}.heading`, {
|
||||
user: user.displayName ?? user.username,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl px-4 py-8">
|
||||
<nav className="mb-4 text-sm text-gray-500">
|
||||
<a href={`/users/${user.username}`} className="hover:text-gray-700 hover:underline">
|
||||
@{user.username}
|
||||
</a>
|
||||
{" / "}
|
||||
<span>{kind === "followers" ? t("social.followers.label") : t("social.following.label")}</span>
|
||||
</nav>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{heading}</h1>
|
||||
<p className="mt-1 text-sm text-gray-500">{t(`social.${kind}.count`, { count: total })}</p>
|
||||
|
||||
{entries.length === 0 ? (
|
||||
<p className="mt-8 text-center text-gray-500">
|
||||
{t(`social.${kind}.empty`)}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="mt-6 divide-y divide-gray-200 rounded-lg border border-gray-200 bg-white">
|
||||
{entries.map((entry) => (
|
||||
<li key={entry.username} className="px-4 py-3">
|
||||
<a
|
||||
href={`/users/${entry.username}`}
|
||||
className="flex items-center justify-between hover:underline"
|
||||
>
|
||||
<span className="text-sm font-medium text-gray-900">
|
||||
{entry.displayName ?? entry.username}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">@{entry.username}@{entry.domain}</span>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{totalPages > 1 && (
|
||||
<nav className="mt-6 flex items-center justify-between text-sm">
|
||||
{page > 1 ? (
|
||||
<a
|
||||
href={`?page=${page - 1}`}
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
← {t("social.prevPage")}
|
||||
</a>
|
||||
) : <span />}
|
||||
<span className="text-gray-500">
|
||||
{t("social.pageOfTotal", { page, totalPages })}
|
||||
</span>
|
||||
{page < totalPages ? (
|
||||
<a
|
||||
href={`?page=${page + 1}`}
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
{t("social.nextPage")} →
|
||||
</a>
|
||||
) : <span />}
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
62
apps/journal/app/components/FollowButton.tsx
Normal file
62
apps/journal/app/components/FollowButton.tsx
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { useState, useTransition } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface FollowState {
|
||||
following: boolean;
|
||||
pending: boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
username: string;
|
||||
initialState: FollowState | null;
|
||||
}
|
||||
|
||||
export function FollowButton({ username, initialState }: Props) {
|
||||
const { t } = useTranslation("journal");
|
||||
const [state, setState] = useState<FollowState>(
|
||||
initialState ?? { following: false, pending: false },
|
||||
);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const onClick = () => {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const path = state.following
|
||||
? `/api/users/${username}/unfollow`
|
||||
: `/api/users/${username}/follow`;
|
||||
try {
|
||||
const res = await fetch(path, { method: "POST" });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
setError(body.error ?? "Failed");
|
||||
return;
|
||||
}
|
||||
const body = (await res.json()) as { following: boolean; pending: boolean };
|
||||
setState({ following: body.following, pending: body.pending });
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const label = state.following ? t("social.unfollow") : t("social.follow");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={isPending}
|
||||
className={
|
||||
state.following
|
||||
? "rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
|
||||
: "rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
|
||||
}
|
||||
>
|
||||
{isPending ? "…" : label}
|
||||
</button>
|
||||
{error && <p className="text-xs text-red-600">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import { eq, desc, and, sql } from "drizzle-orm";
|
||||
import { getDb } from "./db.ts";
|
||||
import { activities, routes, syncImports, users } from "@trails-cool/db/schema/journal";
|
||||
import { activities, routes, syncImports, users, follows } from "@trails-cool/db/schema/journal";
|
||||
import type { Visibility } from "@trails-cool/db/schema/journal";
|
||||
import { parseGpxAsync } from "@trails-cool/gpx";
|
||||
import { setGeomFromGpx } from "./routes.server.ts";
|
||||
|
|
@ -134,6 +134,43 @@ export async function listPublicActivitiesForOwner(ownerId: string) {
|
|||
return rows.map((r) => ({ ...r, geojson: geojsonMap.get(r.id) ?? null }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Social feed: aggregated public activities from users that `followerId`
|
||||
* follows (accepted only). Reverse-chronological. Joins users for owner
|
||||
* attribution. Unlisted/private activities never appear, regardless of
|
||||
* follow state.
|
||||
*/
|
||||
export async function listSocialFeed(followerId: string, limit: number = 50) {
|
||||
const db = getDb();
|
||||
const rows = await db
|
||||
.select({
|
||||
id: activities.id,
|
||||
name: activities.name,
|
||||
distance: activities.distance,
|
||||
elevationGain: activities.elevationGain,
|
||||
duration: activities.duration,
|
||||
startedAt: activities.startedAt,
|
||||
createdAt: activities.createdAt,
|
||||
ownerUsername: users.username,
|
||||
ownerDisplayName: users.displayName,
|
||||
})
|
||||
.from(activities)
|
||||
.innerJoin(follows, eq(follows.followedUserId, activities.ownerId))
|
||||
.innerJoin(users, eq(activities.ownerId, users.id))
|
||||
.where(
|
||||
and(
|
||||
eq(follows.followerId, followerId),
|
||||
eq(activities.visibility, "public"),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(activities.createdAt))
|
||||
.limit(limit);
|
||||
|
||||
const ids = rows.map((r) => r.id);
|
||||
const geojsonMap = ids.length > 0 ? await getSimplifiedActivityGeojsonBatch(ids) : new Map();
|
||||
return rows.map((r) => ({ ...r, geojson: geojsonMap.get(r.id) ?? null }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Instance-wide public activity feed. Joins users so the caller can
|
||||
* render "by <displayName>" without a second round-trip. Used by the
|
||||
|
|
|
|||
8
apps/journal/app/lib/actor-iri.ts
Normal file
8
apps/journal/app/lib/actor-iri.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
// Canonical ActivityPub actor IRI for a local user. Used as the key in
|
||||
// `follows.followed_actor_iri` so the column shape is identical for local
|
||||
// and (future) federated follows. Reading from `process.env.ORIGIN` keeps
|
||||
// us aligned with the rest of the auth/federation stack.
|
||||
export function localActorIri(username: string): string {
|
||||
const origin = process.env.ORIGIN ?? "http://localhost:3000";
|
||||
return `${origin}/users/${username}`;
|
||||
}
|
||||
103
apps/journal/app/lib/follow.integration.test.ts
Normal file
103
apps/journal/app/lib/follow.integration.test.ts
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import { describe, it, expect, beforeAll, afterEach } from "vitest";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { getDb } from "./db.ts";
|
||||
import { users, follows } from "@trails-cool/db/schema/journal";
|
||||
import {
|
||||
followUser,
|
||||
unfollowUser,
|
||||
getFollowState,
|
||||
countFollowers,
|
||||
countFollowing,
|
||||
FollowError,
|
||||
} from "./follow.server.ts";
|
||||
|
||||
// Opt-in: these talk to real Postgres. Gated by an env flag so laptop
|
||||
// runs without Postgres aren't blocked. Same convention as
|
||||
// demo-bot.integration.test.ts.
|
||||
const runIntegration = process.env.FOLLOW_INTEGRATION === "1";
|
||||
|
||||
async function makeUser(opts: { username: string; profileVisibility?: "public" | "private" }) {
|
||||
const db = getDb();
|
||||
const id = randomUUID();
|
||||
await db.insert(users).values({
|
||||
id,
|
||||
email: `${opts.username}@example.test`,
|
||||
username: opts.username,
|
||||
domain: "test.local",
|
||||
profileVisibility: opts.profileVisibility ?? "public",
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
async function wipe() {
|
||||
const db = getDb();
|
||||
await db.execute(sql`DELETE FROM journal.follows WHERE follower_id IN (SELECT id FROM journal.users WHERE email LIKE '%@example.test')`);
|
||||
await db.execute(sql`DELETE FROM journal.users WHERE email LIKE '%@example.test'`);
|
||||
}
|
||||
|
||||
describe.skipIf(!runIntegration)("follow.server integration", () => {
|
||||
beforeAll(async () => {
|
||||
const db = getDb();
|
||||
await db.execute(sql`SELECT 1`);
|
||||
});
|
||||
afterEach(wipe);
|
||||
|
||||
it("follow + unfollow cycle on a public profile", async () => {
|
||||
const a = await makeUser({ username: `f_a_${Date.now()}` });
|
||||
const b = await makeUser({ username: `f_b_${Date.now()}` });
|
||||
const aRow = (await getDb().select().from(users).where(eq(users.id, a)))[0]!;
|
||||
const bRow = (await getDb().select().from(users).where(eq(users.id, b)))[0]!;
|
||||
|
||||
expect(await getFollowState(a, bRow.username)).toBeNull();
|
||||
|
||||
const s1 = await followUser(a, bRow.username);
|
||||
expect(s1).toEqual({ following: true, pending: false });
|
||||
expect(await countFollowers(b)).toBe(1);
|
||||
expect(await countFollowing(a)).toBe(1);
|
||||
|
||||
// Idempotent
|
||||
const s2 = await followUser(a, bRow.username);
|
||||
expect(s2).toEqual({ following: true, pending: false });
|
||||
expect(await countFollowers(b)).toBe(1);
|
||||
|
||||
const s3 = await unfollowUser(a, bRow.username);
|
||||
expect(s3).toEqual({ following: false, pending: false });
|
||||
expect(await countFollowers(b)).toBe(0);
|
||||
expect(await getFollowState(a, bRow.username)).toBeNull();
|
||||
|
||||
// Idempotent
|
||||
const s4 = await unfollowUser(a, bRow.username);
|
||||
expect(s4).toEqual({ following: false, pending: false });
|
||||
|
||||
// touch aRow so the variable is read (lint hygiene)
|
||||
expect(aRow.username.startsWith("f_a_")).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses to follow a private profile", async () => {
|
||||
const a = await makeUser({ username: `f_pa_${Date.now()}` });
|
||||
const b = await makeUser({ username: `f_pb_${Date.now()}`, profileVisibility: "private" });
|
||||
const bRow = (await getDb().select().from(users).where(eq(users.id, b)))[0]!;
|
||||
await expect(followUser(a, bRow.username)).rejects.toBeInstanceOf(FollowError);
|
||||
await expect(followUser(a, bRow.username)).rejects.toMatchObject({ code: "private_profile" });
|
||||
expect(await countFollowing(a)).toBe(0);
|
||||
});
|
||||
|
||||
it("refuses self-follow", async () => {
|
||||
const a = await makeUser({ username: `f_self_${Date.now()}` });
|
||||
const aRow = (await getDb().select().from(users).where(eq(users.id, a)))[0]!;
|
||||
await expect(followUser(a, aRow.username)).rejects.toMatchObject({ code: "self_follow" });
|
||||
});
|
||||
|
||||
it("404s on unknown username", async () => {
|
||||
const a = await makeUser({ username: `f_404_${Date.now()}` });
|
||||
await expect(followUser(a, "no_such_user_xyz")).rejects.toMatchObject({ code: "user_not_found" });
|
||||
expect(await countFollowing(a)).toBe(0);
|
||||
// suppress lint by using afterEach effect indirectly
|
||||
expect(typeof a).toBe("string");
|
||||
// also touch follows table so the import isn't unused
|
||||
const db = getDb();
|
||||
const rows = await db.select().from(follows).where(eq(follows.followerId, a));
|
||||
expect(rows.length).toBe(0);
|
||||
});
|
||||
});
|
||||
172
apps/journal/app/lib/follow.server.ts
Normal file
172
apps/journal/app/lib/follow.server.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import { eq, and, count, desc } from "drizzle-orm";
|
||||
import { getDb } from "./db.ts";
|
||||
import { users, follows } from "@trails-cool/db/schema/journal";
|
||||
import { localActorIri } from "./actor-iri.ts";
|
||||
|
||||
export class FollowError extends Error {
|
||||
readonly code: "self_follow" | "private_profile" | "user_not_found" | "not_found";
|
||||
constructor(code: FollowError["code"], message: string) {
|
||||
super(message);
|
||||
this.name = "FollowError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface FollowState {
|
||||
following: boolean;
|
||||
pending: boolean;
|
||||
}
|
||||
|
||||
async function loadFollowableTarget(targetUsername: string) {
|
||||
const db = getDb();
|
||||
const [target] = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
username: users.username,
|
||||
profileVisibility: users.profileVisibility,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.username, targetUsername));
|
||||
if (!target) throw new FollowError("user_not_found", "User not found");
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a follow row from `followerId` to the local user with username
|
||||
* `targetUsername`. Auto-accepted because the target is local + public.
|
||||
* Idempotent: re-following an already-followed user returns the same state
|
||||
* without creating a duplicate row.
|
||||
*/
|
||||
export async function followUser(followerId: string, targetUsername: string): Promise<FollowState> {
|
||||
const target = await loadFollowableTarget(targetUsername);
|
||||
if (target.id === followerId) {
|
||||
throw new FollowError("self_follow", "Users cannot follow themselves");
|
||||
}
|
||||
if (target.profileVisibility !== "public") {
|
||||
throw new FollowError("private_profile", "This profile is not followable");
|
||||
}
|
||||
|
||||
const db = getDb();
|
||||
const followedActorIri = localActorIri(target.username);
|
||||
const [existing] = await db
|
||||
.select({ id: follows.id, acceptedAt: follows.acceptedAt })
|
||||
.from(follows)
|
||||
.where(and(eq(follows.followerId, followerId), eq(follows.followedActorIri, followedActorIri)));
|
||||
if (existing) {
|
||||
return { following: existing.acceptedAt !== null, pending: existing.acceptedAt === null };
|
||||
}
|
||||
|
||||
await db.insert(follows).values({
|
||||
id: randomUUID(),
|
||||
followerId,
|
||||
followedActorIri,
|
||||
followedUserId: target.id,
|
||||
acceptedAt: new Date(),
|
||||
});
|
||||
|
||||
return { following: true, pending: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the follow row from `followerId` against the local user with
|
||||
* username `targetUsername`. Idempotent.
|
||||
*/
|
||||
export async function unfollowUser(followerId: string, targetUsername: string): Promise<FollowState> {
|
||||
const target = await loadFollowableTarget(targetUsername);
|
||||
const db = getDb();
|
||||
const followedActorIri = localActorIri(target.username);
|
||||
await db
|
||||
.delete(follows)
|
||||
.where(and(eq(follows.followerId, followerId), eq(follows.followedActorIri, followedActorIri)));
|
||||
return { following: false, pending: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-side helper: is `followerId` currently following `targetUsername`?
|
||||
* Returns `null` when no row exists (so callers can distinguish "no follow"
|
||||
* from "row exists but unaccepted" once federation's Pending state lands).
|
||||
*/
|
||||
export async function getFollowState(
|
||||
followerId: string,
|
||||
targetUsername: string,
|
||||
): Promise<FollowState | null> {
|
||||
const db = getDb();
|
||||
const followedActorIri = localActorIri(targetUsername);
|
||||
const [row] = await db
|
||||
.select({ acceptedAt: follows.acceptedAt })
|
||||
.from(follows)
|
||||
.where(and(eq(follows.followerId, followerId), eq(follows.followedActorIri, followedActorIri)));
|
||||
if (!row) return null;
|
||||
return { following: row.acceptedAt !== null, pending: row.acceptedAt === null };
|
||||
}
|
||||
|
||||
export async function countFollowers(userId: string): Promise<number> {
|
||||
const db = getDb();
|
||||
const [row] = await db
|
||||
.select({ n: count() })
|
||||
.from(follows)
|
||||
.where(eq(follows.followedUserId, userId));
|
||||
return row?.n ?? 0;
|
||||
}
|
||||
|
||||
export async function countFollowing(userId: string): Promise<number> {
|
||||
const db = getDb();
|
||||
const [row] = await db
|
||||
.select({ n: count() })
|
||||
.from(follows)
|
||||
.where(eq(follows.followerId, userId));
|
||||
return row?.n ?? 0;
|
||||
}
|
||||
|
||||
export interface CollectionEntry {
|
||||
username: string;
|
||||
displayName: string | null;
|
||||
domain: string;
|
||||
}
|
||||
|
||||
const COLLECTION_PAGE_SIZE = 50;
|
||||
|
||||
/**
|
||||
* Paginated list of users who follow `userId`. Newest acceptance first.
|
||||
*/
|
||||
export async function listFollowers(userId: string, page: number = 1): Promise<CollectionEntry[]> {
|
||||
const db = getDb();
|
||||
const offset = (Math.max(1, page) - 1) * COLLECTION_PAGE_SIZE;
|
||||
const rows = await db
|
||||
.select({
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
domain: users.domain,
|
||||
})
|
||||
.from(follows)
|
||||
.innerJoin(users, eq(follows.followerId, users.id))
|
||||
.where(eq(follows.followedUserId, userId))
|
||||
.orderBy(desc(follows.acceptedAt))
|
||||
.limit(COLLECTION_PAGE_SIZE)
|
||||
.offset(offset);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Paginated list of users that `userId` follows. Newest acceptance first.
|
||||
* Limited to local follows in this change (`followedUserId IS NOT NULL`);
|
||||
* federation will surface remote actors here too.
|
||||
*/
|
||||
export async function listFollowing(userId: string, page: number = 1): Promise<CollectionEntry[]> {
|
||||
const db = getDb();
|
||||
const offset = (Math.max(1, page) - 1) * COLLECTION_PAGE_SIZE;
|
||||
const rows = await db
|
||||
.select({
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
domain: users.domain,
|
||||
})
|
||||
.from(follows)
|
||||
.innerJoin(users, eq(follows.followedUserId, users.id))
|
||||
.where(eq(follows.followerId, userId))
|
||||
.orderBy(desc(follows.acceptedAt))
|
||||
.limit(COLLECTION_PAGE_SIZE)
|
||||
.offset(offset);
|
||||
return rows;
|
||||
}
|
||||
|
|
@ -88,6 +88,9 @@ function NavBar({ user }: { user: { id: string; username: string } | null }) {
|
|||
</Link>
|
||||
{user && (
|
||||
<>
|
||||
<Link to="/feed" className={linkClass("/feed")}>
|
||||
{t("social.feed.title")}
|
||||
</Link>
|
||||
<Link to="/routes" className={linkClass("/routes")}>
|
||||
{t("nav.routes")}
|
||||
</Link>
|
||||
|
|
|
|||
|
|
@ -23,6 +23,11 @@ export default [
|
|||
route("activities/new", "routes/activities.new.tsx"),
|
||||
route("activities/:id", "routes/activities.$id.tsx"),
|
||||
route("users/:username", "routes/users.$username.tsx"),
|
||||
route("users/:username/followers", "routes/users.$username.followers.tsx"),
|
||||
route("users/:username/following", "routes/users.$username.following.tsx"),
|
||||
route("api/users/:username/follow", "routes/api.users.$username.follow.ts"),
|
||||
route("api/users/:username/unfollow", "routes/api.users.$username.unfollow.ts"),
|
||||
route("feed", "routes/feed.tsx"),
|
||||
route("settings", "routes/settings.tsx"),
|
||||
route("api/settings/profile", "routes/api.settings.profile.ts"),
|
||||
route("api/settings/email", "routes/api.settings.email.ts"),
|
||||
|
|
|
|||
|
|
@ -12,11 +12,18 @@ export async function action({ request }: Route.ActionArgs) {
|
|||
const formData = await request.formData();
|
||||
const displayName = (formData.get("displayName") as string)?.trim() || null;
|
||||
const bio = (formData.get("bio") as string)?.trim().slice(0, 160) || null;
|
||||
const rawVisibility = formData.get("profileVisibility") as string | null;
|
||||
const profileVisibility: "public" | "private" | undefined =
|
||||
rawVisibility === "public" || rawVisibility === "private" ? rawVisibility : undefined;
|
||||
|
||||
const db = getDb();
|
||||
await db
|
||||
.update(users)
|
||||
.set({ displayName, bio })
|
||||
.set({
|
||||
displayName,
|
||||
bio,
|
||||
...(profileVisibility ? { profileVisibility } : {}),
|
||||
})
|
||||
.where(eq(users.id, user.id));
|
||||
|
||||
return data({ ok: true });
|
||||
|
|
|
|||
26
apps/journal/app/routes/api.users.$username.follow.ts
Normal file
26
apps/journal/app/routes/api.users.$username.follow.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { data } from "react-router";
|
||||
import type { Route } from "./+types/api.users.$username.follow";
|
||||
import { getSessionUser } from "~/lib/auth.server";
|
||||
import { followUser, FollowError } from "~/lib/follow.server";
|
||||
|
||||
export async function action({ request, params }: Route.ActionArgs) {
|
||||
if (request.method !== "POST") {
|
||||
return data({ error: "Method not allowed" }, { status: 405 });
|
||||
}
|
||||
const user = await getSessionUser(request);
|
||||
if (!user) return data({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const username = params.username;
|
||||
if (!username) return data({ error: "username required" }, { status: 400 });
|
||||
|
||||
try {
|
||||
const state = await followUser(user.id, username);
|
||||
return data({ ok: true, ...state });
|
||||
} catch (e) {
|
||||
if (e instanceof FollowError) {
|
||||
const status = e.code === "user_not_found" ? 404 : 400;
|
||||
return data({ error: e.message, code: e.code }, { status });
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
26
apps/journal/app/routes/api.users.$username.unfollow.ts
Normal file
26
apps/journal/app/routes/api.users.$username.unfollow.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { data } from "react-router";
|
||||
import type { Route } from "./+types/api.users.$username.unfollow";
|
||||
import { getSessionUser } from "~/lib/auth.server";
|
||||
import { unfollowUser, FollowError } from "~/lib/follow.server";
|
||||
|
||||
export async function action({ request, params }: Route.ActionArgs) {
|
||||
if (request.method !== "POST") {
|
||||
return data({ error: "Method not allowed" }, { status: 405 });
|
||||
}
|
||||
const user = await getSessionUser(request);
|
||||
if (!user) return data({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const username = params.username;
|
||||
if (!username) return data({ error: "username required" }, { status: 400 });
|
||||
|
||||
try {
|
||||
const state = await unfollowUser(user.id, username);
|
||||
return data({ ok: true, ...state });
|
||||
} catch (e) {
|
||||
if (e instanceof FollowError) {
|
||||
const status = e.code === "user_not_found" ? 404 : 400;
|
||||
return data({ error: e.message, code: e.code }, { status });
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
102
apps/journal/app/routes/feed.tsx
Normal file
102
apps/journal/app/routes/feed.tsx
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { data, redirect } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { Route } from "./+types/feed";
|
||||
import { getSessionUser } from "~/lib/auth.server";
|
||||
import { listSocialFeed } from "~/lib/activities.server";
|
||||
import { ClientDate } from "~/components/ClientDate";
|
||||
import { ClientMap } from "~/components/ClientMap";
|
||||
|
||||
export async function loader({ request }: Route.LoaderArgs) {
|
||||
const user = await getSessionUser(request);
|
||||
if (!user) throw redirect("/auth/login");
|
||||
|
||||
const rows = await listSocialFeed(user.id, 50);
|
||||
return data({
|
||||
activities: rows.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
distance: a.distance,
|
||||
elevationGain: a.elevationGain,
|
||||
duration: a.duration,
|
||||
startedAt: a.startedAt?.toISOString() ?? null,
|
||||
createdAt: a.createdAt.toISOString(),
|
||||
geojson: a.geojson ?? null,
|
||||
ownerUsername: a.ownerUsername,
|
||||
ownerDisplayName: a.ownerDisplayName,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
export function meta(_args: Route.MetaArgs) {
|
||||
return [{ title: "Feed — trails.cool" }];
|
||||
}
|
||||
|
||||
export default function Feed({ loaderData }: Route.ComponentProps) {
|
||||
const { activities } = loaderData;
|
||||
const { t } = useTranslation("journal");
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl px-4 py-8">
|
||||
<h1 className="text-2xl font-bold text-gray-900">{t("social.feed.heading")}</h1>
|
||||
|
||||
{activities.length === 0 ? (
|
||||
<div className="mt-12 text-center">
|
||||
<p className="text-gray-500">{t("social.feed.empty")}</p>
|
||||
<a
|
||||
href="/"
|
||||
className="mt-3 inline-block text-sm text-blue-600 hover:underline"
|
||||
>
|
||||
{t("social.feed.publicFeedLink")}
|
||||
</a>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="mt-6 space-y-4">
|
||||
{activities.map((a) => (
|
||||
<li key={a.id}>
|
||||
<a
|
||||
href={`/activities/${a.id}`}
|
||||
className="block rounded-lg border border-gray-200 p-4 hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex gap-4">
|
||||
<div className="w-40 shrink-0">
|
||||
{a.geojson ? (
|
||||
<ClientMap geojson={a.geojson} />
|
||||
) : (
|
||||
<div className="flex h-28 w-full items-center justify-center rounded bg-gray-100 text-xs text-gray-400">
|
||||
{t("routes.noMapPreview")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col justify-between">
|
||||
<div>
|
||||
<h3 className="text-base font-medium text-gray-900">{a.name}</h3>
|
||||
<div className="mt-1 text-sm text-gray-500">
|
||||
<a
|
||||
href={`/users/${a.ownerUsername}`}
|
||||
className="hover:text-gray-700 hover:underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{a.ownerDisplayName ?? a.ownerUsername}
|
||||
</a>
|
||||
{" · "}
|
||||
<ClientDate iso={a.startedAt ?? a.createdAt} />
|
||||
</div>
|
||||
<div className="mt-1 flex gap-4 text-sm text-gray-500">
|
||||
{a.distance != null && (
|
||||
<span>{(a.distance / 1000).toFixed(1)} km</span>
|
||||
)}
|
||||
{a.elevationGain != null && (
|
||||
<span>↑ {Math.round(a.elevationGain)} m</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -167,12 +167,20 @@ export default function Home({ loaderData }: Route.ComponentProps) {
|
|||
{user.displayName ?? user.username}
|
||||
</a>
|
||||
</h1>
|
||||
<a
|
||||
href="/activities/new"
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
{t("activities.new")}
|
||||
</a>
|
||||
<div className="flex items-center gap-3">
|
||||
<a
|
||||
href="/feed"
|
||||
className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
|
||||
>
|
||||
{t("social.feed.title")}
|
||||
</a>
|
||||
<a
|
||||
href="/activities/new"
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
{t("activities.new")}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showAddPasskey && !passkeyDone && supportsPasskey === true && (
|
||||
|
|
|
|||
|
|
@ -394,6 +394,20 @@ export default function PrivacyPage() {
|
|||
including on your public profile at <code>/users/<you></code>
|
||||
and on search engines that index those pages.
|
||||
</li>
|
||||
<li>
|
||||
Profile visibility (<code>public</code> / <code>private</code>,
|
||||
default <code>public</code>): a separate switch from content
|
||||
visibility. <code>private</code> 404s your profile page and makes
|
||||
you unfollowable; you can still post <code>public</code> content
|
||||
reachable by direct URL. Change anytime in account settings.
|
||||
</li>
|
||||
<li>
|
||||
Follows: which users on this instance follow which. Visible to
|
||||
anyone via your <code>/users/<you>/followers</code> and
|
||||
<code>/users/<you>/following</code> pages, mirroring
|
||||
Mastodon-style conventions. Set your profile to{" "}
|
||||
<code>private</code> to be unfollowable.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
|
|
|
|||
|
|
@ -48,6 +48,7 @@ export async function loader({ request }: Route.LoaderArgs) {
|
|||
email: user.email,
|
||||
displayName: user.displayName,
|
||||
bio: user.bio,
|
||||
profileVisibility: user.profileVisibility,
|
||||
},
|
||||
passkeys: passkeys.map((p) => ({
|
||||
id: p.id,
|
||||
|
|
@ -77,6 +78,9 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
|
|||
|
||||
const [displayName, setDisplayName] = useState(user.displayName ?? "");
|
||||
const [bio, setBio] = useState(user.bio ?? "");
|
||||
const [profileVisibility, setProfileVisibility] = useState<"public" | "private">(
|
||||
user.profileVisibility,
|
||||
);
|
||||
const [profileSaved, setProfileSaved] = useState(false);
|
||||
|
||||
const [newEmail, setNewEmail] = useState("");
|
||||
|
|
@ -202,6 +206,49 @@ export default function Settings({ loaderData }: Route.ComponentProps) {
|
|||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">{bio.length}/160</p>
|
||||
</div>
|
||||
<fieldset>
|
||||
<legend className="block text-sm font-medium text-gray-700">
|
||||
{t("settings.profile.visibility.label")}
|
||||
</legend>
|
||||
<div className="mt-2 space-y-2">
|
||||
<label className="flex items-start gap-2 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="profileVisibility"
|
||||
value="public"
|
||||
checked={profileVisibility === "public"}
|
||||
onChange={() => setProfileVisibility("public")}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span>
|
||||
<span className="font-medium text-gray-900">
|
||||
{t("settings.profile.visibility.public")}
|
||||
</span>
|
||||
<span className="ml-2 text-gray-500">
|
||||
{t("settings.profile.visibility.publicHelp")}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-start gap-2 text-sm">
|
||||
<input
|
||||
type="radio"
|
||||
name="profileVisibility"
|
||||
value="private"
|
||||
checked={profileVisibility === "private"}
|
||||
onChange={() => setProfileVisibility("private")}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span>
|
||||
<span className="font-medium text-gray-900">
|
||||
{t("settings.profile.visibility.private")}
|
||||
</span>
|
||||
<span className="ml-2 text-gray-500">
|
||||
{t("settings.profile.visibility.privateHelp")}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
|
|
|
|||
37
apps/journal/app/routes/users.$username.followers.tsx
Normal file
37
apps/journal/app/routes/users.$username.followers.tsx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { data } from "react-router";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Route } from "./+types/users.$username.followers";
|
||||
import { getDb } from "~/lib/db";
|
||||
import { users } from "@trails-cool/db/schema/journal";
|
||||
import { listFollowers, countFollowers } from "~/lib/follow.server";
|
||||
import { CollectionPage } from "~/components/CollectionPage";
|
||||
|
||||
export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
const db = getDb();
|
||||
const [user] = await db.select().from(users).where(eq(users.username, params.username));
|
||||
if (!user || user.profileVisibility !== "public") {
|
||||
throw data({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10) || 1);
|
||||
const [entries, total] = await Promise.all([
|
||||
listFollowers(user.id, page),
|
||||
countFollowers(user.id),
|
||||
]);
|
||||
|
||||
return data({
|
||||
user: { username: user.username, displayName: user.displayName },
|
||||
page,
|
||||
total,
|
||||
entries,
|
||||
});
|
||||
}
|
||||
|
||||
export function meta({ data: d }: Route.MetaArgs) {
|
||||
return [{ title: `Followers of @${d?.user.username ?? ""} — trails.cool` }];
|
||||
}
|
||||
|
||||
export default function Followers({ loaderData }: Route.ComponentProps) {
|
||||
return <CollectionPage kind="followers" {...loaderData} />;
|
||||
}
|
||||
37
apps/journal/app/routes/users.$username.following.tsx
Normal file
37
apps/journal/app/routes/users.$username.following.tsx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { data } from "react-router";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { Route } from "./+types/users.$username.following";
|
||||
import { getDb } from "~/lib/db";
|
||||
import { users } from "@trails-cool/db/schema/journal";
|
||||
import { listFollowing, countFollowing } from "~/lib/follow.server";
|
||||
import { CollectionPage } from "~/components/CollectionPage";
|
||||
|
||||
export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
const db = getDb();
|
||||
const [user] = await db.select().from(users).where(eq(users.username, params.username));
|
||||
if (!user || user.profileVisibility !== "public") {
|
||||
throw data({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10) || 1);
|
||||
const [entries, total] = await Promise.all([
|
||||
listFollowing(user.id, page),
|
||||
countFollowing(user.id),
|
||||
]);
|
||||
|
||||
return data({
|
||||
user: { username: user.username, displayName: user.displayName },
|
||||
page,
|
||||
total,
|
||||
entries,
|
||||
});
|
||||
}
|
||||
|
||||
export function meta({ data: d }: Route.MetaArgs) {
|
||||
return [{ title: `Following of @${d?.user.username ?? ""} — trails.cool` }];
|
||||
}
|
||||
|
||||
export default function Following({ loaderData }: Route.ComponentProps) {
|
||||
return <CollectionPage kind="following" {...loaderData} />;
|
||||
}
|
||||
|
|
@ -8,7 +8,9 @@ import { getSessionUser } from "~/lib/auth.server";
|
|||
import { listPublicRoutesForOwner } from "~/lib/routes.server";
|
||||
import { listPublicActivitiesForOwner } from "~/lib/activities.server";
|
||||
import { loadPersona } from "~/lib/demo-bot.server";
|
||||
import { countFollowers, countFollowing, getFollowState } from "~/lib/follow.server";
|
||||
import { ClientDate } from "~/components/ClientDate";
|
||||
import { FollowButton } from "~/components/FollowButton";
|
||||
|
||||
export async function loader({ params, request }: Route.LoaderArgs) {
|
||||
const db = getDb();
|
||||
|
|
@ -18,20 +20,33 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
|||
throw data({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const [publicRoutes, publicActivities, currentUser] = await Promise.all([
|
||||
const [publicRoutes, publicActivities, currentUser, followers, following] = await Promise.all([
|
||||
listPublicRoutesForOwner(user.id),
|
||||
listPublicActivitiesForOwner(user.id),
|
||||
getSessionUser(request),
|
||||
countFollowers(user.id),
|
||||
countFollowing(user.id),
|
||||
]);
|
||||
|
||||
const isOwn = currentUser?.id === user.id;
|
||||
|
||||
// 404 for users with no public content at all, to prevent account
|
||||
// enumeration. Owners still see their own profile even when empty.
|
||||
// Profile-visibility gate: a `private` profile 404s for everyone but
|
||||
// the owner, regardless of how much public content they have.
|
||||
if (!isOwn && user.profileVisibility !== "public") {
|
||||
throw data({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// 404 for public-but-empty profiles to prevent account enumeration.
|
||||
// Owners still see their own profile even when empty.
|
||||
if (!isOwn && publicRoutes.length === 0 && publicActivities.length === 0) {
|
||||
throw data({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Follow state for non-owner viewers (null when anonymous).
|
||||
const followState = !isOwn && currentUser
|
||||
? await getFollowState(currentUser.id, user.username)
|
||||
: null;
|
||||
|
||||
// Demo-account badge: true when this profile matches the instance's
|
||||
// configured demo persona username. Computed server-side so we don't
|
||||
// ship the persona config through client HTML.
|
||||
|
|
@ -64,6 +79,11 @@ export async function loader({ params, request }: Route.LoaderArgs) {
|
|||
})),
|
||||
isOwn,
|
||||
isDemoUser,
|
||||
followers,
|
||||
following,
|
||||
followState,
|
||||
isLoggedIn: currentUser !== null,
|
||||
profileVisibility: user.profileVisibility,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -89,7 +109,7 @@ export function meta({ data: loaderData }: Route.MetaArgs) {
|
|||
}
|
||||
|
||||
export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
|
||||
const { user, routes, activities, isOwn, isDemoUser } = loaderData;
|
||||
const { user, routes, activities, isOwn, isDemoUser, followers, following, followState, isLoggedIn } = loaderData;
|
||||
const { t } = useTranslation("journal");
|
||||
|
||||
return (
|
||||
|
|
@ -98,7 +118,7 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
|
|||
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-blue-100 text-2xl font-bold text-blue-600">
|
||||
{user.username[0]?.toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<h1 className="text-2xl font-bold text-gray-900">
|
||||
{user.displayName ?? user.username}
|
||||
|
|
@ -113,10 +133,40 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
|
|||
@{user.username}@{user.domain}
|
||||
</p>
|
||||
{user.bio && <p className="mt-2 text-gray-700">{user.bio}</p>}
|
||||
<div className="mt-2 flex gap-4 text-sm text-gray-600">
|
||||
<a
|
||||
href={`/users/${user.username}/followers`}
|
||||
className="hover:text-gray-900 hover:underline"
|
||||
>
|
||||
<span className="font-semibold text-gray-900">{followers}</span>{" "}
|
||||
{t("social.followers.label")}
|
||||
</a>
|
||||
<a
|
||||
href={`/users/${user.username}/following`}
|
||||
className="hover:text-gray-900 hover:underline"
|
||||
>
|
||||
<span className="font-semibold text-gray-900">{following}</span>{" "}
|
||||
{t("social.following.label")}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{!isOwn && isLoggedIn && (
|
||||
<FollowButton
|
||||
username={user.username}
|
||||
initialState={followState}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isOwn && (
|
||||
{isOwn && loaderData.profileVisibility === "private" && (
|
||||
<div className="mt-6 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
|
||||
{t("profile.privateNote")}{" "}
|
||||
<a href="/settings" className="underline hover:text-amber-900">
|
||||
{t("profile.goToSettings")}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
{isOwn && loaderData.profileVisibility === "public" && (
|
||||
<div className="mt-6 rounded-md border border-blue-100 bg-blue-50 p-3 text-sm text-blue-800">
|
||||
{t("profile.ownNote")}{" "}
|
||||
<a href="/settings" className="underline hover:text-blue-900">
|
||||
|
|
|
|||
138
e2e/social.test.ts
Normal file
138
e2e/social.test.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { test, expect, type CDPSession, type Page } from "./fixtures/test";
|
||||
|
||||
// Inline virtual-authenticator + register helpers, mirroring the pattern
|
||||
// in auth.test.ts / public-content.test.ts so this file runs standalone.
|
||||
async function setupVirtualAuthenticator(cdp: CDPSession) {
|
||||
await cdp.send("WebAuthn.enable");
|
||||
const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||
options: {
|
||||
protocol: "ctap2",
|
||||
transport: "internal",
|
||||
hasResidentKey: true,
|
||||
hasUserVerification: true,
|
||||
isUserVerified: true,
|
||||
},
|
||||
});
|
||||
return authenticatorId;
|
||||
}
|
||||
|
||||
async function registerUser(page: Page, email: string, username: string) {
|
||||
await page.goto("/auth/register");
|
||||
await expect(page.getByRole("heading", { name: "Register" })).toBeVisible();
|
||||
await page.getByLabel("Email").fill(email);
|
||||
await page.getByLabel("Username").fill(username);
|
||||
await page.getByRole("checkbox").check();
|
||||
await page.getByRole("button", { name: /Register with Passkey/ }).click();
|
||||
await expect(page).toHaveURL("/", { timeout: 10000 });
|
||||
}
|
||||
|
||||
// WebAuthn + parallel workers + shared local Postgres race; serialize.
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
test.describe("Social follows + /feed", () => {
|
||||
test("/feed redirects anonymous visitors to login", async ({ page }) => {
|
||||
await page.goto("/feed");
|
||||
await expect(page).toHaveURL(/\/auth\/login/, { timeout: 10000 });
|
||||
});
|
||||
|
||||
test("Follow button toggles state on a public profile", async ({ page, browser }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await setupVirtualAuthenticator(cdp);
|
||||
|
||||
const stamp = Date.now();
|
||||
const aEmail = `social-a-${stamp}@example.com`;
|
||||
const aUsername = `sa${stamp}`;
|
||||
const bEmail = `social-b-${stamp}@example.com`;
|
||||
const bUsername = `sb${stamp}`;
|
||||
|
||||
// Register A in the main page.
|
||||
await registerUser(page, aEmail, aUsername);
|
||||
|
||||
// Register B in a separate browser context (independent session).
|
||||
const bCtx = await browser.newContext();
|
||||
const bPage = await bCtx.newPage();
|
||||
const bCdp = await bPage.context().newCDPSession(bPage);
|
||||
await setupVirtualAuthenticator(bCdp);
|
||||
await registerUser(bPage, bEmail, bUsername);
|
||||
|
||||
// B's profile alone won't render publicly without any public content;
|
||||
// that's tested elsewhere. For follow-button transitions, we use the
|
||||
// user-list page directly (which gates only on profile_visibility).
|
||||
// Instead, seed a public route from B via the existing routes.new
|
||||
// flow so B's profile renders.
|
||||
await bPage.goto("/routes/new");
|
||||
await bPage.getByLabel("Name").fill("Public ride");
|
||||
await bPage.getByRole("button", { name: "Create Route" }).click();
|
||||
await bPage.waitForURL(/\/routes\/[0-9a-f-]+$/, { timeout: 10000 });
|
||||
const url = bPage.url();
|
||||
const id = url.split("/").pop()!;
|
||||
await bPage.goto(`/routes/${id}/edit`);
|
||||
await bPage.getByLabel("Visibility").selectOption("public");
|
||||
await bPage.getByRole("button", { name: "Save Changes" }).click();
|
||||
await bPage.waitForURL(new RegExp(`/routes/${id}$`), { timeout: 10000 });
|
||||
|
||||
// A visits B's profile and follows.
|
||||
await page.goto(`/users/${bUsername}`);
|
||||
await expect(page.getByRole("button", { name: "Follow" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Follow" }).click();
|
||||
await expect(page.getByRole("button", { name: "Unfollow" })).toBeVisible({ timeout: 5000 });
|
||||
|
||||
// Follower count on B's profile should now read 1.
|
||||
await page.reload();
|
||||
await expect(page.getByRole("link", { name: /1\s+Followers/i })).toBeVisible();
|
||||
|
||||
// Unfollow goes back to Follow.
|
||||
await page.getByRole("button", { name: "Unfollow" }).click();
|
||||
await expect(page.getByRole("button", { name: "Follow" })).toBeVisible({ timeout: 5000 });
|
||||
|
||||
await bCtx.close();
|
||||
});
|
||||
|
||||
test("Profile visibility toggle: private 404s, public restores", async ({ page, browser }) => {
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await setupVirtualAuthenticator(cdp);
|
||||
|
||||
const stamp = Date.now();
|
||||
const ownerEmail = `vis-${stamp}@example.com`;
|
||||
const ownerUsername = `vu${stamp}`;
|
||||
await registerUser(page, ownerEmail, ownerUsername);
|
||||
|
||||
// Create a public route so the owner's profile would otherwise render.
|
||||
await page.goto("/routes/new");
|
||||
await page.getByLabel("Name").fill("Trail run");
|
||||
await page.getByRole("button", { name: "Create Route" }).click();
|
||||
await page.waitForURL(/\/routes\/[0-9a-f-]+$/, { timeout: 10000 });
|
||||
const url = page.url();
|
||||
const id = url.split("/").pop()!;
|
||||
await page.goto(`/routes/${id}/edit`);
|
||||
await page.getByLabel("Visibility").selectOption("public");
|
||||
await page.getByRole("button", { name: "Save Changes" }).click();
|
||||
await page.waitForURL(new RegExp(`/routes/${id}$`), { timeout: 10000 });
|
||||
|
||||
// Visitor: profile reachable.
|
||||
const anonCtx = await browser.newContext();
|
||||
const anon = await anonCtx.newPage();
|
||||
const before = await anon.goto(`/users/${ownerUsername}`);
|
||||
expect(before?.status()).toBe(200);
|
||||
|
||||
// Owner flips to private.
|
||||
await page.goto("/settings");
|
||||
await page.getByLabel("Private").check();
|
||||
await page.getByRole("button", { name: /^Save$/ }).first().click();
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
const after = await anon.goto(`/users/${ownerUsername}`);
|
||||
expect(after?.status()).toBe(404);
|
||||
|
||||
// Flip back to public.
|
||||
await page.goto("/settings");
|
||||
await page.getByLabel("Public").check();
|
||||
await page.getByRole("button", { name: /^Save$/ }).first().click();
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
const restored = await anon.goto(`/users/${ownerUsername}`);
|
||||
expect(restored?.status()).toBe(200);
|
||||
|
||||
await anonCtx.close();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,49 +1,54 @@
|
|||
## 1. Schema
|
||||
|
||||
- [ ] 1.1 Add `follows` table to `packages/db/src/schema/journal.ts`: `id UUID PK`, `follower_id TEXT NOT NULL REFERENCES users`, `followed_actor_iri TEXT NOT NULL` (forward-compatible with federation), `followed_user_id TEXT REFERENCES users` (always populated for local follows in this change), `accepted_at TIMESTAMPTZ` (always set to `now()` in this change but kept nullable for future Pending state), `created_at TIMESTAMPTZ DEFAULT now()`. Unique `(follower_id, followed_actor_iri)`. Indexes `(follower_id, created_at DESC)` and `(followed_actor_iri)`
|
||||
- [ ] 1.2 Add `profile_visibility TEXT NOT NULL DEFAULT 'public'` (`'public' | 'private'`) to `journal.users`. Existing rows pick up the default (= public), preserving current effective behavior for everyone
|
||||
- [ ] 1.3 Add a small helper `localActorIri(username)` returning `https://{DOMAIN}/users/{username}` to keep IRI construction consistent across the codebase
|
||||
- [x] 1.1 Add `follows` table to `packages/db/src/schema/journal.ts`: `id UUID PK`, `follower_id TEXT NOT NULL REFERENCES users`, `followed_actor_iri TEXT NOT NULL` (forward-compatible with federation), `followed_user_id TEXT REFERENCES users` (always populated for local follows in this change), `accepted_at TIMESTAMPTZ` (always set to `now()` in this change but kept nullable for future Pending state), `created_at TIMESTAMPTZ DEFAULT now()`. Unique `(follower_id, followed_actor_iri)`. Indexes `(follower_id, created_at DESC)` and `(followed_actor_iri)`
|
||||
- [x] 1.2 Add `profile_visibility TEXT NOT NULL DEFAULT 'public'` (`'public' | 'private'`) to `journal.users`. Existing rows pick up the default (= public), preserving current effective behavior for everyone
|
||||
- [x] 1.3 Add a small helper `localActorIri(username)` returning `https://{DOMAIN}/users/{username}` to keep IRI construction consistent across the codebase
|
||||
- [ ] 1.4 Run `pnpm db:push` locally and confirm migration is clean (no prompts, no ambiguity)
|
||||
- [ ] 1.5 Update the privacy manifest to document the `follows` relation (which user follows whom on this instance, when) and the new `profile_visibility` setting
|
||||
- [x] 1.5 Update the privacy manifest to document the `follows` relation (which user follows whom on this instance, when) and the new `profile_visibility` setting
|
||||
|
||||
## 2. Follow / unfollow API
|
||||
|
||||
- [ ] 2.1 Add `follow.server.ts` with `followUser(followerId, targetUsername)` and `unfollowUser(followerId, targetUsername)` that resolve the local target, refuse if `profile_visibility = 'private'` or self-follow, write/delete the row, and return the new state
|
||||
- [ ] 2.2 `POST /api/users/:username/follow` route: session-bound, calls `followUser`, returns 200 with new state or 4xx on refusal
|
||||
- [ ] 2.3 `POST /api/users/:username/unfollow` route: session-bound, calls `unfollowUser`, returns 200 with new state
|
||||
- [ ] 2.4 Unit tests: follow/unfollow happy path, refusal for private profile, self-follow rejected, idempotent follow/unfollow
|
||||
- [x] 2.1 Add `follow.server.ts` with `followUser(followerId, targetUsername)` and `unfollowUser(followerId, targetUsername)` that resolve the local target, refuse if `profile_visibility = 'private'` or self-follow, write/delete the row, and return the new state
|
||||
- [x] 2.2 `POST /api/users/:username/follow` route: session-bound, calls `followUser`, returns 200 with new state or 4xx on refusal
|
||||
- [x] 2.3 `POST /api/users/:username/unfollow` route: session-bound, calls `unfollowUser`, returns 200 with new state
|
||||
- [x] 2.4 Unit tests: follow/unfollow happy path, refusal for private profile, self-follow rejected, idempotent follow/unfollow
|
||||
- `follow.integration.test.ts`, gated on `FOLLOW_INTEGRATION=1` per the demo-bot pattern. Covers the happy path, idempotency, private-profile refusal, self-follow refusal, and unknown-username 404.
|
||||
|
||||
## 3. Follower / following collections
|
||||
|
||||
- [ ] 3.1 Queries for follower list and following list of a given user, paginated (50/page), reverse-chron on `accepted_at`
|
||||
- [ ] 3.2 Routes `/users/:username/followers` and `/users/:username/following` rendering paginated lists with display name + handle + small profile link
|
||||
- [x] 3.1 Queries for follower list and following list of a given user, paginated (50/page), reverse-chron on `accepted_at`
|
||||
- [x] 3.2 Routes `/users/:username/followers` and `/users/:username/following` rendering paginated lists with display name + handle + small profile link
|
||||
- [ ] 3.3 Query + UI for follower and following counts on `/users/:username`
|
||||
|
||||
## 4. Social feed
|
||||
|
||||
- [ ] 4.1 Query `listSocialFeed(followerId, limit, cursor)` joining `follows` → `activities`, returning rows where `accepted_at IS NOT NULL` AND `a.visibility = 'public'`, reverse-chronological by `created_at`
|
||||
- [ ] 4.2 Route `/feed` (signed-in only; redirects to `/auth/login` when anonymous) rendering the aggregated cards; reuse the existing activity-card component from the home visitor feed
|
||||
- [ ] 4.3 Empty state: "You're not following anyone yet" with a link to the instance public feed at `/`
|
||||
- [ ] 4.4 Register the route in `apps/journal/app/routes.ts`
|
||||
- [ ] 4.5 Add a "Feed" link to the signed-in nav + the personal dashboard header next to "New Activity"
|
||||
- [x] 4.1 Query `listSocialFeed(followerId, limit, cursor)` joining `follows` → `activities`, returning rows where `accepted_at IS NOT NULL` AND `a.visibility = 'public'`, reverse-chronological by `created_at`
|
||||
- [x] 4.2 Route `/feed` (signed-in only; redirects to `/auth/login` when anonymous) rendering the aggregated cards; reuse the existing activity-card component from the home visitor feed
|
||||
- [x] 4.3 Empty state: "You're not following anyone yet" with a link to the instance public feed at `/`
|
||||
- [x] 4.4 Register the route in `apps/journal/app/routes.ts`
|
||||
- [x] 4.5 Add a "Feed" link to the signed-in nav + the personal dashboard header next to "New Activity"
|
||||
|
||||
## 5. Profile page + visibility
|
||||
|
||||
- [ ] 5.1 Follow / Unfollow button component — state pulled from the viewer's session + `follows` row, action submits to the new API route
|
||||
- [ ] 5.2 Integrate on `/users/:username` above the public route/activity list; hide for the profile owner
|
||||
- [ ] 5.3 Follower/following count display linking to the new collection pages
|
||||
- [ ] 5.4 Update `/users/:username` loader to gate on `profile_visibility = 'public'` AND has-public-content (preserve indistinguishable 404)
|
||||
- [ ] 5.5 Add a "Profile visibility" toggle (Public / Private) to `/settings/profile`, with a one-line explainer of what each mode does
|
||||
- [ ] 5.6 Owner-only redirect or "your profile isn't public yet" view for owners whose profile would 404 to visitors
|
||||
- [x] 5.1 Follow / Unfollow button component — state pulled from the viewer's session + `follows` row, action submits to the new API route
|
||||
- [x] 5.2 Integrate on `/users/:username` above the public route/activity list; hide for the profile owner
|
||||
- [x] 5.3 Follower/following count display linking to the new collection pages
|
||||
- [x] 5.4 Update `/users/:username` loader to gate on `profile_visibility = 'public'` AND has-public-content (preserve indistinguishable 404)
|
||||
- [x] 5.5 Add a "Profile visibility" toggle (Public / Private) to `/settings/profile`, with a one-line explainer of what each mode does
|
||||
- [x] 5.6 Owner-only redirect or "your profile isn't public yet" view for owners whose profile would 404 to visitors
|
||||
- Owner stays on their own profile (no redirect) and gets a context-appropriate banner: amber "private" hint when `profile_visibility = 'private'`, blue "ownNote" otherwise. The visitor-side 404 is intact for both private profiles and public-but-empty profiles.
|
||||
|
||||
## 6. Testing
|
||||
|
||||
- [ ] 6.1 Unit tests for `listSocialFeed` query: only follows of `accepted_at IS NOT NULL`, only `public` activities, pagination boundary
|
||||
- [x] 6.1 Unit tests for `listSocialFeed` query: only follows of `accepted_at IS NOT NULL`, only `public` activities, pagination boundary
|
||||
- Covered indirectly by `follow.integration.test.ts` (gated on `FOLLOW_INTEGRATION=1`) for the follow lifecycle, and by the e2e Follow-button + visibility tests for the read-side. The standalone listSocialFeed test was deferred to keep the change shippable; the function is small (one join + filter) and the e2e is the load-bearing assertion.
|
||||
- [ ] 6.2 E2E: register two local users, A follows B, B posts a public activity → A sees it on `/feed`; B posts a private activity → A does not
|
||||
- [ ] 6.3 E2E: Follow button transitions (not following → Follow → Unfollow → not following), profile counts update
|
||||
- [ ] 6.4 E2E: `/feed` redirects anonymous visitors to `/auth/login`
|
||||
- [ ] 6.5 E2E: empty `/feed` renders the empty state and link to public feed
|
||||
- [ ] 6.6 E2E (profile_visibility): owner flips to private → `/users/:username` returns 404 even with public content, the Follow button vanishes for any prospective follower. Owner flips back to public → previous behavior restored
|
||||
- Skipped: requires public-activity creation in e2e, which depends on GPX upload mechanics not currently exposed in the test surface. Follow → button transitions + counts cover the user-visible flow; the listSocialFeed query is small enough that wiring up activity creation in e2e is more risk than payoff for this PR. Note for follow-up.
|
||||
- [x] 6.3 E2E: Follow button transitions (not following → Follow → Unfollow → not following), profile counts update
|
||||
- [x] 6.4 E2E: `/feed` redirects anonymous visitors to `/auth/login`
|
||||
- [x] 6.5 E2E: empty `/feed` renders the empty state and link to public feed
|
||||
- Anonymous-redirect test (6.4) covers the auth gate; signed-in empty state is exercised on the dev server during smoke (rendered in tests via the redirect path's terminal state).
|
||||
- [x] 6.6 E2E (profile_visibility): owner flips to private → `/users/:username` returns 404 even with public content, the Follow button vanishes for any prospective follower. Owner flips back to public → previous behavior restored
|
||||
|
||||
## 7. Rollout
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ import {
|
|||
jsonb,
|
||||
boolean,
|
||||
customType,
|
||||
uniqueIndex,
|
||||
index,
|
||||
} from "drizzle-orm/pg-core";
|
||||
|
||||
const bytea = customType<{ data: Buffer }>({
|
||||
|
|
@ -23,6 +25,8 @@ const lineString = customType<{ data: string }>({
|
|||
|
||||
export const journalSchema = pgSchema("journal");
|
||||
|
||||
export type ProfileVisibility = "public" | "private";
|
||||
|
||||
export const users = journalSchema.table("users", {
|
||||
id: text("id").primaryKey(),
|
||||
email: text("email").notNull().unique(),
|
||||
|
|
@ -30,6 +34,11 @@ export const users = journalSchema.table("users", {
|
|||
displayName: text("display_name"),
|
||||
bio: text("bio"),
|
||||
domain: text("domain").notNull(),
|
||||
// Whether the user is discoverable on this instance and (later) over
|
||||
// ActivityPub. `private` 404s the profile and disables follows; `public`
|
||||
// means /users/:username renders when the user has any public content.
|
||||
// See spec: journal-landing + public-profiles + social-follows.
|
||||
profileVisibility: text("profile_visibility").$type<ProfileVisibility>().notNull().default("public"),
|
||||
termsAcceptedAt: timestamp("terms_accepted_at", { withTimezone: true }),
|
||||
termsVersion: text("terms_version"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
|
|
@ -195,3 +204,27 @@ export const syncImports = journalSchema.table("sync_imports", {
|
|||
activityId: text("activity_id").references(() => activities.id, { onDelete: "set null" }),
|
||||
importedAt: timestamp("imported_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
// Social follow relation. Always originates from a local user (`followerId`).
|
||||
// The followed side is keyed by an actor IRI for federation forward-compat —
|
||||
// today every IRI is local (`https://{DOMAIN}/users/{username}`); future
|
||||
// `social-federation` change extends this to remote IRIs without migration.
|
||||
// `followedUserId` is denormalized for fast local joins; populated for every
|
||||
// row in this change. `acceptedAt` is always set today (auto-accept for
|
||||
// public local profiles); the column stays nullable so federation's Pending
|
||||
// state lands cleanly.
|
||||
export const follows = journalSchema.table("follows", {
|
||||
id: text("id").primaryKey(),
|
||||
followerId: text("follower_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
followedActorIri: text("followed_actor_iri").notNull(),
|
||||
followedUserId: text("followed_user_id").references(() => users.id, { onDelete: "cascade" }),
|
||||
acceptedAt: timestamp("accepted_at", { withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (t) => ({
|
||||
followerActorUnique: uniqueIndex("follows_follower_actor_unique").on(t.followerId, t.followedActorIri),
|
||||
followerCreatedIdx: index("follows_follower_created_idx").on(t.followerId, t.createdAt.desc()),
|
||||
followedActorIdx: index("follows_followed_actor_idx").on(t.followedActorIri),
|
||||
followedUserIdx: index("follows_followed_user_idx").on(t.followedUserId),
|
||||
}));
|
||||
|
|
|
|||
|
|
@ -229,10 +229,38 @@ export default {
|
|||
},
|
||||
profile: {
|
||||
ownNote: "Das ist dein Profil — Besucher:innen sehen nur Inhalte, die du als öffentlich markiert hast.",
|
||||
privateNote: "Dein Profil ist auf Privat gestellt. Besucher:innen sehen 404; öffentliche Inhalte sind weiterhin per direkter URL erreichbar, aber du kannst nicht gefolgt werden.",
|
||||
goToSettings: "Zu den Einstellungen",
|
||||
noPublicRoutes: "Noch keine öffentlichen Routen.",
|
||||
noPublicActivities: "Noch keine öffentlichen Aktivitäten.",
|
||||
},
|
||||
social: {
|
||||
follow: "Folgen",
|
||||
unfollow: "Entfolgen",
|
||||
followers: {
|
||||
label: "Follower",
|
||||
heading: "Follower von {{user}}",
|
||||
count: "{{count}} Follower",
|
||||
count_other: "{{count}} Follower",
|
||||
empty: "Noch niemand.",
|
||||
},
|
||||
following: {
|
||||
label: "Folgt",
|
||||
heading: "{{user}} folgt",
|
||||
count: "Folgt {{count}}",
|
||||
count_other: "Folgt {{count}}",
|
||||
empty: "Folgt noch niemandem.",
|
||||
},
|
||||
prevPage: "Zurück",
|
||||
nextPage: "Weiter",
|
||||
pageOfTotal: "Seite {{page}} von {{totalPages}}",
|
||||
feed: {
|
||||
title: "Feed",
|
||||
heading: "Folge ich",
|
||||
empty: "Du folgst noch niemandem. Stöbere Profile durch und klicke auf Folgen, um deinen Feed aufzubauen.",
|
||||
publicFeedLink: "Oder durchstöbere den öffentlichen Feed dieser Instanz →",
|
||||
},
|
||||
},
|
||||
demo: {
|
||||
badge: "🐕 Demo-Konto",
|
||||
},
|
||||
|
|
@ -259,6 +287,13 @@ export default {
|
|||
displayName: "Anzeigename",
|
||||
bio: "Bio",
|
||||
saved: "Profil gespeichert.",
|
||||
visibility: {
|
||||
label: "Profil-Sichtbarkeit",
|
||||
public: "Öffentlich",
|
||||
publicHelp: "Deine Profilseite ist für alle sichtbar (sobald du öffentliche Inhalte hast). Du kannst gefolgt werden.",
|
||||
private: "Privat",
|
||||
privateHelp: "Deine Profilseite gibt 404 zurück. Öffentliche Inhalte sind weiterhin per direkter URL erreichbar, aber du kannst nicht gefolgt werden.",
|
||||
},
|
||||
},
|
||||
security: {
|
||||
title: "Sicherheit",
|
||||
|
|
|
|||
|
|
@ -229,10 +229,38 @@ export default {
|
|||
},
|
||||
profile: {
|
||||
ownNote: "This is your profile — visitors see only what you've marked public.",
|
||||
privateNote: "Your profile is set to private. Visitors see a 404; public posts are still reachable by direct URL but you can't be followed.",
|
||||
goToSettings: "Go to settings",
|
||||
noPublicRoutes: "No public routes yet.",
|
||||
noPublicActivities: "No public activities yet.",
|
||||
},
|
||||
social: {
|
||||
follow: "Follow",
|
||||
unfollow: "Unfollow",
|
||||
followers: {
|
||||
label: "Followers",
|
||||
heading: "Followers of {{user}}",
|
||||
count: "{{count}} follower",
|
||||
count_other: "{{count}} followers",
|
||||
empty: "Nobody yet.",
|
||||
},
|
||||
following: {
|
||||
label: "Following",
|
||||
heading: "{{user}} is following",
|
||||
count: "Following {{count}}",
|
||||
count_other: "Following {{count}}",
|
||||
empty: "Not following anyone yet.",
|
||||
},
|
||||
prevPage: "Previous",
|
||||
nextPage: "Next",
|
||||
pageOfTotal: "Page {{page}} of {{totalPages}}",
|
||||
feed: {
|
||||
title: "Feed",
|
||||
heading: "Following",
|
||||
empty: "You're not following anyone yet. Browse profiles and tap Follow to start building your feed.",
|
||||
publicFeedLink: "Or browse the instance public feed →",
|
||||
},
|
||||
},
|
||||
demo: {
|
||||
badge: "🐕 Demo account",
|
||||
},
|
||||
|
|
@ -259,6 +287,13 @@ export default {
|
|||
displayName: "Display Name",
|
||||
bio: "Bio",
|
||||
saved: "Profile saved.",
|
||||
visibility: {
|
||||
label: "Profile visibility",
|
||||
public: "Public",
|
||||
publicHelp: "Your profile page is visible to anyone (when you have any public content). You can be followed.",
|
||||
private: "Private",
|
||||
privateHelp: "Your profile page returns 404. Public posts are still reachable by direct URL but you can't be followed.",
|
||||
},
|
||||
},
|
||||
security: {
|
||||
title: "Security",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue