Skip to content
/ PChat Public

PChat is a high-performance, decentralized chat application built with Elixir/Phoenix and Rust. It offers real-time messaging, WebRTC voice/video calls, offline P2P delivery, IPFS-based file storage, AI-powered features, and advanced security with end-to-end encryption. It supports multiple platforms (web, mobile, Discord bot).

Notifications You must be signed in to change notification settings

pky1987/PChat

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PChat Application

A comprehensive, high-performance chat application featuring real-time messaging, peer-to-peer communication, decentralized storage, and advanced media processing capabilities.

πŸš€ Project Overview

PChat is a modern chat platform that combines the robustness of Elixir/Phoenix with the performance of Rust. The application provides secure, real-time communication with offline P2P delivery, WebRTC voice/video calls, decentralized file storage via IPFS, and AI-powered features.

Key Features

  • Real-time Messaging: Phoenix Channels for instant communication
  • Offline P2P Delivery: Direct device-to-device message transfer (1GB in 5 seconds)
  • WebRTC Integration: Voice and video calling with advanced audio processing
  • Decentralized Storage: IPFS for secure, distributed file storage
  • Multi-platform Support: Web, mobile, and Discord bot integration
  • Advanced Security: End-to-end encryption, JWT authentication, QR code login, zero-knowledge authentication
  • AI-Powered Features: Voice modulation, noise cancellation, content moderation, smart replies
  • Smart Message Scheduling: User-defined send times with AI-powered optimal timing suggestions
  • Voice-Activated Commands: "Hey PChat" wake word for hands-free messaging and navigation
  • Rich Presence Indicators: Activity-based status updates with location-aware presence
  • Anti-Screenshot Watermarking: OS-level screenshot blocking and forensic content tracing
  • Flexible Chat Types: Normal, Important, and Session messaging with different behaviors
  • Organization Groups: Anonymous group chats for organizational communication
  • Self-Destructing Messages: Ephemeral messaging with configurable timers (seconds to weeks)
  • Collaborative Whiteboards: Embedded drawing and brainstorming tools in channels and calls
  • Sentiment-Aware Moderation: LLM-powered toxicity detection and automated responses
  • Real-time Translation: Automatic multilingual translation for global communication
  • Smart Reply Suggestions: AI-generated context-aware response suggestions

πŸ—οΈ Architecture

The application consists of two main components:

Backend (Elixir/Phoenix)

  • Framework: Phoenix 1.7+ with Elixir 1.14+
  • Database: PostgreSQL with Ecto ORM
  • Real-time: Phoenix Channels and Presence
  • Authentication: Guardian JWT with QR code support
  • Media Processing: WebRTC integration with voice enhancement

Performance Layer (Rust)

  • Web Server: Actix-web for high-performance APIs
  • Async Runtime: Tokio for concurrent processing
  • WebRTC: Real-time communication with voice profiles
  • Audio Processing: Opus codec with noise cancellation
  • Storage: IPFS client with content moderation
  • Bot Integration: Discord bot with advanced commands

πŸ“ Project Structure

.
β”œβ”€β”€ elx/                          # Elixir/Phoenix backend
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ elx/                  # Main application modules
β”‚   β”‚   β”‚   β”œβ”€β”€ application.ex    # App supervision tree
β”‚   β”‚   β”‚   β”œβ”€β”€ models.ex         # Ecto schemas
β”‚   β”‚   β”‚   β”œβ”€β”€ offline_messaging.ex # P2P message delivery
β”‚   β”‚   β”‚   β”œβ”€β”€ auth/             # Authentication system
β”‚   β”‚   β”‚   β”œβ”€β”€ channels/         # Real-time communication
β”‚   β”‚   β”‚   β”œβ”€β”€ chats/            # Chat types (normal, important, session)
β”‚   β”‚   β”‚   β”œβ”€β”€ media/            # WebRTC and video processing
β”‚   β”‚   β”‚   └── storage/          # IPFS integration
β”‚   β”‚   └── elx_web/              # Web layer
β”‚   β”œβ”€β”€ config/                   # Configuration files
β”‚   β”œβ”€β”€ assets/                   # Frontend assets
β”‚   └── test/                     # Test suite
└── PRust/                        # Rust performance layer
    β”œβ”€β”€ src/
    β”‚   β”œβ”€β”€ main.rs               # Application entry point
    β”‚   β”œβ”€β”€ actix_server.rs      # REST API server
    β”‚   β”œβ”€β”€ webrtc.rs             # WebRTC manager
    β”‚   β”œβ”€β”€ audio_processor.rs    # Audio processing
    β”‚   β”œβ”€β”€ ipfs_handler.rs       # IPFS operations
    β”‚   β”œβ”€β”€ tokio_runtime.rs      # Async message queuing
    β”‚   └── bot.rs                # Discord bot
    └── Cargo.toml                # Rust dependencies

