feat: user profiles, subscriptions, and subscription feed
Some checks failed
CI / Scraper / Lint (push) Failing after 8s
CI / Scraper / Test (push) Successful in 11s
CI / Scraper / Lint (pull_request) Failing after 7s
CI / Scraper / Test (pull_request) Successful in 9s
CI / Scraper / Docker Push (push) Has been skipped
CI / Scraper / Docker Push (pull_request) Has been skipped
CI / UI / Build (push) Successful in 23s
CI / UI / Build (pull_request) Successful in 22s
CI / UI / Docker Push (pull_request) Has been skipped
CI / UI / Docker Push (push) Successful in 32s
iOS CI / Build (pull_request) Successful in 1m52s
iOS CI / Test (pull_request) Successful in 3m50s

- PocketBase: new user_subscriptions collection (follower_id, followee_id)
- pocketbase.ts: subscribe/unsubscribe/getFollowingIds/getPublicProfile/
  getUserPublicLibrary/getUserCurrentlyReading/getSubscriptionFeed helpers
- GET /api/users/[username] — public profile with subscription state
- POST/DELETE /api/users/[username]/subscribe — follow/unfollow
- /users/[username] — public profile page: avatar, stats, follow button,
  currently reading grid, full library grid
- CommentsSection: usernames are now links to /users/[username]
- Home page: 'From People You Follow' section powered by subscription feed
This commit is contained in:
Admin
2026-03-10 22:27:18 +05:00
parent 8d4bba7964
commit b5bc6ff3de
9 changed files with 689 additions and 3 deletions

View File

