Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(instagram): classify reels by media_product_type and fetch views
spacesdrive8fcfe407e28a
diff --git a/DECISIONS.md b/DECISIONS.mdindex 3a5611e..b4e2af9 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -485,3 +485,24 @@ Records every significant architectural decision, the alternatives considered, a**Trade-offs:**- Including karma in Total Audience makes the number less directly comparable to subscriber/follower counts; this is mitigated by clearly labeling each component (`X subs · Y followers · Z karma`).- The tab interface requires the user to click between views rather than seeing everything at once; this is the correct tradeoff for a dense analytics dashboard.++---++## ADR-022: Instagram content classified by media_product_type; views read from insights++**Date:** 2026-09-17+**Status:** Accepted++**Decision:** Instagram media is classified into exactly one of `reel`, `post`, or `video` by `classifyInstagramMedia()`, using `media_product_type` first, the `/reel/` permalink when the product type is missing, and `media_type` last. Views come from the `views` media insight, requested inline with the `insights.metric(views)` field expansion. Views are counted in Overview Total Views. The `ig:` cache entry gains a `version` so older entries are refetched.++**Context:** Reels were labelled Videos because the code only requested `media_type` and checked for a `REEL` value that the Graph API never returns. Reels come back as `VIDEO`, and only `media_product_type: REELS` identifies them. No views were fetched at all.++**Alternatives considered:**+- One `/{media-id}/insights` request per item: gives views even when a single item's insights fail, but costs up to 500 extra subrequests per refresh, which exceeds Cloudflare Workers subrequest limits on the free plan.+- Keeping `media_type` keys (`IMAGE`, `CAROUSEL_ALBUM`, ...) and adding `REELS` next to them: photos and carousels are both posts to the user, and mixing format with surface allows the same item to look like two categories.+- Changing the cache key prefix instead of versioning: would leave old `ig:` keys orphaned forever, since these keys have no TTL.++**Trade-offs:**+- When any item on a page cannot return insights (for example media posted before the account became professional), Instagram fails the entire page. That page is refetched without views, so its items show `-` rather than a number. Page size is 50 to limit the impact.+- Meta's reference labels `media_product_type` as Facebook Login only, but it is returned for Instagram Login in practice. The permalink fallback keeps classification correct if it is ever omitted.+- Views are organic Instagram views only and can lag by up to 48 hours, per Meta.diff --git a/backend/lib/cache.js b/backend/lib/cache.jsindex d9ec138..f248e20 100644--- a/backend/lib/cache.js+++ b/backend/lib/cache.js@@ -17,14 +17,20 @@ export async function deleteVideosCache(redis, userId, accountId) {try { await redis.del(`videos:${userId}:${accountId}`); } catch { /* non-fatal */ }}+// Bump when the cached media shape changes so entries written by older code read as a miss.+const IG_CACHE_VERSION = 2;+export async function getIGCache(redis, userId, accountId) {if (!redis) return null;- try { return (await redis.get(`ig:${userId}:${accountId}`)) || null; } catch { return null; }+ try {+ const cached = await redis.get(`ig:${userId}:${accountId}`);+ return cached?.version === IG_CACHE_VERSION ? cached : null;+ } catch { return null; }}export async function setIGCache(redis, userId, accountId, data) {if (!redis) return;- try { await redis.set(`ig:${userId}:${accountId}`, data); } catch { /* non-fatal */ }+ try { await redis.set(`ig:${userId}:${accountId}`, { ...data, version: IG_CACHE_VERSION }); } catch { /* non-fatal */ }}export async function deleteIGCache(redis, userId, accountId) {diff --git a/backend/package.json b/backend/package.jsonindex 4ebd760..5e449c3 100644--- a/backend/package.json+++ b/backend/package.json@@ -5,7 +5,8 @@"scripts": {"dev": "wrangler dev","deploy": "wrangler deploy",- "start": "wrangler dev"+ "start": "wrangler dev",+ "test": "node --test"},"dependencies": {"@supabase/supabase-js": "^2.49.4",diff --git a/backend/routes/overview.js b/backend/routes/overview.jsindex c5e7be3..e555f73 100644--- a/backend/routes/overview.js+++ b/backend/routes/overview.js@@ -2,7 +2,7 @@ import { Hono } from 'hono';import { getAccounts, getTrackedPosts } from '../lib/db.js';import { getVideosCache, setVideosCache, getIGCache, setIGCache, getRedditCache } from '../lib/cache.js';import { fetchAllVideos } from '../services/youtube.js';-import { fetchInstagramMedia } from '../services/instagram.js';+import { fetchInstagramMedia, summarizeContentTypes } from '../services/instagram.js';const router = new Hono();@@ -47,11 +47,15 @@ router.get('/overview', async (c) => {}return { id: a.id, cacheWarmed: false };}+ const contentTypes = summarizeContentTypes(media);+ const types = Object.values(contentTypes);return {id: a.id,cacheWarmed: true,- totalLikes: media.reduce((s, m) => s + (m.likeCount ?? 0), 0),- totalComments: media.reduce((s, m) => s + (m.commentsCount ?? 0), 0),+ totalLikes: types.reduce((s, t) => s + t.likes, 0),+ totalComments: types.reduce((s, t) => s + t.comments, 0),+ totalViews: types.reduce((s, t) => s + t.views, 0),+ contentTypes,};}diff --git a/backend/services/instagram.js b/backend/services/instagram.jsindex cbcae87..737d399 100644--- a/backend/services/instagram.js+++ b/backend/services/instagram.js@@ -112,45 +112,114 @@ export async function fetchInstagramProfile(igUserId, accessToken) {};}+export const CONTENT_TYPES = ['reel', 'post', 'video'];++const MEDIA_FIELDS = 'id,caption,media_type,media_product_type,media_url,thumbnail_url,cover_url,permalink,timestamp,like_count,comments_count';+const VIEWS_FIELD = 'insights.metric(views)';+const MEDIA_PAGE_SIZE = 50;+const MAX_MEDIA_PAGES = 10;+const REEL_PERMALINK = /instagram\.com\/reels?\//i;++// media_type never says REELS - Instagram reports reels as VIDEO and only media_product_type tells them apart.+export function classifyInstagramMedia(raw) {+ const productType = String(raw?.media_product_type || '').toUpperCase();+ const mediaType = String(raw?.media_type || '').toUpperCase();++ if (productType === 'REELS') return 'reel';+ if (!productType && REEL_PERMALINK.test(raw?.permalink || '')) return 'reel';+ if (mediaType === 'REELS' || mediaType === 'REEL') return 'reel';+ if (mediaType === 'VIDEO') return 'video';+ return 'post';+}++export function extractInstagramViews(raw) {+ const metric = raw?.insights?.data?.find(d => d.name === 'views');+ const value = metric?.values?.[0]?.value ?? metric?.total_value?.value;+ const views = Number(value);+ return value !== undefined && value !== null && Number.isFinite(views) ? views : null;+}++export function normalizeInstagramMedia(raw) {+ const contentType = classifyInstagramMedia(raw);+ const mediaType = String(raw.media_type || 'IMAGE').toUpperCase();+ return {+ id: raw.id,+ caption: raw.caption || '',+ contentType,+ mediaType,+ mediaUrl: raw.media_url || '',+ thumbnailUrl: raw.cover_url || raw.thumbnail_url || (contentType === 'post' ? raw.media_url || '' : ''),+ permalink: raw.permalink || '',+ timestamp: raw.timestamp || '',+ likeCount: raw.like_count || 0,+ commentsCount: raw.comments_count || 0,+ viewCount: extractInstagramViews(raw),+ };+}++async function fetchMediaPage(igUserId, accessToken, after) {+ const params = { access_token: accessToken, limit: String(MEDIA_PAGE_SIZE) };+ if (after) params.after = after;+ try {+ return await igFetch(`/${igUserId}/media`, { ...params, fields: `${MEDIA_FIELDS},${VIEWS_FIELD}` });+ } catch {+ // One item without insights (e.g. posted before the account went professional) fails the whole page.+ return igFetch(`/${igUserId}/media`, { ...params, fields: MEDIA_FIELDS });+ }+}+export async function fetchInstagramMedia(igUserId, accessToken, limit = 500) {- let allMedia = [];- let url = `${IG_GRAPH_URL}/${IG_API_VERSION}/${igUserId}/media?access_token=${accessToken}&fields=id,caption,media_type,media_url,thumbnail_url,cover_url,permalink,timestamp,like_count,comments_count&limit=${Math.min(limit, 100)}`;-- let pages = 0;- while (url && pages < 10 && allMedia.length < limit) {- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), 15000);- let res;- try {- res = await fetch(url, { signal: controller.signal });- } catch (err) {- clearTimeout(timer);- if (err.name === 'AbortError') throw new Error('Instagram API request timed out');- throw new Error(`Instagram API unreachable (${err.message})`);- }- clearTimeout(timer);- const data = await res.json();- if (data.error) throw new Error(data.error.message || data.error.error_message);- if (data.data) allMedia = allMedia.concat(data.data);- url = data.paging?.next || null;- pages++;+ const allMedia = [];+ let after = null;++ for (let page = 0; page < MAX_MEDIA_PAGES && allMedia.length < limit; page++) {+ const data = await fetchMediaPage(igUserId, accessToken, after);+ if (Array.isArray(data.data)) allMedia.push(...data.data);+ after = data.paging?.next ? data.paging?.cursors?.after : null;+ if (!after) break;}- return allMedia.slice(0, limit).map(m => {- const isVideo = m.media_type === 'REEL' || m.media_type === 'VIDEO';- const thumbnailUrl = m.cover_url || m.thumbnail_url || (isVideo ? '' : m.media_url || '');- return {- id: m.id,- caption: m.caption || '',- mediaType: m.media_type || 'IMAGE',- mediaUrl: m.media_url || '',- thumbnailUrl,- permalink: m.permalink || '',- timestamp: m.timestamp || '',- likeCount: m.like_count || 0,- commentsCount: m.comments_count || 0,+ const unique = new Map();+ allMedia.forEach(m => { if (m?.id && !unique.has(m.id)) unique.set(m.id, m); });+ return [...unique.values()].slice(0, limit).map(normalizeInstagramMedia);+}++export function summarizeContentTypes(media) {+ const summary = {};+ CONTENT_TYPES.forEach(type => {+ summary[type] = { count: 0, likes: 0, comments: 0, views: 0, viewsReported: 0 };+ });+ (media || []).forEach(m => {+ const s = summary[CONTENT_TYPES.includes(m.contentType) ? m.contentType : 'post'];+ s.count++;+ s.likes += m.likeCount || 0;+ s.comments += m.commentsCount || 0;+ if (typeof m.viewCount === 'number') {+ s.views += m.viewCount;+ s.viewsReported++;+ }+ });+ return summary;+}++function buildContentTypeStats(media) {+ const summary = summarizeContentTypes(media);+ const stats = {};+ CONTENT_TYPES.forEach(type => {+ const s = summary[type];+ stats[type] = {+ count: s.count,+ totalLikes: s.likes,+ totalComments: s.comments,+ totalViews: s.views,+ viewsReported: s.viewsReported,+ avgLikes: s.count > 0 ? Math.round(s.likes / s.count) : 0,+ avgComments: s.count > 0 ? Math.round(s.comments / s.count) : 0,+ avgEngagement: s.count > 0 ? Math.round((s.likes + s.comments) / s.count) : 0,+ avgViews: s.viewsReported > 0 ? Math.round(s.views / s.viewsReported) : 0,};});+ return stats;}export function computeInstagramAnalytics(profile, media) {@@ -160,10 +229,11 @@ export function computeInstagramAnalytics(profile, media) {avgLikes: 0, avgComments: 0, avgEngagement: 0,medianLikes: 0, medianComments: 0,engagementRate: 0, likesPerFollower: 0, commentsPerFollower: 0,+ totalViews: 0, avgViews: 0, mediaWithViews: 0,bestByLikes: null, bestByComments: null, worstByLikes: null,- recentMedia: [], mediaTypeDistribution: {},+ recentMedia: [], contentTypeStats: buildContentTypeStats([]),postFrequency: { perWeek: 0, perMonth: 0 },- topPosts: [], performanceByType: {},+ topPosts: [],hashtagAnalysis: [], captionLengthCorrelation: [],postsByDayOfWeek: [], postsByHour: [],engagementTimeline: [], monthlyBreakdown: [],@@ -197,27 +267,10 @@ export function computeInstagramAnalytics(profile, media) {const byComments = [...media].sort((a, b) => b.commentsCount - a.commentsCount);const likesToCommentsRatio = totalComments > 0 ? parseFloat((totalLikes / totalComments).toFixed(1)) : 0;- const mediaTypes = {};- const typeStats = {};- media.forEach(m => {- const t = m.mediaType;- mediaTypes[t] = (mediaTypes[t] || 0) + 1;- if (!typeStats[t]) typeStats[t] = { likes: 0, comments: 0, count: 0 };- typeStats[t].likes += m.likeCount;- typeStats[t].comments += m.commentsCount;- typeStats[t].count++;- });- const performanceByType = {};- Object.entries(typeStats).forEach(([type, s]) => {- performanceByType[type] = {- count: s.count,- avgLikes: Math.round(s.likes / s.count),- avgComments: Math.round(s.comments / s.count),- avgEngagement: Math.round((s.likes + s.comments) / s.count),- totalLikes: s.likes,- totalComments: s.comments,- };- });+ const contentTypeStats = buildContentTypeStats(media);+ const mediaWithViews = CONTENT_TYPES.reduce((s, t) => s + contentTypeStats[t].viewsReported, 0);+ const totalViews = CONTENT_TYPES.reduce((s, t) => s + contentTypeStats[t].totalViews, 0);+ const avgViews = mediaWithViews > 0 ? Math.round(totalViews / mediaWithViews) : 0;const dates = media.map(m => new Date(m.timestamp)).filter(d => !isNaN(d));let perWeek = 0, perMonth = 0;@@ -348,12 +401,12 @@ export function computeInstagramAnalytics(profile, media) {medianLikes, medianComments,engagementRate, likesPerFollower, commentsPerFollower,likesToCommentsRatio,+ totalViews, avgViews, mediaWithViews,bestByLikes: byLikes[0] || null,bestByComments: byComments[0] || null,worstByLikes,recentMedia: media.slice(0, 20),- mediaTypeDistribution: mediaTypes,- performanceByType,+ contentTypeStats,postFrequency: { perWeek, perMonth },topPosts,postsByDayOfWeek, bestPostingDay: bestDayObj?.day || '',diff --git a/backend/services/instagram.test.js b/backend/services/instagram.test.jsnew file mode 100644index 0000000..41aacdd--- /dev/null+++ b/backend/services/instagram.test.js@@ -0,0 +1,174 @@+import { test, describe, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import {+ classifyInstagramMedia,+ extractInstagramViews,+ normalizeInstagramMedia,+ fetchInstagramMedia,+ summarizeContentTypes,+ computeInstagramAnalytics,+} from './instagram.js';++const viewsInsight = (value) => ({ data: [{ name: 'views', period: 'lifetime', values: [{ value }] }] });++describe('classifyInstagramMedia', () => {+ test('reel reported as VIDEO with REELS product type is a reel', () => {+ assert.equal(classifyInstagramMedia({ media_type: 'VIDEO', media_product_type: 'REELS' }), 'reel');+ });++ test('in-feed video with FEED product type is a video', () => {+ assert.equal(classifyInstagramMedia({ media_type: 'VIDEO', media_product_type: 'FEED' }), 'video');+ });++ test('images and carousels are posts', () => {+ assert.equal(classifyInstagramMedia({ media_type: 'IMAGE', media_product_type: 'FEED' }), 'post');+ assert.equal(classifyInstagramMedia({ media_type: 'CAROUSEL_ALBUM', media_product_type: 'FEED' }), 'post');+ });++ test('falls back to the reel permalink when product type is missing', () => {+ assert.equal(classifyInstagramMedia({ media_type: 'VIDEO', permalink: 'https://www.instagram.com/reel/C1a2b3/' }), 'reel');+ assert.equal(classifyInstagramMedia({ media_type: 'VIDEO', permalink: 'https://www.instagram.com/p/C1a2b3/' }), 'video');+ });++ test('product type wins over a reel-looking permalink', () => {+ assert.equal(classifyInstagramMedia({ media_type: 'VIDEO', media_product_type: 'FEED', permalink: 'https://www.instagram.com/reel/x/' }), 'video');+ });++ test('handles lowercase values and legacy REEL media types', () => {+ assert.equal(classifyInstagramMedia({ media_type: 'video', media_product_type: 'reels' }), 'reel');+ assert.equal(classifyInstagramMedia({ media_type: 'REEL' }), 'reel');+ assert.equal(classifyInstagramMedia({ media_type: 'REELS' }), 'reel');+ });++ test('unknown or empty input defaults to post', () => {+ assert.equal(classifyInstagramMedia({}), 'post');+ assert.equal(classifyInstagramMedia(null), 'post');+ });+});++describe('extractInstagramViews', () => {+ test('reads the lifetime value', () => {+ assert.equal(extractInstagramViews({ insights: viewsInsight(1234) }), 1234);+ });++ test('keeps a genuine zero', () => {+ assert.equal(extractInstagramViews({ insights: viewsInsight(0) }), 0);+ });++ test('reads total_value when values is absent', () => {+ assert.equal(extractInstagramViews({ insights: { data: [{ name: 'views', total_value: { value: 88 } }] } }), 88);+ });++ test('returns null when insights are missing, empty, or malformed', () => {+ assert.equal(extractInstagramViews({}), null);+ assert.equal(extractInstagramViews({ insights: { data: [] } }), null);+ assert.equal(extractInstagramViews({ insights: viewsInsight('n/a') }), null);+ });+});++describe('normalizeInstagramMedia', () => {+ test('reel keeps its cover as the thumbnail and never uses the video file', () => {+ const m = normalizeInstagramMedia({+ id: '1', media_type: 'VIDEO', media_product_type: 'REELS',+ media_url: 'https://cdn/video.mp4', like_count: 44, comments_count: 6,+ insights: viewsInsight(900),+ });+ assert.equal(m.contentType, 'reel');+ assert.equal(m.thumbnailUrl, '');+ assert.equal(m.viewCount, 900);+ assert.equal(m.likeCount, 44);+ });++ test('image post uses media_url as the thumbnail', () => {+ const m = normalizeInstagramMedia({ id: '2', media_type: 'IMAGE', media_product_type: 'FEED', media_url: 'https://cdn/img.jpg' });+ assert.equal(m.contentType, 'post');+ assert.equal(m.thumbnailUrl, 'https://cdn/img.jpg');+ assert.equal(m.viewCount, null);+ });+});++describe('fetchInstagramMedia', () => {+ const originalFetch = globalThis.fetch;+ afterEach(() => { globalThis.fetch = originalFetch; });++ test('retries a page without insights when the insights request fails', async () => {+ const requests = [];+ globalThis.fetch = async (url) => {+ const fields = new URL(url).searchParams.get('fields');+ requests.push(fields);+ if (fields.includes('insights')) {+ return { json: async () => ({ error: { message: 'Media posted before business account conversion' } }) };+ }+ return { json: async () => ({ data: [{ id: 'a', media_type: 'VIDEO', media_product_type: 'REELS' }] }) };+ };++ const media = await fetchInstagramMedia('123', 'token', 500);+ assert.equal(requests.length, 2);+ assert.equal(media.length, 1);+ assert.equal(media[0].contentType, 'reel');+ assert.equal(media[0].viewCount, null);+ });++ test('follows cursors, drops duplicate ids, and respects the limit', async () => {+ const pages = {+ '': { data: [{ id: 'a', media_type: 'IMAGE' }, { id: 'b', media_type: 'VIDEO', media_product_type: 'REELS', insights: viewsInsight(5) }], paging: { cursors: { after: 'p2' }, next: 'https://next' } },+ p2: { data: [{ id: 'b', media_type: 'VIDEO', media_product_type: 'REELS' }, { id: 'c', media_type: 'VIDEO', media_product_type: 'FEED' }], paging: { cursors: { after: 'p3' } } },+ };+ globalThis.fetch = async (url) => {+ const after = new URL(url).searchParams.get('after') ?? '';+ return { json: async () => pages[after] };+ };++ const media = await fetchInstagramMedia('123', 'token', 500);+ assert.deepEqual(media.map(m => m.id), ['a', 'b', 'c']);+ assert.deepEqual(media.map(m => m.contentType), ['post', 'reel', 'video']);++ const limited = await fetchInstagramMedia('123', 'token', 1);+ assert.equal(limited.length, 1);+ });+});++describe('content type tracking', () => {+ const media = [+ { id: '1', contentType: 'reel', likeCount: 44, commentsCount: 6, viewCount: 1000, timestamp: '2026-08-20T10:00:00+0000', caption: '' },+ { id: '2', contentType: 'reel', likeCount: 11, commentsCount: 8, viewCount: null, timestamp: '2026-08-21T10:00:00+0000', caption: '' },+ { id: '3', contentType: 'post', likeCount: 2, commentsCount: 0, viewCount: 50, timestamp: '2026-06-01T10:00:00+0000', caption: '' },+ { id: '4', contentType: 'video', likeCount: 7, commentsCount: 1, viewCount: 300, timestamp: '2025-01-01T10:00:00+0000', caption: '' },+ ];++ test('summarizeContentTypes counts each item exactly once', () => {+ const s = summarizeContentTypes(media);+ assert.equal(s.reel.count + s.post.count + s.video.count, media.length);+ assert.deepEqual(s.reel, { count: 2, likes: 55, comments: 14, views: 1000, viewsReported: 1 });+ assert.deepEqual(s.post, { count: 1, likes: 2, comments: 0, views: 50, viewsReported: 1 });+ assert.deepEqual(s.video, { count: 1, likes: 7, comments: 1, views: 300, viewsReported: 1 });+ });++ test('summarizeContentTypes always returns all three types', () => {+ const s = summarizeContentTypes([]);+ assert.deepEqual(Object.keys(s), ['reel', 'post', 'video']);+ assert.equal(s.reel.count, 0);+ });++ test('computeInstagramAnalytics splits counts and views by type without double counting', () => {+ const a = computeInstagramAnalytics({ followersCount: 100, mediaCount: 4 }, media);+ const { reel, post, video } = a.contentTypeStats;++ assert.equal(reel.count, 2);+ assert.equal(post.count, 1);+ assert.equal(video.count, 1);+ assert.equal(reel.totalViews, 1000);+ assert.equal(reel.avgViews, 1000);+ assert.equal(a.totalViews, reel.totalViews + post.totalViews + video.totalViews);+ assert.equal(a.totalLikes, reel.totalLikes + post.totalLikes + video.totalLikes);+ assert.equal(a.mediaWithViews, 3);+ assert.equal(a.avgViews, Math.round(1350 / 3));+ });++ test('computeInstagramAnalytics returns empty type stats with no media', () => {+ const a = computeInstagramAnalytics({ mediaCount: 0 }, []);+ assert.equal(a.totalViews, 0);+ assert.equal(a.contentTypeStats.reel.count, 0);+ assert.equal(a.contentTypeStats.video.avgViews, 0);+ });+});diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdindex 86f5d0b..ac82df5 100644--- a/docs/architecture/backend/CACHING.md+++ b/docs/architecture/backend/CACHING.md@@ -23,12 +23,16 @@ export async function getVideosCache(redis, userId, accountId) {| Key pattern | Content | Set when | Invalidated when ||---|---|---|---|| `videos:{userId}:{accountId}` | Array of YouTube video objects with stats | `GET /api/accounts/:id/analytics` succeeds | `DELETE /api/accounts/:id` |-| `ig:{userId}:{accountId}` | Array of Instagram media objects | `GET /api/accounts/:id/ig-analytics` succeeds | `DELETE /api/accounts/:id` |+| `ig:{userId}:{accountId}` | `{ media, fetchedAt, version }` - normalized Instagram media (see `normalizeInstagramMedia()`) | `GET /api/accounts/:id/ig-analytics` or `ig-media` succeeds, or the Overview warms it | `DELETE /api/accounts/:id`, or a `version` mismatch || `reddit:{userId}:{accountId}` | Object `{ profile, analytics, posts }` for Reddit account | `GET /api/accounts/:id/reddit-analytics` succeeds | `DELETE /api/accounts/:id` || `oauth_ig:{state}` | userId string (legacy, Redis-backed) | Instagram OAuth URL generation | Consumed on callback; 10-min TTL |**Note:** The `oauth_ig:` key is a legacy path. The current OAuth implementation uses HMAC-signed state tokens that don't require Redis. This key is set and consumed only when Redis is available, as a secondary verification layer.+## Cache Versioning++`ig:` entries carry a `version` field written by `setIGCache()`. `getIGCache()` treats an entry whose `version` differs from `IG_CACHE_VERSION` in `lib/cache.js` as a miss, so the next request refetches from Instagram and overwrites it. Bump `IG_CACHE_VERSION` whenever the cached media shape changes. Version 2 added `contentType` and `viewCount`.+## Cache TTLCurrently no TTL is set on `videos:` or `ig:` keys. Cached data persists until:diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 0ba0218..c5463d0 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -32,8 +32,8 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup|---|---|---|---|| GET | `/api/accounts/:id/analytics` | `routes/analytics.js` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics || GET | `/api/accounts/:id/videos` | `routes/analytics.js` | Returns cached video list (from Redis if available) |-| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.js` | Instagram analytics - fetches up to 500 media, runs `computeInstagramAnalytics()` |-| GET | `/api/accounts/:id/ig-media` | `routes/analytics.js` | Returns cached Instagram media list |+| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.js` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` |+| GET | `/api/accounts/:id/ig-media` | `routes/analytics.js` | Returns the Instagram media list (with `contentType` and `viewCount`) from cache, fetching live on a miss || GET | `/api/comparison` | `routes/analytics.js` | Cross-account comparison data for the Overview dashboard |### Instagram OAuthdiff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex a1517c9..fa2af9a 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -28,13 +28,35 @@ async function igFetch(path, token, options = {}) {| `exchangeCodeForToken(code, env)` | Short-lived code -> short-lived token (Instagram OAuth step 1) || `exchangeForLongLivedToken(shortToken, env)` | Short-lived -> 60-day long-lived token (Instagram OAuth step 2) || `getIGProfile(accessToken)` | Fetches `id, username, account_type, media_count` for the token |-| `getIGMedia(accessToken, limit)` | Paginates media items up to `limit` (default 500) |+| `fetchInstagramMedia(igUserId, accessToken, limit)` | Paginates media (50 per page, 10 pages max) up to `limit` (default 500), requesting `views` insights inline; returns normalized items |+| `classifyInstagramMedia(raw)` | Returns `'reel'`, `'post'`, or `'video'` for a raw Graph API media item |+| `extractInstagramViews(raw)` | Reads the `views` insight from a raw item; `null` when Instagram reports none |+| `normalizeInstagramMedia(raw)` | Maps a raw item to the cached media shape (`contentType`, `viewCount`, counts, URLs) |+| `summarizeContentTypes(media)` | Per content type `{ count, likes, comments, views, viewsReported }`; always returns all three types || `refreshLongLivedToken(accessToken)` | Extends a long-lived token; call before expiry || `autoRefreshInstagramTokens(supabase)` | Cron handler - refreshes all tokens expiring within 15 days |-| `computeInstagramAnalytics(media, profile)` | Computes engagement rates, hashtag analysis, timing patterns, monthly breakdown |+| `computeInstagramAnalytics(profile, media)` | Computes engagement rates, views, per-content-type stats, hashtag analysis, timing patterns, monthly breakdown || `publishIGContainer(igUserId, params, token)` | Creates a media container via Graph API || `publishIGMedia(igUserId, containerId, token)` | Publishes a container; returns `mediaId` |+### Content type classification++Instagram's `media_type` is only ever `IMAGE`, `VIDEO`, or `CAROUSEL_ALBUM`. Reels are returned as `VIDEO`; the separate `media_product_type` field (`FEED`, `REELS`, `STORY`, `AD`) is what identifies them. `classifyInstagramMedia()` applies these rules in order, so every item lands in exactly one type:++| Rule | Result |+|---|---|+| `media_product_type` is `REELS` | `reel` |+| `media_product_type` is absent and `permalink` contains `/reel/` | `reel` |+| `media_type` is a legacy `REEL` or `REELS` value | `reel` |+| `media_type` is `VIDEO` (in-feed video published before Reels, or an ad video) | `video` |+| Anything else (`IMAGE`, `CAROUSEL_ALBUM`, unknown) | `post` |++Values are compared case-insensitively.++### Views++Views come from the media insights `views` metric (the replacement for `plays`, `video_views`, and `impressions`, which Meta deprecated in April 2025). They are requested inline with the `insights.metric(views)` field expansion, so views cost no extra requests. If any item on a page cannot return insights, Instagram fails the whole page; `fetchMediaPage()` then refetches that page without the expansion and those items get `viewCount: null`. `null` means "not reported" and is shown as `-`, never counted as zero. This requires the `instagram_business_manage_insights` scope, which the OAuth flow already requests.+### `safeAccount(account)`Strips the `accessToken` field before the account object is returned in any API response:diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdindex 06ceac2..f16175d 100644--- a/docs/architecture/data-flows/ANALYTICS.md+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -73,53 +73,55 @@ InstagramAnalytics.jsx mounts -> api.getIGAnalytics(id)▼Worker: analyticsRouter1. getAccountById(supabase, id, userId) - verify ownership + get accessToken- 2. redis cache check: getIGCache(redis, userId, id)- -> cache hit: return immediately- -> cache miss: continue- 3. Fetch from Instagram Graph API:- a. GET /me?fields=id,username,account_type,media_count,followers_count+ 2. Fetch from Instagram Graph API (always live; the cache is written, not read):+ a. GET /{igUserId}?fields=user_id,username,name,followers_count,follows_count,media_count,...-> profile data- b. Paginate /me/media?fields=id,media_type,timestamp,like_count,comments_count,- caption,permalink,thumbnail_url,media_url- -> up to 500 media items (10 pages × 50)- 4. computeInstagramAnalytics(media, profile)- -> engagement metrics- 5. setIGCache(redis, userId, id, result)- 6. Return JSON+ b. Paginate /{igUserId}/media?fields=id,caption,media_type,media_product_type,+ media_url,thumbnail_url,cover_url,permalink,timestamp,like_count,+ comments_count,insights.metric(views)+ -> up to 500 media items (10 pages x 50)+ -> a page that fails with insights is refetched without them (viewCount: null)+ c. normalizeInstagramMedia() classifies each item as reel, post, or video+ 3. setIGCache(redis, userId, id, { media, fetchedAt }) and update account counts+ 4. computeInstagramAnalytics(profile, media)+ 5. Return JSON++GET /api/accounts/:id/ig-media (IG Content Explorer) returns the cached media when the+cache entry is current, otherwise fetches with the same pipeline and caches it.+```++### Instagram media item (cached shape)++```js+{+ id, caption, permalink, timestamp, mediaUrl, thumbnailUrl,+ contentType: 'reel', // 'reel' | 'post' | 'video' - see SERVICES.md for the rules+ mediaType: 'VIDEO', // raw format: IMAGE | VIDEO | CAROUSEL_ALBUM+ likeCount: 44,+ commentsCount: 6,+ viewCount: 1830, // null when Instagram reports no views insight+}```### computeInstagramAnalytics() Output (partial)```js{- profile: { username, followersCount, mediaCount },- totals: {- totalMedia: 200,- avgLikes: 234,- avgComments: 12,- engagementRate: 4.92, // (avg likes + avg comments) / followers × 100- bestPost: { /* highest likes */ },- },- mediaTypeBreakdown: [- { type: 'IMAGE', count: 120, avgLikes: 200 },- { type: 'REELS', count: 80, avgLikes: 310 },- ],- postingTimeDistribution: {- byHour: [/* 0-23 */],- byDayOfWeek: [/* 0-6 */]+ totalPosts: 200, // profile media_count+ fetchedPosts: 200, // items analyzed (max 500)+ totalLikes, totalComments, avgLikes, avgComments,+ engagementRate: 4.92, // (likes + comments) / items / followers x 100+ totalViews: 48210, // sum of reported views+ avgViews: 402, // totalViews / mediaWithViews+ mediaWithViews: 120, // items that reported a views insight+ contentTypeStats: { // always contains all three keys; counts sum to fetchedPosts+ reel: { count, totalViews, viewsReported, avgViews, totalLikes, totalComments, avgLikes, avgComments, avgEngagement },+ post: { /* same */ },+ video: { /* same */ },},- hashtagAnalysis: [- { tag: '#travel', count: 45, avgLikes: 280 },- // ...- ],- captionLengthCorrelation: [- /* { lengthBucket, avgLikes } showing if longer captions perform better */- ],- monthlyBreakdown: [- { month: '2025-06', posts: 8, avgLikes: 245 },- // ...- ],- media: [ /* all 500 media objects */ ]+ topPosts: [ /* top 10 media items by likes + comments, with engagement */ ],+ postsByDayOfWeek, postsByHour, hashtagAnalysis, captionLengthCorrelation,+ monthlyBreakdown: [ { month: '2025-06', posts: 8, likes, comments, avgLikes, avgComments, engagement } ],}```@@ -225,8 +227,8 @@ and the page re-fetches once after 6 seconds.| Metric | Formula ||---|---|| Total Audience | YouTube subscribers + Instagram followers + Reddit account karma |-| Total Views | YouTube channel views + tracked YouTube video views + manually entered Reddit post views |-| Total Content | YouTube videos + Instagram posts + Reddit account posts (cache) + tracked items |+| Total Views | YouTube channel views + Instagram views (cache, reels + posts + videos) + tracked YouTube video views + manually entered Reddit post views |+| Total Content | YouTube videos + Instagram media count (profile) + Reddit account posts (cache) + tracked items || Total Comments | cache comments (YouTube + Instagram + Reddit) + tracked item comments || Total Likes | Reddit karma (account + tracked) + YouTube likes (cache + tracked) + Instagram likes |