πŸ› οΈ Installation & Setup

Prerequisites

  • Elixir: 1.14+ with Erlang OTP 25+
  • Rust: 1.70+ with Cargo
  • PostgreSQL: 13+
  • Node.js: 18+ (for assets)
  • IPFS: Local node or Infura API
  • Discord Bot Token (optional)

Backend Setup (Elixir)

# Navigate to Elixir project
cd elx

# Install dependencies
mix deps.get

# Create and migrate database
mix ecto.setup

# Install Node.js dependencies
npm install --prefix assets

# Start Phoenix server
mix phx.server

Visit localhost:4000 to access the web interface.

Performance Layer Setup (Rust)

# Navigate to Rust project
cd PRust

# Install dependencies
cargo build

# Set environment variables
export DISCORD_TOKEN="your_discord_bot_token"
export IPFS_API_URL="http://localhost:5001"  # or Infura URL

# Run the server
cargo run

The Rust layer will start on port 8080 with the REST API.

πŸš€ Usage

Starting the Application

  1. Start Elixir Backend:

    cd elx && mix phx.server
  2. Start Rust Performance Layer:

    cd PRust && cargo run
  3. Access Interfaces:

API Endpoints

Messaging

  • POST /api/message - Send text message
  • POST /api/message/ephemeral - Send self-destructing message with timer
  • POST /api/voice - Send voice message
  • POST /api/file - Send file with IPFS storage
  • GET /api/smart_replies/{message_id} - Get AI-powered reply suggestions

WebRTC & Calls

  • POST /api/webrtc/start_call - Initiate voice/video call
  • POST /api/webrtc/end_call - End active call
  • POST /api/whiteboard/create - Create collaborative whiteboard in call
  • GET /api/whiteboard/{call_id} - Access whiteboard for active call

IPFS Storage

  • POST /api/ipfs/upload - Upload file to IPFS
  • GET /api/ipfs/download/{hash} - Download from IPFS

Translation & Moderation

  • POST /api/translate - Translate message to target language
  • POST /api/moderate - Analyze message for sentiment/toxicity
  • GET /api/moderation/report - Get moderation analytics

Organization Groups

  • POST /api/groups/organization - Create anonymous organization group
  • POST /api/groups/{group_id}/message - Send anonymous message to org group

Bot Commands

  • !ping - Check bot status
  • !status - Get system status
  • !help - Show available commands
  • !translate [lang] [text] - Translate text to specified language
  • !whiteboard - Create collaborative whiteboard in channel
  • !smart_reply - Get AI reply suggestions for last message
  • !schedule [time] [message] - Schedule message for future delivery
  • !schedule_list - List all your scheduled messages
  • !schedule_cancel [id] - Cancel a scheduled message

πŸ”§ Configuration

Environment Variables

Elixir (.env)

DATABASE_URL=postgresql://user:pass@localhost/elx_dev
SECRET_KEY_BASE=your_secret_key
IPFS_API_URL=http://localhost:5001

Rust (.env)

DISCORD_TOKEN=your_discord_token
IPFS_API_URL=http://localhost:5001
RUST_LOG=info

Voice Profiles

The application supports multiple voice modulation profiles:

  • male_us: Standard US male voice
  • male_europe: European male accent
  • female_brazil: Brazilian female voice
  • female_east_asia: East Asian female voice

