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(youtube): split service into focused modules

spacesdrive4c1be18c8ab3
diff --git a/backend/services/fixtures/youtubeAnalytics.empty.golden.json b/backend/services/fixtures/youtubeAnalytics.empty.golden.json
new file mode 100644
index 0000000..1ff175c
--- /dev/null
+++ b/backend/services/fixtures/youtubeAnalytics.empty.golden.json
@@ -0,0 +1,136 @@
+{
+ "empty": {
+ "totalVideos": 0,
+ "totalViews": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "avgViews": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "medianViews": 0,
+ "totalEngagement": 0,
+ "overallEngagementRate": 0,
+ "avgDurationSeconds": 0,
+ "avgDurationFormatted": "0:00",
+ "totalDurationSeconds": 0,
+ "totalDurationFormatted": "0:00",
+ "bestByViews": null,
+ "bestByLikes": null,
+ "bestByComments": null,
+ "bestByEngagement": null,
+ "worstByViews": null,
+ "mostRecent": null,
+ "oldest": null,
+ "top10ByViews": [],
+ "top10ByLikes": [],
+ "top10ByComments": [],
+ "top10ByEngagement": [],
+ "shortsCount": 0,
+ "regularCount": 0,
+ "avgShortViews": 0,
+ "avgRegularViews": 0,
+ "hdCount": 0,
+ "sdCount": 0,
+ "hdPercentage": 0,
+ "captionCount": 0,
+ "captionPercentage": 0,
+ "licensedCount": 0,
+ "licensedPercentage": 0,
+ "madeForKidsCount": 0,
+ "embeddableCount": 0,
+ "publishDayDistribution": {},
+ "publishHourDistribution": {},
+ "peakPublishDay": "",
+ "peakPublishHour": 0,
+ "durationDistribution": {
+ "short": 0,
+ "medium": 0,
+ "long": 0,
+ "veryLong": 0
+ },
+ "categoryDistribution": {},
+ "tagFrequency": [],
+ "videosLast7Days": 0,
+ "videosLast30Days": 0,
+ "videosLast90Days": 0,
+ "videosLast365Days": 0,
+ "uploadFrequencyPerWeek": 0,
+ "uploadFrequencyPerMonth": 0,
+ "consistencyScore": 0,
+ "viralityScore": 0,
+ "viewsDistribution": {
+ "ranges": [],
+ "counts": []
+ },
+ "engagementTrend": [],
+ "viewsTrend": [],
+ "likeRateTrend": []
+ },
+ "missing": {
+ "totalVideos": 0,
+ "totalViews": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "avgViews": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "medianViews": 0,
+ "totalEngagement": 0,
+ "overallEngagementRate": 0,
+ "avgDurationSeconds": 0,
+ "avgDurationFormatted": "0:00",
+ "totalDurationSeconds": 0,
+ "totalDurationFormatted": "0:00",
+ "bestByViews": null,
+ "bestByLikes": null,
+ "bestByComments": null,
+ "bestByEngagement": null,
+ "worstByViews": null,
+ "mostRecent": null,
+ "oldest": null,
+ "top10ByViews": [],
+ "top10ByLikes": [],
+ "top10ByComments": [],
+ "top10ByEngagement": [],
+ "shortsCount": 0,
+ "regularCount": 0,
+ "avgShortViews": 0,
+ "avgRegularViews": 0,
+ "hdCount": 0,
+ "sdCount": 0,
+ "hdPercentage": 0,
+ "captionCount": 0,
+ "captionPercentage": 0,
+ "licensedCount": 0,
+ "licensedPercentage": 0,
+ "madeForKidsCount": 0,
+ "embeddableCount": 0,
+ "publishDayDistribution": {},
+ "publishHourDistribution": {},
+ "peakPublishDay": "",
+ "peakPublishHour": 0,
+ "durationDistribution": {
+ "short": 0,
+ "medium": 0,
+ "long": 0,
+ "veryLong": 0
+ },
+ "categoryDistribution": {},
+ "tagFrequency": [],
+ "videosLast7Days": 0,
+ "videosLast30Days": 0,
+ "videosLast90Days": 0,
+ "videosLast365Days": 0,
+ "uploadFrequencyPerWeek": 0,
+ "uploadFrequencyPerMonth": 0,
+ "consistencyScore": 0,
+ "viralityScore": 0,
+ "viewsDistribution": {
+ "ranges": [],
+ "counts": []
+ },
+ "engagementTrend": [],
+ "viewsTrend": [],
+ "likeRateTrend": []
+ }
+}
diff --git a/backend/services/fixtures/youtubeAnalytics.generated.golden.json b/backend/services/fixtures/youtubeAnalytics.generated.golden.json
new file mode 100644
index 0000000..febf302
--- /dev/null
+++ b/backend/services/fixtures/youtubeAnalytics.generated.golden.json
@@ -0,0 +1,892 @@
+{
+ "totalVideos": 36,
+ "totalViews": 838970,
+ "totalLikes": 11590,
+ "totalComments": 1575,
+ "avgViews": 23305,
+ "avgLikes": 322,
+ "avgComments": 44,
+ "medianViews": 22745,
+ "totalEngagement": 13165,
+ "overallEngagementRate": "1.57",
+ "avgDurationSeconds": 5379,
+ "avgDurationFormatted": "1h 29m",
+ "totalDurationSeconds": 193650,
+ "totalDurationFormatted": "53h 47m",
+ "estimatedTotalWatchTimeHours": 45129595,
+ "bestByViews": {
+ "videoId": "g25",
+ "title": "Video g25",
+ "viewCount": 47975,
+ "likeCount": null,
+ "commentCount": 75,
+ "publishedAt": "2026-01-05T08:00:00.000Z",
+ "thumbnail": "https://i/g25/m.jpg",
+ "engagementRate": "0.16",
+ "durationSeconds": 6925
+ },
+ "bestByLikes": {
+ "videoId": "g29",
+ "title": "Video g29",
+ "viewCount": 29651,
+ "likeCount": 899,
+ "commentCount": 87,
+ "publishedAt": "2025-11-28T08:00:00.000Z",
+ "thumbnail": "https://i/g29/m.jpg",
+ "engagementRate": "3.33",
+ "durationSeconds": 8597
+ },
+ "bestByComments": {
+ "videoId": "g34",
+ "title": "Video g34",
+ "viewCount": 19246,
+ "likeCount": 154,
+ "commentCount": 102,
+ "publishedAt": "2025-10-11T20:00:00.000Z",
+ "thumbnail": "https://i/g34/m.jpg",
+ "engagementRate": "1.33",
+ "durationSeconds": 7102
+ },
+ "bestByEngagement": {
+ "videoId": "g19",
+ "title": "Video g19",
+ "viewCount": 461,
+ "likeCount": 589,
+ "commentCount": 57,
+ "publishedAt": "2026-03-03T08:00:00.000Z",
+ "thumbnail": "https://i/g19/m.jpg",
+ "engagementRate": "140.13",
+ "durationSeconds": 4387
+ },
+ "worstByViews": {
+ "videoId": "g00",
+ "title": "Video g00",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-30T20:00:00.000Z",
+ "thumbnail": "https://i/g00/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 0
+ },
+ "mostRecent": {
+ "videoId": "g00",
+ "title": "Video g00",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-30T20:00:00.000Z",
+ "thumbnail": "https://i/g00/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 0
+ },
+ "oldest": {
+ "videoId": "g35",
+ "title": "Video g35",
+ "viewCount": 27165,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2025-10-02T08:00:00.000Z",
+ "thumbnail": "https://i/g35/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 7535
+ },
+ "top10ByViews": [
+ {
+ "videoId": "g25",
+ "title": "Video g25",
+ "viewCount": 47975,
+ "likeCount": null,
+ "commentCount": 75,
+ "publishedAt": "2026-01-05T08:00:00.000Z",
+ "thumbnail": "https://i/g25/m.jpg",
+ "engagementRate": "0.16",
+ "durationSeconds": 6925
+ },
+ {
+ "videoId": "g06",
+ "title": "Video g06",
+ "viewCount": 47514,
+ "likeCount": 186,
+ "commentCount": 18,
+ "publishedAt": "2026-07-04T20:00:00.000Z",
+ "thumbnail": "https://i/g06/m.jpg",
+ "engagementRate": "0.43",
+ "durationSeconds": 2538
+ },
+ {
+ "videoId": "g31",
+ "title": "Video g31",
+ "viewCount": 45489,
+ "likeCount": 61,
+ "commentCount": 93,
+ "publishedAt": "2025-11-09T08:00:00.000Z",
+ "thumbnail": "https://i/g31/m.jpg",
+ "engagementRate": "0.34",
+ "durationSeconds": 5863
+ },
+ {
+ "videoId": "g12",
+ "title": "Video g12",
+ "viewCount": 45028,
+ "likeCount": 372,
+ "commentCount": 36,
+ "publishedAt": "2026-05-08T20:00:00.000Z",
+ "thumbnail": "https://i/g12/m.jpg",
+ "engagementRate": "0.91",
+ "durationSeconds": 1476
+ },
+ {
+ "videoId": "g18",
+ "title": "Video g18",
+ "viewCount": 42542,
+ "likeCount": 558,
+ "commentCount": 54,
+ "publishedAt": "2026-03-12T20:00:00.000Z",
+ "thumbnail": "https://i/g18/m.jpg",
+ "engagementRate": "1.44",
+ "durationSeconds": 414
+ },
+ {
+ "videoId": "g24",
+ "title": "Video g24",
+ "viewCount": 40056,
+ "likeCount": 744,
+ "commentCount": 72,
+ "publishedAt": "2026-01-14T20:00:00.000Z",
+ "thumbnail": "https://i/g24/m.jpg",
+ "engagementRate": "2.04",
+ "durationSeconds": 2892
+ },
+ {
+ "videoId": "g05",
+ "title": "Video g05",
+ "viewCount": 39595,
+ "likeCount": null,
+ "commentCount": 15,
+ "publishedAt": "2026-07-14T08:00:00.000Z",
+ "thumbnail": "https://i/g05/m.jpg",
+ "engagementRate": "0.04",
+ "durationSeconds": 9305
+ },
+ {
+ "videoId": "g30",
+ "title": "Video g30",
+ "viewCount": 37570,
+ "likeCount": null,
+ "commentCount": 90,
+ "publishedAt": "2025-11-18T20:00:00.000Z",
+ "thumbnail": "https://i/g30/m.jpg",
+ "engagementRate": "0.24",
+ "durationSeconds": 1830
+ },
+ {
+ "videoId": "g11",
+ "title": "Video g11",
+ "viewCount": 37109,
+ "likeCount": 341,
+ "commentCount": 33,
+ "publishedAt": "2026-05-18T08:00:00.000Z",
+ "thumbnail": "https://i/g11/m.jpg",
+ "engagementRate": "1.01",
+ "durationSeconds": 8243
+ },
+ {
+ "videoId": "g17",
+ "title": "Video g17",
+ "viewCount": 34623,
+ "likeCount": 527,
+ "commentCount": 51,
+ "publishedAt": "2026-03-22T08:00:00.000Z",
+ "thumbnail": "https://i/g17/m.jpg",
+ "engagementRate": "1.67",
+ "durationSeconds": 10781
+ }
+ ],
+ "top10ByLikes": [
+ {
+ "videoId": "g29",
+ "title": "Video g29",
+ "viewCount": 29651,
+ "likeCount": 899,
+ "commentCount": 87,
+ "publishedAt": "2025-11-28T08:00:00.000Z",
+ "thumbnail": "https://i/g29/m.jpg",
+ "engagementRate": "3.33",
+ "durationSeconds": 8597
+ },
+ {
+ "videoId": "g28",
+ "title": "Video g28",
+ "viewCount": 21732,
+ "likeCount": 868,
+ "commentCount": null,
+ "publishedAt": "2025-12-07T20:00:00.000Z",
+ "thumbnail": "https://i/g28/m.jpg",
+ "engagementRate": "3.99",
+ "durationSeconds": 4564
+ },
+ {
+ "videoId": "g27",
+ "title": "Video g27",
+ "viewCount": 13813,
+ "likeCount": 837,
+ "commentCount": 81,
+ "publishedAt": "2025-12-17T08:00:00.000Z",
+ "thumbnail": "https://i/g27/m.jpg",
+ "engagementRate": "6.65",
+ "durationSeconds": 591
+ },
+ {
+ "videoId": "g26",
+ "title": "Video g26",
+ "viewCount": 5894,
+ "likeCount": 806,
+ "commentCount": 78,
+ "publishedAt": "2025-12-26T20:00:00.000Z",
+ "thumbnail": "https://i/g26/m.jpg",
+ "engagementRate": "15.00",
+ "durationSeconds": 7358
+ },
+ {
+ "videoId": "g24",
+ "title": "Video g24",
+ "viewCount": 40056,
+ "likeCount": 744,
+ "commentCount": 72,
+ "publishedAt": "2026-01-14T20:00:00.000Z",
+ "thumbnail": "https://i/g24/m.jpg",
+ "engagementRate": "2.04",
+ "durationSeconds": 2892
+ },
+ {
+ "videoId": "g23",
+ "title": "Video g23",
+ "viewCount": 32137,
+ "likeCount": 713,
+ "commentCount": 69,
+ "publishedAt": "2026-01-24T08:00:00.000Z",
+ "thumbnail": "https://i/g23/m.jpg",
+ "engagementRate": "2.43",
+ "durationSeconds": 9719
+ },
+ {
+ "videoId": "g22",
+ "title": "Video g22",
+ "viewCount": 24218,
+ "likeCount": 682,
+ "commentCount": 66,
+ "publishedAt": "2026-02-02T20:00:00.000Z",
+ "thumbnail": "https://i/g22/m.jpg",
+ "engagementRate": "3.09",
+ "durationSeconds": 5686
+ },
+ {
+ "videoId": "g21",
+ "title": "Video g21",
+ "viewCount": 16299,
+ "likeCount": 651,
+ "commentCount": null,
+ "publishedAt": "2026-02-12T08:00:00.000Z",
+ "thumbnail": "https://i/g21/m.jpg",
+ "engagementRate": "3.99",
+ "durationSeconds": 1653
+ },
+ {
+ "videoId": "g19",
+ "title": "Video g19",
+ "viewCount": 461,
+ "likeCount": 589,
+ "commentCount": 57,
+ "publishedAt": "2026-03-03T08:00:00.000Z",
+ "thumbnail": "https://i/g19/m.jpg",
+ "engagementRate": "140.13",
+ "durationSeconds": 4387
+ },
+ {
+ "videoId": "g18",
+ "title": "Video g18",
+ "viewCount": 42542,
+ "likeCount": 558,
+ "commentCount": 54,
+ "publishedAt": "2026-03-12T20:00:00.000Z",
+ "thumbnail": "https://i/g18/m.jpg",
+ "engagementRate": "1.44",
+ "durationSeconds": 414
+ }
+ ],
+ "top10ByComments": [
+ {
+ "videoId": "g34",
+ "title": "Video g34",
+ "viewCount": 19246,
+ "likeCount": 154,
+ "commentCount": 102,
+ "publishedAt": "2025-10-11T20:00:00.000Z",
+ "thumbnail": "https://i/g34/m.jpg",
+ "engagementRate": "1.33",
+ "durationSeconds": 7102
+ },
+ {
+ "videoId": "g33",
+ "title": "Video g33",
+ "viewCount": 11327,
+ "likeCount": 123,
+ "commentCount": 99,
+ "publishedAt": "2025-10-21T08:00:00.000Z",
+ "thumbnail": "https://i/g33/m.jpg",
+ "engagementRate": "1.96",
+ "durationSeconds": 3069
+ },
+ {
+ "videoId": "g32",
+ "title": "Video g32",
+ "viewCount": 3408,
+ "likeCount": 92,
+ "commentCount": 96,
+ "publishedAt": "2025-10-30T20:00:00.000Z",
+ "thumbnail": "https://i/g32/m.jpg",
+ "engagementRate": "5.52",
+ "durationSeconds": 9896
+ },
+ {
+ "videoId": "g31",
+ "title": "Video g31",
+ "viewCount": 45489,
+ "likeCount": 61,
+ "commentCount": 93,
+ "publishedAt": "2025-11-09T08:00:00.000Z",
+ "thumbnail": "https://i/g31/m.jpg",
+ "engagementRate": "0.34",
+ "durationSeconds": 5863
+ },
+ {
+ "videoId": "g30",
+ "title": "Video g30",
+ "viewCount": 37570,
+ "likeCount": null,
+ "commentCount": 90,
+ "publishedAt": "2025-11-18T20:00:00.000Z",
+ "thumbnail": "https://i/g30/m.jpg",
+ "engagementRate": "0.24",
+ "durationSeconds": 1830
+ },
+ {
+ "videoId": "g29",
+ "title": "Video g29",
+ "viewCount": 29651,
+ "likeCount": 899,
+ "commentCount": 87,
+ "publishedAt": "2025-11-28T08:00:00.000Z",
+ "thumbnail": "https://i/g29/m.jpg",
+ "engagementRate": "3.33",
+ "durationSeconds": 8597
+ },
+ {
+ "videoId": "g27",
+ "title": "Video g27",
+ "viewCount": 13813,
+ "likeCount": 837,
+ "commentCount": 81,
+ "publishedAt": "2025-12-17T08:00:00.000Z",
+ "thumbnail": "https://i/g27/m.jpg",
+ "engagementRate": "6.65",
+ "durationSeconds": 591
+ },
+ {
+ "videoId": "g26",
+ "title": "Video g26",
+ "viewCount": 5894,
+ "likeCount": 806,
+ "commentCount": 78,
+ "publishedAt": "2025-12-26T20:00:00.000Z",
+ "thumbnail": "https://i/g26/m.jpg",
+ "engagementRate": "15.00",
+ "durationSeconds": 7358
+ },
+ {
+ "videoId": "g25",
+ "title": "Video g25",
+ "viewCount": 47975,
+ "likeCount": null,
+ "commentCount": 75,
+ "publishedAt": "2026-01-05T08:00:00.000Z",
+ "thumbnail": "https://i/g25/m.jpg",
+ "engagementRate": "0.16",
+ "durationSeconds": 6925
+ },
+ {
+ "videoId": "g24",
+ "title": "Video g24",
+ "viewCount": 40056,
+ "likeCount": 744,
+ "commentCount": 72,
+ "publishedAt": "2026-01-14T20:00:00.000Z",
+ "thumbnail": "https://i/g24/m.jpg",
+ "engagementRate": "2.04",
+ "durationSeconds": 2892
+ }
+ ],
+ "top10ByEngagement": [
+ {
+ "videoId": "g19",
+ "title": "Video g19",
+ "viewCount": 461,
+ "likeCount": 589,
+ "commentCount": 57,
+ "publishedAt": "2026-03-03T08:00:00.000Z",
+ "thumbnail": "https://i/g19/m.jpg",
+ "engagementRate": "140.13",
+ "durationSeconds": 4387
+ },
+ {
+ "videoId": "g13",
+ "title": "Video g13",
+ "viewCount": 2947,
+ "likeCount": 403,
+ "commentCount": 39,
+ "publishedAt": "2026-04-29T08:00:00.000Z",
+ "thumbnail": "https://i/g13/m.jpg",
+ "engagementRate": "15.00",
+ "durationSeconds": 5509
+ },
+ {
+ "videoId": "g26",
+ "title": "Video g26",
+ "viewCount": 5894,
+ "likeCount": 806,
+ "commentCount": 78,
+ "publishedAt": "2025-12-26T20:00:00.000Z",
+ "thumbnail": "https://i/g26/m.jpg",
+ "engagementRate": "15.00",
+ "durationSeconds": 7358
+ },
+ {
+ "videoId": "g27",
+ "title": "Video g27",
+ "viewCount": 13813,
+ "likeCount": 837,
+ "commentCount": 81,
+ "publishedAt": "2025-12-17T08:00:00.000Z",
+ "thumbnail": "https://i/g27/m.jpg",
+ "engagementRate": "6.65",
+ "durationSeconds": 591
+ },
+ {
+ "videoId": "g32",
+ "title": "Video g32",
+ "viewCount": 3408,
+ "likeCount": 92,
+ "commentCount": 96,
+ "publishedAt": "2025-10-30T20:00:00.000Z",
+ "thumbnail": "https://i/g32/m.jpg",
+ "engagementRate": "5.52",
+ "durationSeconds": 9896
+ },
+ {
+ "videoId": "g07",
+ "title": "Video g07",
+ "viewCount": 5433,
+ "likeCount": 217,
+ "commentCount": null,
+ "publishedAt": "2026-06-25T08:00:00.000Z",
+ "thumbnail": "https://i/g07/m.jpg",
+ "engagementRate": "3.99",
+ "durationSeconds": 6571
+ },
+ {
+ "videoId": "g14",
+ "title": "Video g14",
+ "viewCount": 10866,
+ "likeCount": 434,
+ "commentCount": null,
+ "publishedAt": "2026-04-19T20:00:00.000Z",
+ "thumbnail": "https://i/g14/m.jpg",
+ "engagementRate": "3.99",
+ "durationSeconds": 9482
+ },
+ {
+ "videoId": "g21",
+ "title": "Video g21",
+ "viewCount": 16299,
+ "likeCount": 651,
+ "commentCount": null,
+ "publishedAt": "2026-02-12T08:00:00.000Z",
+ "thumbnail": "https://i/g21/m.jpg",
+ "engagementRate": "3.99",
+ "durationSeconds": 1653
+ },
+ {
+ "videoId": "g28",
+ "title": "Video g28",
+ "viewCount": 21732,
+ "likeCount": 868,
+ "commentCount": null,
+ "publishedAt": "2025-12-07T20:00:00.000Z",
+ "thumbnail": "https://i/g28/m.jpg",
+ "engagementRate": "3.99",
+ "durationSeconds": 4564
+ },
+ {
+ "videoId": "g29",
+ "title": "Video g29",
+ "viewCount": 29651,
+ "likeCount": 899,
+ "commentCount": 87,
+ "publishedAt": "2025-11-28T08:00:00.000Z",
+ "thumbnail": "https://i/g29/m.jpg",
+ "engagementRate": "3.33",
+ "durationSeconds": 8597
+ }
+ ],
+ "shortsCount": 1,
+ "regularCount": 35,
+ "avgShortViews": 0,
+ "avgRegularViews": 23971,
+ "avgShortLikes": 0,
+ "avgRegularLikes": 331,
+ "hdCount": 36,
+ "sdCount": 0,
+ "hdPercentage": "100.0",
+ "captionCount": 0,
+ "captionPercentage": "0.0",
+ "licensedCount": 36,
+ "licensedPercentage": "100.0",
+ "madeForKidsCount": 0,
+ "embeddableCount": 36,
+ "embeddablePercentage": "100.0",
+ "publishDayDistribution": {
+ "Sunday": 6,
+ "Friday": 5,
+ "Tuesday": 6,
+ "Thursday": 6,
+ "Saturday": 5,
+ "Monday": 4,
+ "Wednesday": 4
+ },
+ "publishHourDistribution": {
+ "8": 18,
+ "20": 18
+ },
+ "peakPublishDay": "Sunday",
+ "peakPublishHour": 8,
+ "durationDistribution": {
+ "short": 1,
+ "medium": 3,
+ "long": 8,
+ "veryLong": 24
+ },
+ "categoryDistribution": {
+ "20": 6,
+ "21": 6,
+ "22": 6,
+ "23": 6,
+ "24": 6,
+ "25": 6
+ },
+ "tagFrequency": [
+ {
+ "tag": "tag0",
+ "count": 9
+ },
+ {
+ "tag": "tag4",
+ "count": 9
+ },
+ {
+ "tag": "tag8",
+ "count": 9
+ },
+ {
+ "tag": "tag12",
+ "count": 9
+ },
+ {
+ "tag": "tag16",
+ "count": 9
+ },
+ {
+ "tag": "tag20",
+ "count": 9
+ },
+ {
+ "tag": "tag24",
+ "count": 9
+ },
+ {
+ "tag": "tag28",
+ "count": 9
+ },
+ {
+ "tag": "tag32",
+ "count": 9
+ },
+ {
+ "tag": "tag36",
+ "count": 9
+ },
+ {
+ "tag": "tag3",
+ "count": 9
+ },
+ {
+ "tag": "tag7",
+ "count": 9
+ },
+ {
+ "tag": "tag11",
+ "count": 9
+ },
+ {
+ "tag": "tag15",
+ "count": 9
+ },
+ {
+ "tag": "tag19",
+ "count": 9
+ },
+ {
+ "tag": "tag23",
+ "count": 9
+ },
+ {
+ "tag": "tag27",
+ "count": 9
+ },
+ {
+ "tag": "tag31",
+ "count": 9
+ },
+ {
+ "tag": "tag35",
+ "count": 9
+ },
+ {
+ "tag": "tag39",
+ "count": 9
+ },
+ {
+ "tag": "tag2",
+ "count": 9
+ },
+ {
+ "tag": "tag6",
+ "count": 9
+ },
+ {
+ "tag": "tag10",
+ "count": 9
+ },
+ {
+ "tag": "tag14",
+ "count": 9
+ },
+ {
+ "tag": "tag18",
+ "count": 9
+ },
+ {
+ "tag": "tag22",
+ "count": 9
+ },
+ {
+ "tag": "tag26",
+ "count": 9
+ },
+ {
+ "tag": "tag30",
+ "count": 9
+ },
+ {
+ "tag": "tag34",
+ "count": 9
+ },
+ {
+ "tag": "tag38",
+ "count": 9
+ }
+ ],
+ "videosLast7Days": 1,
+ "videosLast30Days": 3,
+ "videosLast90Days": 10,
+ "videosLast365Days": 36,
+ "uploadFrequencyPerWeek": "0.8",
+ "uploadFrequencyPerMonth": "3.3",
+ "consistencyScore": 100,
+ "viralityScore": 2.1,
+ "viewsDistribution": {
+ "ranges": [
+ "0-4.8K",
+ "4.8K-9.6K",
+ "9.6K-14.4K",
+ "14.4K-19.2K",
+ "19.2K-24.0K",
+ "24.0K-28.8K",
+ "28.8K-33.6K",
+ "33.6K-38.4K",
+ "38.4K-43.2K",
+ "43.2K-48.0K"
+ ],
+ "counts": [
+ 4,
+ 4,
+ 4,
+ 3,
+ 4,
+ 3,
+ 4,
+ 3,
+ 3,
+ 4
+ ]
+ },
+ "viewsTrend": [
+ {
+ "month": "2025-10",
+ "value": 61146,
+ "count": 4
+ },
+ {
+ "month": "2025-11",
+ "value": 112710,
+ "count": 3
+ },
+ {
+ "month": "2025-12",
+ "value": 41439,
+ "count": 3
+ },
+ {
+ "month": "2026-01",
+ "value": 120168,
+ "count": 3
+ },
+ {
+ "month": "2026-02",
+ "value": 48897,
+ "count": 3
+ },
+ {
+ "month": "2026-03",
+ "value": 104330,
+ "count": 4
+ },
+ {
+ "month": "2026-04",
+ "value": 32598,
+ "count": 3
+ },
+ {
+ "month": "2026-05",
+ "value": 111327,
+ "count": 3
+ },
+ {
+ "month": "2026-06",
+ "value": 40056,
+ "count": 3
+ },
+ {
+ "month": "2026-07",
+ "value": 118785,
+ "count": 3
+ },
+ {
+ "month": "2026-08",
+ "value": 47514,
+ "count": 4
+ }
+ ],
+ "engagementTrend": [
+ {
+ "month": "2025-10",
+ "value": "1.09"
+ },
+ {
+ "month": "2025-11",
+ "value": "1.09"
+ },
+ {
+ "month": "2025-12",
+ "value": "6.44"
+ },
+ {
+ "month": "2026-01",
+ "value": "1.39"
+ },
+ {
+ "month": "2026-02",
+ "value": "2.98"
+ },
+ {
+ "month": "2026-03",
+ "value": "2.28"
+ },
+ {
+ "month": "2026-04",
+ "value": "2.83"
+ },
+ {
+ "month": "2026-05",
+ "value": "0.73"
+ },
+ {
+ "month": "2026-06",
+ "value": "1.98"
+ },
+ {
+ "month": "2026-07",
+ "value": "0.30"
+ },
+ {
+ "month": "2026-08",
+ "value": "0.43"
+ }
+ ],
+ "likeRateTrend": [
+ {
+ "month": "2025-10",
+ "value": "0.60"
+ },
+ {
+ "month": "2025-11",
+ "value": "0.85"
+ },
+ {
+ "month": "2025-12",
+ "value": "6.06"
+ },
+ {
+ "month": "2026-01",
+ "value": "1.21"
+ },
+ {
+ "month": "2026-02",
+ "value": "2.73"
+ },
+ {
+ "month": "2026-03",
+ "value": "2.08"
+ },
+ {
+ "month": "2026-04",
+ "value": "2.57"
+ },
+ {
+ "month": "2026-05",
+ "value": "0.64"
+ },
+ {
+ "month": "2026-06",
+ "value": "1.86"
+ },
+ {
+ "month": "2026-07",
+ "value": "0.26"
+ },
+ {
+ "month": "2026-08",
+ "value": "0.39"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/youtubeAnalytics.rich.golden.json b/backend/services/fixtures/youtubeAnalytics.rich.golden.json
new file mode 100644
index 0000000..641c7a6
--- /dev/null
+++ b/backend/services/fixtures/youtubeAnalytics.rich.golden.json
@@ -0,0 +1,740 @@
+{
+ "totalVideos": 11,
+ "totalViews": 1374428,
+ "totalLikes": 67365,
+ "totalComments": 4629,
+ "avgViews": 124948,
+ "avgLikes": 6124,
+ "avgComments": 421,
+ "medianViews": 5400,
+ "totalEngagement": 71994,
+ "overallEngagementRate": "5.24",
+ "avgDurationSeconds": 1294,
+ "avgDurationFormatted": "21m 34s",
+ "totalDurationSeconds": 14239,
+ "totalDurationFormatted": "3h 57m",
+ "estimatedTotalWatchTimeHours": 5436245,
+ "bestByViews": {
+ "videoId": "v10",
+ "title": "Video v10",
+ "viewCount": 1000000,
+ "likeCount": 50000,
+ "commentCount": 3000,
+ "publishedAt": "2025-09-02T12:00:00Z",
+ "thumbnail": "https://i/v10/m.jpg",
+ "engagementRate": "5.30",
+ "durationSeconds": 260
+ },
+ "bestByLikes": {
+ "videoId": "v10",
+ "title": "Video v10",
+ "viewCount": 1000000,
+ "likeCount": 50000,
+ "commentCount": 3000,
+ "publishedAt": "2025-09-02T12:00:00Z",
+ "thumbnail": "https://i/v10/m.jpg",
+ "engagementRate": "5.30",
+ "durationSeconds": 260
+ },
+ "bestByComments": {
+ "videoId": "v10",
+ "title": "Video v10",
+ "viewCount": 1000000,
+ "likeCount": 50000,
+ "commentCount": 3000,
+ "publishedAt": "2025-09-02T12:00:00Z",
+ "thumbnail": "https://i/v10/m.jpg",
+ "engagementRate": "5.30",
+ "durationSeconds": 260
+ },
+ "bestByEngagement": {
+ "videoId": "v01",
+ "title": "Video v01",
+ "viewCount": 12000,
+ "likeCount": 900,
+ "commentCount": 40,
+ "publishedAt": "2026-08-31T09:15:00Z",
+ "thumbnail": "https://i/v01/m.jpg",
+ "engagementRate": "7.83",
+ "durationSeconds": 45
+ },
+ "worstByViews": {
+ "videoId": "v05",
+ "title": "Video v05",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-07-14T06:30:00Z",
+ "thumbnail": "https://i/v05/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 600
+ },
+ "mostRecent": {
+ "videoId": "v01",
+ "title": "Video v01",
+ "viewCount": 12000,
+ "likeCount": 900,
+ "commentCount": 40,
+ "publishedAt": "2026-08-31T09:15:00Z",
+ "thumbnail": "https://i/v01/m.jpg",
+ "engagementRate": "7.83",
+ "durationSeconds": 45
+ },
+ "oldest": {
+ "videoId": "v11",
+ "title": "Video v11",
+ "viewCount": 1,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2024-01-01T00:00:00Z",
+ "thumbnail": "https://i/v11/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1800
+ },
+ "top10ByViews": [
+ {
+ "videoId": "v10",
+ "title": "Video v10",
+ "viewCount": 1000000,
+ "likeCount": 50000,
+ "commentCount": 3000,
+ "publishedAt": "2025-09-02T12:00:00Z",
+ "thumbnail": "https://i/v10/m.jpg",
+ "engagementRate": "5.30",
+ "durationSeconds": 260
+ },
+ {
+ "videoId": "v09",
+ "title": "Video v09",
+ "viewCount": 250000,
+ "likeCount": 12000,
+ "commentCount": 900,
+ "publishedAt": "2025-12-31T23:30:00Z",
+ "thumbnail": "https://i/v09/m.jpg",
+ "engagementRate": "5.16",
+ "durationSeconds": 59
+ },
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ {
+ "videoId": "v01",
+ "title": "Video v01",
+ "viewCount": 12000,
+ "likeCount": 900,
+ "commentCount": 40,
+ "publishedAt": "2026-08-31T09:15:00Z",
+ "thumbnail": "https://i/v01/m.jpg",
+ "engagementRate": "7.83",
+ "durationSeconds": 45
+ },
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ {
+ "videoId": "v06",
+ "title": "Video v06",
+ "viewCount": 3100,
+ "likeCount": 120,
+ "commentCount": 15,
+ "publishedAt": "2026-06-20T23:59:00Z",
+ "thumbnail": "https://i/v06/m.jpg",
+ "engagementRate": "4.35",
+ "durationSeconds": 7200
+ },
+ {
+ "videoId": "v07",
+ "title": "Video v07",
+ "viewCount": 450,
+ "likeCount": 30,
+ "commentCount": 2,
+ "publishedAt": "2026-06-03T00:00:00Z",
+ "thumbnail": "",
+ "engagementRate": "7.11",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v08",
+ "title": "Video v08",
+ "viewCount": 77,
+ "likeCount": 5,
+ "commentCount": 1,
+ "publishedAt": "2026-03-15T08:00:00Z",
+ "thumbnail": "https://i/v08/m.jpg",
+ "engagementRate": "7.79",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v11",
+ "title": "Video v11",
+ "viewCount": 1,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2024-01-01T00:00:00Z",
+ "thumbnail": "https://i/v11/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1800
+ }
+ ],
+ "top10ByLikes": [
+ {
+ "videoId": "v10",
+ "title": "Video v10",
+ "viewCount": 1000000,
+ "likeCount": 50000,
+ "commentCount": 3000,
+ "publishedAt": "2025-09-02T12:00:00Z",
+ "thumbnail": "https://i/v10/m.jpg",
+ "engagementRate": "5.30",
+ "durationSeconds": 260
+ },
+ {
+ "videoId": "v09",
+ "title": "Video v09",
+ "viewCount": 250000,
+ "likeCount": 12000,
+ "commentCount": 900,
+ "publishedAt": "2025-12-31T23:30:00Z",
+ "thumbnail": "https://i/v09/m.jpg",
+ "engagementRate": "5.16",
+ "durationSeconds": 59
+ },
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ {
+ "videoId": "v01",
+ "title": "Video v01",
+ "viewCount": 12000,
+ "likeCount": 900,
+ "commentCount": 40,
+ "publishedAt": "2026-08-31T09:15:00Z",
+ "thumbnail": "https://i/v01/m.jpg",
+ "engagementRate": "7.83",
+ "durationSeconds": 45
+ },
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ {
+ "videoId": "v06",
+ "title": "Video v06",
+ "viewCount": 3100,
+ "likeCount": 120,
+ "commentCount": 15,
+ "publishedAt": "2026-06-20T23:59:00Z",
+ "thumbnail": "https://i/v06/m.jpg",
+ "engagementRate": "4.35",
+ "durationSeconds": 7200
+ },
+ {
+ "videoId": "v07",
+ "title": "Video v07",
+ "viewCount": 450,
+ "likeCount": 30,
+ "commentCount": 2,
+ "publishedAt": "2026-06-03T00:00:00Z",
+ "thumbnail": "",
+ "engagementRate": "7.11",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v08",
+ "title": "Video v08",
+ "viewCount": 77,
+ "likeCount": 5,
+ "commentCount": 1,
+ "publishedAt": "2026-03-15T08:00:00Z",
+ "thumbnail": "https://i/v08/m.jpg",
+ "engagementRate": "7.79",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ {
+ "videoId": "v05",
+ "title": "Video v05",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-07-14T06:30:00Z",
+ "thumbnail": "https://i/v05/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 600
+ }
+ ],
+ "top10ByComments": [
+ {
+ "videoId": "v10",
+ "title": "Video v10",
+ "viewCount": 1000000,
+ "likeCount": 50000,
+ "commentCount": 3000,
+ "publishedAt": "2025-09-02T12:00:00Z",
+ "thumbnail": "https://i/v10/m.jpg",
+ "engagementRate": "5.30",
+ "durationSeconds": 260
+ },
+ {
+ "videoId": "v09",
+ "title": "Video v09",
+ "viewCount": 250000,
+ "likeCount": 12000,
+ "commentCount": 900,
+ "publishedAt": "2025-12-31T23:30:00Z",
+ "thumbnail": "https://i/v09/m.jpg",
+ "engagementRate": "5.16",
+ "durationSeconds": 59
+ },
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ {
+ "videoId": "v01",
+ "title": "Video v01",
+ "viewCount": 12000,
+ "likeCount": 900,
+ "commentCount": 40,
+ "publishedAt": "2026-08-31T09:15:00Z",
+ "thumbnail": "https://i/v01/m.jpg",
+ "engagementRate": "7.83",
+ "durationSeconds": 45
+ },
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ {
+ "videoId": "v06",
+ "title": "Video v06",
+ "viewCount": 3100,
+ "likeCount": 120,
+ "commentCount": 15,
+ "publishedAt": "2026-06-20T23:59:00Z",
+ "thumbnail": "https://i/v06/m.jpg",
+ "engagementRate": "4.35",
+ "durationSeconds": 7200
+ },
+ {
+ "videoId": "v07",
+ "title": "Video v07",
+ "viewCount": 450,
+ "likeCount": 30,
+ "commentCount": 2,
+ "publishedAt": "2026-06-03T00:00:00Z",
+ "thumbnail": "",
+ "engagementRate": "7.11",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v08",
+ "title": "Video v08",
+ "viewCount": 77,
+ "likeCount": 5,
+ "commentCount": 1,
+ "publishedAt": "2026-03-15T08:00:00Z",
+ "thumbnail": "https://i/v08/m.jpg",
+ "engagementRate": "7.79",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ {
+ "videoId": "v05",
+ "title": "Video v05",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-07-14T06:30:00Z",
+ "thumbnail": "https://i/v05/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 600
+ }
+ ],
+ "top10ByEngagement": [
+ {
+ "videoId": "v01",
+ "title": "Video v01",
+ "viewCount": 12000,
+ "likeCount": 900,
+ "commentCount": 40,
+ "publishedAt": "2026-08-31T09:15:00Z",
+ "thumbnail": "https://i/v01/m.jpg",
+ "engagementRate": "7.83",
+ "durationSeconds": 45
+ },
+ {
+ "videoId": "v08",
+ "title": "Video v08",
+ "viewCount": 77,
+ "likeCount": 5,
+ "commentCount": 1,
+ "publishedAt": "2026-03-15T08:00:00Z",
+ "thumbnail": "https://i/v08/m.jpg",
+ "engagementRate": "7.79",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v07",
+ "title": "Video v07",
+ "viewCount": 450,
+ "likeCount": 30,
+ "commentCount": 2,
+ "publishedAt": "2026-06-03T00:00:00Z",
+ "thumbnail": "",
+ "engagementRate": "7.11",
+ "durationSeconds": 0
+ },
+ {
+ "videoId": "v10",
+ "title": "Video v10",
+ "viewCount": 1000000,
+ "likeCount": 50000,
+ "commentCount": 3000,
+ "publishedAt": "2025-09-02T12:00:00Z",
+ "thumbnail": "https://i/v10/m.jpg",
+ "engagementRate": "5.30",
+ "durationSeconds": 260
+ },
+ {
+ "videoId": "v09",
+ "title": "Video v09",
+ "viewCount": 250000,
+ "likeCount": 12000,
+ "commentCount": 900,
+ "publishedAt": "2025-12-31T23:30:00Z",
+ "thumbnail": "https://i/v09/m.jpg",
+ "engagementRate": "5.16",
+ "durationSeconds": 59
+ },
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ {
+ "videoId": "v06",
+ "title": "Video v06",
+ "viewCount": 3100,
+ "likeCount": 120,
+ "commentCount": 15,
+ "publishedAt": "2026-06-20T23:59:00Z",
+ "thumbnail": "https://i/v06/m.jpg",
+ "engagementRate": "4.35",
+ "durationSeconds": 7200
+ },
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ {
+ "videoId": "v05",
+ "title": "Video v05",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-07-14T06:30:00Z",
+ "thumbnail": "https://i/v05/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 600
+ }
+ ],
+ "shortsCount": 5,
+ "regularCount": 6,
+ "avgShortViews": 53585,
+ "avgRegularViews": 184417,
+ "avgShortLikes": 2629,
+ "avgRegularLikes": 9037,
+ "hdCount": 9,
+ "sdCount": 2,
+ "hdPercentage": "81.8",
+ "captionCount": 2,
+ "captionPercentage": "18.2",
+ "licensedCount": 10,
+ "licensedPercentage": "90.9",
+ "madeForKidsCount": 1,
+ "embeddableCount": 10,
+ "embeddablePercentage": "90.9",
+ "publishDayDistribution": {
+ "Monday": 2,
+ "Tuesday": 4,
+ "Sunday": 2,
+ "Saturday": 1,
+ "Wednesday": 2
+ },
+ "publishHourDistribution": {
+ "0": 2,
+ "6": 1,
+ "8": 1,
+ "9": 1,
+ "12": 3,
+ "21": 1,
+ "23": 2
+ },
+ "peakPublishDay": "Tuesday",
+ "peakPublishHour": 12,
+ "durationDistribution": {
+ "short": 5,
+ "medium": 3,
+ "long": 1,
+ "veryLong": 2
+ },
+ "categoryDistribution": {
+ "10": 2,
+ "22": 8,
+ "Unknown": 1
+ },
+ "tagFrequency": [
+ {
+ "tag": "travel",
+ "count": 4
+ },
+ {
+ "tag": "shorts",
+ "count": 2
+ },
+ {
+ "tag": "vlog",
+ "count": 1
+ },
+ {
+ "tag": "long form",
+ "count": 1
+ },
+ {
+ "tag": "newyear",
+ "count": 1
+ }
+ ],
+ "videosLast7Days": 1,
+ "videosLast30Days": 4,
+ "videosLast90Days": 6,
+ "videosLast365Days": 10,
+ "uploadFrequencyPerWeek": "0.1",
+ "uploadFrequencyPerMonth": "0.3",
+ "consistencyScore": 93,
+ "viralityScore": 8,
+ "viewsDistribution": {
+ "ranges": [
+ "0-100.0K",
+ "100.0K-200.0K",
+ "200.0K-300.0K",
+ "300.0K-400.0K",
+ "400.0K-500.0K",
+ "500.0K-600.0K",
+ "600.0K-700.0K",
+ "700.0K-800.0K",
+ "800.0K-900.0K",
+ "900.0K-1.0M"
+ ],
+ "counts": [
+ 9,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "viewsTrend": [
+ {
+ "month": "2024-01",
+ "value": 1,
+ "count": 1
+ },
+ {
+ "month": "2025-09",
+ "value": 1000000,
+ "count": 1
+ },
+ {
+ "month": "2025-12",
+ "value": 250000,
+ "count": 1
+ },
+ {
+ "month": "2026-03",
+ "value": 77,
+ "count": 1
+ },
+ {
+ "month": "2026-06",
+ "value": 3550,
+ "count": 2
+ },
+ {
+ "month": "2026-07",
+ "value": 0,
+ "count": 1
+ },
+ {
+ "month": "2026-08",
+ "value": 120800,
+ "count": 4
+ }
+ ],
+ "engagementTrend": [
+ {
+ "month": "2024-01",
+ "value": "0.00"
+ },
+ {
+ "month": "2025-09",
+ "value": "5.30"
+ },
+ {
+ "month": "2025-12",
+ "value": "5.16"
+ },
+ {
+ "month": "2026-03",
+ "value": "7.79"
+ },
+ {
+ "month": "2026-06",
+ "value": "4.70"
+ },
+ {
+ "month": "2026-07",
+ "value": 0
+ },
+ {
+ "month": "2026-08",
+ "value": "4.90"
+ }
+ ],
+ "likeRateTrend": [
+ {
+ "month": "2024-01",
+ "value": "0.00"
+ },
+ {
+ "month": "2025-09",
+ "value": "5.00"
+ },
+ {
+ "month": "2025-12",
+ "value": "4.80"
+ },
+ {
+ "month": "2026-03",
+ "value": "6.49"
+ },
+ {
+ "month": "2026-06",
+ "value": "4.23"
+ },
+ {
+ "month": "2026-07",
+ "value": 0
+ },
+ {
+ "month": "2026-08",
+ "value": "4.31"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/youtubeAnalytics.small.golden.json b/backend/services/fixtures/youtubeAnalytics.small.golden.json
new file mode 100644
index 0000000..a086e55
--- /dev/null
+++ b/backend/services/fixtures/youtubeAnalytics.small.golden.json
@@ -0,0 +1,808 @@
+{
+ "single": {
+ "totalVideos": 1,
+ "totalViews": 98000,
+ "totalLikes": 4100,
+ "totalComments": 640,
+ "avgViews": 98000,
+ "avgLikes": 4100,
+ "avgComments": 640,
+ "medianViews": 98000,
+ "totalEngagement": 4740,
+ "overallEngagementRate": "4.84",
+ "avgDurationSeconds": 3723,
+ "avgDurationFormatted": "1h 2m",
+ "totalDurationSeconds": 3723,
+ "totalDurationFormatted": "1h 2m",
+ "estimatedTotalWatchTimeHours": 101348,
+ "bestByViews": {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ "bestByLikes": {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ "bestByComments": {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ "bestByEngagement": {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ "worstByViews": {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ "mostRecent": {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ "oldest": {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ },
+ "top10ByViews": [
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ }
+ ],
+ "top10ByLikes": [
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ }
+ ],
+ "top10ByComments": [
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ }
+ ],
+ "top10ByEngagement": [
+ {
+ "videoId": "v04",
+ "title": "Video v04",
+ "viewCount": 98000,
+ "likeCount": 4100,
+ "commentCount": 640,
+ "publishedAt": "2026-08-02T21:00:00Z",
+ "thumbnail": "https://i/v04/m.jpg",
+ "engagementRate": "4.84",
+ "durationSeconds": 3723
+ }
+ ],
+ "shortsCount": 0,
+ "regularCount": 1,
+ "avgShortViews": 0,
+ "avgRegularViews": 98000,
+ "avgShortLikes": 0,
+ "avgRegularLikes": 4100,
+ "hdCount": 1,
+ "sdCount": 0,
+ "hdPercentage": "100.0",
+ "captionCount": 1,
+ "captionPercentage": "100.0",
+ "licensedCount": 1,
+ "licensedPercentage": "100.0",
+ "madeForKidsCount": 0,
+ "embeddableCount": 1,
+ "embeddablePercentage": "100.0",
+ "publishDayDistribution": {
+ "Sunday": 1
+ },
+ "publishHourDistribution": {
+ "21": 1
+ },
+ "peakPublishDay": "Sunday",
+ "peakPublishHour": 21,
+ "durationDistribution": {
+ "short": 0,
+ "medium": 0,
+ "long": 0,
+ "veryLong": 1
+ },
+ "categoryDistribution": {
+ "22": 1
+ },
+ "tagFrequency": [
+ {
+ "tag": "travel",
+ "count": 1
+ },
+ {
+ "tag": "long form",
+ "count": 1
+ }
+ ],
+ "videosLast7Days": 0,
+ "videosLast30Days": 1,
+ "videosLast90Days": 1,
+ "videosLast365Days": 1,
+ "uploadFrequencyPerWeek": "0.2",
+ "uploadFrequencyPerMonth": "1.0",
+ "consistencyScore": 100,
+ "viralityScore": 1,
+ "viewsDistribution": {
+ "ranges": [
+ "0-9.8K",
+ "9.8K-19.6K",
+ "19.6K-29.4K",
+ "29.4K-39.2K",
+ "39.2K-49.0K",
+ "49.0K-58.8K",
+ "58.8K-68.6K",
+ "68.6K-78.4K",
+ "78.4K-88.2K",
+ "88.2K-98.0K"
+ ],
+ "counts": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "viewsTrend": [
+ {
+ "month": "2026-08",
+ "value": 98000,
+ "count": 1
+ }
+ ],
+ "engagementTrend": [
+ {
+ "month": "2026-08",
+ "value": "4.84"
+ }
+ ],
+ "likeRateTrend": [
+ {
+ "month": "2026-08",
+ "value": "4.18"
+ }
+ ]
+ },
+ "pair": {
+ "totalVideos": 2,
+ "totalViews": 10800,
+ "totalLikes": 210,
+ "totalComments": 31,
+ "avgViews": 5400,
+ "avgLikes": 105,
+ "avgComments": 16,
+ "medianViews": 5400,
+ "totalEngagement": 241,
+ "overallEngagementRate": "2.23",
+ "avgDurationSeconds": 276,
+ "avgDurationFormatted": "4m 36s",
+ "totalDurationSeconds": 552,
+ "totalDurationFormatted": "9m 12s",
+ "estimatedTotalWatchTimeHours": 1656,
+ "bestByViews": {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ "bestByLikes": {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ "bestByComments": {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ "bestByEngagement": {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ "worstByViews": {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ "mostRecent": {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ "oldest": {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ "top10ByViews": [
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ }
+ ],
+ "top10ByLikes": [
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ }
+ ],
+ "top10ByComments": [
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ },
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ }
+ ],
+ "top10ByEngagement": [
+ {
+ "videoId": "v03",
+ "title": "Video v03",
+ "viewCount": 5400,
+ "likeCount": 210,
+ "commentCount": null,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v03/m.jpg",
+ "engagementRate": "3.89",
+ "durationSeconds": 60
+ },
+ {
+ "videoId": "v02",
+ "title": "Video v02",
+ "viewCount": 5400,
+ "likeCount": null,
+ "commentCount": 31,
+ "publishedAt": "2026-08-25T12:00:00Z",
+ "thumbnail": "https://i/v02/m.jpg",
+ "engagementRate": "0.57",
+ "durationSeconds": 492
+ }
+ ],
+ "shortsCount": 1,
+ "regularCount": 1,
+ "avgShortViews": 5400,
+ "avgRegularViews": 5400,
+ "avgShortLikes": 210,
+ "avgRegularLikes": 0,
+ "hdCount": 1,
+ "sdCount": 1,
+ "hdPercentage": "50.0",
+ "captionCount": 0,
+ "captionPercentage": "0.0",
+ "licensedCount": 2,
+ "licensedPercentage": "100.0",
+ "madeForKidsCount": 0,
+ "embeddableCount": 2,
+ "embeddablePercentage": "100.0",
+ "publishDayDistribution": {
+ "Tuesday": 2
+ },
+ "publishHourDistribution": {
+ "12": 2
+ },
+ "peakPublishDay": "Tuesday",
+ "peakPublishHour": 12,
+ "durationDistribution": {
+ "short": 1,
+ "medium": 1,
+ "long": 0,
+ "veryLong": 0
+ },
+ "categoryDistribution": {
+ "22": 1,
+ "Unknown": 1
+ },
+ "tagFrequency": [
+ {
+ "tag": "travel",
+ "count": 1
+ },
+ {
+ "tag": "vlog",
+ "count": 1
+ }
+ ],
+ "videosLast7Days": 0,
+ "videosLast30Days": 2,
+ "videosLast90Days": 2,
+ "videosLast365Days": 2,
+ "uploadFrequencyPerWeek": "2.0",
+ "uploadFrequencyPerMonth": "2.0",
+ "consistencyScore": 100,
+ "viralityScore": 1,
+ "viewsDistribution": {
+ "ranges": [
+ "0-540",
+ "540-1.1K",
+ "1.1K-1.6K",
+ "1.6K-2.2K",
+ "2.2K-2.7K",
+ "2.7K-3.2K",
+ "3.2K-3.8K",
+ "3.8K-4.3K",
+ "4.3K-4.9K",
+ "4.9K-5.4K"
+ ],
+ "counts": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "viewsTrend": [
+ {
+ "month": "2026-08",
+ "value": 10800,
+ "count": 2
+ }
+ ],
+ "engagementTrend": [
+ {
+ "month": "2026-08",
+ "value": "2.23"
+ }
+ ],
+ "likeRateTrend": [
+ {
+ "month": "2026-08",
+ "value": "1.94"
+ }
+ ]
+ },
+ "zero": {
+ "totalVideos": 2,
+ "totalViews": 0,
+ "totalLikes": 0,
+ "totalComments": 0,
+ "avgViews": 0,
+ "avgLikes": 0,
+ "avgComments": 0,
+ "medianViews": 0,
+ "totalEngagement": 0,
+ "overallEngagementRate": 0,
+ "avgDurationSeconds": 615,
+ "avgDurationFormatted": "10m 15s",
+ "totalDurationSeconds": 1230,
+ "totalDurationFormatted": "20m 30s",
+ "estimatedTotalWatchTimeHours": 0,
+ "bestByViews": {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ "bestByLikes": {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ "bestByComments": {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ "bestByEngagement": {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ "worstByViews": {
+ "videoId": "z2",
+ "title": "Video z2",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z2/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1200
+ },
+ "mostRecent": {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ "oldest": {
+ "videoId": "z2",
+ "title": "Video z2",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z2/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1200
+ },
+ "top10ByViews": [
+ {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ {
+ "videoId": "z2",
+ "title": "Video z2",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z2/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1200
+ }
+ ],
+ "top10ByLikes": [
+ {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ {
+ "videoId": "z2",
+ "title": "Video z2",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z2/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1200
+ }
+ ],
+ "top10ByComments": [
+ {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ {
+ "videoId": "z2",
+ "title": "Video z2",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z2/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1200
+ }
+ ],
+ "top10ByEngagement": [
+ {
+ "videoId": "z1",
+ "title": "Video z1",
+ "viewCount": 0,
+ "likeCount": 0,
+ "commentCount": 0,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z1/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 30
+ },
+ {
+ "videoId": "z2",
+ "title": "Video z2",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "thumbnail": "https://i/z2/m.jpg",
+ "engagementRate": "0.00",
+ "durationSeconds": 1200
+ }
+ ],
+ "shortsCount": 1,
+ "regularCount": 1,
+ "avgShortViews": 0,
+ "avgRegularViews": 0,
+ "avgShortLikes": 0,
+ "avgRegularLikes": 0,
+ "hdCount": 2,
+ "sdCount": 0,
+ "hdPercentage": "100.0",
+ "captionCount": 0,
+ "captionPercentage": "0.0",
+ "licensedCount": 2,
+ "licensedPercentage": "100.0",
+ "madeForKidsCount": 0,
+ "embeddableCount": 2,
+ "embeddablePercentage": "100.0",
+ "publishDayDistribution": {
+ "Saturday": 2
+ },
+ "publishHourDistribution": {
+ "10": 2
+ },
+ "peakPublishDay": "Saturday",
+ "peakPublishHour": 10,
+ "durationDistribution": {
+ "short": 1,
+ "medium": 0,
+ "long": 1,
+ "veryLong": 0
+ },
+ "categoryDistribution": {
+ "22": 2
+ },
+ "tagFrequency": [],
+ "videosLast7Days": 0,
+ "videosLast30Days": 0,
+ "videosLast90Days": 2,
+ "videosLast365Days": 2,
+ "uploadFrequencyPerWeek": "0.5",
+ "uploadFrequencyPerMonth": "2.0",
+ "consistencyScore": 100,
+ "viralityScore": 0,
+ "viewsDistribution": {
+ "ranges": [
+ "0-1",
+ "1-2",
+ "2-3",
+ "3-4",
+ "4-5",
+ "5-6",
+ "6-7",
+ "7-8",
+ "8-9",
+ "9-10"
+ ],
+ "counts": [
+ 2,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "viewsTrend": [
+ {
+ "month": "2026-08",
+ "value": 0,
+ "count": 2
+ }
+ ],
+ "engagementTrend": [
+ {
+ "month": "2026-08",
+ "value": 0
+ }
+ ],
+ "likeRateTrend": [
+ {
+ "month": "2026-08",
+ "value": 0
+ }
+ ]
+ }
+}
diff --git a/backend/services/fixtures/youtubeChannels.data.golden.json b/backend/services/fixtures/youtubeChannels.data.golden.json
new file mode 100644
index 0000000..9560d92
--- /dev/null
+++ b/backend/services/fixtures/youtubeChannels.data.golden.json
@@ -0,0 +1,93 @@
+{
+ "outcomes": [
+ {
+ "value": {
+ "channelId": "UCfull",
+ "title": "Ribbon",
+ "description": "Channel",
+ "customUrl": "@ribbon",
+ "publishedAt": "2020-01-01T00:00:00Z",
+ "country": "GB",
+ "thumbnails": {
+ "default": "d",
+ "medium": "m",
+ "high": "h"
+ },
+ "subscriberCount": 1200,
+ "viewCount": 98000,
+ "videoCount": 45,
+ "hiddenSubscriberCount": true,
+ "uploadsPlaylistId": "UUfull",
+ "keywords": "travel vlog",
+ "bannerUrl": "https://banner",
+ "madeForKids": true,
+ "topicCategories": [
+ "https://en.wikipedia.org/wiki/Travel"
+ ],
+ "isLinked": true
+ }
+ },
+ {
+ "value": {
+ "channelId": "UCsparse",
+ "title": "Sparse",
+ "description": "",
+ "customUrl": "",
+ "publishedAt": "2021-01-01T00:00:00Z",
+ "country": "Unknown",
+ "thumbnails": {
+ "default": "",
+ "medium": "",
+ "high": ""
+ },
+ "subscriberCount": 0,
+ "viewCount": 0,
+ "videoCount": 0,
+ "hiddenSubscriberCount": false,
+ "uploadsPlaylistId": "",
+ "keywords": "",
+ "bannerUrl": "",
+ "madeForKids": false,
+ "topicCategories": [],
+ "isLinked": false
+ }
+ },
+ {
+ "error": "Channel not found",
+ "reason": "[undefined]",
+ "status": "[undefined]"
+ },
+ {
+ "error": "Channel not found",
+ "reason": "[undefined]",
+ "status": "[undefined]"
+ },
+ {
+ "error": "API key not valid",
+ "reason": "keyInvalid",
+ "status": 400
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC0&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC1&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC2&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC3&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UC4&key=KEY",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/youtubeChannels.resolve.golden.json b/backend/services/fixtures/youtubeChannels.resolve.golden.json
new file mode 100644
index 0000000..5d15d00
--- /dev/null
+++ b/backend/services/fixtures/youtubeChannels.resolve.golden.json
@@ -0,0 +1,54 @@
+{
+ "outcomes": [
+ {
+ "value": "UCabcdefghijklmnopqrstuv"
+ },
+ {
+ "value": "UC_creator.name"
+ },
+ {
+ "value": "UC_legacy-name"
+ },
+ {
+ "value": "UC_olduser"
+ },
+ {
+ "value": "UC_plainname"
+ },
+ {
+ "value": "UC_just-a-name"
+ },
+ {
+ "error": "Invalid input",
+ "reason": "[undefined]",
+ "status": "[undefined]"
+ },
+ {
+ "error": "Invalid input",
+ "reason": "[undefined]",
+ "status": "[undefined]"
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=creator.name&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=legacy-name&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=olduser&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=plainname&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=just-a-name&key=KEY",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/youtubeFixtures.js b/backend/services/fixtures/youtubeFixtures.js
new file mode 100644
index 0000000..8ba904d
--- /dev/null
+++ b/backend/services/fixtures/youtubeFixtures.js
@@ -0,0 +1,90 @@
+export const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');
+
+function video(videoId, publishedAt, duration, counts, extra = {}) {
+ const [viewCount, likeCount, commentCount] = counts;
+ return {
+ videoId,
+ title: `Video ${videoId}`,
+ description: 'About this video',
+ publishedAt,
+ channelTitle: 'Ribbon',
+ thumbnails: { default: `https://i/${videoId}/d.jpg`, medium: `https://i/${videoId}/m.jpg`, high: '' },
+ tags: [],
+ categoryId: '22',
+ liveBroadcastContent: 'none',
+ defaultAudioLanguage: 'en',
+ duration,
+ dimension: '2d',
+ definition: 'hd',
+ caption: false,
+ licensedContent: true,
+ projection: 'rectangular',
+ viewCount,
+ likeCount,
+ commentCount,
+ privacyStatus: 'public',
+ embeddable: true,
+ madeForKids: false,
+ ...extra,
+ };
+}
+
+export const richVideos = [
+ video('v01', '2026-08-31T09:15:00Z', 'PT45S', [12000, 900, 40], { tags: ['Shorts', 'travel'] }),
+ video('v02', '2026-08-25T12:00:00Z', 'PT8M12S', [5400, null, 31], { tags: ['travel', 'vlog'], definition: 'sd' }),
+ video('v03', '2026-08-25T12:00:00Z', 'PT1M', [5400, 210, null], { categoryId: '' }),
+ video('v04', '2026-08-02T21:00:00Z', 'PT1H2M3S', [98000, 4100, 640], { caption: true, tags: ['Travel', 'long form'] }),
+ video('v05', '2026-07-14T06:30:00Z', 'PT10M', [0, null, null], { embeddable: false, licensedContent: false }),
+ video('v06', '2026-06-20T23:59:00Z', 'PT2H', [3100, 120, 15], { madeForKids: true, categoryId: '10' }),
+ video('v07', '2026-06-03T00:00:00Z', 'P1DT2H3M', [450, 30, 2], { thumbnails: {} }),
+ video('v08', '2026-03-15T08:00:00Z', 'P0D', [77, 5, 1], { definition: 'sd', caption: true }),
+ video('v09', '2025-12-31T23:30:00Z', 'PT59S', [250000, 12000, 900], { tags: ['shorts', 'newyear', 'Travel'] }),
+ video('v10', '2025-09-02T12:00:00Z', 'PT4M20S', [1000000, 50000, 3000], { categoryId: '10' }),
+ video('v11', '2024-01-01T00:00:00Z', 'PT30M', [1, 0, 0]),
+];
+
+export const zeroViewVideos = [
+ video('z1', '2026-08-01T10:00:00Z', 'PT30S', [0, 0, 0]),
+ video('z2', '2026-08-01T10:00:00Z', 'PT20M', [0, null, null]),
+];
+
+function generatedTags(index) {
+ const tags = [];
+ for (let tag = 0; tag < 40; tag++) {
+ if ((tag + index) % 4 === 0) tags.push(`Tag${tag}`);
+ }
+ return tags;
+}
+
+export const generatedVideos = Array.from({ length: 36 }, (_, index) => video(
+ `g${String(index).padStart(2, '0')}`,
+ new Date(Date.UTC(2026, 7, 30, 20) - index * 9.5 * 86400000).toISOString(),
+ `PT${index % 3}H${(index * 7) % 60}M${(index * 13) % 60}S`,
+ [(index * 7919) % 50000, index % 5 === 0 ? null : (index * 31) % 900, index % 7 === 0 ? null : index * 3],
+ { tags: generatedTags(index), categoryId: String(20 + (index % 6)) },
+));
+
+export const rawPlaylistItem = (videoId) => ({ snippet: { resourceId: { videoId } } });
+
+export const rawVideos = {
+ full: {
+ id: 'full',
+ snippet: { title: 'Full', description: 'x'.repeat(260), publishedAt: '2026-08-01T10:00:00Z', channelTitle: 'Ribbon', thumbnails: { default: { url: 'd' }, medium: { url: 'm' }, high: { url: 'h' } }, tags: ['a'], categoryId: '22', liveBroadcastContent: 'live', defaultAudioLanguage: 'de' },
+ contentDetails: { duration: 'PT3M', dimension: '3d', definition: 'sd', caption: 'true', licensedContent: true, projection: '360' },
+ statistics: { viewCount: '1500', likeCount: '40', commentCount: '0' },
+ status: { privacyStatus: 'unlisted', embeddable: true, madeForKids: true },
+ },
+ hidden: {
+ id: 'hidden',
+ snippet: { title: 'Hidden', publishedAt: '2026-08-02T10:00:00Z', channelTitle: 'Ribbon' },
+ contentDetails: { duration: 'PT10S', caption: 'false' },
+ statistics: { viewCount: 'abc' },
+ },
+ odd: {
+ id: 'odd',
+ snippet: { title: 'Odd', description: '', publishedAt: '2026-08-03T10:00:00Z', channelTitle: 'Ribbon' },
+ contentDetails: { duration: 'PT1H' },
+ statistics: { viewCount: '7', likeCount: 'n/a', commentCount: '12.9' },
+ status: {},
+ },
+};
diff --git a/backend/services/fixtures/youtubeTracked.data.golden.json b/backend/services/fixtures/youtubeTracked.data.golden.json
new file mode 100644
index 0000000..0cbfc54
--- /dev/null
+++ b/backend/services/fixtures/youtubeTracked.data.golden.json
@@ -0,0 +1,76 @@
+{
+ "outcomes": [
+ {
+ "value": {
+ "contentType": "youtube",
+ "title": "Watch",
+ "channelTitle": "Ribbon",
+ "channelId": "UC1",
+ "thumbnail": "m",
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "viewCount": 1500,
+ "likeCount": 40,
+ "commentCount": 3,
+ "isShort": false,
+ "permalink": "https://www.youtube.com/watch?v=abc123",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "value": {
+ "contentType": "youtube",
+ "title": "Short",
+ "channelTitle": "Ribbon",
+ "channelId": "UC1",
+ "thumbnail": "d",
+ "publishedAt": "2026-08-02T10:00:00Z",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "isShort": true,
+ "permalink": "https://www.youtube.com/shorts/short1",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "value": {
+ "contentType": "youtube",
+ "title": "Bare",
+ "channelTitle": "Ribbon",
+ "channelId": "UC1",
+ "thumbnail": "",
+ "publishedAt": "2026-08-03T10:00:00Z",
+ "viewCount": 9,
+ "likeCount": 0,
+ "commentCount": null,
+ "isShort": false,
+ "permalink": "https://www.youtube.com/watch?v=bare1",
+ "lastFetchedAt": "2026-09-01T12:00:00.000Z"
+ }
+ },
+ {
+ "error": "Quota exceeded"
+ },
+ {
+ "error": "Invalid YouTube URL - could not extract video ID"
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&id=abc123&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&id=short1&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&id=bare1&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&id=err1&key=KEY",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/services/fixtures/youtubeVideos.errors.golden.json b/backend/services/fixtures/youtubeVideos.errors.golden.json
new file mode 100644
index 0000000..382de1c
--- /dev/null
+++ b/backend/services/fixtures/youtubeVideos.errors.golden.json
@@ -0,0 +1,49 @@
+{
+ "partial": {
+ "value": [
+ {
+ "videoId": "full",
+ "title": "Full",
+ "description": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "channelTitle": "Ribbon",
+ "thumbnails": {
+ "default": "d",
+ "medium": "m",
+ "high": "h"
+ },
+ "tags": [
+ "a"
+ ],
+ "categoryId": "22",
+ "liveBroadcastContent": "live",
+ "defaultAudioLanguage": "de",
+ "duration": "PT3M",
+ "dimension": "3d",
+ "definition": "sd",
+ "caption": true,
+ "licensedContent": true,
+ "projection": "360",
+ "viewCount": 1500,
+ "likeCount": 40,
+ "commentCount": 0,
+ "privacyStatus": "unlisted",
+ "embeddable": true,
+ "madeForKids": true
+ }
+ ]
+ },
+ "none": {
+ "value": []
+ },
+ "quota": {
+ "error": "Quota exceeded",
+ "reason": "quotaExceeded",
+ "status": 403
+ },
+ "bare": {
+ "error": "Bad request",
+ "reason": "",
+ "status": "[undefined]"
+ }
+}
diff --git a/backend/services/fixtures/youtubeVideos.maxPages.golden.json b/backend/services/fixtures/youtubeVideos.maxPages.golden.json
new file mode 100644
index 0000000..2f11d6d
--- /dev/null
+++ b/backend/services/fixtures/youtubeVideos.maxPages.golden.json
@@ -0,0 +1,10 @@
+{
+ "capped": [
+ "full"
+ ],
+ "all": [
+ "full",
+ "hidden"
+ ],
+ "requests": 7
+}
diff --git a/backend/services/fixtures/youtubeVideos.pages.golden.json b/backend/services/fixtures/youtubeVideos.pages.golden.json
new file mode 100644
index 0000000..ee05e64
--- /dev/null
+++ b/backend/services/fixtures/youtubeVideos.pages.golden.json
@@ -0,0 +1,136 @@
+{
+ "videos": [
+ {
+ "videoId": "full",
+ "title": "Full",
+ "description": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ "publishedAt": "2026-08-01T10:00:00Z",
+ "channelTitle": "Ribbon",
+ "thumbnails": {
+ "default": "d",
+ "medium": "m",
+ "high": "h"
+ },
+ "tags": [
+ "a"
+ ],
+ "categoryId": "22",
+ "liveBroadcastContent": "live",
+ "defaultAudioLanguage": "de",
+ "duration": "PT3M",
+ "dimension": "3d",
+ "definition": "sd",
+ "caption": true,
+ "licensedContent": true,
+ "projection": "360",
+ "viewCount": 1500,
+ "likeCount": 40,
+ "commentCount": 0,
+ "privacyStatus": "unlisted",
+ "embeddable": true,
+ "madeForKids": true
+ },
+ {
+ "videoId": "hidden",
+ "title": "Hidden",
+ "description": "",
+ "publishedAt": "2026-08-02T10:00:00Z",
+ "channelTitle": "Ribbon",
+ "thumbnails": {
+ "default": "",
+ "medium": "",
+ "high": ""
+ },
+ "tags": [],
+ "categoryId": "",
+ "liveBroadcastContent": "none",
+ "defaultAudioLanguage": "",
+ "duration": "PT10S",
+ "dimension": "2d",
+ "definition": "hd",
+ "caption": false,
+ "licensedContent": false,
+ "projection": "rectangular",
+ "viewCount": 0,
+ "likeCount": null,
+ "commentCount": null,
+ "privacyStatus": "public",
+ "embeddable": false,
+ "madeForKids": false
+ },
+ {
+ "videoId": "odd",
+ "title": "Odd",
+ "description": "",
+ "publishedAt": "2026-08-03T10:00:00Z",
+ "channelTitle": "Ribbon",
+ "thumbnails": {
+ "default": "",
+ "medium": "",
+ "high": ""
+ },
+ "tags": [],
+ "categoryId": "",
+ "liveBroadcastContent": "none",
+ "defaultAudioLanguage": "",
+ "duration": "PT1H",
+ "dimension": "2d",
+ "definition": "hd",
+ "caption": false,
+ "licensedContent": false,
+ "projection": "rectangular",
+ "viewCount": 7,
+ "likeCount": null,
+ "commentCount": 12,
+ "privacyStatus": "public",
+ "embeddable": false,
+ "madeForKids": false
+ },
+ {
+ "videoId": "extra",
+ "title": "Odd",
+ "description": "",
+ "publishedAt": "2026-08-03T10:00:00Z",
+ "channelTitle": "Ribbon",
+ "thumbnails": {
+ "default": "",
+ "medium": "",
+ "high": ""
+ },
+ "tags": [],
+ "categoryId": "",
+ "liveBroadcastContent": "none",
+ "defaultAudioLanguage": "",
+ "duration": "PT1H",
+ "dimension": "2d",
+ "definition": "hd",
+ "caption": false,
+ "licensedContent": false,
+ "projection": "rectangular",
+ "viewCount": 7,
+ "likeCount": null,
+ "commentCount": 12,
+ "privacyStatus": "public",
+ "embeddable": false,
+ "madeForKids": false
+ }
+ ],
+ "requests": [
+ {
+ "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=UU123&maxResults=50&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=statistics%2CcontentDetails%2Csnippet%2Cstatus&id=full%2Chidden&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=UU123&maxResults=50&pageToken=P2&key=KEY",
+ "method": "GET"
+ },
+ {
+ "url": "https://www.googleapis.com/youtube/v3/videos?part=statistics%2CcontentDetails%2Csnippet%2Cstatus&id=odd%2Cextra&key=KEY",
+ "method": "GET"
+ }
+ ]
+}
diff --git a/backend/services/youtube.js b/backend/services/youtube.js
index 9d37a6f..c645941 100644
--- a/backend/services/youtube.js
+++ b/backend/services/youtube.js
@@ -1,466 +1,4 @@
-// fetch is a global in Cloudflare Workers - no import needed.
-
-async function ytFetch(endpoint, params, apiKey) {
- const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);
- params.key = apiKey;
- Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
- const res = await fetch(url.toString());
- const data = await res.json();
- if (data.error) {
- const err = new Error(data.error.message);
- err.reason = data.error.errors?.[0]?.reason || '';
- err.status = data.error.code;
- throw err;
- }
- return data;
-}
-
-function optionalCount(value) {
- if (value == null) return null;
- const n = parseInt(value, 10);
- return Number.isFinite(n) ? n : null;
-}
-
-function extractChannelId(input) {
- if (!input) return null;
- input = input.trim();
- if (/^UC[\w-]{22}$/.test(input)) return input;
- const patterns = [
- /youtube\.com\/channel\/(UC[\w-]{22})/,
- /youtube\.com\/@([\w.-]+)/,
- /youtube\.com\/c\/([\w.-]+)/,
- /youtube\.com\/user\/([\w.-]+)/,
- /youtube\.com\/([\w.-]+)/,
- ];
- for (const p of patterns) {
- const m = input.match(p);
- if (m) return m[1];
- }
- return input;
-}
-
-// returns null when the lookup finds nothing or fails, so the next strategy can run
-async function lookupChannelId(endpoint, params, pickId, apiKey) {
- try {
- const data = await ytFetch(endpoint, params, apiKey);
- if (data.items && data.items.length > 0) return pickId(data.items[0]);
- return null;
- } catch {
- return null;
- }
-}
-
-export async function resolveChannelId(input, apiKey) {
- const extracted = extractChannelId(input);
- if (!extracted) throw new Error('Invalid input');
- if (/^UC[\w-]{22}$/.test(extracted)) return extracted;
-
- // sequential on purpose: a search costs 100 quota units
- const byHandle = await lookupChannelId('channels', { part: 'id', forHandle: extracted }, (item) => item.id, apiKey);
- if (byHandle !== null) return byHandle;
-
- const byUsername = await lookupChannelId('channels', { part: 'id', forUsername: extracted }, (item) => item.id, apiKey);
- if (byUsername !== null) return byUsername;
-
- const searchParams = { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' };
- const bySearch = await lookupChannelId('search', searchParams, (item) => item.snippet.channelId, apiKey);
- if (bySearch !== null) return bySearch;
-
- throw new Error('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');
-}
-
-export async function fetchChannelData(channelId, apiKey) {
- const data = await ytFetch('channels', {
- part: 'snippet,statistics,contentDetails,brandingSettings,status,topicDetails',
- id: channelId,
- }, apiKey);
-
- if (!data.items || data.items.length === 0) throw new Error('Channel not found');
- const ch = data.items[0];
-
- return {
- channelId: ch.id,
- title: ch.snippet.title,
- description: ch.snippet.description,
- customUrl: ch.snippet.customUrl || '',
- publishedAt: ch.snippet.publishedAt,
- country: ch.snippet.country || 'Unknown',
- thumbnails: {
- default: ch.snippet.thumbnails?.default?.url || '',
- medium: ch.snippet.thumbnails?.medium?.url || '',
- high: ch.snippet.thumbnails?.high?.url || '',
- },
- subscriberCount: parseInt(ch.statistics.subscriberCount) || 0,
- viewCount: parseInt(ch.statistics.viewCount) || 0,
- videoCount: parseInt(ch.statistics.videoCount) || 0,
- hiddenSubscriberCount: ch.statistics.hiddenSubscriberCount || false,
- uploadsPlaylistId: ch.contentDetails?.relatedPlaylists?.uploads || '',
- keywords: ch.brandingSettings?.channel?.keywords || '',
- bannerUrl: ch.brandingSettings?.image?.bannerExternalUrl || '',
- madeForKids: ch.status?.madeForKids || false,
- topicCategories: ch.topicDetails?.topicCategories || [],
- isLinked: ch.status?.isLinked || false,
- };
-}
-
-export async function fetchAllVideos(playlistId, apiKey, maxPages = 10) {
- let allVideos = [];
- let pageToken = '';
- let page = 0;
-
- while (page < maxPages) {
- const params = { part: 'snippet,contentDetails', playlistId, maxResults: '50' };
- if (pageToken) params.pageToken = pageToken;
-
- let data;
- try {
- data = await ytFetch('playlistItems', params, apiKey);
- } catch (err) {
- // YouTube reports a channel's uploads playlist as missing until its first public video.
- if (err.reason === 'playlistNotFound') break;
- throw err;
- }
- if (!data.items || data.items.length === 0) break;
-
- const videoIds = data.items.map(i => i.snippet.resourceId.videoId).join(',');
- const statsData = await ytFetch('videos', {
- part: 'statistics,contentDetails,snippet,status',
- id: videoIds,
- }, apiKey);
-
- if (statsData.items) {
- allVideos = allVideos.concat(statsData.items.map(v => ({
- videoId: v.id,
- title: v.snippet.title,
- description: v.snippet.description?.substring(0, 200) || '',
- publishedAt: v.snippet.publishedAt,
- channelTitle: v.snippet.channelTitle,
- thumbnails: {
- default: v.snippet.thumbnails?.default?.url || '',
- medium: v.snippet.thumbnails?.medium?.url || '',
- high: v.snippet.thumbnails?.high?.url || '',
- },
- tags: v.snippet.tags || [],
- categoryId: v.snippet.categoryId || '',
- liveBroadcastContent: v.snippet.liveBroadcastContent || 'none',
- defaultAudioLanguage: v.snippet.defaultAudioLanguage || '',
- duration: v.contentDetails.duration,
- dimension: v.contentDetails.dimension || '2d',
- definition: v.contentDetails.definition || 'hd',
- caption: v.contentDetails.caption === 'true',
- licensedContent: v.contentDetails.licensedContent || false,
- projection: v.contentDetails.projection || 'rectangular',
- viewCount: parseInt(v.statistics.viewCount) || 0,
- // YouTube omits a count the owner hid (likes) or switched off (comments); null keeps that apart from zero.
- likeCount: optionalCount(v.statistics.likeCount),
- commentCount: optionalCount(v.statistics.commentCount),
- privacyStatus: v.status?.privacyStatus || 'public',
- embeddable: v.status?.embeddable || false,
- madeForKids: v.status?.madeForKids || false,
- })));
- }
-
- pageToken = data.nextPageToken || '';
- if (!pageToken) break;
- page++;
- }
-
- return allVideos;
-}
-
-function parseDuration(iso) {
- const m = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
- if (!m) return 0;
- return (parseInt(m[1] || 0) * 3600) + (parseInt(m[2] || 0) * 60) + parseInt(m[3] || 0);
-}
-
-function formatCompact(n) {
- if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
- if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
- return n.toString();
-}
-
-function extractYouTubeVideoId(url) {
- let parsedUrl;
- try {
- parsedUrl = new URL(url.trim());
- } catch {
- // not a url at all, so it has no video id
- return null;
- }
-
- const { hostname, pathname, searchParams } = parsedUrl;
- if (hostname === 'youtu.be') return pathname.slice(1).split('?')[0];
- if (!hostname.includes('youtube.com')) return null;
- if (pathname.startsWith('/shorts/') || pathname.startsWith('/embed/')) return pathname.split('/')[2];
- return searchParams.get('v');
-}
-
-export async function fetchTrackedYouTubeData(videoUrl, apiKey) {
- const videoId = extractYouTubeVideoId(videoUrl);
- if (!videoId) throw new Error('Invalid YouTube URL - could not extract video ID');
-
- const data = await ytFetch('videos', {
- part: 'snippet,statistics',
- id: videoId,
- }, apiKey);
-
- if (!data.items || data.items.length === 0) throw new Error('YouTube video not found - check the URL');
-
- const item = data.items[0];
- const s = item.snippet;
- const st = item.statistics;
- const isShort = videoUrl.includes('/shorts/');
-
- return {
- contentType: 'youtube',
- title: s.title,
- channelTitle: s.channelTitle,
- channelId: s.channelId,
- thumbnail: s.thumbnails?.medium?.url || s.thumbnails?.default?.url || '',
- publishedAt: s.publishedAt,
- viewCount: parseInt(st.viewCount || '0', 10),
- likeCount: optionalCount(st.likeCount),
- commentCount: optionalCount(st.commentCount),
- isShort,
- permalink: isShort
- ? `https://www.youtube.com/shorts/${videoId}`
- : `https://www.youtube.com/watch?v=${videoId}`,
- lastFetchedAt: new Date().toISOString(),
- };
-}
-
-export function computeVideoAnalytics(videos) {
- if (!videos || videos.length === 0) {
- return {
- totalVideos: 0, totalViews: 0, totalLikes: 0, totalComments: 0,
- avgViews: 0, avgLikes: 0, avgComments: 0, medianViews: 0,
- totalEngagement: 0, overallEngagementRate: 0,
- avgDurationSeconds: 0, avgDurationFormatted: '0:00',
- totalDurationSeconds: 0, totalDurationFormatted: '0:00',
- bestByViews: null, bestByLikes: null, bestByComments: null,
- bestByEngagement: null, worstByViews: null,
- mostRecent: null, oldest: null,
- top10ByViews: [], top10ByLikes: [], top10ByComments: [], top10ByEngagement: [],
- shortsCount: 0, regularCount: 0,
- avgShortViews: 0, avgRegularViews: 0,
- hdCount: 0, sdCount: 0, hdPercentage: 0,
- captionCount: 0, captionPercentage: 0,
- licensedCount: 0, licensedPercentage: 0,
- madeForKidsCount: 0, embeddableCount: 0,
- publishDayDistribution: {}, publishHourDistribution: {},
- peakPublishDay: '', peakPublishHour: 0,
- durationDistribution: { short: 0, medium: 0, long: 0, veryLong: 0 },
- categoryDistribution: {},
- tagFrequency: [],
- videosLast7Days: 0, videosLast30Days: 0, videosLast90Days: 0, videosLast365Days: 0,
- uploadFrequencyPerWeek: 0, uploadFrequencyPerMonth: 0,
- consistencyScore: 0, viralityScore: 0,
- viewsDistribution: { ranges: [], counts: [] },
- engagementTrend: [], viewsTrend: [], likeRateTrend: [],
- };
- }
-
- const now = new Date();
- const durations = videos.map(v => parseDuration(v.duration));
- const totalDuration = durations.reduce((a, b) => a + b, 0);
-
- const withEngagement = videos.map(v => ({
- ...v,
- engagementRate: v.viewCount > 0 ? ((v.likeCount + v.commentCount) / v.viewCount) * 100 : 0,
- likeRate: v.viewCount > 0 ? (v.likeCount / v.viewCount) * 100 : 0,
- commentRate: v.viewCount > 0 ? (v.commentCount / v.viewCount) * 100 : 0,
- durationSeconds: parseDuration(v.duration),
- daysSinceUpload: Math.max(1, Math.floor((now - new Date(v.publishedAt)) / 86400000)),
- }));
-
- const viewsSorted = [...withEngagement].sort((a, b) => b.viewCount - a.viewCount);
- const likesSorted = [...withEngagement].sort((a, b) => b.likeCount - a.likeCount);
- const commentsSorted = [...withEngagement].sort((a, b) => b.commentCount - a.commentCount);
- const dateSorted = [...withEngagement].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
- const engagementSorted = [...withEngagement].sort((a, b) => b.engagementRate - a.engagementRate);
-
- const totalViews = videos.reduce((s, v) => s + v.viewCount, 0);
- const totalLikes = videos.reduce((s, v) => s + v.likeCount, 0);
- const totalComments = videos.reduce((s, v) => s + v.commentCount, 0);
- const avgViews = Math.round(totalViews / videos.length);
- const avgLikes = Math.round(totalLikes / videos.length);
- const avgComments = Math.round(totalComments / videos.length);
-
- const sortedViews = [...videos].map(v => v.viewCount).sort((a, b) => a - b);
- const mid = Math.floor(sortedViews.length / 2);
- const medianViews = sortedViews.length % 2 ? sortedViews[mid] : Math.round((sortedViews[mid - 1] + sortedViews[mid]) / 2);
-
- const shorts = withEngagement.filter(v => v.durationSeconds <= 60);
- const regular = withEngagement.filter(v => v.durationSeconds > 60);
-
- const durationDist = { short: 0, medium: 0, long: 0, veryLong: 0 };
- withEngagement.forEach(v => {
- if (v.durationSeconds <= 60) durationDist.short++;
- else if (v.durationSeconds <= 600) durationDist.medium++;
- else if (v.durationSeconds <= 3600) durationDist.long++;
- else durationDist.veryLong++;
- });
-
- const hdCount = videos.filter(v => v.definition === 'hd').length;
- const captionCount = videos.filter(v => v.caption).length;
- const licensedCount = videos.filter(v => v.licensedContent).length;
- const madeForKidsCount = videos.filter(v => v.madeForKids).length;
- const embeddableCount = videos.filter(v => v.embeddable).length;
-
- const dayDist = {};
- const hourDist = {};
- const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
- videos.forEach(v => {
- const d = new Date(v.publishedAt);
- const day = dayNames[d.getUTCDay()];
- const hour = d.getUTCHours();
- dayDist[day] = (dayDist[day] || 0) + 1;
- hourDist[hour] = (hourDist[hour] || 0) + 1;
- });
-
- const peakDay = Object.entries(dayDist).sort((a, b) => b[1] - a[1])[0];
- const peakHour = Object.entries(hourDist).sort((a, b) => b[1] - a[1])[0];
-
- const catDist = {};
- videos.forEach(v => {
- const cat = v.categoryId || 'Unknown';
- catDist[cat] = (catDist[cat] || 0) + 1;
- });
-
- const tagMap = {};
- videos.forEach(v => {
- (v.tags || []).forEach(t => {
- const lower = t.toLowerCase();
- tagMap[lower] = (tagMap[lower] || 0) + 1;
- });
- });
- const tagFrequency = Object.entries(tagMap)
- .sort((a, b) => b[1] - a[1])
- .slice(0, 30)
- .map(([tag, count]) => ({ tag, count }));
-
- const msDay = 86400000;
- const videosLast7 = videos.filter(v => (now - new Date(v.publishedAt)) < 7 * msDay).length;
- const videosLast30 = videos.filter(v => (now - new Date(v.publishedAt)) < 30 * msDay).length;
- const videosLast90 = videos.filter(v => (now - new Date(v.publishedAt)) < 90 * msDay).length;
- const videosLast365 = videos.filter(v => (now - new Date(v.publishedAt)) < 365 * msDay).length;
-
- const oldestDate = new Date(dateSorted[dateSorted.length - 1]?.publishedAt || now);
- const totalWeeks = Math.max(1, (now - oldestDate) / (7 * msDay));
- const totalMonths = Math.max(1, totalWeeks / 4.33);
-
- const weeklyUploads = videos.reduce((acc, v) => {
- const weekNum = Math.floor((now - new Date(v.publishedAt)) / (7 * msDay));
- acc[weekNum] = (acc[weekNum] || 0) + 1;
- return acc;
- }, {});
- const weekValues = Object.values(weeklyUploads);
- const avgWeekly = weekValues.reduce((a, b) => a + b, 0) / Math.max(1, weekValues.length);
- const variance = weekValues.reduce((s, v) => s + Math.pow(v - avgWeekly, 2), 0) / Math.max(1, weekValues.length);
- const stdDev = Math.sqrt(variance);
- const consistencyScore = Math.max(0, Math.min(100, Math.round(100 - (stdDev / Math.max(0.01, avgWeekly)) * 25)));
- const viralityScore = avgViews > 0 ? Math.round((viewsSorted[0]?.viewCount || 0) / avgViews * 10) / 10 : 0;
-
- const maxViews = viewsSorted[0]?.viewCount || 0;
- const step = Math.max(1, Math.ceil(maxViews / 10));
- const viewsRanges = [];
- const viewsCounts = [];
- for (let i = 0; i < 10; i++) {
- const low = i * step;
- const high = (i + 1) * step;
- viewsRanges.push(`${formatCompact(low)}-${formatCompact(high)}`);
- viewsCounts.push(videos.filter(v => v.viewCount >= low && v.viewCount < high).length);
- }
-
- const monthlyData = {};
- withEngagement.forEach(v => {
- const d = new Date(v.publishedAt);
- const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
- if (!monthlyData[key]) monthlyData[key] = { views: 0, likes: 0, comments: 0, count: 0 };
- monthlyData[key].views += v.viewCount;
- monthlyData[key].likes += v.likeCount;
- monthlyData[key].comments += v.commentCount;
- monthlyData[key].count++;
- });
- const sortedMonths = Object.keys(monthlyData).sort();
- const viewsTrend = sortedMonths.map(m => ({ month: m, value: monthlyData[m].views, count: monthlyData[m].count }));
- const engagementTrend = sortedMonths.map(m => ({
- month: m,
- value: monthlyData[m].views > 0
- ? ((monthlyData[m].likes + monthlyData[m].comments) / monthlyData[m].views * 100).toFixed(2)
- : 0,
- }));
- const likeRateTrend = sortedMonths.map(m => ({
- month: m,
- value: monthlyData[m].views > 0 ? ((monthlyData[m].likes / monthlyData[m].views) * 100).toFixed(2) : 0,
- }));
-
- const formatDuration = (s) => {
- const h = Math.floor(s / 3600);
- const m = Math.floor((s % 3600) / 60);
- const sec = s % 60;
- return h > 0 ? `${h}h ${m}m` : `${m}m ${sec}s`;
- };
-
- const formatVid = (v) => v ? {
- videoId: v.videoId, title: v.title, viewCount: v.viewCount,
- likeCount: v.likeCount, commentCount: v.commentCount,
- publishedAt: v.publishedAt,
- thumbnail: v.thumbnails?.medium || v.thumbnails?.default || '',
- engagementRate: v.engagementRate?.toFixed(2) || 0,
- durationSeconds: v.durationSeconds || parseDuration(v.duration),
- } : null;
-
- return {
- totalVideos: videos.length,
- totalViews, totalLikes, totalComments,
- avgViews, avgLikes, avgComments, medianViews,
- totalEngagement: totalLikes + totalComments,
- overallEngagementRate: totalViews > 0 ? ((totalLikes + totalComments) / totalViews * 100).toFixed(2) : 0,
- avgDurationSeconds: Math.round(totalDuration / videos.length),
- avgDurationFormatted: formatDuration(Math.round(totalDuration / videos.length)),
- totalDurationSeconds: totalDuration,
- totalDurationFormatted: formatDuration(totalDuration),
- estimatedTotalWatchTimeHours: Math.round((totalDuration * totalViews) / 3600),
- bestByViews: formatVid(viewsSorted[0]),
- bestByLikes: formatVid(likesSorted[0]),
- bestByComments: formatVid(commentsSorted[0]),
- bestByEngagement: formatVid(engagementSorted[0]),
- worstByViews: formatVid(viewsSorted[viewsSorted.length - 1]),
- mostRecent: formatVid(dateSorted[0]),
- oldest: formatVid(dateSorted[dateSorted.length - 1]),
- top10ByViews: viewsSorted.slice(0, 10).map(formatVid),
- top10ByLikes: likesSorted.slice(0, 10).map(formatVid),
- top10ByComments: commentsSorted.slice(0, 10).map(formatVid),
- top10ByEngagement: engagementSorted.slice(0, 10).map(formatVid),
- shortsCount: shorts.length,
- regularCount: regular.length,
- avgShortViews: shorts.length > 0 ? Math.round(shorts.reduce((s, v) => s + v.viewCount, 0) / shorts.length) : 0,
- avgRegularViews: regular.length > 0 ? Math.round(regular.reduce((s, v) => s + v.viewCount, 0) / regular.length) : 0,
- avgShortLikes: shorts.length > 0 ? Math.round(shorts.reduce((s, v) => s + v.likeCount, 0) / shorts.length) : 0,
- avgRegularLikes: regular.length > 0 ? Math.round(regular.reduce((s, v) => s + v.likeCount, 0) / regular.length) : 0,
- hdCount, sdCount: videos.length - hdCount,
- hdPercentage: ((hdCount / videos.length) * 100).toFixed(1),
- captionCount, captionPercentage: ((captionCount / videos.length) * 100).toFixed(1),
- licensedCount, licensedPercentage: ((licensedCount / videos.length) * 100).toFixed(1),
- madeForKidsCount, embeddableCount,
- embeddablePercentage: ((embeddableCount / videos.length) * 100).toFixed(1),
- publishDayDistribution: dayDist,
- publishHourDistribution: hourDist,
- peakPublishDay: peakDay ? peakDay[0] : '',
- peakPublishHour: peakHour ? parseInt(peakHour[0]) : 0,
- durationDistribution: durationDist,
- categoryDistribution: catDist,
- tagFrequency,
- videosLast7Days: videosLast7,
- videosLast30Days: videosLast30,
- videosLast90Days: videosLast90,
- videosLast365Days: videosLast365,
- uploadFrequencyPerWeek: (videos.length / totalWeeks).toFixed(1),
- uploadFrequencyPerMonth: (videos.length / totalMonths).toFixed(1),
- consistencyScore, viralityScore,
- viewsDistribution: { ranges: viewsRanges, counts: viewsCounts },
- viewsTrend, engagementTrend, likeRateTrend,
- };
-}
+export { resolveChannelId, fetchChannelData } from './youtubeChannels.js';
+export { fetchAllVideos } from './youtubeVideos.js';
+export { fetchTrackedYouTubeData } from './youtubeTracked.js';
+export { computeVideoAnalytics } from './youtubeAnalytics.js';
diff --git a/backend/services/youtubeAnalytics.js b/backend/services/youtubeAnalytics.js
new file mode 100644
index 0000000..aa01c90
--- /dev/null
+++ b/backend/services/youtubeAnalytics.js
@@ -0,0 +1,184 @@
+import { DAY_MS, sumOf, roundedAverage, medianOf } from './analyticsMath.js';
+import { parseDuration, formatDuration, formatVideoSummary } from './youtubeFormat.js';
+import {
+ buildPublishTiming, buildCategoryDistribution, buildTagFrequency, countRecentUploads,
+ buildUploadFrequency, weeklyConsistencyScore, buildViewsDistribution, buildMonthlyTrends,
+} from './youtubeTrends.js';
+
+// shorts are judged by duration alone, so any video up to 60 seconds counts as one
+const SHORT_MAX_SECONDS = 60;
+
+function emptyVideoAnalytics() {
+ return {
+ totalVideos: 0, totalViews: 0, totalLikes: 0, totalComments: 0,
+ avgViews: 0, avgLikes: 0, avgComments: 0, medianViews: 0,
+ totalEngagement: 0, overallEngagementRate: 0,
+ avgDurationSeconds: 0, avgDurationFormatted: '0:00',
+ totalDurationSeconds: 0, totalDurationFormatted: '0:00',
+ bestByViews: null, bestByLikes: null, bestByComments: null,
+ bestByEngagement: null, worstByViews: null,
+ mostRecent: null, oldest: null,
+ top10ByViews: [], top10ByLikes: [], top10ByComments: [], top10ByEngagement: [],
+ shortsCount: 0, regularCount: 0,
+ avgShortViews: 0, avgRegularViews: 0,
+ hdCount: 0, sdCount: 0, hdPercentage: 0,
+ captionCount: 0, captionPercentage: 0,
+ licensedCount: 0, licensedPercentage: 0,
+ madeForKidsCount: 0, embeddableCount: 0,
+ publishDayDistribution: {}, publishHourDistribution: {},
+ peakPublishDay: '', peakPublishHour: 0,
+ durationDistribution: { short: 0, medium: 0, long: 0, veryLong: 0 },
+ categoryDistribution: {},
+ tagFrequency: [],
+ videosLast7Days: 0, videosLast30Days: 0, videosLast90Days: 0, videosLast365Days: 0,
+ uploadFrequencyPerWeek: 0, uploadFrequencyPerMonth: 0,
+ consistencyScore: 0, viralityScore: 0,
+ viewsDistribution: { ranges: [], counts: [] },
+ engagementTrend: [], viewsTrend: [], likeRateTrend: [],
+ };
+}
+
+function rateOfViews(count, video) {
+ return video.viewCount > 0 ? (count / video.viewCount) * 100 : 0;
+}
+
+function withEngagementRates(video, now) {
+ return {
+ ...video,
+ engagementRate: rateOfViews(video.likeCount + video.commentCount, video),
+ likeRate: rateOfViews(video.likeCount, video),
+ commentRate: rateOfViews(video.commentCount, video),
+ durationSeconds: parseDuration(video.duration),
+ daysSinceUpload: Math.max(1, Math.floor((now - new Date(video.publishedAt)) / DAY_MS)),
+ };
+}
+
+function sortVideos(videos) {
+ return {
+ byViews: [...videos].sort((first, second) => second.viewCount - first.viewCount),
+ byLikes: [...videos].sort((first, second) => second.likeCount - first.likeCount),
+ byComments: [...videos].sort((first, second) => second.commentCount - first.commentCount),
+ byDate: [...videos].sort((first, second) => new Date(second.publishedAt) - new Date(first.publishedAt)),
+ byEngagement: [...videos].sort((first, second) => second.engagementRate - first.engagementRate),
+ };
+}
+
+function summarizeTotals(videos) {
+ const totalViews = sumOf(videos, video => video.viewCount);
+ const totalLikes = sumOf(videos, video => video.likeCount);
+ const totalComments = sumOf(videos, video => video.commentCount);
+ return {
+ totalViews, totalLikes, totalComments,
+ avgViews: Math.round(totalViews / videos.length),
+ avgLikes: Math.round(totalLikes / videos.length),
+ avgComments: Math.round(totalComments / videos.length),
+ medianViews: medianOf(videos.map(video => video.viewCount)),
+ totalEngagement: totalLikes + totalComments,
+ overallEngagementRate: totalViews > 0 ? ((totalLikes + totalComments) / totalViews * 100).toFixed(2) : 0,
+ };
+}
+
+function summarizeDurations(totalDuration, totalViews, videoCount) {
+ return {
+ avgDurationSeconds: Math.round(totalDuration / videoCount),
+ avgDurationFormatted: formatDuration(Math.round(totalDuration / videoCount)),
+ totalDurationSeconds: totalDuration,
+ totalDurationFormatted: formatDuration(totalDuration),
+ // multiplies the summed durations by the summed views; kept to match stored analytics
+ estimatedTotalWatchTimeHours: Math.round((totalDuration * totalViews) / 3600),
+ };
+}
+
+function summarizeRankings(sorted) {
+ const { byViews, byLikes, byComments, byDate, byEngagement } = sorted;
+ return {
+ bestByViews: formatVideoSummary(byViews[0]),
+ bestByLikes: formatVideoSummary(byLikes[0]),
+ bestByComments: formatVideoSummary(byComments[0]),
+ bestByEngagement: formatVideoSummary(byEngagement[0]),
+ worstByViews: formatVideoSummary(byViews[byViews.length - 1]),
+ mostRecent: formatVideoSummary(byDate[0]),
+ oldest: formatVideoSummary(byDate[byDate.length - 1]),
+ top10ByViews: byViews.slice(0, 10).map(video => formatVideoSummary(video)),
+ top10ByLikes: byLikes.slice(0, 10).map(video => formatVideoSummary(video)),
+ top10ByComments: byComments.slice(0, 10).map(video => formatVideoSummary(video)),
+ top10ByEngagement: byEngagement.slice(0, 10).map(video => formatVideoSummary(video)),
+ };
+}
+
+function summarizeShorts(videos) {
+ const shorts = videos.filter(video => video.durationSeconds <= SHORT_MAX_SECONDS);
+ const regular = videos.filter(video => video.durationSeconds > SHORT_MAX_SECONDS);
+ return {
+ shortsCount: shorts.length,
+ regularCount: regular.length,
+ avgShortViews: roundedAverage(sumOf(shorts, video => video.viewCount), shorts.length),
+ avgRegularViews: roundedAverage(sumOf(regular, video => video.viewCount), regular.length),
+ avgShortLikes: roundedAverage(sumOf(shorts, video => video.likeCount), shorts.length),
+ avgRegularLikes: roundedAverage(sumOf(regular, video => video.likeCount), regular.length),
+ };
+}
+
+function percentOf(count, total) {
+ return ((count / total) * 100).toFixed(1);
+}
+
+function summarizeFlags(videos) {
+ const hdCount = videos.filter(video => video.definition === 'hd').length;
+ const captionCount = videos.filter(video => video.caption).length;
+ const licensedCount = videos.filter(video => video.licensedContent).length;
+ const embeddableCount = videos.filter(video => video.embeddable).length;
+ return {
+ hdCount, sdCount: videos.length - hdCount,
+ hdPercentage: percentOf(hdCount, videos.length),
+ captionCount, captionPercentage: percentOf(captionCount, videos.length),
+ licensedCount, licensedPercentage: percentOf(licensedCount, videos.length),
+ madeForKidsCount: videos.filter(video => video.madeForKids).length, embeddableCount,
+ embeddablePercentage: percentOf(embeddableCount, videos.length),
+ };
+}
+
+function buildDurationDistribution(videos) {
+ const distribution = { short: 0, medium: 0, long: 0, veryLong: 0 };
+ videos.forEach(video => {
+ if (video.durationSeconds <= SHORT_MAX_SECONDS) distribution.short++;
+ else if (video.durationSeconds <= 600) distribution.medium++;
+ else if (video.durationSeconds <= 3600) distribution.long++;
+ else distribution.veryLong++;
+ });
+ return distribution;
+}
+
+function viralityScore(topViews, avgViews) {
+ return avgViews > 0 ? Math.round(topViews / avgViews * 10) / 10 : 0;
+}
+
+export function computeVideoAnalytics(videos) {
+ if (!videos || videos.length === 0) return emptyVideoAnalytics();
+
+ const now = new Date();
+ const enriched = videos.map(video => withEngagementRates(video, now));
+ const sorted = sortVideos(enriched);
+ const totals = summarizeTotals(videos);
+ const totalDuration = videos.map(video => parseDuration(video.duration)).reduce((total, seconds) => total + seconds, 0);
+ const topViews = sorted.byViews[0]?.viewCount || 0;
+
+ return {
+ totalVideos: videos.length,
+ ...totals,
+ ...summarizeDurations(totalDuration, totals.totalViews, videos.length),
+ ...summarizeRankings(sorted),
+ ...summarizeShorts(enriched),
+ ...summarizeFlags(videos),
+ ...buildPublishTiming(videos),
+ durationDistribution: buildDurationDistribution(enriched),
+ categoryDistribution: buildCategoryDistribution(videos),
+ tagFrequency: buildTagFrequency(videos),
+ ...countRecentUploads(videos, now),
+ ...buildUploadFrequency(videos.length, sorted.byDate[sorted.byDate.length - 1], now),
+ consistencyScore: weeklyConsistencyScore(videos, now),
+ viralityScore: viralityScore(topViews, totals.avgViews),
+ viewsDistribution: buildViewsDistribution(videos, topViews),
+ ...buildMonthlyTrends(enriched),
+ };
+}
diff --git a/backend/services/youtubeAnalytics.test.js b/backend/services/youtubeAnalytics.test.js
new file mode 100644
index 0000000..8048131
--- /dev/null
+++ b/backend/services/youtubeAnalytics.test.js
@@ -0,0 +1,34 @@
+process.env.TZ = 'UTC';
+
+import { test, describe, before, after, mock } from 'node:test';
+import { computeVideoAnalytics } from './youtubeAnalytics.js';
+import { assertGolden } from './fixtures/golden.js';
+import { FIXED_NOW, richVideos, zeroViewVideos, generatedVideos } from './fixtures/youtubeFixtures.js';
+
+describe('computeVideoAnalytics golden output', () => {
+ before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+ after(() => mock.timers.reset());
+
+ test('empty and missing videos return the empty state', () => {
+ assertGolden({
+ empty: computeVideoAnalytics([]),
+ missing: computeVideoAnalytics(null),
+ }, 'youtubeAnalytics.empty');
+ });
+
+ test('a varied channel with hidden counts, shorts and long videos', () => {
+ assertGolden(computeVideoAnalytics(richVideos), 'youtubeAnalytics.rich');
+ });
+
+ test('a single video and videos without views', () => {
+ assertGolden({
+ single: computeVideoAnalytics(richVideos.slice(3, 4)),
+ pair: computeVideoAnalytics(richVideos.slice(1, 3)),
+ zero: computeVideoAnalytics(zeroViewVideos),
+ }, 'youtubeAnalytics.small');
+ });
+
+ test('a long upload history with many tags and categories', () => {
+ assertGolden(computeVideoAnalytics(generatedVideos), 'youtubeAnalytics.generated');
+ });
+});
diff --git a/backend/services/youtubeApi.js b/backend/services/youtubeApi.js
new file mode 100644
index 0000000..68f5cd9
--- /dev/null
+++ b/backend/services/youtubeApi.js
@@ -0,0 +1,23 @@
+// fetch is a global in Cloudflare Workers - no import needed.
+
+// adds the key to the caller's params object, as callers always pass a fresh one
+export async function ytFetch(endpoint, params, apiKey) {
+ const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);
+ params.key = apiKey;
+ Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
+ const response = await fetch(url.toString());
+ const data = await response.json();
+ if (data.error) {
+ const err = new Error(data.error.message);
+ err.reason = data.error.errors?.[0]?.reason || '';
+ err.status = data.error.code;
+ throw err;
+ }
+ return data;
+}
+
+export function optionalCount(value) {
+ if (value == null) return null;
+ const count = parseInt(value, 10);
+ return Number.isFinite(count) ? count : null;
+}
diff --git a/backend/services/youtubeChannels.js b/backend/services/youtubeChannels.js
new file mode 100644
index 0000000..ee16a7e
--- /dev/null
+++ b/backend/services/youtubeChannels.js
@@ -0,0 +1,85 @@
+import { ytFetch } from './youtubeApi.js';
+
+const CHANNEL_ID_PATTERN = /^UC[\w-]{22}$/;
+const CHANNEL_URL_PATTERNS = [
+ /youtube\.com\/channel\/(UC[\w-]{22})/,
+ /youtube\.com\/@([\w.-]+)/,
+ /youtube\.com\/c\/([\w.-]+)/,
+ /youtube\.com\/user\/([\w.-]+)/,
+ /youtube\.com\/([\w.-]+)/,
+];
+
+function extractChannelId(input) {
+ if (!input) return null;
+ const trimmed = input.trim();
+ if (CHANNEL_ID_PATTERN.test(trimmed)) return trimmed;
+ for (const pattern of CHANNEL_URL_PATTERNS) {
+ const match = trimmed.match(pattern);
+ if (match) return match[1];
+ }
+ return trimmed;
+}
+
+// returns null when the lookup finds nothing or fails, so the next strategy can run
+async function lookupChannelId(endpoint, params, pickId, apiKey) {
+ try {
+ const data = await ytFetch(endpoint, params, apiKey);
+ if (data.items && data.items.length > 0) return pickId(data.items[0]);
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+export async function resolveChannelId(input, apiKey) {
+ const extracted = extractChannelId(input);
+ if (!extracted) throw new Error('Invalid input');
+ if (CHANNEL_ID_PATTERN.test(extracted)) return extracted;
+
+ // sequential on purpose: a search costs 100 quota units
+ const byHandle = await lookupChannelId('channels', { part: 'id', forHandle: extracted }, (item) => item.id, apiKey);
+ if (byHandle !== null) return byHandle;
+
+ const byUsername = await lookupChannelId('channels', { part: 'id', forUsername: extracted }, (item) => item.id, apiKey);
+ if (byUsername !== null) return byUsername;
+
+ const searchParams = { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' };
+ const bySearch = await lookupChannelId('search', searchParams, (item) => item.snippet.channelId, apiKey);
+ if (bySearch !== null) return bySearch;
+
+ throw new Error('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');
+}
+
+export async function fetchChannelData(channelId, apiKey) {
+ const data = await ytFetch('channels', {
+ part: 'snippet,statistics,contentDetails,brandingSettings,status,topicDetails',
+ id: channelId,
+ }, apiKey);
+
+ if (!data.items || data.items.length === 0) throw new Error('Channel not found');
+ const channel = data.items[0];
+
+ return {
+ channelId: channel.id,
+ title: channel.snippet.title,
+ description: channel.snippet.description,
+ customUrl: channel.snippet.customUrl || '',
+ publishedAt: channel.snippet.publishedAt,
+ country: channel.snippet.country || 'Unknown',
+ thumbnails: {
+ default: channel.snippet.thumbnails?.default?.url || '',
+ medium: channel.snippet.thumbnails?.medium?.url || '',
+ high: channel.snippet.thumbnails?.high?.url || '',
+ },
+ subscriberCount: parseInt(channel.statistics.subscriberCount) || 0,
+ viewCount: parseInt(channel.statistics.viewCount) || 0,
+ videoCount: parseInt(channel.statistics.videoCount) || 0,
+ hiddenSubscriberCount: channel.statistics.hiddenSubscriberCount || false,
+ uploadsPlaylistId: channel.contentDetails?.relatedPlaylists?.uploads || '',
+ keywords: channel.brandingSettings?.channel?.keywords || '',
+ bannerUrl: channel.brandingSettings?.image?.bannerExternalUrl || '',
+ madeForKids: channel.status?.madeForKids || false,
+ topicCategories: channel.topicDetails?.topicCategories || [],
+ isLinked: channel.status?.isLinked || false,
+ };
+}
diff --git a/backend/services/youtubeChannels.test.js b/backend/services/youtubeChannels.test.js
new file mode 100644
index 0000000..9d2eb9e
--- /dev/null
+++ b/backend/services/youtubeChannels.test.js
@@ -0,0 +1,68 @@
+import { test, describe, afterEach } from 'node:test';
+import { resolveChannelId, fetchChannelData } from './youtubeChannels.js';
+import { assertGolden } from './fixtures/golden.js';
+import { installFetch, reply } from './fixtures/fakeFetch.js';
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+async function outcomeOf(promise) {
+ try {
+ return { value: await promise };
+ } catch (err) {
+ return { error: err.message, reason: err.reason, status: err.status };
+ }
+}
+
+const fullChannel = {
+ id: 'UCfull',
+ snippet: { title: 'Ribbon', description: 'Channel', customUrl: '@ribbon', publishedAt: '2020-01-01T00:00:00Z', country: 'GB', thumbnails: { default: { url: 'd' }, medium: { url: 'm' }, high: { url: 'h' } } },
+ statistics: { subscriberCount: '1200', viewCount: '98000', videoCount: '45', hiddenSubscriberCount: true },
+ contentDetails: { relatedPlaylists: { uploads: 'UUfull' } },
+ brandingSettings: { channel: { keywords: 'travel vlog' }, image: { bannerExternalUrl: 'https://banner' } },
+ status: { madeForKids: true, isLinked: true },
+ topicDetails: { topicCategories: ['https://en.wikipedia.org/wiki/Travel'] },
+};
+
+const sparseChannel = {
+ id: 'UCsparse',
+ snippet: { title: 'Sparse', description: '', publishedAt: '2021-01-01T00:00:00Z' },
+ statistics: { subscriberCount: 'hidden' },
+};
+
+describe('youtube channel golden output', () => {
+ test('maps full and sparse channels and reports missing ones', async () => {
+ const bodies = [
+ { items: [fullChannel] },
+ { items: [sparseChannel] },
+ { items: [] },
+ {},
+ { error: { message: 'API key not valid', errors: [{ reason: 'keyInvalid' }], code: 400 } },
+ ];
+ fetchMock = installFetch((_request, count) => reply(bodies[count - 1]));
+ const outcomes = [];
+ for (let i = 0; i < bodies.length; i++) outcomes.push(await outcomeOf(fetchChannelData(`UC${i}`, 'KEY')));
+ assertGolden({ outcomes, requests: fetchMock.requests }, 'youtubeChannels.data');
+ });
+
+ test('resolves every supported input form', async () => {
+ fetchMock = installFetch((request) => {
+ const params = new URL(request.url).searchParams;
+ const handle = params.get('forHandle') ?? params.get('forUsername') ?? params.get('q');
+ return reply({ items: [{ id: `UC_${handle}`, snippet: { channelId: `UC_search_${handle}` } }] });
+ });
+ const inputs = [
+ ' https://www.youtube.com/channel/UCabcdefghijklmnopqrstuv ',
+ 'https://youtube.com/@creator.name',
+ 'https://youtube.com/c/legacy-name',
+ 'https://youtube.com/user/olduser',
+ 'https://youtube.com/plainname',
+ 'just-a-name',
+ '',
+ null,
+ ];
+ const outcomes = [];
+ for (const input of inputs) outcomes.push(await outcomeOf(resolveChannelId(input, 'KEY')));
+ assertGolden({ outcomes, requests: fetchMock.requests }, 'youtubeChannels.resolve');
+ });
+});
diff --git a/backend/services/youtubeFormat.js b/backend/services/youtubeFormat.js
new file mode 100644
index 0000000..ff9a73e
--- /dev/null
+++ b/backend/services/youtubeFormat.js
@@ -0,0 +1,31 @@
+// ignores the day part of durations such as P1DT2H, which then parse as zero seconds
+export function parseDuration(iso) {
+ const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
+ if (!match) return 0;
+ return (parseInt(match[1] || 0) * 3600) + (parseInt(match[2] || 0) * 60) + parseInt(match[3] || 0);
+}
+
+export function formatCompact(value) {
+ if (value >= 1e6) return (value / 1e6).toFixed(1) + 'M';
+ if (value >= 1e3) return (value / 1e3).toFixed(1) + 'K';
+ return value.toString();
+}
+
+export function formatDuration(totalSeconds) {
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = totalSeconds % 60;
+ return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m ${seconds}s`;
+}
+
+export function formatVideoSummary(video) {
+ if (!video) return null;
+ return {
+ videoId: video.videoId, title: video.title, viewCount: video.viewCount,
+ likeCount: video.likeCount, commentCount: video.commentCount,
+ publishedAt: video.publishedAt,
+ thumbnail: video.thumbnails?.medium || video.thumbnails?.default || '',
+ engagementRate: video.engagementRate?.toFixed(2) || 0,
+ durationSeconds: video.durationSeconds || parseDuration(video.duration),
+ };
+}
diff --git a/backend/services/youtubeTracked.js b/backend/services/youtubeTracked.js
new file mode 100644
index 0000000..24b65fe
--- /dev/null
+++ b/backend/services/youtubeTracked.js
@@ -0,0 +1,49 @@
+import { ytFetch, optionalCount } from './youtubeApi.js';
+
+export function extractYouTubeVideoId(url) {
+ let parsedUrl;
+ try {
+ parsedUrl = new URL(url.trim());
+ } catch {
+ // not a url at all, so it has no video id
+ return null;
+ }
+
+ const { hostname, pathname, searchParams } = parsedUrl;
+ if (hostname === 'youtu.be') return pathname.slice(1).split('?')[0];
+ if (!hostname.includes('youtube.com')) return null;
+ if (pathname.startsWith('/shorts/') || pathname.startsWith('/embed/')) return pathname.split('/')[2];
+ return searchParams.get('v');
+}
+
+export async function fetchTrackedYouTubeData(videoUrl, apiKey) {
+ const videoId = extractYouTubeVideoId(videoUrl);
+ if (!videoId) throw new Error('Invalid YouTube URL - could not extract video ID');
+
+ const data = await ytFetch('videos', {
+ part: 'snippet,statistics',
+ id: videoId,
+ }, apiKey);
+
+ if (!data.items || data.items.length === 0) throw new Error('YouTube video not found - check the URL');
+
+ const { snippet, statistics } = data.items[0];
+ const isShort = videoUrl.includes('/shorts/');
+
+ return {
+ contentType: 'youtube',
+ title: snippet.title,
+ channelTitle: snippet.channelTitle,
+ channelId: snippet.channelId,
+ thumbnail: snippet.thumbnails?.medium?.url || snippet.thumbnails?.default?.url || '',
+ publishedAt: snippet.publishedAt,
+ viewCount: parseInt(statistics.viewCount || '0', 10),
+ likeCount: optionalCount(statistics.likeCount),
+ commentCount: optionalCount(statistics.commentCount),
+ isShort,
+ permalink: isShort
+ ? `https://www.youtube.com/shorts/${videoId}`
+ : `https://www.youtube.com/watch?v=${videoId}`,
+ lastFetchedAt: new Date().toISOString(),
+ };
+}
diff --git a/backend/services/youtubeTracked.test.js b/backend/services/youtubeTracked.test.js
new file mode 100644
index 0000000..fbf07ce
--- /dev/null
+++ b/backend/services/youtubeTracked.test.js
@@ -0,0 +1,41 @@
+import { test, describe, before, after, afterEach, mock } from 'node:test';
+import { fetchTrackedYouTubeData } from './youtubeTracked.js';
+import { assertGolden } from './fixtures/golden.js';
+import { installFetch, reply } from './fixtures/fakeFetch.js';
+import { FIXED_NOW } from './fixtures/youtubeFixtures.js';
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+async function outcomeOf(promise) {
+ try {
+ return { value: await promise };
+ } catch (err) {
+ return { error: err.message };
+ }
+}
+
+describe('fetchTrackedYouTubeData golden output', () => {
+ before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));
+ after(() => mock.timers.reset());
+
+ test('maps watch and short links, hidden counts and missing thumbnails', async () => {
+ const bodies = [
+ { items: [{ snippet: { title: 'Watch', channelTitle: 'Ribbon', channelId: 'UC1', publishedAt: '2026-08-01T10:00:00Z', thumbnails: { medium: { url: 'm' }, default: { url: 'd' } } }, statistics: { viewCount: '1500', likeCount: '40', commentCount: '3' } }] },
+ { items: [{ snippet: { title: 'Short', channelTitle: 'Ribbon', channelId: 'UC1', publishedAt: '2026-08-02T10:00:00Z', thumbnails: { default: { url: 'd' } } }, statistics: {} }] },
+ { items: [{ snippet: { title: 'Bare', channelTitle: 'Ribbon', channelId: 'UC1', publishedAt: '2026-08-03T10:00:00Z' }, statistics: { viewCount: '9', likeCount: '0', commentCount: 'x' } }] },
+ { error: { message: 'Quota exceeded', errors: [{ reason: 'quotaExceeded' }], code: 403 } },
+ ];
+ fetchMock = installFetch((_request, count) => reply(bodies[count - 1]));
+ const links = [
+ 'https://www.youtube.com/watch?v=abc123&t=5',
+ 'https://youtube.com/shorts/short1?feature=share',
+ ' https://youtu.be/bare1?t=1 ',
+ 'https://www.youtube.com/embed/err1',
+ 'https://www.youtube.com/playlist?list=PL1',
+ ];
+ const outcomes = [];
+ for (const link of links) outcomes.push(await outcomeOf(fetchTrackedYouTubeData(link, 'KEY')));
+ assertGolden({ outcomes, requests: fetchMock.requests }, 'youtubeTracked.data');
+ });
+});
diff --git a/backend/services/youtubeTrends.js b/backend/services/youtubeTrends.js
new file mode 100644
index 0000000..985b403
--- /dev/null
+++ b/backend/services/youtubeTrends.js
@@ -0,0 +1,130 @@
+import { DAY_NAMES, DAY_MS, monthKey } from './analyticsMath.js';
+import { formatCompact } from './youtubeFormat.js';
+
+const WEEK_MS = 7 * DAY_MS;
+const HISTOGRAM_BUCKETS = 10;
+const MAX_TAGS = 30;
+
+function byCountDescending(first, second) {
+ return second[1] - first[1];
+}
+
+export function buildPublishTiming(videos) {
+ const dayDistribution = {};
+ const hourDistribution = {};
+ videos.forEach(video => {
+ const date = new Date(video.publishedAt);
+ const day = DAY_NAMES[date.getUTCDay()];
+ const hour = date.getUTCHours();
+ dayDistribution[day] = (dayDistribution[day] || 0) + 1;
+ hourDistribution[hour] = (hourDistribution[hour] || 0) + 1;
+ });
+ const peakDay = Object.entries(dayDistribution).sort(byCountDescending)[0];
+ const peakHour = Object.entries(hourDistribution).sort(byCountDescending)[0];
+ return {
+ publishDayDistribution: dayDistribution,
+ publishHourDistribution: hourDistribution,
+ peakPublishDay: peakDay ? peakDay[0] : '',
+ peakPublishHour: peakHour ? parseInt(peakHour[0]) : 0,
+ };
+}
+
+export function buildCategoryDistribution(videos) {
+ const distribution = {};
+ videos.forEach(video => {
+ const category = video.categoryId || 'Unknown';
+ distribution[category] = (distribution[category] || 0) + 1;
+ });
+ return distribution;
+}
+
+export function buildTagFrequency(videos) {
+ const tagCounts = {};
+ videos.forEach(video => {
+ (video.tags || []).forEach(tag => {
+ const lower = tag.toLowerCase();
+ tagCounts[lower] = (tagCounts[lower] || 0) + 1;
+ });
+ });
+ return Object.entries(tagCounts)
+ .sort(byCountDescending)
+ .slice(0, MAX_TAGS)
+ .map(([tag, count]) => ({ tag, count }));
+}
+
+// strict < unlike the inclusive instagram and reddit counts; kept to match stored analytics
+export function countRecentUploads(videos, now) {
+ const uploadedWithin = (days) => videos.filter(video => (now - new Date(video.publishedAt)) < days * DAY_MS).length;
+ return {
+ videosLast7Days: uploadedWithin(7),
+ videosLast30Days: uploadedWithin(30),
+ videosLast90Days: uploadedWithin(90),
+ videosLast365Days: uploadedWithin(365),
+ };
+}
+
+export function buildUploadFrequency(videoCount, oldestVideo, now) {
+ const oldestDate = new Date(oldestVideo?.publishedAt || now);
+ const totalWeeks = Math.max(1, (now - oldestDate) / WEEK_MS);
+ const totalMonths = Math.max(1, totalWeeks / 4.33);
+ return {
+ uploadFrequencyPerWeek: (videoCount / totalWeeks).toFixed(1),
+ uploadFrequencyPerMonth: (videoCount / totalMonths).toFixed(1),
+ };
+}
+
+// scores how evenly uploads spread across the weeks that have any
+export function weeklyConsistencyScore(videos, now) {
+ const weeklyUploads = videos.reduce((weeks, video) => {
+ const weekNumber = Math.floor((now - new Date(video.publishedAt)) / WEEK_MS);
+ weeks[weekNumber] = (weeks[weekNumber] || 0) + 1;
+ return weeks;
+ }, {});
+ const weekValues = Object.values(weeklyUploads);
+ const weekCount = Math.max(1, weekValues.length);
+ const avgWeekly = weekValues.reduce((total, value) => total + value, 0) / weekCount;
+ const variance = weekValues.reduce((total, value) => total + Math.pow(value - avgWeekly, 2), 0) / weekCount;
+ const stdDev = Math.sqrt(variance);
+ return Math.max(0, Math.min(100, Math.round(100 - (stdDev / Math.max(0.01, avgWeekly)) * 25)));
+}
+
+// < high drops the top video when its views split evenly into ten buckets; kept as is
+export function buildViewsDistribution(videos, maxViews) {
+ const step = Math.max(1, Math.ceil(maxViews / HISTOGRAM_BUCKETS));
+ const ranges = [];
+ const counts = [];
+ for (let i = 0; i < HISTOGRAM_BUCKETS; i++) {
+ const low = i * step;
+ const high = (i + 1) * step;
+ ranges.push(`${formatCompact(low)}-${formatCompact(high)}`);
+ counts.push(videos.filter(video => video.viewCount >= low && video.viewCount < high).length);
+ }
+ return { ranges, counts };
+}
+
+function percentOfViews(count, views) {
+ return views > 0 ? ((count / views) * 100).toFixed(2) : 0;
+}
+
+export function buildMonthlyTrends(videos) {
+ const months = {};
+ videos.forEach(video => {
+ const key = monthKey(new Date(video.publishedAt));
+ if (!months[key]) months[key] = { views: 0, likes: 0, comments: 0, count: 0 };
+ months[key].views += video.viewCount;
+ months[key].likes += video.likeCount;
+ months[key].comments += video.commentCount;
+ months[key].count++;
+ });
+ const sortedMonths = Object.keys(months).sort();
+ return {
+ viewsTrend: sortedMonths.map(month => ({ month, value: months[month].views, count: months[month].count })),
+ engagementTrend: sortedMonths.map(month => ({
+ month,
+ value: months[month].views > 0
+ ? ((months[month].likes + months[month].comments) / months[month].views * 100).toFixed(2)
+ : 0,
+ })),
+ likeRateTrend: sortedMonths.map(month => ({ month, value: percentOfViews(months[month].likes, months[month].views) })),
+ };
+}
diff --git a/backend/services/youtubeVideos.js b/backend/services/youtubeVideos.js
new file mode 100644
index 0000000..7949dd5
--- /dev/null
+++ b/backend/services/youtubeVideos.js
@@ -0,0 +1,74 @@
+import { ytFetch, optionalCount } from './youtubeApi.js';
+
+export function normalizeYouTubeVideo(video) {
+ const { snippet, contentDetails, statistics, status } = video;
+ return {
+ videoId: video.id,
+ title: snippet.title,
+ description: snippet.description?.substring(0, 200) || '',
+ publishedAt: snippet.publishedAt,
+ channelTitle: snippet.channelTitle,
+ thumbnails: {
+ default: snippet.thumbnails?.default?.url || '',
+ medium: snippet.thumbnails?.medium?.url || '',
+ high: snippet.thumbnails?.high?.url || '',
+ },
+ tags: snippet.tags || [],
+ categoryId: snippet.categoryId || '',
+ liveBroadcastContent: snippet.liveBroadcastContent || 'none',
+ defaultAudioLanguage: snippet.defaultAudioLanguage || '',
+ duration: contentDetails.duration,
+ dimension: contentDetails.dimension || '2d',
+ definition: contentDetails.definition || 'hd',
+ caption: contentDetails.caption === 'true',
+ licensedContent: contentDetails.licensedContent || false,
+ projection: contentDetails.projection || 'rectangular',
+ viewCount: parseInt(statistics.viewCount) || 0,
+ // null when the owner hid likes or switched comments off, so it stays apart from zero
+ likeCount: optionalCount(statistics.likeCount),
+ commentCount: optionalCount(statistics.commentCount),
+ privacyStatus: status?.privacyStatus || 'public',
+ embeddable: status?.embeddable || false,
+ madeForKids: status?.madeForKids || false,
+ };
+}
+
+async function fetchPlaylistPage(playlistId, pageToken, apiKey) {
+ const params = { part: 'snippet,contentDetails', playlistId, maxResults: '50' };
+ if (pageToken) params.pageToken = pageToken;
+ try {
+ return await ytFetch('playlistItems', params, apiKey);
+ } catch (err) {
+ // youtube reports a channel's uploads playlist as missing until its first public video
+ if (err.reason === 'playlistNotFound') return null;
+ throw err;
+ }
+}
+
+async function fetchVideoDetails(playlistItems, apiKey) {
+ const videoIds = playlistItems.map(item => item.snippet.resourceId.videoId).join(',');
+ const statsData = await ytFetch('videos', {
+ part: 'statistics,contentDetails,snippet,status',
+ id: videoIds,
+ }, apiKey);
+ return statsData.items ? statsData.items.map(normalizeYouTubeVideo) : [];
+}
+
+export async function fetchAllVideos(playlistId, apiKey, maxPages = 10) {
+ const allVideos = [];
+ let pageToken = '';
+ let page = 0;
+
+ while (page < maxPages) {
+ const data = await fetchPlaylistPage(playlistId, pageToken, apiKey);
+ if (!data || !data.items || data.items.length === 0) break;
+
+ allVideos.push(...await fetchVideoDetails(data.items, apiKey));
+
+ pageToken = data.nextPageToken || '';
+ if (!pageToken) break;
+ page++;
+ }
+
+ return allVideos;
+}
diff --git a/backend/services/youtubeVideos.test.js b/backend/services/youtubeVideos.test.js
new file mode 100644
index 0000000..2d14dc8
--- /dev/null
+++ b/backend/services/youtubeVideos.test.js
@@ -0,0 +1,76 @@
+import { test, describe, afterEach } from 'node:test';
+import { fetchAllVideos } from './youtubeVideos.js';
+import { assertGolden } from './fixtures/golden.js';
+import { installFetch, reply } from './fixtures/fakeFetch.js';
+import { rawPlaylistItem, rawVideos } from './fixtures/youtubeFixtures.js';
+
+let fetchMock = null;
+afterEach(() => fetchMock?.restore());
+
+async function outcomeOf(promise) {
+ try {
+ return { value: await promise };
+ } catch (err) {
+ return { error: err.message, reason: err.reason, status: err.status };
+ }
+}
+
+function apiError(message, reason, code) {
+ const errors = reason === undefined ? undefined : [{ reason }];
+ return reply({ error: { message, errors, code } });
+}
+
+function youtubeServer(playlistPages) {
+ return installFetch((request) => {
+ const url = new URL(request.url);
+ if (url.pathname.endsWith('/videos')) {
+ const items = url.searchParams.get('id').split(',').map(id => rawVideos[id] ?? { ...rawVideos.odd, id });
+ return reply({ items });
+ }
+ const page = playlistPages[url.searchParams.get('pageToken') ?? ''];
+ return page ?? reply({ items: [] });
+ });
+}
+
+describe('fetchAllVideos golden output', () => {
+ test('maps every page of videos and stops at the last page token', async () => {
+ fetchMock = youtubeServer({
+ '': reply({ items: [rawPlaylistItem('full'), rawPlaylistItem('hidden')], nextPageToken: 'P2' }),
+ P2: reply({ items: [rawPlaylistItem('odd'), rawPlaylistItem('extra')] }),
+ });
+ const videos = await fetchAllVideos('UU123', 'KEY');
+ assertGolden({ videos, requests: fetchMock.requests }, 'youtubeVideos.pages');
+ });
+
+ test('respects maxPages and stops on an empty page', async () => {
+ fetchMock = youtubeServer({
+ '': reply({ items: [rawPlaylistItem('full')], nextPageToken: 'P2' }),
+ P2: reply({ items: [rawPlaylistItem('hidden')], nextPageToken: 'P3' }),
+ P3: reply({ items: [], nextPageToken: 'P4' }),
+ });
+ const capped = await fetchAllVideos('UU123', 'KEY', 1);
+ const all = await fetchAllVideos('UU123', 'KEY');
+ assertGolden({ capped: capped.map(item => item.videoId), all: all.map(item => item.videoId), requests: fetchMock.requests.length }, 'youtubeVideos.maxPages');
+ });
+
+ test('treats a missing uploads playlist as no videos and rethrows other errors', async () => {
+ fetchMock = youtubeServer({
+ '': reply({ items: [rawPlaylistItem('full')], nextPageToken: 'P2' }),
+ P2: apiError('Playlist not found', 'playlistNotFound', 404),
+ });
+ const partial = await outcomeOf(fetchAllVideos('UU123', 'KEY'));
+ fetchMock.restore();
+
+ fetchMock = youtubeServer({ '': apiError('Playlist not found', 'playlistNotFound', 404) });
+ const none = await outcomeOf(fetchAllVideos('UU123', 'KEY'));
+ fetchMock.restore();
+
+ fetchMock = youtubeServer({ '': apiError('Quota exceeded', 'quotaExceeded', 403) });
+ const quota = await outcomeOf(fetchAllVideos('UU123', 'KEY'));
+ fetchMock.restore();
+
+ fetchMock = youtubeServer({ '': apiError('Bad request') });
+ const bare = await outcomeOf(fetchAllVideos('UU123', 'KEY'));
+ assertGolden({ partial, none, quota, bare }, 'youtubeVideos.errors');
+ });
+});
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 0b9ba50..8099ae5 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -72,30 +72,28 @@ function safeAccount(account) {
---
-## `backend/services/youtube.js`
+## YouTube (`backend/services/youtube*.js`)
-### HTTP Client
-
-All YouTube Data API v3 calls use `ytFetch(path, params, env)`:
+`services/youtube.js` is a barrel that re-exports `resolveChannelId`, `fetchChannelData`, `fetchAllVideos`, `fetchTrackedYouTubeData` and `computeVideoAnalytics`, so importers are unchanged.
-```js
-async function ytFetch(path, params, env) {
- const qs = new URLSearchParams({ ...params, key: env.YOUTUBE_API_KEY });
- const res = await fetch(`https://www.googleapis.com/youtube/v3${path}?${qs}`);
- const data = await res.json();
- if (data.error) throw new Error(data.error.message);
- return data;
-}
-```
+| Module | Contents |
+|---|---|
+| `youtubeApi.js` | `ytFetch(endpoint, params, apiKey)` (adds `key` to the params object it is given; errors carry `reason` and `status`) and `optionalCount` (null for a hidden or missing count) |
+| `youtubeChannels.js` | Channel id extraction from URLs and handles, the handle, username, search lookup chain, `resolveChannelId`, `fetchChannelData` |
+| `youtubeVideos.js` | `normalizeYouTubeVideo`, the playlist page fetch that treats `playlistNotFound` as no videos, `fetchAllVideos` |
+| `youtubeTracked.js` | `extractYouTubeVideoId`, `fetchTrackedYouTubeData` |
+| `youtubeFormat.js` | `parseDuration`, `formatCompact`, `formatDuration`, `formatVideoSummary` |
+| `youtubeAnalytics.js` | `computeVideoAnalytics` orchestrator, the empty state, totals, durations, rankings, Shorts split, format flags |
+| `youtubeTrends.js` | Publish day and hour distribution, categories, tags, recency counts, upload frequency, weekly consistency, views histogram, monthly trends |
### Key Functions
| Function | Purpose |
|---|---|
-| `resolveChannelId(input, env)` | Resolves a YouTube URL, handle, or channel ID to a canonical channel ID |
-| `fetchChannelData(channelId, env)` | Fetches channel snippet, statistics, and branding |
-| `fetchAllVideos(channelId, uploadPlaylistId, env)` | Paginates through playlist items API (50 per page, up to 10 pages = 500 videos) + batch-fetches video statistics |
-| `computeVideoAnalytics(videos, channel)` | Computes 50+ analytics metrics from the video dataset |
+| `resolveChannelId(input, apiKey)` | Resolves a YouTube URL, handle, or channel ID to a canonical channel ID |
+| `fetchChannelData(channelId, apiKey)` | Fetches channel snippet, statistics, and branding |
+| `fetchAllVideos(playlistId, apiKey, maxPages)` | Paginates through playlist items API (50 per page, up to 10 pages = 500 videos) + batch-fetches video statistics |
+| `computeVideoAnalytics(videos)` | Computes 50+ analytics metrics from the video dataset; captures the current time once and passes it to the trend helpers |
### Analytics Computation