@@ -1079,3 +1079,231 @@ export async function getMyVotes(
}
return map;
}
// ─── User subscriptions ───────────────────────────────────────────────────────
export interface UserSubscription {
id: string;
follower_id: string;
followee_id: string;
created: string;
}
/**
* Returns the subscription record if follower_id follows followee_id, else null.
*/
export async function getSubscription(
followerId: string,
followeeId: string
): Promise<UserSubscription | null> {
const filter = encodeURIComponent(`follower_id="${followerId}"&&followee_id="${followeeId}"`);
const res = await pbGet<{ items: UserSubscription[]; totalItems: number }>(
`/api/collections/user_subscriptions/records?filter=${filter}&perPage=1`
).catch(() => null);
return res?.items?.[0] ?? null;
}
/**
* Subscribe follower_id to followee_id. No-ops if already subscribed.
* Returns the subscription record.
*/
export async function subscribe(followerId: string, followeeId: string): Promise<void> {
const existing = await getSubscription(followerId, followeeId);
if (existing) return;
const res = await pbPost('/api/collections/user_subscriptions/records', {
follower_id: followerId,
followee_id: followeeId,
created: new Date().toISOString()
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`Failed to subscribe: ${res.status}${body}`);
}
}
/**
* Unsubscribe follower_id from followee_id. No-ops if not subscribed.
*/
export async function unsubscribe(followerId: string, followeeId: string): Promise<void> {
const existing = await getSubscription(followerId, followeeId);
if (!existing) return;
const token = await getToken();
await fetch(`${PB_URL}/api/collections/user_subscriptions/records/${existing.id}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` }
});
}
/**
* Returns the list of user IDs that followerId is subscribed to.
*/
export async function getFollowingIds(followerId: string): Promise<string[]> {
const items = await listAll<UserSubscription>(
'user_subscriptions',
`follower_id="${followerId}"`,
'-created'
).catch(() => [] as UserSubscription[]);
return items.map((s) => s.followee_id);
}
/**
* Returns the count of subscribers (followers) for a given user.
*/
export async function getFollowerCount(followeeId: string): Promise<number> {
return countCollection('user_subscriptions', `followee_id="${followeeId}"`).catch(() => 0);
}
/**
* Returns the count of accounts a user is following.
*/
export async function getFollowingCount(followerId: string): Promise<number> {
return countCollection('user_subscriptions', `follower_id="${followerId}"`).catch(() => 0);
}
/**
* Public profile data for a user.
*/
export interface PublicProfile {
id: string;
username: string;
avatar_url?: string;
created: string;
followerCount: number;
followingCount: number;
}
/**
* Returns a user's public profile (no sensitive fields) by username.
*/
export async function getPublicProfile(username: string): Promise<PublicProfile | null> {
const user = await getUserByUsername(username);
if (!user) return null;
const [followerCount, followingCount] = await Promise.all([
getFollowerCount(user.id),
getFollowingCount(user.id)
]);
return {
id: user.id,
username: user.username,
avatar_url: user.avatar_url,
created: user.created,
followerCount,
followingCount
};
}
/**
* Returns a user's public library: books they have saved or are reading.
* Only includes books with progress or explicit saves (user_library).
*/
export async function getUserPublicLibrary(
userId: string
): Promise<Array<{ book: Book; chapter: number | null; saved: boolean }>> {
const [allBooks, progressList, savedEntries] = await Promise.all([
listBooks(),
listAll<Progress>('progress', `user_id="${userId}"`, '-updated').catch(() => [] as Progress[]),
listAll<{ id: string; slug: string; saved_at: string }>(
'user_library',
`user_id="${userId}"`,
'-saved_at'
).catch(() => [] as { id: string; slug: string; saved_at: string }[])
]);
const bookMap = new Map<string, Book>(allBooks.map((b) => [b.slug, b]));
const result: Array<{ book: Book; chapter: number | null; saved: boolean }> = [];
const seen = new Set<string>();
// Books with progress first (most recently read)
for (const p of progressList) {
const book = bookMap.get(p.slug);
if (!book || seen.has(p.slug)) continue;
seen.add(p.slug);
result.push({ book, chapter: p.chapter, saved: false });
}
// Saved-only books next
for (const e of savedEntries) {
const book = bookMap.get(e.slug);
if (!book || seen.has(e.slug)) continue;
seen.add(e.slug);
result.push({ book, chapter: null, saved: true });
}
// Mark saved flag for books that are both in progress AND saved
const savedSlugs = new Set(savedEntries.map((e) => e.slug));
return result.map((r) => ({ ...r, saved: savedSlugs.has(r.book.slug) }));
}
/**
* Returns the currently-reading books (books with progress, not completed)
* for a given user ID.
*/
export async function getUserCurrentlyReading(
userId: string
): Promise<Array<{ book: Book; chapter: number }>> {
const [allBooks, progressList] = await Promise.all([
listBooks(),
listAll<Progress>('progress', `user_id="${userId}"`, '-updated').catch(() => [] as Progress[])
]);
const bookMap = new Map<string, Book>(allBooks.map((b) => [b.slug, b]));
return progressList
.filter((p) => {
const book = bookMap.get(p.slug);
return book && p.chapter > 0 && p.chapter < book.total_chapters;
})
.slice(0, 10)
.map((p) => ({ book: bookMap.get(p.slug)!, chapter: p.chapter }));
}
/**
* Returns recently-updated books from ALL users that followerId is subscribed to.
* Deduplicates across followed users; sorts by most recently updated.
*/
export async function getSubscriptionFeed(
followerId: string,
limit = 12
): Promise<Array<{ book: Book; readerUsername: string }>> {
const followingIds = await getFollowingIds(followerId);
if (followingIds.length === 0) return [];
// Fetch all users we follow (for display names)
const token = await getToken();
const userFetches = followingIds.map((id) =>
fetch(`${PB_URL}/api/collections/app_users/records/${id}`, {
headers: { Authorization: `Bearer ${token}` }
})
.then((r) => (r.ok ? (r.json() as Promise<User>) : null))
.catch(() => null)
);
const users = (await Promise.all(userFetches)).filter(Boolean) as User[];
const userMap = new Map<string, User>(users.map((u) => [u.id, u]));
// Fetch progress for each followed user
const progressFetches = followingIds.map((id) =>
listAll<Progress>('progress', `user_id="${id}"`, '-updated').catch(() => [] as Progress[])
);
const allProgressArrays = await Promise.all(progressFetches);
const allBooks = await listBooks();
const bookMap = new Map<string, Book>(allBooks.map((b) => [b.slug, b]));
// Merge: per slug take the most-recent progress entry
const seen = new Set<string>();
const feed: Array<{ book: Book; readerUsername: string; updated: string }> = [];
for (let i = 0; i < followingIds.length; i++) {
const uid = followingIds[i];
const username = userMap.get(uid)?.username ?? 'unknown';
for (const p of allProgressArrays[i]) {
if (seen.has(p.slug)) continue;
const book = bookMap.get(p.slug);
if (!book) continue;
seen.add(p.slug);
feed.push({ book, readerUsername: username, updated: p.updated });
}
}
// Sort by most recently read across all followed users
feed.sort((a, b) => b.updated.localeCompare(a.updated));
return feed.slice(0, limit).map(({ book, readerUsername }) => ({ book, readerUsername }));
}