Messaging System
Real-time communication platform for drivers and passengers in WI-CARPOOL
Overview
The WI-CARPOOL messaging system provides secure, real-time communication between drivers and passengers. Built with modern web technologies, it ensures seamless coordination for ride planning and execution.
💬 Real-time Chat
Instant messaging with automatic updates and push notifications.
🔒 Secure Communication
Platform-mediated messaging that protects user privacy.
📱 Cross-platform
Consistent messaging experience across web and mobile devices.
📷 Media Sharing
Share images, locations, and other media content securely.
Chat Service Architecture
Service Implementation
The messaging system is built using a dedicated chat service that handles all communication:
Chat Service Structure
// Location: src/api/services/chatService.ts
export const chatService = {
// Get list of conversations for current user
getConversationList: () => apiCall(AppConstants.conversationListUri),
// Start new conversation
startConversation: (params) => apiCall(AppConstants.startConversationUri, params),
// Search conversations
searchConversationList: (query) =>
apiCall(AppConstants.searchConversationListUri, { query }),
// Get message history
getMessageList: (conversationId) =>
apiCall(AppConstants.messageListUri, { conversation_id: conversationId }),
// Send new message
sendMessage: (conversationId, message) =>
apiCall(AppConstants.sendMessageUri, {
conversation_id: conversationId,
message: message
}),
// Pusher authentication for real-time features
pusherAuth: (channel, socketId) =>
apiCall(AppConstants.pusherAuth, { channel_name: channel, socket_id: socketId })
};
Conversation Management
Conversation List
Users can view and manage all their active conversations:
Conversation List Implementation
// Location: src/pages/driver/Messages.tsx or src/pages/passenger/Messages.tsx
const Messages = () => {
const { data: conversations, isLoading } = useQuery({
queryKey: ['conversations'],
queryFn: () => chatService.getConversationList(),
refetchInterval: 30000 // Refetch every 30 seconds
});
const startNewConversation = async (userId) => {
const response = await chatService.startConversation({
receiver_id: userId,
message: "Hello! I'd like to discuss the ride details."
});
// Handle new conversation creation
};
};
Conversation Features
- Active Conversations - List of ongoing chats with other users
- Last Message Preview - Quick view of the most recent message
- Unread Indicators - Visual notifications for new messages
- Conversation Search - Find specific conversations by participant name
- Archive Functionality - Archive completed ride conversations
Starting Conversations
Conversations are typically initiated in the context of ride bookings:
1. Ride Context
Conversations start when passengers book rides or drivers accept bookings.
2. Automatic Creation
The system automatically creates conversation channels for ride participants.
3. Initial Messages
Welcome messages with ride details are sent to establish context.
4. Ongoing Communication
Participants can exchange messages throughout the ride lifecycle.
Real-time Messaging
Chat Interface
The chat interface provides a modern messaging experience:
Chat Component Implementation
// Location: src/pages/driver/Chat.tsx or src/pages/passenger/Chat.tsx
const Chat = () => {
const { conversationId } = useParams();
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState('');
// Load message history
const { data: messageHistory } = useQuery({
queryKey: ['messages', conversationId],
queryFn: () => chatService.getMessageList(conversationId),
enabled: !!conversationId
});
// Send message function
const handleSendMessage = async () => {
if (!newMessage.trim()) return;
await chatService.sendMessage(conversationId, newMessage);
setNewMessage('');
// Optimistically update UI
setMessages(prev => [...prev, {
id: Date.now(),
message: newMessage,
sender_id: user.id,
created_at: new Date().toISOString()
}]);
};
};
Chat Features
- Message History - Complete conversation history with timestamps
- Real-time Updates - Instant message delivery and receipt
- Message Status - Delivery and read receipt indicators
- Typing Indicators - Show when other participants are typing
- Emoji Support - Rich text messaging with emoji reactions
- Message Timestamps - Clear timing information for all messages
Message Status System
Message Status Component
Visual indicators show message delivery and read status:
Message Status Implementation
// Location: src/components/chat/MessageStatus.tsx
interface MessageStatusProps {
status: 'sending' | 'sent' | 'delivered' | 'read';
timestamp?: string;
}
export const MessageStatus: React.FC<MessageStatusProps> = ({ status, timestamp }) => {
const getStatusIcon = () => {
switch (status) {
case 'sending':
return <Clock className="w-4 h-4 text-gray-400" />;
case 'sent':
return <Check className="w-4 h-4 text-gray-500" />;
case 'delivered':
return <CheckCheck className="w-4 h-4 text-gray-500" />;
case 'read':
return <CheckCheck className="w-4 h-4 text-blue-500" />;
default:
return null;
}
};
return (
<div className="flex items-center gap-1 text-xs">
{timestamp && <span className="text-gray-500">{timestamp}</span>}
{getStatusIcon()}
</div>
);
};
Status Types
- Sending - Message is being transmitted to the server
- Sent - Message successfully delivered to server
- Delivered - Message delivered to recipient's device
- Read - Recipient has viewed the message
Pusher Integration
Real-time Communication
The system uses Pusher for real-time messaging capabilities:
Pusher Configuration
// Real-time messaging setup
const initializePusher = () => {
const pusher = new Pusher(PUSHER_KEY, {
cluster: PUSHER_CLUSTER,
authEndpoint: AppConstants.pusherAuth,
auth: {
headers: {
Authorization: `Bearer ${user.token}`
}
}
});
// Subscribe to user's private channel
const channel = pusher.subscribe(`private-user-${user.id}`);
// Listen for new messages
channel.bind('new-message', (data) => {
// Update message list in real-time
updateMessages(data.message);
});
// Listen for message status updates
channel.bind('message-status', (data) => {
// Update message status indicators
updateMessageStatus(data.message_id, data.status);
});
};
Real-time Events
- New Messages - Instant delivery of incoming messages
- Message Status Updates - Real-time status change notifications
- Typing Indicators - Show when other users are composing messages
- Online Status - Display user availability and activity
- Conversation Updates - New conversation notifications
Privacy & Security
🔐 Platform-mediated
All communication goes through the platform, protecting personal contact information.
🛡️ Message Encryption
Messages are encrypted in transit and stored securely on servers.
📋 Content Moderation
Automated and manual content moderation to ensure appropriate communication.
🚨 Report System
Users can report inappropriate messages or behavior for review.
Privacy Features
- Anonymous Messaging - Users communicate without sharing personal phone numbers
- Conversation Archiving - Automatic archival of completed ride conversations
- Data Retention - Clear policies on message storage and deletion
- Block/Mute Options - Users can block or mute problematic contacts
- Privacy Controls - Granular control over who can initiate conversations
Mobile Experience
Progressive Web App Features
The messaging system is optimized for mobile use through PWA capabilities:
📱 Push Notifications
Receive notifications for new messages even when the app is closed.
💾 Offline Support
View conversation history and compose messages while offline.
📷 Camera Integration
Take and share photos directly within conversations.
📍 Location Sharing
Share current location for pickup coordination.
Responsive Design
The chat interface adapts seamlessly to different screen sizes:
- Mobile-first Design - Optimized for touch interaction and small screens
- Keyboard Handling - Smart keyboard behavior with auto-resize chat area
- Gesture Support - Swipe gestures for navigation and message actions
- Voice Input - Speech-to-text functionality for hands-free messaging
Integration with Ride Flow
Context-aware Messaging
Messages are automatically contextualized with ride information:
Ride Context Integration
// Automatic ride context in messages
const sendRideUpdateMessage = async (rideId, updateType) => {
const rideDetails = await rideService.getRideDetails(rideId);
const contextMessage = {
type: 'ride_update',
ride_id: rideId,
update_type: updateType,
pickup_location: rideDetails.pickup_location,
drop_location: rideDetails.drop_location,
departure_time: rideDetails.departure_time
};
await chatService.sendMessage(conversationId, contextMessage);
};
Ride-related Message Types
- Booking Confirmations - Automatic messages when rides are booked
- Departure Alerts - Notifications when drivers are en route
- Location Updates - Real-time location sharing during trips
- Completion Confirmations - Messages when rides are completed
- Rating Reminders - Prompts to rate the ride experience
Smart Notifications
Intelligent notification system that adapts to user preferences and ride status:
⚡ Priority Messages
Critical ride updates receive priority notification treatment.
⏰ Time-sensitive Alerts
Departure and arrival notifications sent at optimal times.
🔇 Smart Muting
Automatic muting of non-critical messages during rides.
📊 Delivery Optimization
Notifications optimized based on user activity patterns.
Performance & Optimization
Message Loading Strategy
Efficient message loading to ensure smooth user experience:
Optimized Message Loading
// Pagination and lazy loading for messages
const useMessages = (conversationId) => {
const [messages, setMessages] = useState([]);
const [hasMore, setHasMore] = useState(true);
const [loading, setLoading] = useState(false);
const loadMoreMessages = async () => {
if (loading || !hasMore) return;
setLoading(true);
const olderMessages = await chatService.getMessageList(
conversationId,
{ before: messages[0]?.id }
);
if (olderMessages.length < 20) setHasMore(false);
setMessages(prev => [...olderMessages, ...prev]);
setLoading(false);
};
return { messages, loadMoreMessages, hasMore, loading };
};
Performance Features
- Message Pagination - Load messages in chunks to reduce initial load time
- Virtual Scrolling - Efficiently render large conversation histories
- Image Optimization - Automatic compression and resizing of shared images
- Caching Strategy - Smart caching of conversations and message history
- Connection Management - Efficient WebSocket connection handling
API Endpoints
Endpoint | Method | Purpose | Parameters |
---|---|---|---|
get_conversation_list | GET | Fetch user's conversations | token (auth) |
start_conversation | POST | Create new conversation | receiver_id, initial_message |
search_conversation_list | POST | Search conversations | query, filters |
message_list | GET | Get message history | conversation_id, pagination |
send_message | POST | Send new message | conversation_id, message, type |
pusher_auth | POST | Authenticate Pusher connection | channel_name, socket_id |
Troubleshooting
Common Issues
Messages Not Sending
- Check internet connection stability
- Verify authentication token validity
- Ensure conversation ID is valid
- Check for API rate limiting
Real-time Updates Not Working
- Verify Pusher connection status
- Check WebSocket support in browser
- Ensure proper channel subscription
- Verify authentication for private channels
Message History Loading Issues
- Check conversation access permissions
- Verify pagination parameters
- Clear conversation cache and retry
- Check for API response errors