Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

refactor(analytics): services for YouTube, Instagram and Reddit analytics

spacesdrive3bce9808b608
diff --git a/backend/container.ts b/backend/container.ts
index 32b4024..cff7a7b 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -1,7 +1,13 @@
import { createAccountRepository } from './repositories/accountRepository.ts';
import { createAnalyticsCacheRepository } from './repositories/analyticsCacheRepository.ts';
import { createAccountService } from './services/accountService.ts';
+import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
+import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
+import { createRedditAnalyticsService } from './services/redditAnalyticsService.ts';
import type { AccountService } from './services/accountService.ts';
+import type { YouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
+import type { InstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
+import type { RedditAnalyticsService } from './services/redditAnalyticsService.ts';
import type { AppConfig } from './lib/config.ts';
import type { RequestContext } from './types/context.ts';
import type { Redis, SupabaseClient } from './types/app.ts';
@@ -13,6 +19,9 @@ export interface Clients {
export interface Services {
accounts: AccountService;
+ youtubeAnalytics: YouTubeAnalyticsService;
+ instagramAnalytics: InstagramAnalyticsService;
+ redditAnalytics: RedditAnalyticsService;
}
// the composition root: wires repositories into services for one request or one cron run; building them is cheap
@@ -21,5 +30,8 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
const cache = createAnalyticsCacheRepository(clients.redis);
return {
accounts: createAccountService({ accounts, cache, config, context }),
+ youtubeAnalytics: createYouTubeAnalyticsService({ accounts, cache, config, context }),
+ instagramAnalytics: createInstagramAnalyticsService({ accounts, cache, context }),
+ redditAnalytics: createRedditAnalyticsService({ accounts, cache, context }),
};
}
diff --git a/backend/controllers/analyticsController.ts b/backend/controllers/analyticsController.ts
new file mode 100644
index 0000000..4a46569
--- /dev/null
+++ b/backend/controllers/analyticsController.ts
@@ -0,0 +1,37 @@
+import { controller, pathParam, servicesFor } from './http.ts';
+import { queryParams } from '../middleware/validate.ts';
+import { parseVideoLibraryQuery } from '../validators/analyticsValidators.ts';
+import type {
+ YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeLibraryResponse, YouTubeVideosResponse,
+} from '../../shared/types/youtube.ts';
+import type { InstagramAnalyticsResponse, InstagramMediaResponse } from '../../shared/types/instagram.ts';
+
+export const getChannelAnalytics = controller.createHandlers(async c => {
+ const result = await servicesFor(c).youtubeAnalytics.channelAnalytics(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, ...result } satisfies YouTubeAnalyticsPayload);
+});
+
+export const getChannelVideos = controller.createHandlers(async c => {
+ const result = await servicesFor(c).youtubeAnalytics.channelVideos(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, ...result } satisfies YouTubeVideosResponse);
+});
+
+export const getComparison = controller.createHandlers(async c => {
+ const comparison = await servicesFor(c).youtubeAnalytics.comparison(c.get('userId'));
+ return c.json({ success: true, comparison } satisfies YouTubeComparisonResponse);
+});
+
+export const getVideoLibrary = controller.createHandlers(queryParams(parseVideoLibraryQuery), async c => {
+ const { videos, channels } = await servicesFor(c).youtubeAnalytics.videoLibrary(c.get('userId'), c.req.valid('query'));
+ return c.json({ success: true, videos, total: videos.length, channels } satisfies YouTubeLibraryResponse);
+});
+
+export const getInstagramAnalytics = controller.createHandlers(async c => {
+ const result = await servicesFor(c).instagramAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, ...result } satisfies InstagramAnalyticsResponse);
+});
+
+export const getInstagramMedia = controller.createHandlers(async c => {
+ const result = await servicesFor(c).instagramAnalytics.media(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, ...result } satisfies InstagramMediaResponse);
+});
diff --git a/backend/controllers/redditController.ts b/backend/controllers/redditController.ts
new file mode 100644
index 0000000..f7f030a
--- /dev/null
+++ b/backend/controllers/redditController.ts
@@ -0,0 +1,12 @@
+import { controller, pathParam, servicesFor } from './http.ts';
+import type { RedditCacheData, RedditPost } from '../../shared/types/reddit.ts';
+
+export const getRedditAnalytics = controller.createHandlers(async c => {
+ const result = await servicesFor(c).redditAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));
+ return c.json(result satisfies RedditCacheData);
+});
+
+export const getRedditPosts = controller.createHandlers(async c => {
+ const posts = await servicesFor(c).redditAnalytics.posts(c.get('userId'), pathParam(c, 'id'));
+ return c.json(posts satisfies RedditPost[]);
+});
diff --git a/backend/routes/analytics.ts b/backend/routes/analytics.ts
deleted file mode 100644
index 93727ff..0000000
--- a/backend/routes/analytics.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-import { Hono } from 'hono';
-import { safeAccount } from '../lib/safeAccount.ts';
-import { getAccounts, getAccountById, updateAccount } from '../lib/db.ts';
-import { getVideosCache, setVideosCache, getIGCache, setIGCache } from '../lib/cache.ts';
-import { fetchAllVideos } from '../services/youtube/youtubeVideos.ts';
-import { computeVideoAnalytics } from '../services/youtube/youtubeAnalytics.ts';
-import { fetchInstagramProfile } from '../services/instagram/instagramApi.ts';
-import { fetchInstagramMedia } from '../services/instagram/instagramMedia.ts';
-import { computeInstagramAnalytics } from '../services/instagram/instagramAnalytics.ts';
-import { channelMetrics, accountComparison, filterAndSortVideos } from '../services/youtube/youtubeLibrary.ts';
-import { backfillChannelData } from '../services/accountRefresh.ts';
-import type { AppEnv, Redis, SupabaseClient } from '../types/app.ts';
-import type { Account } from '../../shared/types/domain.ts';
-import type {
- YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeLibraryResponse, YouTubeLibraryVideo, YouTubeVideosResponse,
-} from '../../shared/types/youtube.ts';
-import type {
- InstagramAnalyticsResponse, InstagramMedia, InstagramMediaResponse, InstagramProfile,
-} from '../../shared/types/instagram.ts';
-
-interface SnapshotScope {
- supabase: SupabaseClient;
- redis: Redis | null;
- userId: string;
- id: string;
-}
-
-const NO_PLAYLIST_MESSAGE = 'No uploads playlist stored - delete this channel and add it again';
-
-const app = new Hono<AppEnv>();
-
-// api errors can echo request urls that carry the api key or access token
-function redactUrls(message: string): string {
- return message.replace(/https?:\/\/[^\s)]+/g, '[url]');
-}
-
-async function storeInstagramSnapshot(
- { supabase, redis, userId, id }: SnapshotScope, account: Account, profile: InstagramProfile, media: InstagramMedia[],
-): Promise<void> {
- await Promise.all([
- setIGCache(redis, userId, id, { media, fetchedAt: new Date().toISOString() }),
- updateAccount(supabase, account.id, {
- followersCount: profile.followersCount,
- followsCount: profile.followsCount,
- mediaCount: profile.mediaCount,
- profilePictureUrl: profile.profilePictureUrl,
- lastUpdated: new Date().toISOString(),
- }, userId),
- ]);
-}
-
-app.get('/accounts/:id/analytics', async (c) => {
- try {
- const supabase = c.get('supabase');
- const userId = c.get('userId');
- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();
- if (!apiKey) return c.json({ success: false, message: 'No API key' }, 400);
-
- const account = await getAccountById(supabase, c.req.param('id'), userId);
- if (!account || account.platform !== 'youtube') return c.json({ success: false, message: 'YouTube channel not found' }, 404);
- if (!account.uploadsPlaylistId) return c.json({ success: false, message: NO_PLAYLIST_MESSAGE }, 400);
-
- const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);
- await setVideosCache(c.get('redis'), userId, c.req.param('id'), { videos, fetchedAt: new Date().toISOString() });
- const analytics = computeVideoAnalytics(videos);
-
- if (!account.publishedAt) await backfillChannelData(supabase, account, apiKey, userId);
-
- return c.json({
- success: true,
- channel: { ...account, ...channelMetrics(account) },
- analytics,
- videoCount: videos.length,
- } satisfies YouTubeAnalyticsPayload);
- } catch (err) {
- return c.json({ success: false, message: redactUrls((err as Error).message) }, 400);
- }
-});
-
-app.get('/accounts/:id/videos', async (c) => {
- try {
- const supabase = c.get('supabase');
- const redis = c.get('redis');
- const userId = c.get('userId');
- const id = c.req.param('id');
-
- const cached = await getVideosCache(redis, userId, id);
- if (cached && cached.videos) {
- return c.json({ success: true, videos: cached.videos, fetchedAt: cached.fetchedAt } satisfies YouTubeVideosResponse);
- }
-
- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();
- if (!apiKey) return c.json({ success: false, message: 'No API key' }, 400);
-
- const account = await getAccountById(supabase, id, userId);
- if (!account || account.platform !== 'youtube') return c.json({ success: false, message: 'YouTube channel not found' }, 404);
- if (!account.uploadsPlaylistId) return c.json({ success: false, message: NO_PLAYLIST_MESSAGE }, 400);
-
- const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);
- const fetchedAt = new Date().toISOString();
- await setVideosCache(redis, userId, id, { videos, fetchedAt });
-
- return c.json({ success: true, videos, fetchedAt } satisfies YouTubeVideosResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 400);
- }
-});
-
-app.get('/comparison', async (c) => {
- try {
- const accounts = await getAccounts(c.get('supabase'), c.get('userId'));
- // only channels have the counts being ranked, and stored secrets never leave the Worker
- const channels = accounts.filter(account => account.platform === 'youtube').map(safeAccount);
- if (channels.length === 0) return c.json({ success: true, comparison: null } satisfies YouTubeComparisonResponse);
- return c.json({ success: true, comparison: accountComparison(channels) } satisfies YouTubeComparisonResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.get('/accounts/:id/ig-analytics', async (c) => {
- try {
- const supabase = c.get('supabase');
- const userId = c.get('userId');
- const id = c.req.param('id');
-
- const account = await getAccountById(supabase, id, userId);
- if (!account || account.platform !== 'instagram') {
- return c.json({ success: false, message: 'Instagram account not found' }, 404);
- }
- if (!account.accessToken || !account.igUserId) {
- return c.json({ success: false, message: 'No access token stored' }, 400);
- }
-
- const [profile, media] = await Promise.all([
- fetchInstagramProfile(account.igUserId, account.accessToken),
- fetchInstagramMedia(account.igUserId, account.accessToken, 500),
- ]);
- await storeInstagramSnapshot({ supabase, redis: c.get('redis'), userId, id }, account, profile, media);
-
- const analytics = computeInstagramAnalytics(profile, media);
- const { accessToken: _, ...publicAccount } = account;
-
- return c.json({
- success: true,
- profile: { ...profile },
- account: publicAccount,
- analytics,
- mediaCount: media.length,
- } satisfies InstagramAnalyticsResponse);
- } catch (err) {
- return c.json({ success: false, message: redactUrls((err as Error).message) }, 400);
- }
-});
-
-app.get('/accounts/:id/ig-media', async (c) => {
- try {
- const supabase = c.get('supabase');
- const redis = c.get('redis');
- const userId = c.get('userId');
- const id = c.req.param('id');
-
- const cached = await getIGCache(redis, userId, id);
- if (cached && cached.media) {
- return c.json({ success: true, media: cached.media, fetchedAt: cached.fetchedAt } satisfies InstagramMediaResponse);
- }
-
- const account = await getAccountById(supabase, id, userId);
- if (!account || account.platform !== 'instagram') {
- return c.json({ success: false, message: 'Not found' }, 404);
- }
- if (!account.accessToken || !account.igUserId) {
- return c.json({ success: false, message: 'No access token' }, 400);
- }
-
- const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);
- const fetchedAt = new Date().toISOString();
- await setIGCache(redis, userId, id, { media, fetchedAt });
-
- return c.json({ success: true, media, fetchedAt } satisfies InstagramMediaResponse);
- } catch (err) {
- return c.json({ success: false, message: redactUrls((err as Error).message) }, 400);
- }
-});
-
-app.get('/videos/all', async (c) => {
- try {
- const supabase = c.get('supabase');
- const redis = c.get('redis');
- const userId = c.get('userId');
- const { channelId, sort, order, search, minViews, maxViews } = c.req.query();
- const accounts = await getAccounts(supabase, userId);
-
- const allVideos: YouTubeLibraryVideo[] = [];
- for (const account of accounts) {
- if (channelId && account.id !== channelId) continue;
- const cached = await getVideosCache(redis, userId, account.id);
- if (cached && cached.videos) {
- allVideos.push(...cached.videos.map(video => ({
- ...video,
- channelTitle: account.title || video.channelTitle,
- channelId: account.id,
- channelThumbnail: account.thumbnails?.default || '',
- })));
- }
- }
-
- const videos = filterAndSortVideos(allVideos, { search, minViews, maxViews, sort, order });
-
- return c.json({
- success: true,
- videos,
- total: videos.length,
- channels: accounts.map(account => ({ id: account.id, title: account.title })),
- } satisfies YouTubeLibraryResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-export default app;
diff --git a/backend/routes/analyticsRoutes.ts b/backend/routes/analyticsRoutes.ts
new file mode 100644
index 0000000..a1ca156
--- /dev/null
+++ b/backend/routes/analyticsRoutes.ts
@@ -0,0 +1,16 @@
+import { Hono } from 'hono';
+import {
+ getChannelAnalytics, getChannelVideos, getComparison, getVideoLibrary, getInstagramAnalytics, getInstagramMedia,
+} from '../controllers/analyticsController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/accounts/:id/analytics', ...getChannelAnalytics);
+router.get('/accounts/:id/videos', ...getChannelVideos);
+router.get('/comparison', ...getComparison);
+router.get('/videos/all', ...getVideoLibrary);
+router.get('/accounts/:id/ig-analytics', ...getInstagramAnalytics);
+router.get('/accounts/:id/ig-media', ...getInstagramMedia);
+
+export default router;
diff --git a/backend/routes/reddit.ts b/backend/routes/reddit.ts
deleted file mode 100644
index 3e124b0..0000000
--- a/backend/routes/reddit.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { Hono } from 'hono';
-import { getAccountById } from '../lib/db.ts';
-import { getRedditCache, setRedditCache } from '../lib/cache.ts';
-import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '../services/reddit/redditApi.ts';
-import type { AppEnv } from '../types/app.ts';
-import type { RedditCacheData } from '../../shared/types/reddit.ts';
-
-const router = new Hono<AppEnv>();
-
-// Full analytics: profile + computed stats + recent posts
-router.get('/accounts/:id/reddit-analytics', async (c) => {
- const id = c.req.param('id');
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- const redis = c.get('redis');
- try {
- const account = await getAccountById(supabase, id, userId);
- if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
- if (!account.cookie) return c.json({ error: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);
- if (!account.username) return c.json({ error: 'No Reddit username stored - delete this account and add it again' }, 400);
-
- const cached = await getRedditCache(redis, userId, id);
- if (cached) return c.json(cached);
-
- const [profile, posts] = await Promise.all([
- fetchRedditProfile(account.username, account.cookie),
- fetchRedditPosts(account.username, account.cookie, 100),
- ]);
- const analytics = computeRedditAnalytics(profile, posts);
- const result: RedditCacheData = { profile, analytics, posts };
-
- await setRedditCache(redis, userId, id, result);
- return c.json(result);
- } catch (err) {
- console.error(`GET /accounts/${id}/reddit-analytics:`, (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-// Post list only (served from cache when available)
-router.get('/accounts/:id/reddit-posts', async (c) => {
- const id = c.req.param('id');
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- const redis = c.get('redis');
- try {
- const account = await getAccountById(supabase, id, userId);
- if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);
- if (!account.cookie) return c.json({ error: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);
- if (!account.username) return c.json({ error: 'No Reddit username stored - delete this account and add it again' }, 400);
-
- const cached = await getRedditCache(redis, userId, id);
- if (cached?.posts) return c.json(cached.posts);
-
- const posts = await fetchRedditPosts(account.username, account.cookie, 100);
- return c.json(posts);
- } catch (err) {
- console.error(`GET /accounts/${id}/reddit-posts:`, (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-export default router;
diff --git a/backend/routes/redditRoutes.ts b/backend/routes/redditRoutes.ts
new file mode 100644
index 0000000..5f85d8e
--- /dev/null
+++ b/backend/routes/redditRoutes.ts
@@ -0,0 +1,10 @@
+import { Hono } from 'hono';
+import { getRedditAnalytics, getRedditPosts } from '../controllers/redditController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/accounts/:id/reddit-analytics', ...getRedditAnalytics);
+router.get('/accounts/:id/reddit-posts', ...getRedditPosts);
+
+export default router;
diff --git a/backend/server.ts b/backend/server.ts
index 2880d44..618ad4a 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -10,11 +10,11 @@ import { rateLimit, clientIp, userKey, RATE_LIMIT_HEADERS } from './middleware/r
import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from './lib/rateLimit/rules.ts';
import keysRouter from './routes/keys.ts';
import accountRoutes from './routes/accountRoutes.ts';
-import analyticsRouter from './routes/analytics.ts';
+import analyticsRoutes from './routes/analyticsRoutes.ts';
import publishingRouter from './routes/publishing.ts';
import scheduledPostsRouter from './routes/scheduledPosts.ts';
import settingsRouter from './routes/settings.ts';
-import redditRouter from './routes/reddit.ts';
+import redditRoutes from './routes/redditRoutes.ts';
import trackedContentRouter from './routes/trackedContent.ts';
import overviewRouter from './routes/overview.ts';
import { urlHandler, callbackHandler } from './routes/instagramAuth.ts';
@@ -57,11 +57,11 @@ api.use('*', rateLimit(RATE_LIMIT_RULES.publish, userKey, c => matchesRoute(PUBL
api.route('/', keysRouter);
api.route('/', accountRoutes);
-api.route('/', analyticsRouter);
+api.route('/', analyticsRoutes);
api.route('/', publishingRouter);
api.route('/', scheduledPostsRouter);
api.route('/', settingsRouter);
-api.route('/', redditRouter);
+api.route('/', redditRoutes);
api.route('/', trackedContentRouter);
api.route('/', overviewRouter);
diff --git a/backend/services/accountConnect.ts b/backend/services/accountConnect.ts
deleted file mode 100644
index 19c8e2f..0000000
--- a/backend/services/accountConnect.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { getAccounts, getAccountById, createAccount, updateAccount } from '../lib/db.ts';
-import { resolveChannelId, fetchChannelData } from './youtube/youtubeChannels.ts';
-import { fetchRedditProfile } from './reddit/redditApi.ts';
-import { fetchInstagramProfile } from './instagram/instagramApi.ts';
-import { exchangeForLongLivedToken, refreshLongLivedToken } from './instagram/instagramTokens.ts';
-import { buildYouTubeAccount, buildRedditAccount, buildInstagramAccount } from './accountFactory.ts';
-import type { SupabaseClient } from '../types/app.ts';
-import type { Account, NewAccount } from '../../shared/types/domain.ts';
-
-export interface ServiceFailure {
- status: 400 | 404;
- message: string;
-}
-
-export type TokenRefreshOutcome = { failure: ServiceFailure; expiresAt?: undefined } | { expiresAt: string; failure?: undefined };
-
-interface PastedToken {
- token: string;
- expiresIn: number;
-}
-
-const DEFAULT_TOKEN_LIFETIME_S = 5184000;
-
-// duplicates throw like other failures; the route answers all with a 400
-export async function addYouTubeAccount(supabase: SupabaseClient, userId: string, input: string, apiKey: string): Promise<NewAccount> {
- const channelId = await resolveChannelId(input, apiKey);
- const [channelData, accounts] = await Promise.all([
- fetchChannelData(channelId, apiKey),
- getAccounts(supabase, userId),
- ]);
-
- if (accounts.find(account => account.channelId === channelId)) {
- throw new Error('This channel is already added');
- }
-
- const newAccount = buildYouTubeAccount(channelData);
- await createAccount(supabase, newAccount, userId);
- return newAccount;
-}
-
-export async function addRedditAccount(supabase: SupabaseClient, userId: string, username: string, cookie: string): Promise<Account> {
- const cleanUsername = username.replace(/^u\//i, '').trim();
- const profile = await fetchRedditProfile(cleanUsername, cookie);
-
- const accounts = await getAccounts(supabase, userId);
- if (accounts.find(account => account.platform === 'reddit' && account.username === profile.username)) {
- throw new Error('This Reddit account is already added');
- }
-
- const newAccount = buildRedditAccount(profile, cookie);
- await createAccount(supabase, newAccount, userId);
- return newAccount;
-}
-
-// a pasted token may already be long-lived, so a failed exchange keeps it as is
-async function exchangePastedToken(accessToken: string, appSecret: string | undefined): Promise<PastedToken> {
- if (!appSecret) return { token: accessToken, expiresIn: 0 };
- try {
- const longToken = await exchangeForLongLivedToken(accessToken, appSecret);
- return { token: longToken.accessToken, expiresIn: longToken.expiresIn };
- } catch (err) {
- console.log('Token exchange skipped (token may already be long-lived):', (err as Error).message);
- return { token: accessToken, expiresIn: 0 };
- }
-}
-
-export async function addInstagramAccount(supabase: SupabaseClient, userId: string, accessToken: string, appSecret: string | undefined): Promise<Account> {
- const { token, expiresIn } = await exchangePastedToken(accessToken, appSecret);
-
- const profile = await fetchInstagramProfile(null, token);
- if (!profile.igUserId) {
- throw new Error('Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.');
- }
-
- const accounts = await getAccounts(supabase, userId);
- if (accounts.find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) {
- throw new Error('This Instagram account is already added');
- }
-
- const newAccount = buildInstagramAccount(profile, token, expiresIn);
- await createAccount(supabase, newAccount, userId);
- return newAccount;
-}
-
-export async function refreshInstagramToken(supabase: SupabaseClient, userId: string, accountId: string): Promise<TokenRefreshOutcome> {
- const account = await getAccountById(supabase, accountId, userId);
- if (!account || account.platform !== 'instagram') {
- return { failure: { status: 404, message: 'Instagram account not found' } };
- }
- if (!account.accessToken) {
- return { failure: { status: 400, message: 'No access token stored' } };
- }
-
- const refreshed = await refreshLongLivedToken(account.accessToken);
- const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();
- await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt }, userId);
- return { expiresAt: tokenExpiresAt };
-}
diff --git a/backend/services/accountRefresh.ts b/backend/services/accountRefresh.ts
deleted file mode 100644
index 1fdf98a..0000000
--- a/backend/services/accountRefresh.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import { getAccounts, getAccountById, updateAccount } from '../lib/db.ts';
-import { fetchChannelData } from './youtube/youtubeChannels.ts';
-import { fetchRedditProfile } from './reddit/redditApi.ts';
-import { fetchInstagramProfile } from './instagram/instagramApi.ts';
-import type { SupabaseClient } from '../types/app.ts';
-import type { ServiceFailure } from './accountConnect.ts';
-import type { Account, AccountRefreshResult } from '../../shared/types/domain.ts';
-import type { YouTubeChannelData } from '../../shared/types/youtube.ts';
-import type { RedditProfile } from '../../shared/types/reddit.ts';
-import type { InstagramProfile } from '../../shared/types/instagram.ts';
-
-type Credential = 'accessToken' | 'cookie' | 'username' | 'channelId' | 'apiKey';
-
-export type AccountRefreshOutcome = { failure: ServiceFailure; account?: undefined } | { account: Account; failure?: undefined };
-
-export interface RefreshAllOutcome {
- accounts: Account[];
- results: AccountRefreshResult[];
-}
-
-const NO_COOKIE_MESSAGE = 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools';
-
-// known issue: the two refresh paths word a missing YouTube key differently
-const NO_USERNAME_MESSAGE = 'No Reddit username stored - delete this account and add it again';
-const NO_CHANNEL_MESSAGE = 'No YouTube channel ID stored - delete this channel and add it again';
-const SINGLE_REFRESH_MESSAGES: Record<Credential, string> = {
- accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, username: NO_USERNAME_MESSAGE, channelId: NO_CHANNEL_MESSAGE, apiKey: 'No API key',
-};
-const REFRESH_ALL_MESSAGES: Record<Credential, string> = { ...SINGLE_REFRESH_MESSAGES, apiKey: 'No YouTube API key' };
-
-function findMissingCredential(account: Account, apiKey: string | undefined): Credential | null {
- if (account.platform === 'instagram') return account.accessToken ? null : 'accessToken';
- if (account.platform === 'reddit') {
- if (!account.username) return 'username';
- return account.cookie ? null : 'cookie';
- }
- if (!account.channelId) return 'channelId';
- return apiKey ? null : 'apiKey';
-}
-
-// full adds the fields only a single account refresh updates
-function instagramUpdates(profile: InstagramProfile, full: boolean): Partial<Account> {
- const updates = {
- followersCount: profile.followersCount,
- followsCount: profile.followsCount,
- mediaCount: profile.mediaCount,
- title: profile.name || profile.username,
- username: profile.username,
- profilePictureUrl: profile.profilePictureUrl,
- };
- if (!full) return updates;
- return { ...updates, biography: profile.biography, website: profile.website };
-}
-
-function redditUpdates(profile: RedditProfile): Partial<Account> {
- return {
- totalKarma: profile.totalKarma,
- postKarma: profile.postKarma,
- commentKarma: profile.commentKarma,
- iconUrl: profile.iconUrl,
- };
-}
-
-function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial<Account> {
- const { subscriberCount, viewCount, videoCount, title, thumbnails } = channelData;
- if (!full) return { subscriberCount, viewCount, videoCount, title, thumbnails };
- return {
- subscriberCount, viewCount, videoCount, title,
- description: channelData.description,
- thumbnails,
- customUrl: channelData.customUrl,
- country: channelData.country,
- keywords: channelData.keywords,
- topicCategories: channelData.topicCategories,
- };
-}
-
-// fills creation dates on older accounts once; a failure only skips the extras
-export async function backfillChannelData(supabase: SupabaseClient, account: Account, apiKey: string, userId: string): Promise<void> {
- if (!account.channelId) return;
- try {
- const channelData = await fetchChannelData(account.channelId, apiKey);
- const updates: Partial<Account> = {
- publishedAt: channelData.publishedAt,
- subscriberCount: channelData.subscriberCount,
- viewCount: channelData.viewCount,
- videoCount: channelData.videoCount,
- title: channelData.title,
- thumbnails: channelData.thumbnails,
- customUrl: channelData.customUrl,
- country: channelData.country,
- lastUpdated: new Date().toISOString(),
- };
- await updateAccount(supabase, account.id, updates, userId);
- Object.assign(account, updates);
- } catch (err) {
- console.error('Failed to backfill channel data:', (err as Error).message);
- }
-}
-
-export async function fetchAccountUpdates(account: Account, apiKey: string | undefined, full: boolean): Promise<Partial<Account>> {
- if (account.platform === 'instagram') {
- if (!account.accessToken) throw new Error(SINGLE_REFRESH_MESSAGES.accessToken);
- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
- return instagramUpdates(profile, full);
- }
- if (account.platform === 'reddit') {
- if (!account.username) throw new Error(NO_USERNAME_MESSAGE);
- const profile = await fetchRedditProfile(account.username, account.cookie);
- return redditUpdates(profile);
- }
- if (!account.channelId) throw new Error(NO_CHANNEL_MESSAGE);
- if (!apiKey) throw new Error(SINGLE_REFRESH_MESSAGES.apiKey);
- const channelData = await fetchChannelData(account.channelId, apiKey);
- return youtubeUpdates(channelData, full);
-}
-
-export async function refreshAccount(supabase: SupabaseClient, userId: string, accountId: string, apiKey: string | undefined): Promise<AccountRefreshOutcome> {
- const account = await getAccountById(supabase, accountId, userId);
- if (!account) return { failure: { status: 404, message: 'Not found' } };
-
- const lastUpdated = new Date().toISOString();
- const missing = findMissingCredential(account, apiKey);
- if (missing) return { failure: { status: 400, message: SINGLE_REFRESH_MESSAGES[missing] } };
-
- const updates = { lastUpdated, ...await fetchAccountUpdates(account, apiKey, true) };
- await updateAccount(supabase, account.id, updates, userId);
- return { account: { ...account, ...updates } };
-}
-
-async function refreshListedAccount(supabase: SupabaseClient, userId: string, account: Account, apiKey: string | undefined): Promise<string> {
- const lastUpdated = new Date().toISOString();
- const missing = findMissingCredential(account, apiKey);
- if (missing) throw new Error(REFRESH_ALL_MESSAGES[missing]);
-
- const updates = { lastUpdated, ...await fetchAccountUpdates(account, apiKey, false) };
- await updateAccount(supabase, account.id, updates, userId);
- return account.id;
-}
-
-// one failure must not stop the rest; results align with the accounts by index
-export async function refreshAllAccounts(supabase: SupabaseClient, userId: string, apiKey: string | undefined): Promise<RefreshAllOutcome> {
- const accounts = await getAccounts(supabase, userId);
- const settled = await Promise.allSettled(accounts.map(account => refreshListedAccount(supabase, userId, account, apiKey)));
-
- const results: AccountRefreshResult[] = settled.map((outcome, i) => (outcome.status === 'fulfilled'
- ? { id: accounts[i].id, success: true }
- : { id: accounts[i].id, success: false, error: outcome.reason?.message }));
-
- const updatedAccounts = await getAccounts(supabase, userId);
- return { accounts: updatedAccounts, results };
-}
diff --git a/backend/services/instagramAnalyticsService.ts b/backend/services/instagramAnalyticsService.ts
new file mode 100644
index 0000000..3a5302a
--- /dev/null
+++ b/backend/services/instagramAnalyticsService.ts
@@ -0,0 +1,80 @@
+import { fetchInstagramProfile } from './instagram/instagramApi.ts';
+import { fetchInstagramMedia } from './instagram/instagramMedia.ts';
+import { computeInstagramAnalytics } from './instagram/instagramAnalytics.ts';
+import { NotFoundError, ValidationError } from '../lib/errors.ts';
+import { safeAccount } from '../lib/safeAccount.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { Account, SafeAccount } from '../../shared/types/domain.ts';
+import type { InstagramAnalytics, InstagramMedia, InstagramProfile } from '../../shared/types/instagram.ts';
+
+export interface InstagramAnalyticsDeps {
+ accounts: AccountRepository;
+ cache: AnalyticsCacheRepository;
+ context: RequestContext;
+}
+
+export interface InstagramAccountAnalytics {
+ profile: InstagramProfile;
+ account: SafeAccount;
+ analytics: InstagramAnalytics;
+ mediaCount: number;
+}
+
+export interface InstagramMediaList {
+ media: InstagramMedia[];
+ fetchedAt: string;
+}
+
+export interface InstagramAnalyticsService {
+ analytics(userId: string, accountId: string): Promise<InstagramAccountAnalytics>;
+ media(userId: string, accountId: string): Promise<InstagramMediaList>;
+}
+
+type ConnectedInstagramAccount = Account & { igUserId: string; accessToken: string };
+
+const MEDIA_LIMIT = 500;
+
+export function createInstagramAnalyticsService({ accounts, cache, context }: InstagramAnalyticsDeps): InstagramAnalyticsService {
+ const { signal } = context;
+
+ async function findConnected(userId: string, accountId: string): Promise<ConnectedInstagramAccount> {
+ const account = await accounts.findForUser(accountId, userId);
+ if (!account || account.platform !== 'instagram') throw new NotFoundError('Instagram account not found');
+ if (!account.accessToken || !account.igUserId) throw new ValidationError('No access token stored - reconnect this Instagram account');
+ return { ...account, igUserId: account.igUserId, accessToken: account.accessToken };
+ }
+
+ return {
+ // always live: the media is cached and the profile counts are saved for the Overview
+ async analytics(userId, accountId) {
+ const account = await findConnected(userId, accountId);
+ const [profile, media] = await Promise.all([
+ fetchInstagramProfile(account.igUserId, account.accessToken, signal),
+ fetchInstagramMedia(account.igUserId, account.accessToken, MEDIA_LIMIT, signal),
+ ]);
+ await Promise.all([
+ cache.setInstagramMedia(userId, accountId, { media, fetchedAt: new Date().toISOString() }),
+ accounts.updateForUser(account.id, {
+ followersCount: profile.followersCount,
+ followsCount: profile.followsCount,
+ mediaCount: profile.mediaCount,
+ profilePictureUrl: profile.profilePictureUrl,
+ lastUpdated: new Date().toISOString(),
+ }, userId),
+ ]);
+ return { profile, account: safeAccount(account), analytics: computeInstagramAnalytics(profile, media), mediaCount: media.length };
+ },
+
+ async media(userId, accountId) {
+ const cached = await cache.getInstagramMedia(userId, accountId);
+ if (cached?.media) return { media: cached.media, fetchedAt: cached.fetchedAt };
+ const account = await findConnected(userId, accountId);
+ const media = await fetchInstagramMedia(account.igUserId, account.accessToken, MEDIA_LIMIT, signal);
+ const fetchedAt = new Date().toISOString();
+ await cache.setInstagramMedia(userId, accountId, { media, fetchedAt });
+ return { media, fetchedAt };
+ },
+ };
+}
diff --git a/backend/services/redditAnalyticsService.ts b/backend/services/redditAnalyticsService.ts
new file mode 100644
index 0000000..eb7df21
--- /dev/null
+++ b/backend/services/redditAnalyticsService.ts
@@ -0,0 +1,62 @@
+import { fetchRedditProfile, fetchRedditPosts } from './reddit/redditApi.ts';
+import { computeRedditAnalytics } from './reddit/redditAnalytics.ts';
+import { NO_COOKIE_MESSAGE } from './accountService.ts';
+import { NotFoundError, ValidationError } from '../lib/errors.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { RedditCacheData, RedditPost } from '../../shared/types/reddit.ts';
+
+export interface RedditAnalyticsDeps {
+ accounts: AccountRepository;
+ cache: AnalyticsCacheRepository;
+ context: RequestContext;
+}
+
+export interface RedditAnalyticsService {
+ analytics(userId: string, accountId: string): Promise<RedditCacheData>;
+ posts(userId: string, accountId: string): Promise<RedditPost[]>;
+}
+
+interface RedditCredentials {
+ username: string;
+ cookie: string;
+}
+
+const POST_LIMIT = 100;
+
+export function createRedditAnalyticsService({ accounts, cache, context }: RedditAnalyticsDeps): RedditAnalyticsService {
+ const { signal } = context;
+
+ async function credentialsFor(userId: string, accountId: string): Promise<RedditCredentials> {
+ const account = await accounts.findForUser(accountId, userId);
+ if (!account || account.platform !== 'reddit') throw new NotFoundError('Reddit account not found');
+ if (!account.cookie) throw new ValidationError(NO_COOKIE_MESSAGE);
+ if (!account.username) throw new ValidationError('No Reddit username stored - delete this account and add it again');
+ return { username: account.username, cookie: account.cookie };
+ }
+
+ return {
+ async analytics(userId, accountId) {
+ const { username, cookie } = await credentialsFor(userId, accountId);
+ const cached = await cache.getReddit(userId, accountId);
+ if (cached) return cached;
+
+ const [profile, posts] = await Promise.all([
+ fetchRedditProfile(username, cookie, signal),
+ fetchRedditPosts(username, cookie, POST_LIMIT, signal),
+ ]);
+ const result: RedditCacheData = { profile, analytics: computeRedditAnalytics(profile, posts), posts };
+ await cache.setReddit(userId, accountId, result);
+ return result;
+ },
+
+ // the post list alone is not cached; only a full analytics load writes the cache
+ async posts(userId, accountId) {
+ const { username, cookie } = await credentialsFor(userId, accountId);
+ const cached = await cache.getReddit(userId, accountId);
+ if (cached?.posts) return cached.posts;
+ return fetchRedditPosts(username, cookie, POST_LIMIT, signal);
+ },
+ };
+}
diff --git a/backend/services/youtubeAnalyticsService.ts b/backend/services/youtubeAnalyticsService.ts
new file mode 100644
index 0000000..f533783
--- /dev/null
+++ b/backend/services/youtubeAnalyticsService.ts
@@ -0,0 +1,148 @@
+import { fetchAllVideos } from './youtube/youtubeVideos.ts';
+import { fetchChannelData } from './youtube/youtubeChannels.ts';
+import { computeVideoAnalytics } from './youtube/youtubeAnalytics.ts';
+import { channelMetrics, accountComparison, filterAndSortVideos } from './youtube/youtubeLibrary.ts';
+import { NO_YOUTUBE_KEY_MESSAGE } from './accountService.ts';
+import { NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
+import { errorFields } from '../lib/logger.ts';
+import { safeAccount } from '../lib/safeAccount.ts';
+import type { VideoLibraryFilters } from './youtube/youtubeLibrary.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
+import type { AppConfig } from '../lib/config.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { Account, SafeAccount } from '../../shared/types/domain.ts';
+import type {
+ VideoAnalytics, YouTubeAccountComparison, YouTubeChannelMetrics, YouTubeLibraryChannel, YouTubeLibraryVideo, YouTubeVideo,
+} from '../../shared/types/youtube.ts';
+
+export interface YouTubeAnalyticsDeps {
+ accounts: AccountRepository;
+ cache: AnalyticsCacheRepository;
+ config: AppConfig;
+ context: RequestContext;
+}
+
+export interface ChannelAnalytics {
+ channel: SafeAccount & YouTubeChannelMetrics;
+ analytics: VideoAnalytics;
+ videoCount: number;
+}
+
+export interface ChannelVideos {
+ videos: YouTubeVideo[];
+ fetchedAt: string;
+}
+
+export interface VideoLibraryQuery extends VideoLibraryFilters {
+ channelId?: string;
+}
+
+export interface VideoLibrary {
+ videos: YouTubeLibraryVideo[];
+ channels: YouTubeLibraryChannel[];
+}
+
+export interface YouTubeAnalyticsService {
+ channelAnalytics(userId: string, accountId: string): Promise<ChannelAnalytics>;
+ channelVideos(userId: string, accountId: string): Promise<ChannelVideos>;
+ comparison(userId: string): Promise<YouTubeAccountComparison<SafeAccount> | null>;
+ videoLibrary(userId: string, query: VideoLibraryQuery): Promise<VideoLibrary>;
+}
+
+const MAX_PLAYLIST_PAGES = 10;
+const NO_PLAYLIST_MESSAGE = 'No uploads playlist stored - delete this channel and add it again';
+
+export function createYouTubeAnalyticsService({ accounts, cache, config, context }: YouTubeAnalyticsDeps): YouTubeAnalyticsService {
+ const { signal, log } = context;
+
+ function youtubeKey(): string {
+ if (!config.youtubeApiKey) throw new NotConfiguredError(NO_YOUTUBE_KEY_MESSAGE);
+ return config.youtubeApiKey;
+ }
+
+ async function findChannel(userId: string, accountId: string): Promise<Account & { uploadsPlaylistId: string }> {
+ const account = await accounts.findForUser(accountId, userId);
+ if (!account || account.platform !== 'youtube') throw new NotFoundError('YouTube channel not found');
+ if (!account.uploadsPlaylistId) throw new ValidationError(NO_PLAYLIST_MESSAGE);
+ return { ...account, uploadsPlaylistId: account.uploadsPlaylistId };
+ }
+
+ async function fetchAndCacheVideos(userId: string, accountId: string, playlistId: string, apiKey: string): Promise<ChannelVideos> {
+ const videos = await fetchAllVideos(playlistId, apiKey, MAX_PLAYLIST_PAGES, signal);
+ const fetchedAt = new Date().toISOString();
+ await cache.setVideos(userId, accountId, { videos, fetchedAt });
+ return { videos, fetchedAt };
+ }
+
+ // fills creation dates on older accounts once; a failure only skips the extras
+ async function backfillChannelData(userId: string, account: Account, apiKey: string): Promise<Account> {
+ if (!account.channelId) return account;
+ try {
+ const channelData = await fetchChannelData(account.channelId, apiKey, signal);
+ const updates: Partial<Account> = {
+ publishedAt: channelData.publishedAt,
+ subscriberCount: channelData.subscriberCount,
+ viewCount: channelData.viewCount,
+ videoCount: channelData.videoCount,
+ title: channelData.title,
+ thumbnails: channelData.thumbnails,
+ customUrl: channelData.customUrl,
+ country: channelData.country,
+ lastUpdated: new Date().toISOString(),
+ };
+ await accounts.updateForUser(account.id, updates, userId);
+ return { ...account, ...updates };
+ } catch (err) {
+ log.warn('channel backfill skipped', { accountId: account.id, ...errorFields(err) });
+ return account;
+ }
+ }
+
+ return {
+ async channelAnalytics(userId, accountId) {
+ const apiKey = youtubeKey();
+ const account = await findChannel(userId, accountId);
+ const { videos } = await fetchAndCacheVideos(userId, accountId, account.uploadsPlaylistId, apiKey);
+ const analytics = computeVideoAnalytics(videos);
+ const channel = account.publishedAt ? account : await backfillChannelData(userId, account, apiKey);
+ return { channel: { ...safeAccount(channel), ...channelMetrics(channel) }, analytics, videoCount: videos.length };
+ },
+
+ // served from the cache when it has the channel, without spending quota
+ async channelVideos(userId, accountId) {
+ const cached = await cache.getVideos(userId, accountId);
+ if (cached?.videos) return { videos: cached.videos, fetchedAt: cached.fetchedAt };
+ const apiKey = youtubeKey();
+ const account = await findChannel(userId, accountId);
+ return fetchAndCacheVideos(userId, accountId, account.uploadsPlaylistId, apiKey);
+ },
+
+ // only channels have the counts being ranked, and stored secrets never leave the Worker
+ async comparison(userId) {
+ const channels = (await accounts.listForUser(userId)).filter(account => account.platform === 'youtube').map(safeAccount);
+ return channels.length === 0 ? null : accountComparison(channels);
+ },
+
+ // built from cached videos only; a channel that was never opened contributes nothing yet
+ async videoLibrary(userId, { channelId, ...filters }) {
+ const listed = await accounts.listForUser(userId);
+ const videos: YouTubeLibraryVideo[] = [];
+ for (const account of listed) {
+ if (channelId && account.id !== channelId) continue;
+ const cached = await cache.getVideos(userId, account.id);
+ if (!cached?.videos) continue;
+ videos.push(...cached.videos.map(video => ({
+ ...video,
+ channelTitle: account.title || video.channelTitle,
+ channelId: account.id,
+ channelThumbnail: account.thumbnails?.default || '',
+ })));
+ }
+ return {
+ videos: filterAndSortVideos(videos, filters),
+ channels: listed.map(account => ({ id: account.id, title: account.title })),
+ };
+ },
+ };
+}
diff --git a/backend/tests/fixtures/analyticsRoutes.youtube.golden.json b/backend/tests/fixtures/analyticsRoutes.youtube.golden.json
index ca1e1e1..10f31ea 100644
--- a/backend/tests/fixtures/analyticsRoutes.youtube.golden.json
+++ b/backend/tests/fixtures/analyticsRoutes.youtube.golden.json
@@ -29,22 +29,22 @@
{
"call": "GET /accounts/yt1/analytics",
"status": 200,
- "body": "{\"success\":true,\"channel\":{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UC1\",\"uploadsPlaylistId\":\"UU1\",\"title\":\"Alpha\",\"subscriberCount\":100,\"viewCount\":5000,\"videoCount\":10,\"publishedAt\":\"2024-09-01T00:00:00Z\",\"thumbnails\":{\"default\":\"a.jpg\"},\"channelAge\":730,\"channelAgeYears\":\"2.0\",\"viewsPerSubscriber\":50,\"subscriberToViewRatio\":2,\"avgViewsPerVideo\":500,\"avgSubGainPerDay\":0,\"avgViewsPerDay\":7,\"estimatedMonthlyViews\":210,\"estimatedMonthlySubGain\":0,\"estimatedYearlyViews\":2555,\"estimatedYearlySubGain\":0},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"
+ "body": "{\"success\":true,\"channel\":{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UC1\",\"uploadsPlaylistId\":\"UU1\",\"title\":\"Alpha\",\"subscriberCount\":100,\"viewCount\":5000,\"videoCount\":10,\"publishedAt\":\"2024-09-01T00:00:00Z\",\"thumbnails\":{\"default\":\"a.jpg\"},\"hasCookie\":false,\"channelAge\":730,\"channelAgeYears\":\"2.0\",\"viewsPerSubscriber\":50,\"subscriberToViewRatio\":2,\"avgViewsPerVideo\":500,\"avgSubGainPerDay\":0,\"avgViewsPerDay\":7,\"estimatedMonthlyViews\":210,\"estimatedMonthlySubGain\":0,\"estimatedYearlyViews\":2555,\"estimatedYearlySubGain\":0},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"
},
{
"call": "GET /accounts/yt2/analytics",
"status": 200,
- "body": "{\"success\":true,\"channel\":{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UC2\",\"uploadsPlaylistId\":\"UU2\",\"title\":\"Beta\",\"subscriberCount\":300,\"viewCount\":1000,\"videoCount\":0,\"channelAge\":365,\"channelAgeYears\":\"1.0\",\"viewsPerSubscriber\":3.3,\"subscriberToViewRatio\":30,\"avgViewsPerVideo\":0,\"avgSubGainPerDay\":1,\"avgViewsPerDay\":3,\"estimatedMonthlyViews\":90,\"estimatedMonthlySubGain\":30,\"estimatedYearlyViews\":1095,\"estimatedYearlySubGain\":365},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"
+ "body": "{\"success\":true,\"channel\":{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UC2\",\"uploadsPlaylistId\":\"UU2\",\"title\":\"Beta\",\"subscriberCount\":300,\"viewCount\":1000,\"videoCount\":0,\"hasCookie\":false,\"channelAge\":365,\"channelAgeYears\":\"1.0\",\"viewsPerSubscriber\":3.3,\"subscriberToViewRatio\":30,\"avgViewsPerVideo\":0,\"avgSubGainPerDay\":1,\"avgViewsPerDay\":3,\"estimatedMonthlyViews\":90,\"estimatedMonthlySubGain\":30,\"estimatedYearlyViews\":1095,\"estimatedYearlySubGain\":365},\"analytics\":{\"totalVideos\":1,\"totalViews\":70,\"totalLikes\":7,\"totalComments\":1,\"avgViews\":70,\"avgLikes\":7,\"avgComments\":1,\"medianViews\":70,\"totalEngagement\":8,\"overallEngagementRate\":\"11.43\",\"avgDurationSeconds\":45,\"avgDurationFormatted\":\"0m 45s\",\"totalDurationSeconds\":45,\"totalDurationFormatted\":\"0m 45s\",\"estimatedTotalWatchTimeHours\":1,\"bestByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByLikes\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByComments\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"bestByEngagement\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"worstByViews\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"mostRecent\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"oldest\":{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45},\"top10ByViews\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByLikes\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByComments\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"top10ByEngagement\":[{\"videoId\":\"v1\",\"title\":\"Fresh\",\"viewCount\":70,\"likeCount\":7,\"commentCount\":1,\"publishedAt\":\"2026-08-20T10:00:00Z\",\"thumbnail\":\"\",\"engagementRate\":\"11.43\",\"durationSeconds\":45}],\"shortsCount\":1,\"regularCount\":0,\"avgShortViews\":70,\"avgRegularViews\":0,\"avgShortLikes\":7,\"avgRegularLikes\":0,\"hdCount\":1,\"sdCount\":0,\"hdPercentage\":\"100.0\",\"captionCount\":0,\"captionPercentage\":\"0.0\",\"licensedCount\":0,\"licensedPercentage\":\"0.0\",\"madeForKidsCount\":0,\"embeddableCount\":0,\"embeddablePercentage\":\"0.0\",\"publishDayDistribution\":{\"Thursday\":1},\"publishHourDistribution\":{\"10\":1},\"peakPublishDay\":\"Thursday\",\"peakPublishHour\":10,\"durationDistribution\":{\"short\":1,\"medium\":0,\"long\":0,\"veryLong\":0},\"categoryDistribution\":{\"Unknown\":1},\"tagFrequency\":[],\"videosLast7Days\":0,\"videosLast30Days\":1,\"videosLast90Days\":1,\"videosLast365Days\":1,\"uploadFrequencyPerWeek\":\"0.6\",\"uploadFrequencyPerMonth\":\"1.0\",\"consistencyScore\":100,\"viralityScore\":1,\"viewsDistribution\":{\"ranges\":[\"0-7\",\"7-14\",\"14-21\",\"21-28\",\"28-35\",\"35-42\",\"42-49\",\"49-56\",\"56-63\",\"63-70\"],\"counts\":[0,0,0,0,0,0,0,0,0,0]},\"viewsTrend\":[{\"month\":\"2026-08\",\"value\":70,\"count\":1}],\"engagementTrend\":[{\"month\":\"2026-08\",\"value\":\"11.43\"}],\"likeRateTrend\":[{\"month\":\"2026-08\",\"value\":\"10.00\"}]},\"videoCount\":1}"
},
{
"call": "GET /accounts/yt3/analytics",
"status": 400,
- "body": "{\"success\":false,\"message\":\"No uploads playlist stored - delete this channel and add it again\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"No uploads playlist stored - delete this channel and add it again\",\"requestId\":\"req-test\"}"
},
{
"call": "GET /accounts/missing/analytics",
"status": 404,
- "body": "{\"success\":false,\"message\":\"YouTube channel not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"YouTube channel not found\",\"requestId\":\"req-test\"}"
}
],
"queries": [
@@ -188,9 +188,16 @@
],
"logLines": [
[
- "error",
- "Failed to backfill channel data:",
- "Channel lookup failed"
+ "warn",
+ "{\"level\":\"warn\",\"message\":\"channel backfill skipped\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"accountId\":\"yt2\",\"error\":\"Channel lookup failed\",\"errorName\":\"UpstreamError\"}"
+ ],
+ [
+ "warn",
+ "{\"level\":\"warn\",\"message\":\"request rejected\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"VALIDATION_ERROR\",\"status\":400,\"error\":\"No uploads playlist stored - delete this channel and add it again\",\"errorName\":\"ValidationError\"}"
+ ],
+ [
+ "warn",
+ "{\"level\":\"warn\",\"message\":\"request rejected\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_FOUND\",\"status\":404,\"error\":\"YouTube channel not found\",\"errorName\":\"NotFoundError\"}"
]
],
"redisWrites": [
@@ -214,13 +221,18 @@
"responses": [
{
"call": "GET /accounts/yt1/analytics",
- "status": 400,
- "body": "{\"success\":false,\"message\":\"No API key\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"YouTube API key not configured on server\",\"requestId\":\"req-test\"}"
}
],
"queries": [],
"requests": [],
- "logLines": [],
+ "logLines": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"YouTube API key not configured on server\",\"errorName\":\"NotConfiguredError\"}"
+ ]
+ ],
"redisWrites": null
}
}
diff --git a/backend/tests/routes/analytics.test.ts b/backend/tests/routes/analytics.test.ts
index 545a394..7f9e32b 100644
--- a/backend/tests/routes/analytics.test.ts
+++ b/backend/tests/routes/analytics.test.ts
@@ -4,7 +4,7 @@ process.removeAllListeners('warning');
import { test, describe, before, after, afterEach, mock } from 'node:test';
import type { Mock } from 'node:test';
import type { Hono } from 'hono';
-import analyticsRouter from '../../routes/analytics.ts';
+import analyticsRouter from '../../routes/analyticsRoutes.ts';
import overviewRouter from '../../routes/overview.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
@@ -96,11 +96,13 @@ async function runCalls(router: Hono<AppEnv>, calls: RouteStep[], { redis = null
fetchMock = installFetch(youtubeReply);
const logLines: unknown[][] = [];
mock.method(console, 'error', (...args: unknown[]) => logLines.push(['error', ...args]));
+ mock.method(console, 'warn', (...args: unknown[]) => logLines.push(['warn', ...args]));
const responses = [];
for (const [method, path] of calls) {
responses.push({ call: `${method} ${path}`, ...(await callRoute(app, method, path, { env })) });
}
(console.error as Mock<typeof console.error>).mock.restore();
+ (console.warn as Mock<typeof console.warn>).mock.restore();
return { responses, queries: supabase.calls, requests: fetchMock.requests, logLines, redisWrites: redis?.writes ?? null };
}
@@ -131,8 +133,9 @@ describe('analytics and overview routes golden output', () => {
]);
const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis: null, userId: 'user-1' });
fetchMock = installFetch(youtubeReply);
- const notChannel = { status: 404, body: JSON.stringify({ success: false, message: 'YouTube channel not found' }) };
- const noPlaylist = { status: 400, body: JSON.stringify({ success: false, message: 'No uploads playlist stored - delete this channel and add it again' }) };
+ const failure = (status: number, code: string, message: string) => ({ status, body: JSON.stringify({ success: false, code, message, requestId: 'req-test' }) });
+ const notChannel = failure(404, 'NOT_FOUND', 'YouTube channel not found');
+ const noPlaylist = failure(400, 'VALIDATION_ERROR', 'No uploads playlist stored - delete this channel and add it again');
assert.deepEqual(await callRoute(app, 'GET', '/accounts/ig1/analytics', { env: ENV }), notChannel);
assert.deepEqual(await callRoute(app, 'GET', '/accounts/ig1/videos', { env: ENV }), notChannel);
assert.deepEqual(await callRoute(app, 'GET', '/accounts/ytOld/analytics', { env: ENV }), noPlaylist);
diff --git a/backend/tests/routes/redditRoutes.test.ts b/backend/tests/routes/redditRoutes.test.ts
new file mode 100644
index 0000000..b5b572f
--- /dev/null
+++ b/backend/tests/routes/redditRoutes.test.ts
@@ -0,0 +1,69 @@
+import { test, describe, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import redditRoutes from '../../routes/redditRoutes.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
+import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
+import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+
+const ACCOUNTS = [
+ accountRow({ id: 'rd1', platform: 'reddit', username: 'ribbon', cookie: 'COOKIE' }),
+ accountRow({ id: 'rdNoCookie', platform: 'reddit', username: 'nocookie' }),
+ accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' }),
+];
+
+const CACHED = { profile: { username: 'ribbon' }, analytics: { fetchedPosts: 1 }, posts: [{ id: 'p1' }] };
+
+function storeRedis(store: Record<string, unknown>) {
+ const writes: string[] = [];
+ return {
+ writes,
+ async get(key: string) { return store[key] ?? null; },
+ async set(key: string, value: unknown) { writes.push(key); store[key] = value; },
+ };
+}
+
+let fetchMock: FetchMock | null = null;
+afterEach(() => {
+ fetchMock?.restore();
+ mock.restoreAll();
+});
+
+async function call(path: string, redis: unknown) {
+ mock.method(console, 'warn', () => undefined);
+ const app = mountWithContext(app => app.route('/', redditRoutes), { supabase: fakeSupabase(ACCOUNTS), redis, userId: 'user-1' });
+ const response = await callRoute(app, 'GET', path);
+ return { status: response.status, body: JSON.parse(response.body) as unknown };
+}
+
+describe('Reddit analytics routes', () => {
+ test('refuse other platforms and accounts without a session cookie, before any Reddit call', async () => {
+ fetchMock = installFetch(() => reply({}));
+ const failure = (code: string, message: string) => ({ success: false, code, message, requestId: 'req-test' });
+ assert.deepEqual(await call('/accounts/yt1/reddit-analytics', null), { status: 404, body: failure('NOT_FOUND', 'Reddit account not found') });
+ assert.deepEqual(await call('/accounts/rdNoCookie/reddit-posts', null), {
+ status: 400, body: failure('VALIDATION_ERROR', 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools'),
+ });
+ assert.deepEqual(fetchMock.requests, []);
+ });
+
+ test('serve the cache when it has the account', async () => {
+ fetchMock = installFetch(() => reply({}));
+ const redis = storeRedis({ 'reddit:user-1:rd1': CACHED });
+ assert.deepEqual(await call('/accounts/rd1/reddit-analytics', redis), { status: 200, body: CACHED });
+ assert.deepEqual(await call('/accounts/rd1/reddit-posts', redis), { status: 200, body: CACHED.posts });
+ assert.deepEqual(fetchMock.requests, []);
+ });
+
+ test('fetch live analytics with the stored cookie and cache them', async () => {
+ fetchMock = installFetch(request => (request.url.includes('/about.json')
+ ? reply({ data: { name: 'ribbon', total_karma: 5 } })
+ : reply({ data: { children: [], after: null } })));
+ const redis = storeRedis({});
+ const { status, body } = await call('/accounts/rd1/reddit-analytics', redis);
+ assert.equal(status, 200);
+ assert.equal((body as { profile: { totalKarma: number } }).profile.totalKarma, 5);
+ assert.deepEqual(redis.writes, ['reddit:user-1:rd1']);
+ assert.deepEqual(fetchMock.requests.map(request => (request.headers as Record<string, string>).Cookie), ['reddit_session=COOKIE', 'reddit_session=COOKIE']);
+ });
+});
diff --git a/backend/validators/analyticsValidators.ts b/backend/validators/analyticsValidators.ts
new file mode 100644
index 0000000..97c499a
--- /dev/null
+++ b/backend/validators/analyticsValidators.ts
@@ -0,0 +1,26 @@
+import { ValidationError } from '../lib/errors.ts';
+import { optionalString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type { VideoLibraryQuery } from '../services/youtubeAnalyticsService.ts';
+
+const SORT_ORDERS = ['asc', 'desc'];
+
+function optionalCount(query: Fields, name: string): string | undefined {
+ const value = optionalString(query, name);
+ if (value && !/^\d+$/.test(value)) throw new ValidationError(`${name} must be a whole number`);
+ return value || undefined;
+}
+
+// GET /api/videos/all?channelId=&search=&minViews=&maxViews=&sort=&order=
+export function parseVideoLibraryQuery(query: Fields): VideoLibraryQuery {
+ const order = optionalString(query, 'order');
+ if (order && !SORT_ORDERS.includes(order)) throw new ValidationError('order must be asc or desc');
+ return {
+ channelId: optionalString(query, 'channelId') || undefined,
+ search: optionalString(query, 'search') || undefined,
+ minViews: optionalCount(query, 'minViews'),
+ maxViews: optionalCount(query, 'maxViews'),
+ sort: optionalString(query, 'sort') || undefined,
+ order: order || undefined,
+ };
+}
diff --git a/shared/types/instagram.ts b/shared/types/instagram.ts
index 5ea5aa7..6586e43 100644
--- a/shared/types/instagram.ts
+++ b/shared/types/instagram.ts
@@ -1,4 +1,4 @@
-import type { Account, MediaType, UserTag } from './domain.ts';
+import type { MediaType, SafeAccount, UserTag } from './domain.ts';
import type { PostFrequency } from './reddit.ts';
export type InstagramContentType = 'reel' | 'post' | 'video';
@@ -217,7 +217,7 @@ export interface CloudinaryConfigResponse {
export interface InstagramAnalyticsResponse {
success: true;
profile: InstagramProfile;
- account: Omit<Account, 'accessToken'>;
+ account: SafeAccount;
analytics: InstagramAnalytics;
mediaCount: number;
}
diff --git a/shared/types/youtube.ts b/shared/types/youtube.ts
index 4c76937..3f9658b 100644
--- a/shared/types/youtube.ts
+++ b/shared/types/youtube.ts
@@ -200,7 +200,7 @@ export interface YouTubeChannelMetrics {
// GET /api/accounts/:id/analytics
export interface YouTubeAnalyticsPayload {
success: true;
- channel: Account & YouTubeChannelMetrics;
+ channel: SafeAccount & YouTubeChannelMetrics;
analytics: VideoAnalytics;
videoCount: number;
}