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.

15.1 KB
Raw Blame
import { supabase } from '../lib/supabase';
import { failureMessage } from '../lib/apiErrors.ts';
import type {
    AccountListResponse, AccountRefreshAllResponse, AccountResponse, ApiFailure, GitHubSettingsRequest,
    GitHubSettingsResponse, HealthResponse, KeysStatusResponse, OverviewResponse, ScheduledPostDeleteAllResponse,
    ScheduledPostListResponse, ScheduledPostRequest, ScheduledPostResponse, ScheduledPostUpdateRequest,
    ScheduledPostUpdateResponse, SuccessMessageResponse, SuccessResponse,
    TrackedContentAddRequest, TrackedContentItem, TrackedContentUpdateRequest, YouTubeAccountAddResponse,
} from '@shared/types/domain.ts';
import type {
    CloudinaryConfigResponse, InstagramAnalyticsResponse, InstagramAuthUrlResponse, InstagramConnectCompleteResponse, InstagramContainerStatusResponse,
    InstagramMediaPublishRequest, InstagramMediaPublishResponse, InstagramMediaResponse, InstagramPublishRequest,
    InstagramPublishResponse,
} from '@shared/types/instagram.ts';
import type {
    AutomationAccountResponse, AutomationActivityItemResponse, AutomationActivityResponse, AutomationOverviewResponse,
    AutomationRuleRequest, AutomationRuleResponse, AutomationRuleUpdateRequest, AutomationStatsResponse, AutomationTestRequest,
    AutomationTestResponse,
} from '@shared/types/automation.ts';
import type {
    ResolveChannelResponse, YouTubeAnalyticsPayload, YouTubeVideosResponse,
} from '@shared/types/youtube.ts';
import type {
    McpAccessTokenCreateRequest, McpAccessTokenCreateResponse, McpAccessTokenListResponse, McpClientApprovalRequest,
    McpClientGrantListResponse, McpServerInfoResponse,
} from '@shared/types/mcp.ts';
import type { MediaListResponse, MediaRegistrationRequest, MediaResponse } from '@shared/types/media.ts';
import type {
    YouTubeAuthUrlResponse, YouTubeConnectCompleteResponse, YouTubeConnectionListResponse, YouTubeUploadListResponse, YouTubeUploadRequest,
    YouTubeUploadResponse, YouTubeUploadUpdateRequest,
} from '@shared/types/youtubePublishing.ts';

const API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';

// every failure arrives with a 4xx or 5xx status and the ApiFailure body, so a 2xx is always a success
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
    const { data: { session } } = await supabase.auth.getSession();
    const token = session?.access_token;

    const res = await fetch(`${API}${path}`, {
        headers: {
            'Content-Type': 'application/json',
            ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        },
        ...options,
    });
    // a proxy error page is not JSON; the status still explains the failure
    const data = await res.json().catch(() => null) as unknown;
    if (!res.ok) throw new Error(failureMessage(res.status, data as Partial<ApiFailure> | null));
    return data as T;
}

const CLOUDINARY_API = 'https://api.cloudinary.com/v1_1';

export type UploadErrorReason = 'network' | 'rejected';

interface UploadErrorDetails {
    cloudinaryMessage?: string;
    parseMessage?: string;
}

// what uploadToCloudinary rejects with
export type UploadError = Error & UploadErrorDetails & { reason: UploadErrorReason };

export type CloudinaryUploadConfig = Pick<CloudinaryConfigResponse, 'cloudName' | 'uploadPreset'>;

export interface UploadOptions {
    onProgress?: (percent: number) => void;
}

// the parts of a Cloudinary upload response the client reads
interface CloudinaryUploadBody {
    secure_url?: string;
    public_id?: string;
    resource_type?: string;
    format?: string;
    width?: number;
    height?: number;
    duration?: number;
    error?: { message?: string };
}

// what a finished upload tells the media library
export interface CloudinaryUpload {
    url: string;
    publicId: string;
    resourceType: 'image' | 'video';
    format: string | null;
    width: number | null;
    height: number | null;
    durationSeconds: number | null;
}

const UPLOAD_ERROR_MESSAGES: Record<UploadErrorReason, string> = {
    network: 'The upload lost its network connection',
    rejected: 'Upload failed',
};

// callers read the reason and details so each page keeps its own wording
function uploadError(reason: UploadErrorReason, details: UploadErrorDetails = {}): UploadError {
    return Object.assign(new Error(UPLOAD_ERROR_MESSAGES[reason]), { reason, ...details });
}

function readUploadError(responseText: string): UploadErrorDetails {
    try {
        return { cloudinaryMessage: (JSON.parse(responseText) as CloudinaryUploadBody).error?.message };
    } catch (err) {
        return { parseMessage: (err as Error).message };
    }
}

// the browser posts straight to Cloudinary so the Worker never handles binaries
function uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, options: UploadOptions = {}): Promise<string> {
    return uploadWithDetails(file, cloudConfig, options).then(upload => upload.url);
}

