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.

feat(youtube): add the Google client and the publishing repositories

spacesdrive9fea53e9c32c
diff --git a/backend/repositories/youtubeConnectionRepository.ts b/backend/repositories/youtubeConnectionRepository.ts
new file mode 100644
index 0000000..dde3a8c
--- /dev/null
+++ b/backend/repositories/youtubeConnectionRepository.ts
@@ -0,0 +1,151 @@
+import { execute, maybeRow, rows } from './query.ts';
+import { newRowId } from '../lib/ids.ts';
+import type { SupabaseClient } from '../types/app.ts';
+import type { YouTubeConnectionStatus, YouTubeConnectionSummary } from '../../shared/types/youtubePublishing.ts';
+
+interface ConnectionRow {
+ id: string;
+ user_id: string;
+ account_id: string | null;
+ channel_id: string;
+ channel_title: string;
+ scopes: string[];
+ status: YouTubeConnectionStatus;
+ refresh_token_enc: string;
+ access_token_enc: string | null;
+ access_token_expires_at: string | null;
+ created_at: string;
+}
+
+// the sealed tokens travel only between this repository and the services that unseal them
+export interface StoredYouTubeConnection extends YouTubeConnectionSummary {
+ userId: string;
+ refreshTokenEnc: string;
+ accessTokenEnc: string | null;
+ accessTokenExpiresAt: string | null;
+}
+
+export interface NewYouTubeConnection {
+ accountId: string | null;
+ channelId: string;
+ channelTitle: string;
+ scopes: string[];
+ refreshTokenEnc: string;
+ accessTokenEnc: string;
+ accessTokenExpiresAt: string;
+}
+
+export type YouTubeConnectionTokens = Pick<NewYouTubeConnection, 'accessTokenEnc' | 'accessTokenExpiresAt'> & Partial<Pick<NewYouTubeConnection, 'refreshTokenEnc' | 'scopes' | 'channelTitle' | 'accountId'>>;
+
+const COLUMNS = 'id, user_id, account_id, channel_id, channel_title, scopes, status, refresh_token_enc, access_token_enc, access_token_expires_at, created_at';
+
+function toConnection(row: ConnectionRow): StoredYouTubeConnection {
+ return {
+ id: row.id,
+ userId: row.user_id,
+ accountId: row.account_id,
+ channelId: row.channel_id,
+ channelTitle: row.channel_title,
+ scopes: row.scopes ?? [],
+ status: row.status,
+ createdAt: row.created_at,
+ refreshTokenEnc: row.refresh_token_enc,
+ accessTokenEnc: row.access_token_enc,
+ accessTokenExpiresAt: row.access_token_expires_at,
+ };
+}
+
+export function connectionSummary(connection: StoredYouTubeConnection): YouTubeConnectionSummary {
+ const { id, channelId, channelTitle, accountId, status, scopes, createdAt } = connection;
+ return { id, channelId, channelTitle, accountId, status, scopes, createdAt };
+}
+
+function tokenColumns(tokens: YouTubeConnectionTokens): Record<string, unknown> {
+ return {
+ access_token_enc: tokens.accessTokenEnc,
+ access_token_expires_at: tokens.accessTokenExpiresAt,
+ ...(tokens.refreshTokenEnc ? { refresh_token_enc: tokens.refreshTokenEnc } : {}),
+ ...(tokens.scopes ? { scopes: tokens.scopes } : {}),
+ ...(tokens.channelTitle !== undefined ? { channel_title: tokens.channelTitle } : {}),
+ ...(tokens.accountId !== undefined ? { account_id: tokens.accountId } : {}),
+ };
+}
+
+// ...ForUser methods filter by the verified user; findById and updateById serve the upload runner across all users
+export interface YouTubeConnectionRepository {
+ listForUser(userId: string): Promise<StoredYouTubeConnection[]>;
+ findForUser(id: string, userId: string): Promise<StoredYouTubeConnection | null>;
+ findByChannelForUser(channelId: string, userId: string): Promise<StoredYouTubeConnection | null>;
+ createForUser(userId: string, connection: NewYouTubeConnection): Promise<StoredYouTubeConnection>;
+ reconnectForUser(id: string, userId: string, tokens: YouTubeConnectionTokens): Promise<StoredYouTubeConnection | null>;
+ deleteForUser(id: string, userId: string): Promise<boolean>;
+ findById(id: string): Promise<StoredYouTubeConnection | null>;
+ updateTokensById(id: string, tokens: YouTubeConnectionTokens): Promise<void>;
+ markNeedsReconnectById(id: string): Promise<void>;
+}
+
+export function createYouTubeConnectionRepository(db: SupabaseClient): YouTubeConnectionRepository {
+ return {
+ async listForUser(userId) {
+ const found = await rows<ConnectionRow>('youtubeConnections.listForUser', () => db
+ .from('youtube_connections').select(COLUMNS).eq('user_id', userId).order('created_at', { ascending: true }));
+ return found.map(toConnection);
+ },
+
+ async findForUser(id, userId) {
+ const row = await maybeRow<ConnectionRow>('youtubeConnections.findForUser', () => db
+ .from('youtube_connections').select(COLUMNS).eq('id', id).eq('user_id', userId).maybeSingle());
+ return row ? toConnection(row) : null;
+ },
+
+ async findByChannelForUser(channelId, userId) {
+ const row = await maybeRow<ConnectionRow>('youtubeConnections.findByChannelForUser', () => db
+ .from('youtube_connections').select(COLUMNS).eq('channel_id', channelId).eq('user_id', userId).maybeSingle());
+ return row ? toConnection(row) : null;
+ },
+
+ async createForUser(userId, connection) {
+ const created = await rows<ConnectionRow>('youtubeConnections.create', () => db.from('youtube_connections').insert({
+ id: newRowId(),
+ user_id: userId,
+ account_id: connection.accountId,
+ channel_id: connection.channelId,
+ channel_title: connection.channelTitle,
+ scopes: connection.scopes,
+ status: 'active',
+ refresh_token_enc: connection.refreshTokenEnc,
+ access_token_enc: connection.accessTokenEnc,
+ access_token_expires_at: connection.accessTokenExpiresAt,
+ }).select(COLUMNS));
+ return toConnection(created[0]);
+ },
+
+ // a new sign-in for a channel already connected renews its tokens in place and makes it active again
+ async reconnectForUser(id, userId, tokens) {
+ const updated = await rows<ConnectionRow>('youtubeConnections.reconnect', () => db
+ .from('youtube_connections').update({ ...tokenColumns(tokens), status: 'active' }).eq('id', id).eq('user_id', userId).select(COLUMNS));
+ return updated[0] ? toConnection(updated[0]) : null;
+ },
+
+ async deleteForUser(id, userId) {
+ const deleted = await rows<{ id: string }>('youtubeConnections.deleteForUser', () => db
+ .from('youtube_connections').delete().eq('id', id).eq('user_id', userId).select('id'));
+ return deleted.length > 0;
+ },
+
+ async findById(id) {
+ const row = await maybeRow<ConnectionRow>('youtubeConnections.findById', () => db
+ .from('youtube_connections').select(COLUMNS).eq('id', id).maybeSingle());
+ return row ? toConnection(row) : null;
+ },
+
+ async updateTokensById(id, tokens) {
+ await execute('youtubeConnections.updateTokens', () => db.from('youtube_connections').update(tokenColumns(tokens)).eq('id', id));
+ },
+
+ async markNeedsReconnectById(id) {
+ await execute('youtubeConnections.markNeedsReconnect', () => db
+ .from('youtube_connections').update({ status: 'needs_reconnect', access_token_enc: null, access_token_expires_at: null }).eq('id', id));
+ },
+ };
+}
diff --git a/backend/repositories/youtubeQuotaLedgerRepository.ts b/backend/repositories/youtubeQuotaLedgerRepository.ts
new file mode 100644
index 0000000..a953f13
--- /dev/null
+++ b/backend/repositories/youtubeQuotaLedgerRepository.ts
@@ -0,0 +1,19 @@
+import { execute } from './query.ts';
+import type { SupabaseClient } from '../types/app.ts';
+
+export type QuotaBucket = 'uploads' | 'default';
+
+// the Google project's daily YouTube allowance across all users; a reservation is taken before each call, so the ledger
+// stops calls before Google refuses them
+export interface YouTubeQuotaLedgerRepository {
+ reserve(day: string, bucket: QuotaBucket, units: number, limit: number): Promise<boolean>;
+}
+
+export function createYouTubeQuotaLedgerRepository(db: SupabaseClient): YouTubeQuotaLedgerRepository {
+ return {
+ async reserve(day, bucket, units, limit) {
+ const { data } = await execute('youtubeQuota.reserve', () => db.rpc('reserve_youtube_quota', { p_day: day, p_bucket: bucket, p_units: units, p_limit: limit }));
+ return data === true;
+ },
+ };
+}
diff --git a/backend/repositories/youtubeUploadRepository.ts b/backend/repositories/youtubeUploadRepository.ts
new file mode 100644
index 0000000..2701176
--- /dev/null
+++ b/backend/repositories/youtubeUploadRepository.ts
@@ -0,0 +1,253 @@
+import { execute, maybeRow, rows } from './query.ts';
+import { newRowId } from '../lib/ids.ts';
+import { isUniqueViolation } from '../lib/errors.ts';
+import type { SupabaseClient } from '../types/app.ts';
+import type { YouTubePrivacy, YouTubeUploadState, YouTubeUploadSummary } from '../../shared/types/youtubePublishing.ts';
+
+interface UploadRow {
+ id: string;
+ user_id: string;
+ connection_id: string;
+ source_url: string;
+ source_bytes: number | string;
+ content_type: string;
+ thumbnail_url: string | null;
+ is_short: boolean;
+ title: string;
+ description: string;
+ tags: string[];
+ category_id: string;
+ privacy: YouTubePrivacy;
+ publish_at: string | null;
+ made_for_kids: boolean;
+ synthetic_media: boolean;
+ notify_subscribers: boolean;
+ state: YouTubeUploadState;
+ session_uri: string | null;
+ bytes_confirmed: number | string;
+ video_id: string | null;
+ attempts: number;
+ next_attempt_at: string;
+ lease_owner: string | null;
+ last_error: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+// the job as the runner sees it: the source address and session never leave the Worker
+export interface StoredYouTubeUpload extends YouTubeUploadSummary {
+ userId: string;
+ sourceUrl: string;
+ contentType: string;
+ thumbnailUrl: string | null;
+ sessionUri: string | null;
+}
+
+export interface NewYouTubeUpload {
+ connectionId: string;
+ sourceUrl: string;
+ sourceBytes: number;
+ contentType: string;
+ thumbnailUrl: string | null;
+ isShort: boolean;
+ title: string;
+ description: string;
+ tags: string[];
+ categoryId: string;
+ privacy: YouTubePrivacy;
+ publishAt: string | null;
+ madeForKids: boolean;
+ syntheticMedia: boolean;
+ notifySubscribers: boolean;
+ clientRequestId: string | null;
+}
+
+// what the runner may change on a job it holds
+export interface UploadProgress {
+ state?: YouTubeUploadState;
+ sessionUri?: string | null;
+ bytesConfirmed?: number;
+ videoId?: string;
+ attempts?: number;
+ nextAttemptAt?: string;
+ lastError?: string | null;
+}
+
+// the metadata a person may change before the upload starts
+export type UploadEdit = Partial<Pick<NewYouTubeUpload, 'title' | 'description' | 'tags' | 'categoryId' | 'privacy' | 'publishAt' | 'madeForKids' | 'syntheticMedia' | 'notifySubscribers'>>;
+
+const COLUMNS = 'id, user_id, connection_id, source_url, source_bytes, content_type, thumbnail_url, is_short, title, description, tags, category_id, privacy, publish_at, made_for_kids, synthetic_media, notify_subscribers, state, session_uri, bytes_confirmed, video_id, attempts, next_attempt_at, lease_owner, last_error, created_at, updated_at';
+
+function toUpload(row: UploadRow): StoredYouTubeUpload {
+ return {
+ id: row.id,
+ userId: row.user_id,
+ connectionId: row.connection_id,
+ title: row.title,
+ description: row.description,
+ tags: row.tags ?? [],
+ categoryId: row.category_id,
+ privacy: row.privacy,
+ publishAt: row.publish_at,
+ madeForKids: row.made_for_kids,
+ syntheticMedia: row.synthetic_media,
+ notifySubscribers: row.notify_subscribers,
+ isShort: row.is_short,
+ hasThumbnail: row.thumbnail_url !== null,
+ state: row.state,
+ bytesConfirmed: Number(row.bytes_confirmed),
+ sourceBytes: Number(row.source_bytes),
+ videoId: row.video_id,
+ attempts: row.attempts,
+ nextAttemptAt: row.next_attempt_at,
+ lastError: row.last_error,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ sourceUrl: row.source_url,
+ contentType: row.content_type,
+ thumbnailUrl: row.thumbnail_url,
+ sessionUri: row.session_uri,
+ };
+}
+
+export function uploadSummary(upload: StoredYouTubeUpload): YouTubeUploadSummary {
+ const { userId: _userId, sourceUrl: _sourceUrl, contentType: _contentType, thumbnailUrl: _thumbnailUrl, sessionUri: _sessionUri, ...summary } = upload;
+ return summary;
+}
+
+function editColumns(edit: UploadEdit): Record<string, unknown> {
+ const columns: Record<string, unknown> = {};
+ if (edit.title !== undefined) columns.title = edit.title;
+ if (edit.description !== undefined) columns.description = edit.description;
+ if (edit.tags !== undefined) columns.tags = edit.tags;
+ if (edit.categoryId !== undefined) columns.category_id = edit.categoryId;
+ if (edit.privacy !== undefined) columns.privacy = edit.privacy;
+ if (edit.publishAt !== undefined) columns.publish_at = edit.publishAt;
+ if (edit.madeForKids !== undefined) columns.made_for_kids = edit.madeForKids;
+ if (edit.syntheticMedia !== undefined) columns.synthetic_media = edit.syntheticMedia;
+ if (edit.notifySubscribers !== undefined) columns.notify_subscribers = edit.notifySubscribers;
+ return columns;
+}
+
+function progressColumns(progress: UploadProgress): Record<string, unknown> {
+ const columns: Record<string, unknown> = {};
+ if (progress.state !== undefined) columns.state = progress.state;
+ if (progress.sessionUri !== undefined) columns.session_uri = progress.sessionUri;
+ if (progress.bytesConfirmed !== undefined) columns.bytes_confirmed = progress.bytesConfirmed;
+ if (progress.videoId !== undefined) columns.video_id = progress.videoId;
+ if (progress.attempts !== undefined) columns.attempts = progress.attempts;
+ if (progress.nextAttemptAt !== undefined) columns.next_attempt_at = progress.nextAttemptAt;
+ if (progress.lastError !== undefined) columns.last_error = progress.lastError;
+ return columns;
+}
+
+// ...ForUser methods filter by the verified user; claim, saveLeased, releaseLeased and parkForConnection serve the runner
+export interface YouTubeUploadRepository {
+ createForUser(userId: string, upload: NewYouTubeUpload): Promise<{ upload: StoredYouTubeUpload; existing: boolean }>;
+ listForUser(userId: string): Promise<StoredYouTubeUpload[]>;
+ findForUser(id: string, userId: string): Promise<StoredYouTubeUpload | null>;
+ // only a queued job that has not opened an upload session can change; null when it is gone or already started
+ editQueuedForUser(id: string, userId: string, edit: UploadEdit): Promise<StoredYouTubeUpload | null>;
+ // moves a job between states only from the ones listed, so a running job is never pulled from under a run
+ setStateForUser(id: string, userId: string, from: YouTubeUploadState[], to: YouTubeUploadState, extra?: UploadProgress): Promise<StoredYouTubeUpload | null>;
+ claim(owner: string, leaseSeconds: number): Promise<StoredYouTubeUpload | null>;
+ // false when the lease was lost to another run; the caller then stops touching the job
+ saveLeased(id: string, owner: string, progress: UploadProgress): Promise<boolean>;
+ releaseLeased(id: string, owner: string, progress: UploadProgress): Promise<void>;
+ parkForConnection(connectionId: string, lastError: string): Promise<void>;
+}
+
+const RUNNABLE: YouTubeUploadState[] = ['queued', 'uploading', 'processing', 'finalizing', 'waiting_quota'];
+
+export function createYouTubeUploadRepository(db: SupabaseClient): YouTubeUploadRepository {
+ async function findByRequestForUser(clientRequestId: string, userId: string): Promise<StoredYouTubeUpload | null> {
+ const row = await maybeRow<UploadRow>('youtubeUploads.findByRequest', () => db
+ .from('youtube_uploads').select(COLUMNS).eq('client_request_id', clientRequestId).eq('user_id', userId).maybeSingle());
+ return row ? toUpload(row) : null;
+ }
+
+ return {
+ async createForUser(userId, upload) {
+ try {
+ const created = await rows<UploadRow>('youtubeUploads.create', () => db.from('youtube_uploads').insert({
+ id: newRowId(),
+ user_id: userId,
+ connection_id: upload.connectionId,
+ source_url: upload.sourceUrl,
+ source_bytes: upload.sourceBytes,
+ content_type: upload.contentType,
+ thumbnail_url: upload.thumbnailUrl,
+ is_short: upload.isShort,
+ title: upload.title,
+ description: upload.description,
+ tags: upload.tags,
+ category_id: upload.categoryId,
+ privacy: upload.privacy,
+ publish_at: upload.publishAt,
+ made_for_kids: upload.madeForKids,
+ synthetic_media: upload.syntheticMedia,
+ notify_subscribers: upload.notifySubscribers,
+ client_request_id: upload.clientRequestId,
+ }).select(COLUMNS));
+ return { upload: toUpload(created[0]), existing: false };
+ } catch (err) {
+ // the same request sent twice: the first job stands
+ const existing = upload.clientRequestId && isUniqueViolation(err) ? await findByRequestForUser(upload.clientRequestId, userId) : null;
+ if (!existing) throw err;
+ return { upload: existing, existing: true };
+ }
+ },
+
+ async listForUser(userId) {
+ const found = await rows<UploadRow>('youtubeUploads.listForUser', () => db
+ .from('youtube_uploads').select(COLUMNS).eq('user_id', userId).order('created_at', { ascending: false }).limit(200));
+ return found.map(toUpload);
+ },
+
+ async findForUser(id, userId) {
+ const row = await maybeRow<UploadRow>('youtubeUploads.findForUser', () => db
+ .from('youtube_uploads').select(COLUMNS).eq('id', id).eq('user_id', userId).maybeSingle());
+ return row ? toUpload(row) : null;
+ },
+
+ async editQueuedForUser(id, userId, edit) {
+ const updated = await rows<UploadRow>('youtubeUploads.editQueued', () => db
+ .from('youtube_uploads').update(editColumns(edit))
+ .eq('id', id).eq('user_id', userId).eq('state', 'queued').is('session_uri', null).is('lease_owner', null)
+ .select(COLUMNS));
+ return updated[0] ? toUpload(updated[0]) : null;
+ },
+
+ async setStateForUser(id, userId, from, to, extra = {}) {
+ const updated = await rows<UploadRow>('youtubeUploads.setState', () => db
+ .from('youtube_uploads').update({ ...progressColumns(extra), state: to })
+ .eq('id', id).eq('user_id', userId).in('state', from).is('lease_owner', null)
+ .select(COLUMNS));
+ return updated[0] ? toUpload(updated[0]) : null;
+ },
+
+ async claim(owner, leaseSeconds) {
+ const { data } = await execute('youtubeUploads.claim', () => db.rpc('claim_youtube_upload', { p_owner: owner, p_lease_seconds: leaseSeconds }));
+ const claimed = (data as UploadRow[] | null) ?? [];
+ return claimed[0] ? toUpload(claimed[0]) : null;
+ },
+
+ async saveLeased(id, owner, progress) {
+ const updated = await rows<{ id: string }>('youtubeUploads.saveLeased', () => db
+ .from('youtube_uploads').update(progressColumns(progress)).eq('id', id).eq('lease_owner', owner).select('id'));
+ return updated.length > 0;
+ },
+
+ async releaseLeased(id, owner, progress) {
+ await execute('youtubeUploads.releaseLeased', () => db
+ .from('youtube_uploads').update({ ...progressColumns(progress), lease_owner: null, lease_until: null }).eq('id', id).eq('lease_owner', owner));
+ },
+
+ // a connection that needs a new sign-in holds its jobs without spending their attempts
+ async parkForConnection(connectionId, lastError) {
+ await execute('youtubeUploads.parkForConnection', () => db
+ .from('youtube_uploads').update({ state: 'needs_reconnect', last_error: lastError })
+ .eq('connection_id', connectionId).in('state', RUNNABLE).is('lease_owner', null));
+ },
+ };
+}
diff --git a/backend/services/youtube/googleApi.ts b/backend/services/youtube/googleApi.ts
new file mode 100644
index 0000000..ab1ceba
--- /dev/null
+++ b/backend/services/youtube/googleApi.ts
@@ -0,0 +1,226 @@
+import { UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';
+import { createOAuthState } from '../../lib/oauthState.ts';
+import type { YouTubeOAuthConfig } from '../../lib/config.ts';
+import type { YouTubePrivacy } from '../../../shared/types/youtubePublishing.ts';
+
+const AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
+const TOKEN_URL = 'https://oauth2.googleapis.com/token';
+const REVOKE_URL = 'https://oauth2.googleapis.com/revoke';
+const API = 'https://www.googleapis.com/youtube/v3';
+const UPLOAD_API = 'https://www.googleapis.com/upload/youtube/v3';
+
+// upload videos and read the channel; nothing that can change or delete what is already on it
+export const YOUTUBE_SCOPES = ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.readonly'];
+
+// Google's answer when a call is refused; the reason decides retry, wait or reconnect
+export class GoogleApiError extends UpstreamError {
+ readonly httpStatus: number;
+ readonly googleReason: string;
+
+ constructor(message: string, httpStatus: number, googleReason: string) {
+ super(message, { reason: googleReason, status: httpStatus });
+ this.httpStatus = httpStatus;
+ this.googleReason = googleReason;
+ }
+}
+
+interface GoogleErrorBody {
+ error?: string | { code?: number; message?: string; errors?: { reason?: string }[] };
+ error_description?: string;
+}
+
+async function googleError(response: Response, what: string): Promise<GoogleApiError> {
+ const body = await response.json().catch(() => ({})) as GoogleErrorBody;
+ if (typeof body.error === 'string') {
+ return new GoogleApiError(`Google refused ${what}: ${body.error_description ?? body.error}`, response.status, body.error);
+ }
+ const reason = body.error?.errors?.[0]?.reason ?? '';
+ return new GoogleApiError(`YouTube refused ${what}: ${body.error?.message ?? `status ${response.status}`}`, response.status, reason);
+}
+
+async function send(url: string, init: RequestInit, what: string): Promise<Response> {
+ try {
+ return await fetch(url, init);
+ } catch (err) {
+ if (isAbortError(err)) throw new UpstreamTimeoutError('YouTube', err);
+ throw new UpstreamError(`YouTube could not be reached while ${what} (${(err as Error).message})`, { reason: 'unreachable', cause: err });
+ }
+}
+
+// the signed state names the person who started, so only they can finish the connection
+export async function authorizationUrl(config: YouTubeOAuthConfig, userId: string): Promise<string> {
+ const params = new URLSearchParams({
+ client_id: config.clientId,
+ redirect_uri: config.redirectUri,
+ response_type: 'code',
+ scope: YOUTUBE_SCOPES.join(' '),
+ // offline and consent make Google return a refresh token every time, so a reconnect always gets one
+ access_type: 'offline',
+ prompt: 'consent',
+ include_granted_scopes: 'true',
+ state: await createOAuthState(userId, config.clientSecret),
+ });
+ return `${AUTHORIZE_URL}?${params}`;
+}
+
+export interface GoogleTokens {
+ accessToken: string;
+ refreshToken: string | null;
+ expiresAt: string;
+ scopes: string[];
+}
+
+interface TokenAnswer {
+ access_token: string;
+ refresh_token?: string;
+ expires_in: number;
+ scope?: string;
+}
+
+async function tokenRequest(params: Record<string, string>, what: string, signal?: AbortSignal): Promise<GoogleTokens> {
+ const response = await send(TOKEN_URL, { method: 'POST', body: new URLSearchParams(params), signal }, what);
+ if (!response.ok) throw await googleError(response, what);
+ const answer = await response.json() as TokenAnswer;
+ return {
+ accessToken: answer.access_token,
+ refreshToken: answer.refresh_token ?? null,
+ expiresAt: new Date(Date.now() + answer.expires_in * 1000).toISOString(),
+ scopes: (answer.scope ?? '').split(' ').filter(Boolean),
+ };
+}
+
+export function exchangeCode(config: YouTubeOAuthConfig, code: string, signal?: AbortSignal): Promise<GoogleTokens> {
+ return tokenRequest({
+ code, client_id: config.clientId, client_secret: config.clientSecret, redirect_uri: config.redirectUri, grant_type: 'authorization_code',
+ }, 'the sign-in code', signal);
+}
+
+export function refreshAccessToken(config: YouTubeOAuthConfig, refreshToken: string, signal?: AbortSignal): Promise<GoogleTokens> {
+ return tokenRequest({
+ refresh_token: refreshToken, client_id: config.clientId, client_secret: config.clientSecret, grant_type: 'refresh_token',
+ }, 'the token refresh', signal);
+}
+
+// best effort: a token Google already dropped is the same outcome
+export async function revokeToken(token: string, signal?: AbortSignal): Promise<void> {
+ await send(REVOKE_URL, { method: 'POST', body: new URLSearchParams({ token }), signal }, 'revoking access').catch(() => undefined);
+}
+
+export interface GoogleChannel {
+ id: string;
+ title: string;
+}
+
+export async function fetchMyChannel(accessToken: string, signal?: AbortSignal): Promise<GoogleChannel> {
+ const response = await send(`${API}/channels?part=snippet&mine=true`, { headers: { Authorization: `Bearer ${accessToken}` }, signal }, 'reading the channel');
+ if (!response.ok) throw await googleError(response, 'reading the channel');
+ const answer = await response.json() as { items?: { id: string; snippet?: { title?: string } }[] };
+ const channel = answer.items?.[0];
+ if (!channel) throw new GoogleApiError('This Google account has no YouTube channel. Create one on YouTube, then connect again.', 404, 'noChannel');
+ return { id: channel.id, title: channel.snippet?.title ?? '' };
+}
+
+export interface VideoInsert {
+ title: string;
+ description: string;
+ tags: string[];
+ categoryId: string;
+ privacy: YouTubePrivacy;
+ publishAt: string | null;
+ madeForKids: boolean;
+ syntheticMedia: boolean;
+ notifySubscribers: boolean;
+}
+
+// opens a resumable session; Google answers with the session address in Location, which the caller saves before sending bytes
+export async function startUploadSession(accessToken: string, video: VideoInsert, bytes: number, contentType: string, signal?: AbortSignal): Promise<string> {
+ const url = `${UPLOAD_API}/videos?uploadType=resumable&part=snippet,status&notifySubscribers=${video.notifySubscribers}`;
+ const body = {
+ snippet: { title: video.title, description: video.description, tags: video.tags, categoryId: video.categoryId },
+ status: {
+ privacyStatus: video.privacy,
+ ...(video.publishAt ? { publishAt: video.publishAt } : {}),
+ selfDeclaredMadeForKids: video.madeForKids,
+ containsSyntheticMedia: video.syntheticMedia,
+ },
+ };
+ const response = await send(url, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json; charset=UTF-8',
+ 'X-Upload-Content-Length': String(bytes),
+ 'X-Upload-Content-Type': contentType,
+ },
+ body: JSON.stringify(body),
+ signal,
+ }, 'starting the upload');
+ if (!response.ok) throw await googleError(response, 'starting the upload');
+ const session = response.headers.get('Location');
+ if (!session?.startsWith('https://')) throw new GoogleApiError('YouTube did not return an upload address.', 502, 'noSession');
+ return session;
+}
+
+export type SessionStatus = { kind: 'incomplete'; range: string | null } | { kind: 'done'; videoId: string };
+
+async function sessionAnswer(response: Response, what: string): Promise<SessionStatus> {
+ if (response.status === 308) return { kind: 'incomplete', range: response.headers.get('Range') };
+ if (response.status === 200 || response.status === 201) {
+ const video = await response.json() as { id?: string };
+ if (!video.id) throw new GoogleApiError('YouTube finished the upload without a video id.', 502, 'noVideoId');
+ return { kind: 'done', videoId: video.id };
+ }
+ throw await googleError(response, what);
+}
+
+// asks how much of the file Google holds; the answer is the truth after any lost response
+export async function querySession(accessToken: string, session: string, total: number, signal?: AbortSignal): Promise<SessionStatus> {
+ const response = await send(session, {
+ method: 'PUT',
+ headers: { Authorization: `Bearer ${accessToken}`, 'Content-Length': '0', 'Content-Range': `bytes */${total}` },
+ signal,
+ }, 'checking the upload');
+ return sessionAnswer(response, 'checking the upload');
+}
+
+export async function sendChunk(accessToken: string, session: string, chunk: ArrayBuffer, first: number, total: number, signal?: AbortSignal): Promise<SessionStatus> {
+ const last = first + chunk.byteLength - 1;
+ const response = await send(session, {
+ method: 'PUT',
+ headers: { Authorization: `Bearer ${accessToken}`, 'Content-Length': String(chunk.byteLength), 'Content-Range': `bytes ${first}-${last}/${total}` },
+ body: chunk,
+ signal,
+ }, 'sending part of the video');
+ return sessionAnswer(response, 'sending part of the video');
+}
+
+export interface VideoProcessing {
+ id: string;
+ uploadStatus: string;
+ failureReason: string | null;
+ processingStatus: string | null;
+}
+
+export async function videoStatus(accessToken: string, videoId: string, signal?: AbortSignal): Promise<VideoProcessing | null> {
+ const response = await send(`${API}/videos?part=status,processingDetails&id=${encodeURIComponent(videoId)}`, { headers: { Authorization: `Bearer ${accessToken}` }, signal }, 'checking the video');
+ if (!response.ok) throw await googleError(response, 'checking the video');
+ const answer = await response.json() as { items?: { id: string; status?: { uploadStatus?: string; failureReason?: string; rejectionReason?: string }; processingDetails?: { processingStatus?: string } }[] };
+ const video = answer.items?.[0];
+ if (!video) return null;
+ return {
+ id: video.id,
+ uploadStatus: video.status?.uploadStatus ?? 'uploaded',
+ failureReason: video.status?.failureReason ?? video.status?.rejectionReason ?? null,
+ processingStatus: video.processingDetails?.processingStatus ?? null,
+ };
+}
+
+export async function setThumbnail(accessToken: string, videoId: string, image: ArrayBuffer, contentType: string, signal?: AbortSignal): Promise<void> {
+ const response = await send(`${UPLOAD_API}/thumbnails/set?videoId=${encodeURIComponent(videoId)}`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': contentType, 'Content-Length': String(image.byteLength) },
+ body: image,
+ signal,
+ }, 'setting the thumbnail');
+ if (!response.ok) throw await googleError(response, 'setting the thumbnail');
+}