Chat System Features

Overview

The chat system provides real-time messaging capabilities through two main communication channels: 1-on-1 Direct Conversations and Group Chats. Both channels support rich messaging features including media attachments, reactions, replies, and more.

The system operates on WebSocket technology for real-time communication and integrates with a user plan system to manage feature access and usage limits.


Core Communication Models

1-on-1 Direct Conversations

Direct conversations enable private messaging between two users with built-in privacy controls and status management.

Conversation Lifecycle

Each conversation progresses through defined states: - Pending: Initial state when the first user sends a message - Accepted: Recipient has responded or explicitly accepted the conversation
- Rejected: Recipient declined the conversation request - Blocked: Recipient blocked further communication

Message Limits in Pending State

When a conversation is pending, the system enforces specific rules: - The initiator can send up to 2 messages before the recipient responds - The recipient's first reply automatically transitions the conversation to "accepted" status - Once accepted, both users can exchange unlimited messages

This mechanism prevents spam while allowing legitimate conversation initiation.

Conversation Actions

Recipients can perform three actions on pending conversations: - Accept: Opens the conversation for unlimited messaging - Reject: Declines the request without blocking future attempts - Block: Permanently prevents the initiator from contacting them

Group Chats

Groups enable multi-user conversations with hierarchical permission systems and advanced messaging features.

Group Roles & Permissions

Four distinct roles govern group interactions:

Owner: Creator of the group with full control - Manage all group settings (name, bio, profile picture, type) - Add/remove members, admins, and instructors - Delete the group - Always able to send messages

Admin: Elevated privileges for group management - Add/remove regular members - Promote members to admin or instructor - Manage group settings (excluding deletion) - Always able to send messages

Instructor: Special role for educational contexts - Can send messages even when member chat is disabled - Cannot perform administrative actions - Designed for teaching scenarios where instructors need messaging priority

Member: Standard group participants - Send messages (when enabled) - React to messages - Vote in polls - Cannot modify group settings

Chat Control for Members

Groups support a "disable member chat" mode where: - Only owner, admins, and instructors can send messages - Members retain read access and can react to messages - Useful for announcements or structured educational sessions


Messaging Features

Message Composition

Text Messages

Basic text content with support for: - Plain text communication - Message replies (threading) - User mentions in groups (notifies mentioned users)

Media Attachments

Messages support multiple media types: - Images: Photos with automatic thumbnail generation - Documents: PDFs, text files, spreadsheets - Video: Video clips with thumbnail and duration metadata - Files: Any other file type

Each media attachment stores: - File name and size - MIME type for proper handling - Upload timestamp - Media-specific metadata (dimensions for images/videos, duration for audio/video)

Message Management

Message Editing

Users can edit their sent messages with full edit tracking: - Mark messages as edited - Record edit timestamp - Track total number of edits per message - Only the original sender can edit their messages

Message Replies

Create threaded conversations by replying to specific messages: - Works in both 1-on-1 and group chats - Replies maintain reference to the original message - If original message is deleted, reply remains but reference is cleared

Message Pinning

Important messages can be pinned for visibility: - In 1-on-1: Either participant can pin messages - In groups: Only owner and admins can pin messages - Pinned messages appear prominently in the interface

Soft Delete (Message Hiding)

Users can hide messages from their view without affecting others: - Messages are not permanently deleted - Hidden from the user who deleted it - Other participants still see the message - Useful for personal message management

Message Interactions

Emoji Reactions

Users express quick responses through emoji reactions: - Each user can add one reaction per message - If user changes reaction, previous one is replaced - 8 emoji options available: 👍 ❤️ 😂 😮 😢 🔥 🎉 👏 - Reaction counts visible to all participants

Read Receipts (1-on-1 only)

Track message read status in direct conversations: - Messages marked as unread when sent - Automatically marked as read when recipient views them - Read timestamp recorded for tracking - Helps users know when their message was seen

Polls (Group Only)

Groups support interactive polls for gathering opinions:

Poll Structure: - Question/title (up to 500 characters) - Multiple options (each up to 200 characters) - Option ordering for consistent display

Voting Mechanics: - Each member can vote once per poll - Users can change their vote before poll closes - Vote counts visible in real-time - Creator or admins can close the poll to stop voting

Poll Messages: - Polls are special message types in groups - Displayed differently from text messages - Can be replied to like regular messages


Privacy & Control Features

Conversation Muting

Users can mute conversations to stop notifications: - Applies to both 1-on-1 and group chats - Messages still received but notifications suppressed - Can unmute anytime - Personal setting that doesn't affect other participants

User Visibility Management

The system controls which users can see and message each other:

Privacy Acceptance: - Users must accept chat privacy policy to appear in user lists - Profile must be complete (username required) - Upon acceptance, users receive automated welcome message

Daily Visibility Limits: - Based on user's subscription plan - Free plans may see limited number of users per day - Premium plans may have unlimited visibility - System randomly selects visible users within limits - Resets daily at midnight

Conversation Deletion

Users can delete conversations from their view: - Soft delete: removes conversation from user's list - Other participant still sees the conversation - Can be applied to entire conversation history - Useful for decluttering without notifying the other party


Real-Time Communication

WebSocket Integration

The system uses WebSocket connections for instant updates:

Connection Management: - Users connect to personal WebSocket channels - Groups have dedicated channels for all members - Automatic reconnection on connection loss

Real-Time Events: - New messages delivered instantly - Message status updates (read receipts, reactions) - Conversation status changes (accepted, blocked) - User presence information - Poll updates (new votes, results) - Group changes (new members, setting updates)

Push Notifications