function uploadWithDetails(file: File, cloudConfig: CloudinaryUploadConfig, { onProgress }: UploadOptions = {}): Promise<CloudinaryUpload> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('upload_preset', cloudConfig.uploadPreset);
    const type = file.type.startsWith('video/') ? 'video' : 'image';
    const xhr = new XMLHttpRequest();
    return new Promise<CloudinaryUpload>((resolve, reject) => {
        if (onProgress) {
            xhr.upload.addEventListener('progress', e => {
                if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
            });
        }
        xhr.addEventListener('load', () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                const body = JSON.parse(xhr.responseText) as CloudinaryUploadBody;
                resolve({
                    url: body.secure_url ?? '',
                    publicId: body.public_id ?? '',
                    resourceType: body.resource_type === 'video' ? 'video' : 'image',
                    format: body.format ?? null,
                    width: body.width ?? null,
                    height: body.height ?? null,
                    durationSeconds: body.duration ?? null,
                });
                return;
            }
            reject(uploadError('rejected', readUploadError(xhr.responseText)));
        });
        xhr.addEventListener('error', () => reject(uploadError('network')));
        xhr.open('POST', `${CLOUDINARY_API}/${cloudConfig.cloudName}/${type}/upload`);
        xhr.send(formData);
    });
}

export const api = {
    health: () => request<HealthResponse>('/health'),

    // Server key status - all keys are env vars, this just returns configured: true/false
    getKeys: () => request<KeysStatusResponse>('/keys'),

    getAccounts: () => request<AccountListResponse>('/accounts'),
    addAccount: (input: string) => request<YouTubeAccountAddResponse>('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),
    deleteAccount: (id: string) => request<SuccessResponse>(`/accounts/${id}`, { method: 'DELETE' }),
    refreshAccount: (id: string) => request<AccountResponse>(`/accounts/${id}/refresh`, { method: 'POST' }),
    refreshAll: () => request<AccountRefreshAllResponse>('/accounts/refresh-all', { method: 'POST' }),

    // Instagram OAuth - gets the auth URL to redirect the browser to
    getInstagramAuthUrl: () => request<InstagramAuthUrlResponse>('/auth/instagram/url'),
    // finishes the sign-in Instagram returned in the fragment; the server checks that this person started it
    completeInstagramConnection: (code: string, state: string) => request<InstagramConnectCompleteResponse>('/auth/instagram/complete', { method: 'POST', body: JSON.stringify({ code, state }) }),

    getIGAnalytics: (id: string) => request<InstagramAnalyticsResponse>(`/accounts/${id}/ig-analytics`),
    getIGMedia: (id: string, fresh = false) => request<InstagramMediaResponse>(`/accounts/${id}/ig-media${fresh ? '?fresh=1' : ''}`),

    // Channel URL/ID resolution
    resolveChannel: (input: string) => request<ResolveChannelResponse>('/resolve-channel', { method: 'POST', body: JSON.stringify({ input }) }),

    // Analytics (YouTube)
    getAnalytics: (id: string) => request<YouTubeAnalyticsPayload>(`/accounts/${id}/analytics`),
    getVideos: (id: string, fresh = false) => request<YouTubeVideosResponse>(`/accounts/${id}/videos${fresh ? '?fresh=1' : ''}`),

    getCloudinaryConfig: () => request<CloudinaryConfigResponse>('/cloudinary-config'),
    uploadToCloudinary,

    // Instagram Publishing
    createIGContainer: (id: string, data: InstagramPublishRequest) => request<InstagramPublishResponse>(`/accounts/${id}/ig-publish`, { method: 'POST', body: JSON.stringify(data) }),
    getIGContainerStatus: (containerId: string, accountId: string) => request<InstagramContainerStatusResponse>(`/ig-container/${containerId}/status?accountId=${accountId}`),
    publishIGContainer: (id: string, containerId: string) => request<InstagramMediaPublishResponse>(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId } satisfies InstagramMediaPublishRequest) }),


    // Overview dashboard (tracked content + per-account analytics cache)
    getOverview: () => request<OverviewResponse>('/overview'),

    // Tracked content (YouTube videos)
    getTrackedContent: () => request<TrackedContentItem[]>('/tracked-content'),
    addTrackedContent: (url: string, label: string, category: string) => request<TrackedContentItem>('/tracked-content', { method: 'POST', body: JSON.stringify({ url, label, category } satisfies TrackedContentAddRequest) }),
    updateTrackedContent: (id: string, updates: TrackedContentUpdateRequest) => request<TrackedContentItem>(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
    deleteTrackedContent: (id: string) => request<SuccessResponse>(`/tracked-content/${id}`, { method: 'DELETE' }),
    refreshTrackedContent: (id: string) => request<TrackedContentItem>(`/tracked-content/${id}/refresh`, { method: 'POST' }),

    // GitHub settings
    getGithubSettings: () => request<GitHubSettingsResponse>('/settings/github'),
    saveGithubSettings: (data: GitHubSettingsRequest) => request<SuccessResponse>('/settings/github', { method: 'PUT', body: JSON.stringify(data) }),

    getScheduledPosts: () => request<ScheduledPostListResponse>('/scheduled-posts'),
    createScheduledPost: (data: ScheduledPostRequest) => request<ScheduledPostResponse>('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
    updateScheduledPost: (id: string, data: ScheduledPostUpdateRequest) => request<ScheduledPostUpdateResponse>(`/scheduled-posts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    deleteScheduledPost: (id: string) => request<SuccessMessageResponse>(`/scheduled-posts/${id}`, { method: 'DELETE' }),
    deleteAllScheduledPosts: () => request<ScheduledPostDeleteAllResponse>('/scheduled-posts', { method: 'DELETE' }),

    // Comment-to-DM automation; activity and stats take filters as query parameters
    getAutomations: () => request<AutomationOverviewResponse>('/automations'),
    createAutomationRule: (data: AutomationRuleRequest) => request<AutomationRuleResponse>('/automations/rules', { method: 'POST', body: JSON.stringify(data) }),
    updateAutomationRule: (id: string, data: AutomationRuleUpdateRequest) => request<AutomationRuleResponse>(`/automations/rules/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    duplicateAutomationRule: (id: string) => request<AutomationRuleResponse>(`/automations/rules/${id}/duplicate`, { method: 'POST' }),
    deleteAutomationRule: (id: string) => request<SuccessMessageResponse>(`/automations/rules/${id}`, { method: 'DELETE' }),
    testAutomationRule: (data: AutomationTestRequest) => request<AutomationTestResponse>('/automations/test', { method: 'POST', body: JSON.stringify(data) }),
    getAutomationActivity: (query: URLSearchParams) => request<AutomationActivityResponse>(`/automations/activity?${query}`),
    retryAutomationActivity: (id: string) => request<AutomationActivityItemResponse>(`/automations/activity/${id}/retry`, { method: 'POST' }),
    retryAutomationPublicReply: (id: string) => request<AutomationActivityItemResponse>(`/automations/activity/${id}/public-reply/retry`, { method: 'POST' }),
    getAutomationStats: (query: URLSearchParams) => request<AutomationStatsResponse>(`/automations/stats?${query}`),
    setAutomationAccountPaused: (accountId: string, paused: boolean) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify({ paused }) }),
    subscribeAutomationAccount: (accountId: string) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}/subscribe`, { method: 'POST' }),

    // how Claude clients reach this account: the server address, personal access tokens and approved OAuth clients
    getMcpInfo: () => request<McpServerInfoResponse>('/mcp/info'),
    getMcpTokens: () => request<McpAccessTokenListResponse>('/mcp/tokens'),
    createMcpToken: (data: McpAccessTokenCreateRequest) => request<McpAccessTokenCreateResponse>('/mcp/tokens', { method: 'POST', body: JSON.stringify(data) }),
    revokeMcpToken: (id: string) => request<SuccessResponse>(`/mcp/tokens/${id}`, { method: 'DELETE' }),
    getMcpClients: () => request<McpClientGrantListResponse>('/mcp/clients'),
    approveMcpClient: (data: McpClientApprovalRequest) => request<SuccessResponse>('/mcp/clients', { method: 'POST', body: JSON.stringify(data) }),
    revokeMcpClient: (id: string) => request<SuccessResponse>(`/mcp/clients/${id}`, { method: 'DELETE' }),

    // the person's media library on the instance's Cloudinary account; a browser upload is registered after Cloudinary answers
    getMedia: () => request<MediaListResponse>('/media'),
    registerMedia: (data: MediaRegistrationRequest) => request<MediaResponse>('/media', { method: 'POST', body: JSON.stringify(data) }),
    uploadWithDetails,

    // YouTube publishing: verifying a channel with Google, then upload jobs the scheduled runs move
    getYouTubeConnections: () => request<YouTubeConnectionListResponse>('/youtube/connections'),
    // the sign-in proves the Google account manages this YouTube account's channel
    getYouTubeAuthUrl: (accountId: string) => request<YouTubeAuthUrlResponse>(`/auth/youtube/url?accountId=${encodeURIComponent(accountId)}`),
    completeYouTubeConnection: (code: string, state: string) => request<YouTubeConnectCompleteResponse>('/auth/youtube/complete', { method: 'POST', body: JSON.stringify({ code, state }) }),
    deleteYouTubeConnection: (id: string) => request<SuccessResponse>(`/youtube/connections/${id}`, { method: 'DELETE' }),
    getYouTubeUploads: () => request<YouTubeUploadListResponse>('/youtube/uploads'),
    createYouTubeUpload: (data: YouTubeUploadRequest) => request<YouTubeUploadResponse>('/youtube/uploads', { method: 'POST', body: JSON.stringify(data) }),
    updateYouTubeUpload: (id: string, data: YouTubeUploadUpdateRequest) => request<YouTubeUploadResponse>(`/youtube/uploads/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    cancelYouTubeUpload: (id: string) => request<YouTubeUploadResponse>(`/youtube/uploads/${id}/cancel`, { method: 'POST' }),
    retryYouTubeUpload: (id: string) => request<YouTubeUploadResponse>(`/youtube/uploads/${id}/retry`, { method: 'POST' }),
};