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.

9.6 KB
Raw Blame
import type { InstagramContentTypeSummary } from './instagram.ts';
import type { YouTubeTrackedVideoData } from './youtube.ts';

export type Platform = 'youtube' | 'instagram';

// fetchChannelData() flattens each size to its url, and accounts store that shape
export interface ChannelThumbnails {
    default: string;
    medium: string;
    high: string;
}

// one row of `accounts`: id and platform are columns, every other field lives in the data jsonb
export interface Account {
    id: string;
    platform: Platform;
    title?: string;
    addedAt?: string;
    lastUpdated?: string;

    // youtube
    channelId?: string;
    description?: string;
    customUrl?: string;
    publishedAt?: string;
    country?: string;
    thumbnails?: ChannelThumbnails;
    subscriberCount?: number;
    viewCount?: number;
    videoCount?: number;
    hiddenSubscriberCount?: boolean;
    uploadsPlaylistId?: string;
    keywords?: string;
    topicCategories?: string[];
    madeForKids?: boolean;

    // instagram
    username?: string;
    // null when neither the profile nor the request had an id
    igUserId?: string | null;
    biography?: string;
    website?: string;
    profilePictureUrl?: string;
    followersCount?: number;
    followsCount?: number;
    mediaCount?: number;
    accessToken?: string;
    tokenExpiresAt?: string | null;
}

// youtube accounts are created without a platform field; createAccount stores them as 'youtube'
export type NewAccount = Omit<Account, 'platform'> & { platform?: Platform };

// what an account looks like in a response: the access token removed
export type SafeAccount = Omit<Account, 'accessToken'>;

// how often an account posts, from its fetched posts
export interface PostFrequency {
    perWeek: number;
    perMonth: number;
}

export type PostStatus = 'pending' | 'publishing' | 'published' | 'failed';

export type MediaType = 'IMAGE' | 'VIDEO' | 'REELS' | 'STORIES' | 'CAROUSEL';

export interface UserTag {
    username: string;
    x?: number;
    y?: number;
}

export interface CarouselItem {
    mediaUrl: string;
    mediaType?: MediaType;
}

// a comment automation that waits for its post: once the post is published, a rule answers any comment on it
export interface ScheduledPostAutomation {
    // the private reply sent to each person who comments
    replyText: string;
    // replies posted under the comment, one picked per comment; empty for none
    publicReplyTexts: string[];
}

// one row of `scheduled_posts`: id, account_id, status and scheduled_at are columns, the rest is data jsonb
export interface ScheduledPost {
    id: string;
    accountId: string;
    status: PostStatus;
    scheduledAt: string;
    platform?: Platform;
    mediaType?: MediaType;
    mediaUrl?: string;
    caption?: string;
    coverUrl?: string | null;
    shareToFeed?: boolean;
    collaborators?: string[];
    audioName?: string;
    thumbOffset?: number | null;
    locationId?: string;
    userTags?: UserTag[];
    altText?: string;
    children?: string[];
    carouselItems?: CarouselItem[];
    createdAt?: string;
    publishedAt?: string;
    publishedMediaId?: string | null;
    error?: string | null;
    // when a scheduler last claimed the post and how many times one has; a claim older than the lease is taken over
    claimedAt?: string | null;
    attempts?: number;
    // saved before the publish call, so a later run can ask Instagram whether the post went out
    containerId?: string | null;
    automation?: ScheduledPostAutomation | null;
    // the rule made for the automation after publishing, or why it could not be made
    automationRuleId?: string | null;
    automationError?: string | null;
}

export interface ScheduledPublishFailure {
    id: string;
    error: string;
}

// what one run of the scheduled publisher did, for the cron log
export interface ScheduledPublishRun {
    processed: number;
    errors: ScheduledPublishFailure[];
}

// one row of `tracked_posts`; fields refreshed from the platform live in the data jsonb
export interface TrackedPost {
    id: string;
    url: string;
    label: string;
    category: string;
    contentType: string;
    createdAt: string;
    updatedAt: string;
    [field: string]: unknown;
}

// one entry of the refresh-all response, in the same order as the accounts
export interface AccountRefreshResult {
    id: string;
    success: boolean;
    error?: string;
}

// an account whose analytics cache is empty; syncing is true once a background fetch started
export interface PendingAccountSummary {
    id: string;
    cacheWarmed: false;
    syncing: boolean;
}

// fetchedAt is when the cached numbers came from the platform, so the Overview can say how old they are
export interface InstagramAccountSummary {
    id: string;
    cacheWarmed: true;
    fetchedAt?: string;
    totalLikes: number;
    totalComments: number;
    totalViews: number;
    contentTypes: InstagramContentTypeSummary;
}

export interface YouTubeAccountSummary {
    id: string;
    cacheWarmed: true;
    fetchedAt?: string;
    totalLikes: number;
    totalComments: number;
}