Integration with Najva push notification service: - Notify users when they receive messages while offline - New conversation requests - Group mentions and important updates - Customizable notification preferences - Click-through URLs to open relevant conversation


Plan-Based Feature Access

Feature Gating

Different user plans control access to: - Direct Messaging: Number of new conversations per day - User Visibility: How many users appear in contact list - Group Creation: Ability to create new groups - Media Upload Limits: File size and type restrictions

Usage Tracking

The system monitors feature usage: - Counts daily new conversation initiations - Tracks user visibility selections - Records group creation - Enforces limits based on plan tier

Admin Override

Staff and superuser accounts: - Bypass most restrictions - Conversations auto-accepted instead of pending - Unlimited visibility and messaging - Used for support and moderation purposes


Data Organization

Unique Identifiers

All major entities use UUIDs for secure access: - Conversations identified by UUID (not sequential IDs) - Groups identified by UUID - Prevents enumeration attacks - Safe for use in URLs

Timestamp Tracking

Comprehensive time tracking for: - Entity creation (created_at) - Last update (updated_at) - Status changes (status_changed_at) - Message read times (read_at) - Privacy acceptance time (chat_privacy_accepted_at) - Mute timestamps (muted_at)

Soft Relationships

Many features use soft relationships: - Deleted messages not removed, just hidden - Blocked users don't delete conversation history - Maintains data integrity for auditing - Allows undoing actions


Message Type System

Standard Text Messages

Default message type for both conversations and groups: - Plain text content - Optional media attachments - Reply references - Reactions and pinning

Poll Messages (Group Only)

Special message type that embeds a poll: - Message content is empty - Poll data attached to message - Displays as interactive poll widget - Can be replied to but not edited - Creator and admins can close voting


Group-Specific Features

Group Metadata

Groups maintain rich profile information: - Name: Group title displayed to all members - Bio: Description of group purpose/rules - Profile Picture: Visual identifier for the group - Type: Categorization (e.g., "education") set by owner

Member Management

Structured membership system: - Add members individually or in bulk - Remove members (owner/admin only) - Promote members to admin or instructor roles - Demote admins/instructors back to members - Track member join dates

Mention System

Tag users in group messages to get their attention: - Uses @username format - Mentioned users receive special notifications - Mention data stored as list of user IDs - Works only in group chats (not 1-on-1)

Instructor Role Benefits

Special role designed for educational groups: - Instructors bypass member chat restrictions - Can send messages even when members can't - Cannot perform admin actions like removing members - Ideal for teachers/trainers who need messaging priority without full admin control


Technical Behaviors

Auto-Accept Mechanism

Certain scenarios trigger automatic conversation acceptance: - Recipient replies to pending conversation - Admin (staff/superuser) initiates conversation - Welcome message from system account

Message Ordering

Messages maintain chronological order: - Sorted by creation timestamp - Pagination preserves order - Replies reference earlier messages - Edited timestamp separate from creation time

Validation & Limits

System enforces various constraints: - File upload size limits per media type - Allowed file extensions for security - Message content length restrictions (polls: 500 chars, options: 200 chars) - One reaction per user per message - One vote per user per poll

Notification Smart Delivery

Notifications sent strategically: - Only to users not currently viewing the conversation - Muted conversations don't trigger push notifications - Combines WebSocket and push for reliability - Batch notifications when appropriate


Integration Points

User Profile System

Chat integrates with user profiles for: - Display names and profile pictures - Privacy acceptance flags - Username requirements - Admin status detection

User Plan System

Subscription plans control: - Feature availability checks - Usage limit enforcement - Daily reset mechanics - Upgrade prompts when limits reached

Activity Tracking

User actions logged for: - Platform engagement metrics - Feature usage analytics - Plan upgrade recommendations - Moderation and support


Architecture Patterns

Synchronous vs Asynchronous

The system handles both: - REST API endpoints: Synchronous HTTP requests for CRUD operations - WebSocket consumers: Asynchronous real-time message delivery - Hybrid helpers: Utility functions that work in both contexts

Database Optimization

Performance considerations: - Selected related data to reduce queries (select_related, prefetch_related) - Indexed fields for fast lookups (UUIDs, timestamps, foreign keys) - Aggregated queries for counts and stats - Pagination for large result sets

Error Handling

Graceful degradation: - WebSocket failures don't prevent REST operations - Push notification failures logged but don't block message delivery - Media upload errors tracked per-file, don't fail entire message - Feature check failures allow operation but log warning


User Experience Flows

Initiating a Conversation

  1. User browses visible users (respecting plan limits)
  2. Selects recipient and sends first message
  3. Conversation created in "pending" state
  4. User can send one more message (2 total)
  5. Recipient notified of pending request
  6. Recipient accepts, rejects, or blocks
  7. If accepted, unlimited messaging begins

Group Interaction

  1. Owner creates group with name and settings
  2. Owner adds members, assigns roles
  3. Members receive notifications and join
  4. Messages sent to group channel
  5. All members receive real-time updates
  6. Polls created for group decisions
  7. Admins manage membership and settings

Message Engagement

  1. User sends message with optional media
  2. Message delivered instantly via WebSocket
  3. Recipients see message in conversation
  4. Recipients can react with emoji
  5. Recipients can reply to create thread
  6. Sender can edit message if needed
  7. Read receipts update sender's view (1-on-1)

Poll Creation & Voting

  1. Group member creates poll with question
  2. Adds multiple choice options
  3. Poll appears as special message type
  4. Members cast votes on options
  5. Results update in real-time
  6. Voters can change their selection
  7. Creator closes poll when ready
  8. Final results visible to all