🎯 Key Features Explained

Chat Types

The application supports three distinct chat types with different behaviors and lifecycles:

  • Normal Chat: Standard messaging with 24-hour message retention. Messages are delivered in real-time when possible, with P2P fallback for offline delivery.
  • Important Chat: Priority messaging that never expires. Features delivery confirmation, escalation workflows, and guaranteed delivery even for offline recipients.
  • Session Chat: Temporary conversations with 5-minute auto-cleanup. Perfect for quick, ephemeral interactions that self-destruct after a short time.

Organization Groups

  • Anonymous Communication: Groups marked as "organization" type maintain sender anonymity
  • Irreversible: Organization groups cannot be modified or deleted once created
  • Secure Collaboration: Enables confidential team communication without revealing individual identities
  • Audit Trail: All messages are logged while preserving anonymity

Offline P2P Messaging

  • Messages are queued when recipients are offline
  • Direct P2P delivery when peers come online
  • High-speed file transfer (1GB in 5 seconds target)
  • Automatic retry with exponential backoff

Advanced Audio Processing

  • Voice Modulation: Real-time voice changing with pitch/formant shifting
  • Noise Cancellation: Multi-algorithm noise reduction
  • Quality Enhancement: Dynamic range compression and equalization
  • Opus Codec: Low-latency audio compression

Content Moderation

  • Malware Scanning: Pattern-based threat detection
  • NSFW Content: Image and video analysis
  • Text Filtering: Inappropriate content detection
  • Private Data: Email/phone/credit card detection

Decentralized Storage

  • IPFS Integration: Content-addressed storage
  • Encryption: AES-256-GCM file encryption
  • Compression: Zstd compression for efficiency
  • Optimization: Automatic image/video optimization

Self-Destructing Messages

  • Ephemeral Messaging: Messages automatically delete after configurable timers (seconds to weeks)
  • E2EE Guarantees: End-to-end encryption maintained throughout message lifecycle
  • Decentralized Routing: Messages routed through P2P networks before self-destruction
  • Timer Options: Flexible timing from instant deletion to extended retention periods
  • Screenshot Protection: Advanced anti-screenshot measures for sensitive communications

Collaborative Whiteboards

  • Embedded Drawing Tools: Integrated whiteboards in channels and video calls
  • Real-time Collaboration: Multi-user simultaneous editing and brainstorming
  • Channel Integration: Whiteboards launched via slash commands with permission inheritance
  • Browser-Based Canvases: No additional installations required for participants
  • Video Call Integration: Whiteboards accessible during voice/video sessions

Sentiment-Aware Moderation

  • LLM-Powered Analysis: Advanced language models for context-aware content review
  • Toxicity Detection: Multi-language toxicity scoring (50+ languages supported)
  • Sentiment Scoring: Automated severity levels (Low-Critical) with smart responses
  • Automated Actions: Auto-nudge, cool-down periods, or moderator escalation
  • Code-Switching Detection: Identifies abuse attempts across multiple languages

Real-time Translation

  • Automatic Translation: Instant translation of incoming and outgoing messages
  • Multilingual Support: Seamless communication across language barriers
  • Context Preservation: Maintains conversation flow and intent during translation
  • Inline Translation: Translations appear instantly without leaving chat interface
  • Global Communication: Enables worldwide collaboration without language constraints

Smart Message Scheduling

  • User-Defined Send Times: Set specific times for messages to be delivered to receivers
  • Universal Availability: Works in all chat sections (Normal, Important, Session, Group chats)
  • AI-Powered Optimization: Intelligent suggestions for optimal send times based on recipient behavior
  • Timezone Intelligence: Automatic timezone handling for global messaging
  • Delivery Confirmation: Real-time tracking and confirmation of message delivery
  • Smart Retry Logic: Automatic retry with exponential backoff for failed deliveries
  • Privacy-Aware: User-controlled scheduling preferences and analytics
  • Engagement Analytics: Success rate tracking and delivery performance metrics