export type AccountSummary = PendingAccountSummary | InstagramAccountSummary | YouTubeAccountSummary;

// the overview's analyticsCache, keyed by account id; accounts whose cache read failed are left out
export type OverviewAnalyticsCache = Record<string, AccountSummary>;

// GET /api/accounts
export type AccountListResponse = SafeAccount[];

// the instagram and single refresh account routes
export interface AccountResponse {
    success: true;
    account: SafeAccount;
}

// POST /api/accounts adds a youtube account, which stores no secrets, so it is sent as created
export interface YouTubeAccountAddResponse {
    success: true;
    account: NewAccount;
}

// POST /api/accounts/refresh-all
export interface AccountRefreshAllResponse {
    success: true;
    accounts: SafeAccount[];
    results: AccountRefreshResult[];
    updatedAt: string;
}

// GET /api/scheduled-posts
export interface ScheduledPostListResponse {
    success: true;
    posts: ScheduledPost[];
}

// POST /api/scheduled-posts
export interface ScheduledPostResponse {
    success: true;
    post: ScheduledPost;
}

// PUT /api/scheduled-posts/:id; post is null when the row is gone by the time it is read back
export interface ScheduledPostUpdateResponse {
    success: true;
    post: ScheduledPost | null;
}

// DELETE /api/scheduled-posts; posts that are publishing are kept
export interface ScheduledPostDeleteAllResponse {
    success: true;
    deleted: number;
    kept: number;
}

// GET /api/tracked-content
export type TrackedContentListResponse = TrackedPost[];

// GET /api/overview
export interface OverviewResponse {
    tracked: TrackedPost[];
    analyticsCache: OverviewAnalyticsCache;
}

// body of PUT /api/settings/github; the repository fills the scheduling guide links
export interface GitHubSettingsRequest {
    repoOwner?: string;
    repoName?: string;
    branch?: string;
}

// GET /api/settings/github, exactly what is stored under settings.github
export interface GitHubSettingsResponse {
    repoOwner: string;
    repoName: string;
    branch: string;
}

export interface KeyStatus {
    configured: boolean;
}

// GET /api/keys reports which server secrets are set
export interface KeysStatusResponse {
    youtube: KeyStatus;
    instagram: KeyStatus;
    cloudinary: KeyStatus;
}

export type ApiErrorCode =
    | 'VALIDATION_ERROR' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'CONFLICT' | 'RATE_LIMITED'
    | 'UPSTREAM_ERROR' | 'UPSTREAM_TIMEOUT' | 'NOT_CONFIGURED' | 'DATABASE_ERROR' | 'INTERNAL_ERROR';

// the one body every failed request gets, from the error handler or the rate limiter, always with a 4xx or 5xx status
export interface ApiFailure {
    success: false;
    code: ApiErrorCode;
    message: string;
    requestId?: string;
    // seconds, on 429 only
    retryAfter?: number;
}

// DELETE /api/accounts/:id, DELETE /api/tracked-content/:id and PUT /api/settings/github
export interface SuccessResponse {
    success: true;
}

// DELETE /api/scheduled-posts/:id
export interface SuccessMessageResponse {
    success: true;
    message: string;
}

// GET /api/health
export interface HealthResponse {
    status: string;
    timestamp: string;
}

// GET /api/health/ready; a missing secret or a failed database check answers the usual ApiFailure instead
export interface ReadinessResponse {
    status: 'ready';
    // how long the database check took, so a monitor can see it slowing before it fails
    databaseMs: number;
    timestamp: string;
}

// body of POST /api/scheduled-posts; the route fills in defaults for the optional fields
export interface ScheduledPostRequest {
    accountId: string;
    mediaUrl: string;
    scheduledAt: string;
    platform?: Platform;
    mediaType?: MediaType;
    caption?: string;
    coverUrl?: string | null;
    shareToFeed?: boolean;
    collaborators?: string[];
    audioName?: string;
    thumbOffset?: number | null;
    locationId?: string;
    userTags?: UserTag[];
    altText?: string;
    automation?: ScheduledPostAutomation;
}

// body of PUT /api/scheduled-posts/:id; any other field is ignored
export type ScheduledPostUpdateRequest = Partial<Pick<ScheduledPost,
    'caption' | 'scheduledAt' | 'shareToFeed' | 'collaborators' | 'audioName' | 'thumbOffset' | 'locationId' | 'userTags' | 'altText' | 'coverUrl'>>;

// a tracked video with the fields fetched from YouTube
export type TrackedContentItem = TrackedPost & Partial<Omit<YouTubeTrackedVideoData, 'contentType'>>;

// body of POST /api/tracked-content
export interface TrackedContentAddRequest {
    url: string;
    label?: string;
    category?: string;
}

// body of PUT /api/tracked-content/:id
export interface TrackedContentUpdateRequest {
    label?: string;
    category?: string;
}