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.

5.9 KB
Raw Blame
import { SERIES, trendSummary } from '../../../lib/chart.ts';
import { CATEGORY_MAP, fmtDate, fmtNum, fmtNumFull, fmtPercent } from '../../../utils/formatters.ts';
import type {
  VideoAnalytics, YouTubeAnalyticsPayload, YouTubeDurationDistribution, YouTubeMonthlyViews, YouTubeVideoSummary,
  YouTubeViewsDistribution,
} from '../../../../../shared/types/youtube.ts';

// the channel as GET /api/accounts/:id/analytics sends it: the stored account plus derived metrics
export type ChannelDetails = YouTubeAnalyticsPayload['channel'];

export interface BestVideo {
  label: string;
  video: YouTubeVideoSummary;
}

export function watchUrl(videoId: string): string {
  return `https://www.youtube.com/watch?v=${videoId}`;
}

export function channelMeta(channel: Pick<ChannelDetails, 'customUrl' | 'country' | 'channelAgeYears' | 'publishedAt'>): string[] {
  return [
    channel.customUrl,
    channel.country && channel.country !== 'Unknown' ? channel.country : null,
    `${channel.channelAgeYears} years old`,
    `Since ${fmtDate(channel.publishedAt)}`,
  ].filter(Boolean) as string[];
}

export function dayDataOf(distribution: Record<string, number> | null | undefined) {
  if (!distribution) return [];
  return Object.entries(distribution).map(([day, count]) => ({ day, count }));
}

export function hourDataOf(distribution: Record<string, number> | null | undefined) {
  if (!distribution) return [];
  return Object.entries(distribution)
    .sort((a, b) => parseInt(a[0], 10) - parseInt(b[0], 10))
    .map(([hour, count]) => ({ hour: `${hour}:00`, count }));
}

export function durationDataOf(distribution: YouTubeDurationDistribution | null | undefined) {
  if (!distribution) return [];
  return [
    { name: 'Shorts (under 1m)', value: distribution.short,    color: SERIES.primary },
    { name: 'Medium (1 to 10m)', value: distribution.medium,   color: SERIES.cool },
    { name: 'Long (10 to 60m)',  value: distribution.long,     color: SERIES.neutral },
    { name: 'Very long (1h+)',   value: distribution.veryLong, color: SERIES.warm },
  ].filter(slice => slice.value > 0);
}

export function categoryDataOf(distribution: Record<string, number> | null | undefined) {
  if (!distribution) return [];
  return Object.entries(distribution).map(([catId, count]) => ({ name: CATEGORY_MAP[catId] || `Category ${catId}`, value: count }));
}

export function splitDataOf(analytics: Pick<VideoAnalytics, 'shortsCount' | 'regularCount'>) {
  return [
    { name: 'Shorts', value: analytics.shortsCount, color: SERIES.primary },
    { name: 'Regular', value: analytics.regularCount, color: SERIES.cool },
  ].filter(slice => slice.value > 0);
}

export function shortsComparisonOf(analytics: Pick<VideoAnalytics, 'avgShortViews' | 'avgRegularViews' | 'avgShortLikes' | 'avgRegularLikes'>) {
  return [
    { metric: 'Average views', Shorts: analytics.avgShortViews, Regular: analytics.avgRegularViews },
    { metric: 'Average likes', Shorts: analytics.avgShortLikes, Regular: analytics.avgRegularLikes },
  ];
}

// an ellipsis only when the title was actually cut
function shortTitle(title: string, max = 28): string {
  return title.length > max ? `${title.slice(0, max)}…` : title;
}

export function topVideosChartOf(videos: (YouTubeVideoSummary | null)[] | null | undefined) {
  return (videos || []).map(video => ({
    name: shortTitle(video?.title || ''), views: video?.viewCount || 0, likes: video?.likeCount || 0,
  }));
}

// most viewed and most liked overlap, so each video is listed once, by views
export function topVideoRowsOf(analytics: Partial<Pick<VideoAnalytics, 'top10ByViews' | 'top10ByLikes'>>): YouTubeVideoSummary[] {
  return (analytics.top10ByViews || []).concat(analytics.top10ByLikes || [])
    .filter((video, i, all) => video && all.findIndex(other => other?.videoId === video?.videoId) === i)
    .sort((a, b) => (b?.viewCount || 0) - (a?.viewCount || 0));
}

export function viewRangeDataOf(viewsDistribution: YouTubeViewsDistribution | null | undefined) {
  return (viewsDistribution?.ranges || []).map((range, i) => ({ range, count: viewsDistribution!.counts[i] || 0 }));
}

export function uploadsByMonthOf(viewsTrend: YouTubeMonthlyViews[] | null | undefined) {
  return (viewsTrend || []).map(point => ({ month: point.month, uploads: point.count }));
}

export function rateOf(part: number, total: number): string {
  if (total > 0) return fmtPercent(part / total * 100);
  return '0%';
}

export function likesPerComment(analytics: Pick<VideoAnalytics, 'totalLikes' | 'totalComments'>): string {
  if (analytics.totalComments > 0) return `${(analytics.totalLikes / analytics.totalComments).toFixed(1)}:1`;
  return 'Not available';
}

// only a missing hour reads as unavailable; null still prints as an hour
export function peakHourLabel(hour: number | null | undefined): string {
  if (hour !== undefined) return `${hour}:00 UTC`;
  return 'Not available';
}

export function bestVideosOf(analytics: Pick<VideoAnalytics, 'bestByViews' | 'bestByLikes' | 'bestByComments' | 'bestByEngagement'>): BestVideo[] {
  return [
    { label: 'Most viewed',     video: analytics.bestByViews },
    { label: 'Most liked',      video: analytics.bestByLikes },
    { label: 'Most comments',   video: analytics.bestByComments },
    { label: 'Best engagement', video: analytics.bestByEngagement },
  ].filter(({ video }) => video) as BestVideo[];
}

export function likesLabel(likeCount: number | null | undefined): string {
  if (likeCount == null) return 'likes hidden';
  return `${fmtNum(likeCount)} likes`;
}

export interface MonthlyPoint {
  month: string;
  value: number | string;
}

// the takeaway of a month-by-month chart in words, read by screen readers in place of the plot
export function monthlySummary(data: readonly MonthlyPoint[], unit: string, percent = false): string {
  const points = data.map(point => ({ name: point.month, value: Number(point.value) || 0 }));
  return trendSummary(points, percent ? (value: number) => `${value}%` : fmtNumFull, unit);
}