Skip to content
TrackGeekPublic

About

API for a unified media tracking platform, with progress, statistics, and social authentication.

Topics

Resources

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

 

History

622 Commits

Folders and files

Repository files navigation

Api

API for a unified media tracking platform, with progress, reviews, statistics, and social features.


About

TrackGeek API is a NestJS-based backend that powers a unified media tracking platform. Users can track their progress across six different media types — Anime, Manga, TV Shows, Movies, Games, and Books — while interacting with a social community through reviews, comments, reactions, and activity feeds.

The API integrates with external media databases (Tenrai, TMDB, IGDB, Hardcover) to provide rich metadata and uses background job processing for async tasks like email delivery and feed event aggregation.

Features

Media Tracking

  • Track progress across 6 media types: Anime, Manga, TV Shows, Movies, Games, and Books;
  • Episode-level tracking for Anime and TV Shows (per season/episode);
  • Progress statuses: Watching, Playing, Reading, Completed, Paused, Dropped, Planning;
  • Detailed review system with media-specific rating criteria (e.g., animation/sound for anime, gameplay/graphics for games);
  • Screenshot uploads for game reviews.

Social Features

  • Follow/unfollow users;
  • Comments on media and user profiles;
  • Emoji reactions on comments and feed events;
  • Activity feed with event aggregation (new follows, favorites, reviews, progress updates);
  • Custom lists for organizing media collections;
  • Favorites system.

Developer Integrations

  • TrackGeek OAuth authorization with PKCE, per-application scopes, consent, rotating refresh tokens, and revocation;
  • Scoped REST API at /integrations/v1 for other interfaces and bots;
  • Remote MCP server at /mcp for media discovery and personal tracking through AI clients;
  • Application registration and authorized application management in Settings → Connections.

User Management

  • OAuth authentication with 10 social providers (Google, GitHub, Discord, Twitch, Kick, Twitter, Slack, Microsoft, Notion, Spotify);
  • Magic link and password-based authentication;
  • Customizable profiles (avatar, banner, color, bio, language, timezone);
  • Medal/achievement system;
  • Tiered subscription plans (Tracker, Archivist, ArchiveMaster).

Payments

  • Stripe integration for subscriptions and one-time payments;
  • Webhook handling for payment lifecycle events;
  • Transactional email notifications for payment success, failure, and cancellation.

Infrastructure

  • Background job processing with BullMQ (email delivery, feed event aggregation);
  • Redis caching for performance optimization;
  • Rate limiting with configurable read/write throttlers;
  • Internationalization (i18n) support;
  • File uploads via ImgBB or Cloudflare R2, with WebP conversion for R2;
  • Swagger/OpenAPI documentation with Scalar API Reference.

Tech Stack

Category Technology
Framework NestJS 11
Language TypeScript 5.7
ORM Prisma 7
Database PostgreSQL 18
Cache / Queue Redis 6, BullMQ
Authentication Better Auth (OAuth2, Magic Link, Credentials)
Payments Stripe
Email Resend + Handlebars templates
API Docs Swagger/OpenAPI + Scalar
Linting Biome
Testing Vitest (unit), Playwright (e2e), k6 (load)
Containerization Docker Compose

External Integrations

Service Purpose
Anilist Manga metadata
Tenrai Anime metadata (MyAnimeList)
TMDB TV Shows and Movies metadata
IGDB Video Games metadata
Hardcover Books metadata
ImgBB Optional image hosting
Cloudflare R2 Optional S3-compatible image hosting
Stripe Payment processing
Resend Transactional email delivery

Project Structure

src/
├── main.ts                          # Application bootstrap
├── app.module.ts                    # Root module
├── modules/
│   ├── admin/                       # Admin operations
│   ├── anime/                       # Anime tracking, reviews, episodes
│   ├── auth/                        # Authentication (Better Auth)
│   ├── book/                        # Book tracking and reviews
│   ├── comment/                     # Comments system
│   ├── favorite/                    # Favorites management
│   ├── feed-event/                  # Activity feed and aggregation
│   ├── game/                        # Game tracking, reviews, screenshots
│   ├── list/                        # Custom lists
│   ├── manga/                       # Manga tracking and reviews
│   ├── movie/                       # Movie tracking and reviews
│   ├── payment/                     # Stripe payments and webhooks
│   ├── profile/                     # User profile customization
│   ├── reaction/                    # Emoji reactions
│   ├── tv-show/                     # TV Show tracking, reviews, episodes
│   └── user/                        # User management
└── shared/
    ├── constants/                   # Queue and job name constants
    ├── decorators/                  # Custom decorators
    ├── exceptions/                  # Custom exceptions
    ├── filters/                     # HTTP exception filter
    ├── guards/                      # Throttler guard
    ├── interceptors/                # Metrics interceptor
    ├── utils/                       # Utility functions
    ├── validators/                  # Custom validators
    └── infra/
        ├── cache/                   # Redis cache module
        ├── cron/                    # Scheduled tasks
        ├── database/                # Prisma database service
        ├── docs/                    # Swagger/Scalar setup
        ├── email/                   # Resend email service + templates
        ├── health/                  # Health check endpoints
        ├── i18n/                    # Internationalization
        ├── integrations/            # External API clients (Tenrai, TMDB, IGDB, Hardcover)
        ├── queue/                   # BullMQ queue setup and processors
        └── upload/                  # Provider selection and WebP conversion

Run Locally

Prerequisites: Bun, Docker, and Docker Compose.

Clone the project

git clone https://github.com/TrackGeek/api.git

Go to the project directory

cd api

Copy the environment file and fill in the required variables

cp .env.example .env

Install dependencies

bun install

Start PostgreSQL and Redis containers

docker compose up -d

Run database migrations, generate the Prisma client, and seed data

bun db:migrate
bun db:generate
bun db:seed

Start the development server

bun dev

The API will be available at http://localhost:40287 with documentation at http://localhost:40287/docs.

Testing Stripe Webhooks

To test Stripe locally you need the Stripe CLI installed.

With the development server running, use the listen command to forward Stripe events to the local webhook endpoint:

bun stripe:webhook
# equivalent to: stripe listen --forward-to localhost:40287/stripe/webhook

The CLI prints a webhook signing secret (whsec_...) — set it as STRIPE_WEBHOOK_SECRET in your .env.

This is only for local development. In production, configure the webhook endpoint through the Stripe Dashboard.

Scripts

Script Description
bun dev Start development server with hot reload
bun run build Build for production
bun start Start production server
bun db:migrate Run database migrations
bun db:generate Generate Prisma client
bun db:seed Seed the database
bun stripe:webhook Forward Stripe events to the local webhook
bun test:unit Run unit tests (Vitest)
bun test:unit:watch Run unit tests in watch mode
bun test:unit:ui Run unit tests with the Vitest UI
bun test:unit:cov Run unit tests with coverage
bun test:e2e Run end-to-end tests (Playwright)
bun test:e2e:ui Run end-to-end tests with the Playwright UI
bun test:e2e:debug Run end-to-end tests in debug mode
bun test:load Run load tests (k6)
bun lint Run Biome linter
bun lint:fix Run Biome linter and apply fixes
bun check Run Biome checks
bun check:fix Run Biome checks and apply fixes
bun format Check formatting with Biome
bun format:fix Format code with Biome
bun types Type check with TypeScript
bun run verify Format, type check, and build before pushing
bun run hooks:install Install the repository Git hooks

Git hooks

bun install installs the versioned pre-push hook automatically when this directory contains a Git checkout. For an existing checkout, run bun run hooks:install once.

Every push runs bun run format:fix, bun run types, and bun run build in that order. Any failure stops the remaining commands and blocks the push. The working tree must be clean after verification; commit or stash local changes, including any formatting changes, before retrying. The hook never stages or commits files automatically.

Environment Variables

Variable Description
PORT Server port (default: 40287)
NODE_ENV Runtime environment (development/production)
DATABASE_URL PostgreSQL connection string
REDIS_URL Redis connection string
BETTER_AUTH_URL Auth base URL
BETTER_AUTH_SECRET Auth secret key
OAUTH_ALLOW_DYNAMIC_REGISTRATION Allow public OAuth client registration for MCP clients (default: true)
MCP_ALLOWED_ORIGINS Additional browser origins allowed to call MCP, comma-separated
BETTER_AUTH_LOG_LEVEL Auth log level (default: info)
WEB_URL Frontend URL for CORS
GOOGLE_CLIENT_ID/SECRET Google OAuth credentials
DISCORD_CLIENT_ID/SECRET Discord OAuth credentials
GITHUB_CLIENT_ID/SECRET GitHub OAuth credentials
TWITCH_CLIENT_ID/SECRET Twitch OAuth credentials
KICK_CLIENT_ID/SECRET Kick OAuth credentials
TWITTER_CLIENT_ID/SECRET Twitter OAuth credentials
SLACK_CLIENT_ID/SECRET Slack OAuth credentials
MICROSOFT_CLIENT_ID/SECRET Microsoft OAuth credentials
NOTION_CLIENT_ID/SECRET Notion OAuth credentials
SPOTIFY_CLIENT_ID/SECRET Spotify OAuth credentials
RESEND_API_KEY Resend API key for emails
RESEND_FROM Sender email address
STRIPE_SECRET_KEY Optional; enables Stripe payments
STRIPE_WEBHOOK_SECRET Required only when using Stripe webhooks
IMAGE_STORAGE_PROVIDER Image provider: imgbb (default) or r2
IMGBB_API_KEY ImgBB API key when using ImgBB
R2_ACCOUNT_ID Cloudflare account ID when using R2
R2_ACCESS_KEY_ID R2 API token access key ID
R2_SECRET_ACCESS_KEY R2 API token secret access key
R2_BUCKET_NAME R2 bucket name
R2_PUBLIC_URL Public bucket or custom-domain base URL
R2_MAX_STORAGE_BYTES Hard cap on total bucket size; uploads are refused beyond it (default: 9000000000, under the 10 GB free tier)
IMGBB_R2_MIGRATION_MAX_IMAGES Maximum distinct images per migration run (default: 100)
IMGBB_R2_MIGRATION_MAX_BYTES Maximum WebP bytes uploaded per run (default: 262144000)
IMGBB_R2_MIGRATION_DELAY_MS Delay between ImgBB downloads (default: 2000)
HARDCOVER_API_KEY Hardcover API key for books
TMDB_API_KEY TMDB API key for movies/TV shows
IGDB_CLIENT_ID/SECRET IGDB credentials for games

ImgBB to R2 Migration

Back up PostgreSQL before applying the migration. The script updates database URLs but never deletes ImgBB images or R2 objects.

Inspect candidates without network uploads or database writes:

bun run images:migrate-imgbb-r2 --dry-run

Apply a bounded batch:

bun run images:migrate-imgbb-r2

Repeat the command until the dry-run reports zero matching rows and unique URLs. A run with failed URLs exits with a non-zero status. Fix or retry those URLs in the next run.

Every R2 upload (API and migration) first measures real bucket usage and is refused with STORAGE_QUOTA_EXCEEDED if it would pass R2_MAX_STORAGE_BYTES; the migration then stops cleanly. Defaults per run are 100 distinct images, 250 MiB of uploaded WebP data, and 2 seconds between ImgBB downloads. These limits only control this script; they do not account for other R2 usage in the same Cloudflare account. Tune them with environment variables or CLI flags:

bun run images:migrate-imgbb-r2 --max-images 50 --max-bytes 104857600 --delay-ms 3000

Additional flags: --batch-size, --download-timeout-ms, --max-download-bytes, --download-attempts, and --webp-quality.

The migrator scans URL and image string fields plus every JSON field from Prisma models. It converts images to WebP with quality 82, preserves animated images, and replaces nested JSON references. Duplicate source URLs share a deterministic R2 key. Existing R2 objects are reused after interruptions, and conditional updates avoid overwriting rows changed concurrently.

Contributing

Contributions are always welcome!

See CONTRIBUTING.md for ways to get started.

Please adhere to this project's code of conduct.

TMDB anime mapping

The API downloads Fribb's anime-list-mini.json to ANIME_MAPPING_FILE (default .data/anime-list-mini.json). Mount that path on persistent storage. The snapshot refreshes every seven days; a failed refresh keeps the previous valid snapshot and retries hourly.

GET /anime/resolve/movie/:tmdbId and GET /anime/resolve/tv/:tmdbId return { "anime": { "type": "anime", "malId": 164, "path": "/anime/164" } } for mapped content, or { "anime": null }. Movie and TV ID namespaces are independent. Where a series maps to multiple anime, the first season takes precedence for navigation; episode migration uses each mapped season and episode offset.

After database migrations deploy, existing tracking is migrated automatically at startup and hourly. Progress and review dates are preserved, source tracking is removed only inside the successful transaction, and an existing anime entry takes precedence on conflicts. Original rows, including review fields without an anime equivalent, are retained in AnimeMigrationArchive, linked to the user with cascading account deletion. Unmapped TV seasons remain untouched. Favorites, comments, posts, activities and review reactions follow the anime. Movie/TV custom list items move into a corresponding Anime list. Writes against mapped movie/TV IDs return HTTP 409 MEDIA_MOVED_TO_ANIME with the canonical anime target.

About

API for a unified media tracking platform, with progress, statistics, and social authentication.

Topics

Resources

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Used by

Contributors

Languages