Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add support for youtube stats

Steven Tey7273d9030457
diff --git a/apps/web/app/(ee)/api/cron/online-presence/youtube/route.ts b/apps/web/app/(ee)/api/cron/online-presence/youtube/route.ts
new file mode 100644
index 0000000000..37fa17b35e
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/online-presence/youtube/route.ts
@@ -0,0 +1,93 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { prisma } from "@dub/prisma";
+import { chunk, deepEqual } from "@dub/utils";
+import { google } from "googleapis";
+
+export const dynamic = "force-dynamic";
+
+/*
+ This route is used to update youtube stats for youtubeVerified partners
+ Runs once a day at 12:00 AM UTC
+*/
+export async function GET(req: Request) {
+ try {
+ await verifyVercelSignature(req);
+
+ const youtube = google.youtube("v3");
+
+ const youtubeVerifiedPartners = await prisma.partner.findMany({
+ where: {
+ youtubeVerifiedAt: {
+ not: null,
+ },
+ youtubeChannelId: {
+ not: null,
+ },
+ },
+ select: {
+ id: true,
+ youtubeChannelId: true,
+ youtubeSubscriberCount: true,
+ youtubeVideoCount: true,
+ youtubeViewCount: true,
+ },
+ });
+
+ const chunks = chunk(youtubeVerifiedPartners, 50);
+
+ for (const chunk of chunks) {
+ const channelIds = chunk.map(
+ (partner) => partner.youtubeChannelId as string, // coerce this cause we already filtered above
+ );
+
+ if (channelIds.length === 0) continue;
+
+ const response = await youtube.channels.list({
+ key: process.env.YOUTUBE_API_KEY,
+ part: ["statistics", "snippet"],
+ id: channelIds,
+ });
+
+ const stats = response.data.items;
+
+ if (!stats) {
+ continue;
+ }
+
+ for (const stat of stats) {
+ const partner = chunk.find((p) => p.youtubeChannelId === stat.id);
+
+ if (!partner || !stat.statistics) {
+ continue;
+ }
+
+ const { viewCount, subscriberCount, videoCount } = stat.statistics;
+
+ // Only compare the YouTube stats
+ const currentStats = {
+ youtubeViewCount: partner.youtubeViewCount,
+ youtubeSubscriberCount: partner.youtubeSubscriberCount,
+ youtubeVideoCount: partner.youtubeVideoCount,
+ };
+
+ const newStats = {
+ youtubeViewCount: parseInt(viewCount || "0", 10),
+ youtubeSubscriberCount: parseInt(subscriberCount || "0", 10),
+ youtubeVideoCount: parseInt(videoCount || "0", 10),
+ };
+
+ if (deepEqual(currentStats, newStats)) {
+ continue;
+ }
+
+ await prisma.partner.update({
+ where: { id: partner.id },
+ data: newStats,
+ });
+ }
+ }
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts b/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts
index 134a2d5f61..421f8fd53a 100644
--- a/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts
+++ b/apps/web/app/(ee)/api/partners/online-presence/callback/route.ts
@@ -104,7 +104,7 @@ export async function GET(req: Request) {
},
});
- const isVerified = await verify({
+ const { verified: isVerified, metadata } = await verify({
partner,
accessToken: result.access_token,
});
@@ -117,6 +117,16 @@ export async function GET(req: Request) {
data: {
[provider]: partner[provider],
[verifiedColumn]: new Date(),
+ ...(provider === "youtube" &&
+ metadata && {
+ youtubeChannelId: metadata.channelId,
+ youtubeSubscriberCount: parseInt(
+ metadata.subscriberCount || "0",
+ 10,
+ ),
+ youtubeVideoCount: parseInt(metadata.videoCount || "0", 10),
+ youtubeViewCount: parseInt(metadata.viewCount || "0", 10),
+ }),
},
});
}
diff --git a/apps/web/lib/actions/partners/online-presence-providers.ts b/apps/web/lib/actions/partners/online-presence-providers.ts
index 93337f0fea..7281301304 100644
--- a/apps/web/lib/actions/partners/online-presence-providers.ts
+++ b/apps/web/lib/actions/partners/online-presence-providers.ts
@@ -9,10 +9,10 @@ type OnlinePresenceProvider = {
clientIdParam?: string;
pkce?: boolean;
scopes: string;
- verify: (props: {
- partner: Partner;
- accessToken: string;
- }) => Promise<boolean>;
+ verify: (props: { partner: Partner; accessToken: string }) => Promise<{
+ verified: boolean;
+ metadata?: Record<string, string>;
+ }>;
};
export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
@@ -25,19 +25,34 @@ export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
clientSecret: process.env.YOUTUBE_CLIENT_SECRET ?? null,
scopes: "https://www.googleapis.com/auth/youtube.readonly",
verify: async ({ partner, accessToken }) => {
- if (!partner.youtube) return false;
+ if (!partner.youtube)
+ return {
+ verified: false,
+ };
// Fetch channel info
const channelResponse = await fetch(
`https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true&access_token=${accessToken}`,
).then((r) => r.json());
+ const channelId = channelResponse?.items?.[0]?.id;
const handle = channelResponse?.items?.[0]?.snippet?.customUrl;
- return (
- !!handle &&
- `@${partner.youtube?.toLowerCase()}` === handle.toLowerCase()
- );
+ const { subscriberCount, viewCount, videoCount } =
+ channelResponse?.items?.[0]?.statistics;
+
+ return {
+ verified:
+ !!handle &&
+ `@${partner.youtube?.toLowerCase()}` === handle.toLowerCase(),
+ metadata: {
+ channelId,
+ handle,
+ subscriberCount,
+ videoCount,
+ viewCount,
+ },
+ };
},
},
twitter: {
@@ -49,7 +64,10 @@ export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
pkce: true,
scopes: "users.read tweet.read",
verify: async ({ partner, accessToken }) => {
- if (!partner.twitter) return false;
+ if (!partner.twitter)
+ return {
+ verified: false,
+ };
// Fetch user info
const userResponse = await fetch("https://api.twitter.com/2/users/me", {
@@ -60,9 +78,11 @@ export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
const username = userResponse?.data?.username;
- return (
- !!username && partner.twitter.toLowerCase() === username.toLowerCase()
- );
+ return {
+ verified:
+ !!username &&
+ partner.twitter.toLowerCase() === username.toLowerCase(),
+ };
},
},
tiktok: {
@@ -74,7 +94,10 @@ export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
clientIdParam: "client_key",
scopes: "user.info.basic,user.info.profile",
verify: async ({ partner, accessToken }) => {
- if (!partner.tiktok) return false;
+ if (!partner.tiktok)
+ return {
+ verified: false,
+ };
// Fetch user info
const userResponse = await fetch(
@@ -88,9 +111,11 @@ export const ONLINE_PRESENCE_PROVIDERS: Record<string, OnlinePresenceProvider> =
const username = userResponse?.data?.user?.username;
- return (
- !!username && partner.tiktok.toLowerCase() === username.toLowerCase()
- );
+ return {
+ verified:
+ !!username &&
+ partner.tiktok.toLowerCase() === username.toLowerCase(),
+ };
},
},
};
diff --git a/apps/web/package.json b/apps/web/package.json
index fb4de6e6ef..0fbd3bf5a8 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -78,6 +78,7 @@
"fuse.js": "^6.6.2",
"geist": "^1.3.1",
"github-slugger": "^2.0.0",
+ "googleapis": "^150.0.1",
"he": "^1.2.0",
"html-escaper": "^3.0.3",
"input-otp": "^1.2.4",
diff --git a/apps/web/scripts/get-subscriber-count.ts b/apps/web/scripts/get-subscriber-count.ts
new file mode 100644
index 0000000000..8b127d84cf
--- /dev/null
+++ b/apps/web/scripts/get-subscriber-count.ts
@@ -0,0 +1,54 @@
+import "dotenv-flow/config";
+import { google } from "googleapis";
+
+const youtube = google.youtube("v3");
+
+// First, we need to get the channel IDs from the handles
+async function getChannelIds(handles: string[]) {
+ const channelIds = await Promise.all(
+ handles.map(async (handle) => {
+ const response = await youtube.channels.list({
+ key: process.env.YOUTUBE_API_KEY,
+ part: ["id"],
+ forHandle: handle,
+ });
+ return response.data.items?.[0]?.id;
+ }),
+ );
+ return channelIds.filter(Boolean) as string[];
+}
+
+async function main() {
+ if (!process.env.YOUTUBE_API_KEY) {
+ throw new Error("Missing YouTube API key");
+ }
+
+ const handles = ["efficientapp", "stey", "hubermanlab"];
+
+ try {
+ // First get the channel IDs
+ const channelIds = await getChannelIds(handles);
+ console.log("Found channel IDs:", channelIds);
+
+ // Then get the statistics for all channels
+ const response = await youtube.channels.list({
+ key: process.env.YOUTUBE_API_KEY,
+ part: ["statistics", "snippet"],
+ id: channelIds,
+ });
+
+ // Log data for each channel
+ response.data.items?.forEach((channel) => {
+ console.log(
+ `\nChannel: @${channel.snippet?.customUrl || channel.snippet?.title}`,
+ );
+ console.log("Subscriber count:", channel.statistics?.subscriberCount);
+ console.log("View count:", channel.statistics?.viewCount);
+ console.log("Video count:", channel.statistics?.videoCount);
+ });
+ } catch (error) {
+ console.error("Error fetching channel data:", error);
+ }
+}
+
+main();
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index 1677f11522..52e7d6e904 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -42,7 +42,11 @@ model Partner {
websiteVerifiedAt DateTime?
youtube String?
+ youtubeChannelId String?
youtubeVerifiedAt DateTime?
+ youtubeSubscriberCount Int?
+ youtubeVideoCount Int?
+ youtubeViewCount Int?
twitter String?
twitterVerifiedAt DateTime?
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 28739ccff3..4255ec2b65 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -223,6 +223,9 @@ importers:
github-slugger:
specifier: ^2.0.0
version: 2.0.0
+ googleapis:
+ specifier: ^150.0.1
+ version: 150.0.1
he:
specifier: ^1.2.0
version: 1.2.0
@@ -7504,10 +7507,18 @@ packages:
resolution: {integrity: sha512-bw8smrX+XlAoo9o1JAksBwX+hi/RG15J+NTSxmNPIclKC3ZVK6C2afwY8OSdRvOK0+ZLecUJYtj2MmjOt3Dm0w==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-y1Q0MX1Ba6eg67Zz92kW0MHHhdtWksYckQy1KJsI6P4UlDQ8cvdvpLEPslD/k7vFkdPppMESFGTvk7XpSiKj8g==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-Ozxyi23/1Ar51wjUT2RDklK+3HxqDr8TLBNK8rBBFQ7T85iIGnXnVusauj06QyqCXRFZig8LZC+TUddWbndlpQ==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-3PfRTzvT3Msu0Hy8Gf9ypxJvaClG2IB9pyH0r8QOmRBW5mUcrHgYpF4GYP+XulDbfhxEhBYtJtJJQb5S2wM+LA==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-Q4gC1pBVPN+D579pBaz0TRRnGA4p9UK6elDY/xizXdFk/g4EKR5g0I+4p/Kj6gM0SajDBZ/0FvDV9ey9ud7BWw==}
peerDependencies:
@@ -7613,14 +7624,30 @@ packages:
resolution: {integrity: sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==}
+ resolution: {integrity: sha512-GspVjZj1RbyRWpQ9FbAXMKjFGzZwDKnUHi66JJ+tcjcu5/xYAP1pdlWotCuIkMwjfVsxxDvsGZXGLzRt72D0sQ==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-1M9HdOcQNPV5BwSXqwwT238MTKodJFBxZ/V2JP397ieOLv4FjQdfYb9SooR7Mb+oUT2IJ92mLJQf804dyx0MJA==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-rcX58I7nqpu4mbKztFeOAObbomBbHU2oIb/d3tJfF3dizGSApqtSwYJigGCooHdnMyQBIw8BrWyK96w3YXgr6A==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-58iSybJPQZ8XZNMpjrklICefuOuyJ0lMxfKmBqmaC0/xGT4SiOs4BE60LAOOGtBURy1n8fHa2X2YUNFEWWbXyQ==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-JTcxRvmFa9Ec1uyfMEimEMeeKq1sHNZX3vn2qmoUMtnvixXXvcqTcbDZvEZXkEWpGlPlOf4joyep6/qs0BrLyg==}
+ engines: {node: '>=18.0.0'}
+
+ resolution: {integrity: sha512-9Wa9vm3WtDpss0VFBHsbZWcoRccpOSWdpz7YIfb1LBXopZJEg/Zc8ymmaSgvDkP4FhN+pqPS9nZjO7REAJWSUg==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==}
@@ -7645,6 +7672,10 @@ packages:
resolution: {integrity: sha512-KcFVtoP1CVFtQu0aSk3AyAt2og66PFhZAlkUOuWKwzMLoulHXG5W5wE5xAnHb+yl3/wEFoqGW7/cDGMU8igDZQ==}
engines: {node: '>=14.0.0'}
+ resolution: {integrity: sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==}
@@ -20214,6 +20245,14 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ extend: 3.0.2
+ https-proxy-agent: 7.0.2
+ node-fetch: 3.3.2
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
gaxios: 6.1.1([email protected])
@@ -20222,6 +20261,14 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ gaxios: 7.1.0
+ google-logging-utils: 1.1.1
+ json-bigint: 1.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
@@ -20343,6 +20390,18 @@ snapshots:
+ dependencies:
+ base64-js: 1.5.1
+ ecdsa-sig-formatter: 1.0.11
+ gaxios: 7.1.0
+ gcp-metadata: 7.0.0
+ google-logging-utils: 1.1.1
+ gtoken: 8.0.0
+ jws: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
base64-js: 1.5.1
@@ -20356,6 +20415,8 @@ snapshots:
- encoding
- supports-color
+
dependencies:
extend: 3.0.2
@@ -20368,6 +20429,23 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ extend: 3.0.2
+ gaxios: 7.1.0
+ google-auth-library: 10.1.0
+ qs: 6.11.2
+ url-template: 2.0.8
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ google-auth-library: 10.1.0
+ googleapis-common: 8.0.2-rc.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
get-intrinsic: 1.2.4
@@ -20402,6 +20480,13 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ gaxios: 7.1.0
+ jws: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+