AI-Powered Smart Replies

  • Context-Aware Suggestions: LLM-generated response suggestions based on conversation history
  • Workflow Automation: Smart routing to support, ticket logging, or specialized responses
  • Professional Responses: Polished reply suggestions for business communications
  • Privacy-First: All processing respects end-to-end encryption boundaries
  • Customizable Suggestions: Adaptable to different communication styles and contexts

Anti-Screenshot Watermarking

  • OS-Level Screenshot Blocking: Native platform integration to prevent unauthorized screenshots on iOS and Android
  • Dynamic User-Specific Watermarks: Real-time generation of unique, user-specific visual watermarks
  • Screen Recording Prevention: Detection and blocking of screen mirroring and recording attempts
  • App Switcher Protection: Prevention of content capture through app switching interfaces
  • Forensic Watermarking: Invisible digital signatures for tracing leaked content back to source
  • Multi-Layered Protection: Frontend and backend integration for comprehensive content security
  • Real-Time Updates: Dynamic watermark rotation to prevent circumvention attempts

Rich Presence Indicators

  • Activity-Based Status Updates: Automatic status changes based on user activities (typing, in meeting, etc.)
  • Location-Aware Presence: Optional location sharing with privacy controls (approximate, city-level, or disabled)
  • Meeting Status Synchronization: Integration with calendar systems for automatic "in meeting" status
  • Custom Availability Settings: User-defined availability states with custom messages and expiration times
  • Contextual Presence Information: Rich metadata about current activity and engagement level
  • Privacy-Controlled Sharing: Granular privacy settings for presence information sharing
  • Real-Time Broadcasting: Instant presence updates via Phoenix Channels to all connected clients

Voice-Activated Commands

  • "Hey PChat" Wake Word: Customizable wake word detection with high accuracy speech recognition
  • Voice Message Dictation: Hands-free message composition and sending
  • Smart Query Responses: Natural language processing for intelligent command interpretation
  • Privacy-Aware Processing: Configurable privacy modes (high, standard, offline) for voice data handling
  • Custom Wake Word Support: Personalized wake words with validation and security checks
  • Session Management: Intelligent voice session handling with automatic timeouts and cleanup
  • Command History: Voice command logging and analytics for usage optimization

Zero-Knowledge Authentication

  • Password-Less Authentication: Schnorr zero-knowledge proofs for secure login without credential exposure
  • Anonymous Group Verification: Membership verification without revealing individual identities
  • KYC-Compliant Privacy: Selective disclosure of attributes for regulatory compliance
  • Anti-Phishing Protection: Cryptographic domain verification to prevent phishing attacks
  • Challenge-Response Protocol: Time-limited authentication challenges with automatic cleanup
  • Session Token Management: Secure session creation with configurable expiration
  • Multi-Factor Integration: Combines ZKP with existing authentication methods for enhanced security

πŸ§ͺ Testing

Elixir Tests

cd elx
mix test

Rust Tests

cd PRust
cargo test

Integration Tests

# Run both test suites
cd elx && mix test && cd ../PRust && cargo test

πŸ“Š Performance Benchmarks

  • Message Delivery: < 100ms for online peers
  • P2P Transfer: 1GB file in < 5 seconds
  • Concurrent Users: 10,000+ simultaneous connections
  • Audio Latency: < 50ms end-to-end
  • Storage: Decentralized with IPFS replication

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Elixir: Follow Phoenix conventions and use proper supervision trees
  • Rust: Use async/await patterns and proper error handling
  • Testing: Maintain >80% test coverage
  • Documentation: Update README and inline docs for new features

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Phoenix Framework: For the robust Elixir web framework
  • Actix: For high-performance Rust web services
  • IPFS: For decentralized storage capabilities
  • WebRTC: For real-time communication standards
  • Tokio: For async runtime excellence

πŸ“ž Support


Built with ❀️ using Elixir, Phoenix, Rust, and modern web technologies

About

PChat is a high-performance, decentralized chat application built with Elixir/Phoenix and Rust. It offers real-time messaging, WebRTC voice/video calls, offline P2P delivery, IPFS-based file storage, AI-powered features, and advanced security with end-to-end encryption. It supports multiple platforms (web, mobile, Discord bot).

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages