📊 Post View Tracking WebSocket API Documentation

Overview: This WebSocket API provides efficient, real-time tracking of post views. Views are recorded asynchronously using Celery tasks to ensure high performance and prevent duplicate tracking.

🔌 WebSocket Connection

WS Endpoint: ws://api.qsocial.net/ws/posts/views/
Secure: wss://api.qsocial.net/ws/posts/views/

Authentication

Authentication is handled via JWT token in the WebSocket connection. Include the token in the connection URL:

ws://api.qsocial.net/ws/posts/views/?token=YOUR_JWT_TOKEN
âš ī¸ Important: The token must be included in the connection URL query parameters. The WebSocket connection will be rejected (code 4001) if the user is not authenticated.

Connection Flow

  1. Client establishes WebSocket connection with JWT token
  2. Server validates token and authenticates user
  3. Server sends connection success message
  4. Client can now send view events

📤 Events to Send (Client → Server)

1. View Post Event

Send this event when a user views a post.

{ "type": "view_post", "post_id": 123 }
Field Type Required Description
type string Yes Must be "view_post"
post_id integer Yes ID of the post being viewed
✅ Duplicate Prevention: Views from the same user on the same post are automatically prevented. The system uses a unique constraint on (user, post) to ensure no duplicate views are recorded.
â„šī¸ Own Posts: Views on posts authored by the viewing user are not recorded. The server will respond with "recorded": false and a message indicating the view was not recorded.

đŸ“Ĩ Events to Receive (Server → Client)

1. Connection Success

Sent immediately after successful WebSocket connection.

{ "type": "connection_success", "message": "Connected to post view tracking", "user_id": 456 }

2. View Recorded

Sent after successfully processing a view event.

{ "type": "view_recorded", "post_id": 123, "recorded": true, "message": "View recorded successfully" }

3. View Skipped (Own Post)

Sent when user views their own post (not recorded).

{ "type": "view_recorded", "post_id": 123, "recorded": false, "message": "View not recorded for own posts" }

4. Error

Sent when an error occurs.

{ "type": "error", "message": "Error message here" }

⚡ Performance & Efficiency

Asynchronous Processing

View recording is handled asynchronously using Celery tasks. This means:

Database Optimization

View Count Updates

The view_count field on the Post model is automatically updated when views are recorded. This field is returned in all post-related API endpoints.

📱 Mobile Implementation Example

Flutter/Dart Example

// Connect to WebSocket final token = await getAuthToken(); // Get JWT token final wsUrl = 'wss://api.qsocial.net/ws/posts/views/?token=$token'; final channel = IOWebSocketChannel.connect(Uri.parse(wsUrl)); // Listen for messages channel.stream.listen( (message) { final data = jsonDecode(message); if (data['type'] == 'connection_success') { print('Connected to post view tracking'); } else if (data['type'] == 'view_recorded') { print('View recorded: ${data['post_id']}'); } }, onError: (error) => print('WebSocket error: $error'), ); // Send view event when user views a post void recordPostView(int postId) { channel.sink.add(jsonEncode({ 'type': 'view_post', 'post_id': postId, })); }

React Native Example

// Using react-native-websocket or similar library import WebSocket from 'react-native-websocket'; const token = await getAuthToken(); const ws = new WebSocket(`wss://api.qsocial.net/ws/posts/views/?token=${token}`); ws.onopen = () => { console.log('Connected to post view tracking'); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'view_recorded') { console.log('View recorded:', data.post_id); } }; // Send view event const recordPostView = (postId) => { ws.send(JSON.stringify({ type: 'view_post', post_id: postId, })); };

🔍 API Endpoints Returning View Count

All post-related endpoints return the view_count field:

Example Response

{ "id": 123, "author": { ... }, "content": "Post content here", "like_count": 10, "comment_count": 5, "view_count": 150, ← View count "created_at": "2024-11-30T10:00:00Z" }

🚨 Error Codes

Code Description
4001 Unauthorized - User not authenticated
4003 Forbidden - Post not accessible
1011 Internal Server Error

✅ Best Practices

  1. Connection Management: Maintain a single WebSocket connection per user session
  2. Reconnection: Implement automatic reconnection logic with exponential backoff
  3. View Triggering: Trigger view events when a post becomes visible (e.g., in viewport)
  4. Debouncing: Consider debouncing rapid view events for the same post
  5. Error Handling: Always handle error messages and connection failures gracefully
âš ī¸ Important Notes: