Automated Action 545563e776 Implement comprehensive real-time chat API with NestJS
- Complete NestJS TypeScript implementation with WebSocket support
- Direct messaging (DM) and group chat functionality
- End-to-end encryption with AES encryption and key pairs
- Media file support (images, videos, audio, documents) up to 100MB
- Push notifications with Firebase Cloud Messaging integration
- Mention alerts and real-time typing indicators
- User authentication with JWT and Passport
- SQLite database with TypeORM entities and relationships
- Comprehensive API documentation with Swagger/OpenAPI
- File upload handling with secure access control
- Online/offline status tracking and presence management
- Message editing, deletion, and reply functionality
- Notification management with automatic cleanup
- Health check endpoint for monitoring
- CORS configuration for cross-origin requests
- Environment-based configuration management
- Structured for Flutter SDK integration

Features implemented:
 Real-time messaging with Socket.IO
 User registration and authentication
 Direct messages and group chats
 Media file uploads and management
 End-to-end encryption
 Push notifications
 Mention alerts
 Typing indicators
 Message read receipts
 Online status tracking
 File access control
 Comprehensive API documentation

Ready for Flutter SDK development and production deployment.
2025-06-21 17:13:05 +00:00
2025-06-21 16:59:44 +00:00

Real-time Chat API with Media Support

A comprehensive real-time chat API built with NestJS (TypeScript) featuring WebSocket support, direct messaging, group chats, end-to-end encryption, push notifications, mention alerts, and media file sharing.

Features

Core Chat Features

  • Real-time messaging with WebSocket support
  • Direct Messages (DM) between users
  • Group chat functionality with member management
  • Message editing and deletion
  • Reply to messages functionality
  • Typing indicators
  • Online/offline status tracking
  • Message read receipts

Media Support

  • File uploads (images, videos, audio, documents)
  • Media types supported: JPG, PNG, GIF, WebP, SVG, MP4, MPEG, QuickTime, AVI, MP3, WAV, OGG, PDF, Word, Excel, PowerPoint, ZIP, RAR, 7z
  • File size limit: Up to 100MB per file
  • Automatic media type detection
  • Secure media access (only chat members can access)

Security & Encryption

  • End-to-end encryption for messages
  • JWT-based authentication
  • User key pair generation for encryption
  • Secure file uploads with access control
  • Input validation and sanitization

Push Notifications

  • Firebase Cloud Messaging (FCM) integration
  • New message notifications for offline users
  • Mention alerts with push notifications
  • Device management for multi-device support
  • Automatic retry for failed notifications
  • Notification cleanup (removes old notifications)

User Management

  • User registration and authentication
  • Profile management with avatar support
  • User search functionality
  • Public key sharing for encryption
  • Online status management

Tech Stack

  • Framework: NestJS (TypeScript)
  • Database: SQLite with TypeORM
  • Real-time: Socket.IO
  • Authentication: JWT with Passport
  • File Storage: Local filesystem
  • Push Notifications: Firebase Cloud Messaging
  • API Documentation: Swagger/OpenAPI
  • Encryption: CryptoJS (AES encryption)

Project Structure

src/
├── auth/                 # Authentication module
│   ├── dto/             # Data transfer objects
│   ├── guards/          # Authentication guards
│   └── strategies/      # Passport strategies
├── chat/                # Chat functionality
│   └── dto/             # Chat DTOs
├── database/            # Database entities
│   └── entities/        # TypeORM entities
├── encryption/          # Encryption service
├── media/               # Media upload handling
├── notification/        # Push notifications
├── users/               # User management
│   └── dto/             # User DTOs
├── app.module.ts        # Main application module
└── main.ts             # Application entry point

Quick Start

1. Install Dependencies

npm install

2. Environment Configuration

Copy the example environment file and configure it:

cp .env.example .env

Required environment variables:

  • PORT: Server port (default: 3000)
  • JWT_SECRET: Secret key for JWT tokens
  • FIREBASE_SERVICE_ACCOUNT: Firebase service account JSON for push notifications

3. Start the Application

# Development
npm run start:dev

# Production
npm run build
npm run start:prod

The application will be available at:

API Endpoints

Authentication

  • POST /auth/register - Register new user
  • POST /auth/login - Login user
  • POST /auth/logout - Logout user

Users

  • GET /users - Get all users (with search)
  • GET /users/me - Get current user profile
  • PUT /users/me - Update user profile
  • PUT /users/me/avatar - Update user avatar
  • GET /users/:id - Get user by ID
  • GET /users/username/:username - Get user by username
  • GET /users/:id/public-key - Get user's public key

Chat

  • GET /chat/rooms - Get user's chat rooms
  • POST /chat/rooms/direct - Create/get direct message room
  • POST /chat/rooms/group - Create group chat room
  • GET /chat/rooms/:roomId - Get chat room details
  • GET /chat/rooms/:roomId/messages - Get chat room messages
  • POST /chat/messages - Create new message
  • PUT /chat/messages/:messageId - Edit message
  • DELETE /chat/messages/:messageId - Delete message
  • POST /chat/rooms/:roomId/members - Add members to group
  • DELETE /chat/rooms/:roomId/members/:memberId - Remove member from group

Media

  • POST /media/upload/:messageId - Upload media file
  • GET /media/:mediaId - Get media file details
  • DELETE /media/:mediaId - Delete media file
  • GET /media/message/:messageId - Get all media for message

Notifications

  • GET /notifications - Get user notifications
  • GET /notifications/unread-count - Get unread notification count
  • PUT /notifications/:notificationId/read - Mark notification as read
  • PUT /notifications/read-all - Mark all notifications as read

WebSocket Events

Client to Server

  • join_room - Join a chat room
  • leave_room - Leave a chat room
  • send_message - Send a new message
  • edit_message - Edit existing message
  • delete_message - Delete message
  • typing_start - Start typing indicator
  • typing_stop - Stop typing indicator
  • mark_as_read - Mark message as read

Server to Client

  • connected - Connection established
  • new_message - New message received
  • message_edited - Message was edited
  • message_deleted - Message was deleted
  • user_typing - User started typing
  • user_stopped_typing - User stopped typing
  • message_read - Message was read
  • mentioned - User was mentioned
  • user_online - User came online
  • user_offline - User went offline
  • joined_room - Successfully joined room
  • left_room - Successfully left room
  • error - Error occurred

Flutter SDK Integration

This API is designed to work seamlessly with Flutter applications. Key considerations for Flutter integration:

WebSocket Connection

// Connect with JWT token
const socket = io('ws://localhost:3000', {
  auth: {
    token: 'your-jwt-token'
  }
});

File Upload

The API supports multipart/form-data uploads, compatible with Flutter's HTTP client and dio package.

Push Notifications

Firebase Cloud Messaging integration allows direct push notification support in Flutter apps.

Real-time Features

Socket.IO events are designed to map directly to Flutter state management patterns (Provider, Bloc, Riverpod).

Database Schema

The application uses SQLite with the following main entities:

  • Users: User accounts with encryption keys
  • ChatRooms: Direct and group chat rooms
  • Messages: Chat messages with encryption support
  • MessageMedia: File attachments
  • MessageMentions: User mentions in messages
  • UserDevices: Device registration for push notifications
  • Notifications: Push notification records

Security Features

  • JWT Authentication: Secure token-based auth
  • End-to-end Encryption: Messages encrypted with room-specific keys
  • File Access Control: Only chat members can access uploaded files
  • Input Validation: All inputs validated and sanitized
  • CORS Configuration: Configured for cross-origin requests
  • Rate Limiting: Built-in protection against abuse

Development

Running Tests

npm run test
npm run test:e2e
npm run test:cov

Linting and Formatting

npm run lint
npm run format

Building for Production

npm run build

Environment Variables

Variable Description Required Default
PORT Server port No 3000
NODE_ENV Environment No development
JWT_SECRET JWT secret key Yes -
FIREBASE_SERVICE_ACCOUNT Firebase config JSON No -

Storage

The application uses local filesystem storage:

  • Database: /app/storage/db/chat.sqlite
  • Media Files: /app/storage/media/
  • User Avatars: /app/storage/media/avatars/
  • Message Media: /app/storage/media/messages/

Health Check

The API includes a comprehensive health check endpoint at /health that reports:

  • Service status
  • Uptime
  • Memory usage
  • Environment information

License

MIT License - see LICENSE file for details.

Support

For issues and questions, please check the API documentation at /docs or refer to the source code.

Description
Project: Real-time Chat API with Media Support
Readme 26 MiB
Languages
TypeScript 100%