# du.pe - API Documentation ## 🔌 API Overview The du.pe server provides a RESTful API with WebSocket support for managing torrents, streaming media, and handling file operations. The API is designed to be simple, intuitive, and provides real-time updates through WebSocket connections. **Base URL**: `http://localhost:3001` (configurable via environment) ## 📡 WebSocket Connection ### **Connection Endpoint** ``` ws://localhost:3001/?token={auth_token} ``` ### **WebSocket Events** #### **Progress Updates** ```json { "type": "progress", "torrents": [ { "infoHash": "abc123...", "name": "Example Movie", "progress": 0.75, "downloadSpeed": 1048576, "uploadSpeed": 524288, "numPeers": 15, "state": "downloading", "timeRemaining": 1800 } ] } ``` #### **File Updates** ```json { "type": "fileUpdate", "action": "added|removed|modified", "path": "/downloads/example/", "mediaType": "movie|tvshow|file" } ``` ## 🛣️ REST API Endpoints ### **Torrent Management** #### **GET /api/torrents** **Description**: Retrieve list of active torrents and their status **Response**: ```json { "torrents": [ { "infoHash": "abc123def456...", "name": "Example Movie 2024", "progress": 0.85, "downloadSpeed": 2097152, "uploadSpeed": 1048576, "numPeers": 25, "state": "downloading", "timeRemaining": 600, "files": [ { "name": "movie.mp4", "length": 1073741824, "path": "/downloads/example/movie.mp4", "type": "video" } ], "magnetURI": "magnet:?xt=urn:btih:abc123...", "added": "2024-01-15T10:30:00.000Z" } ] } ``` **Response Codes**: - `200` - Success - `500` - Server error --- #### **POST /api/transfer** **Description**: Add a torrent via file upload **Content-Type**: `multipart/form-data` **Request Body**: ``` torrent: [file] - .torrent file ``` **Response**: ```json { "success": true, "infoHash": "abc123def456...", "name": "Uploaded Torrent Name" } ``` **Response Codes**: - `200` - Torrent added successfully - `400` - Invalid torrent file - `500` - Server error --- #### **POST /api/magnet** **Description**: Add a torrent via magnet link **Content-Type**: `application/json` **Request Body**: ```json { "magnet": "magnet:?xt=urn:btih:abc123def456..." } ``` **Response**: ```json { "success": true, "infoHash": "abc123def456...", "name": "Torrent Name from Magnet" } ``` **Response Codes**: - `200` - Torrent added successfully - `400` - Invalid magnet link - `500` - Server error --- #### **DELETE /api/torrents/:infoHash** **Description**: Remove a torrent and optionally delete downloaded files **Request Parameters**: - `infoHash` (path): Torrent info hash - `deleteFiles` (query, optional): `true` to delete downloaded files **Response**: ```json { "success": true, "message": "Torrent removed successfully" } ``` **Response Codes**: - `200` - Torrent removed successfully - `404` - Torrent not found - `500` - Server error --- ### **File Streaming** #### **GET /stream/:infoHash/:fileIndex** **Description**: Stream a file from a torrent **Request Parameters**: - `infoHash` (path): Torrent info hash - `fileIndex` (path): Index of the file within the torrent - `range` (header, optional): HTTP Range header for partial content **Response**: - Binary file stream with appropriate MIME headers - Supports HTTP Range requests for seeking in video files **Response Codes**: - `200` - Streaming successfully - `206` - Partial content (range requests) - `404` - File not found - `500` - Server error **Example Usage**: ```javascript // HTML5 Video Player ``` --- ### **Media Library** #### **GET /api/movies** **Description**: Retrieve movie library with metadata **Query Parameters**: - `page` (optional): Page number for pagination - `limit` (optional): Items per page - `search` (optional): Search term - `genre` (optional): Filter by genre - `year` (optional): Filter by year **Response**: ```json { "movies": [ { "id": "movie_123", "title": "Example Movie", "year": 2024, "runtime": 120, "rating": 8.5, "genres": ["Action", "Drama"], "poster": "/cache/movie_data/123/poster.jpg", "backdrop": "/cache/movie_data/123/backdrop.jpg", "overview": "Movie description...", "filePath": "/downloads/example/movie.mp4", "fileSize": 1073741824, "added": "2024-01-15T10:30:00.000Z", "watched": false, "thumbnail": "/cache/thumbnails/videos/123/movie.jpg" } ], "pagination": { "page": 1, "limit": 20, "total": 45, "totalPages": 3 } } ``` --- #### **GET /api/tvshows** **Description**: Retrieve TV show library with metadata **Query Parameters**: - `page` (optional): Page number for pagination - `limit` (optional): Items per page - `search` (optional): Search term **Response**: ```json { "shows": [ { "id": "show_456", "title": "Example TV Series", "year": 2023, "rating": 9.0, "seasons": 2, "poster": "/cache/tv_data/456/poster.jpg", "backdrop": "/cache/tv_data/456/backdrop.jpg", "overview": "Series description...", "episodes": [ { "season": 1, "episode": 1, "title": "Pilot Episode", "overview": "Episode description...", "airDate": "2023-01-15", "filePath": "/downloads/example/series/s01e01.mp4", "thumbnail": "/cache/tv_data/456/episodes/s01e01.jpg" } ] } ], "pagination": { "page": 1, "limit": 20, "total": 12, "totalPages": 1 } } ``` --- #### **GET /api/files** **Description**: Browse downloaded files and folders **Query Parameters**: - `path` (optional): Directory path to browse (default: root downloads) - `type` (optional): Filter by file type (`video`, `audio`, `image`, `document`) **Response**: ```json { "path": "/downloads/", "parent": "..", "items": [ { "name": "Example Folder", "type": "directory", "path": "/downloads/Example Folder/", "size": null, "modified": "2024-01-15T10:30:00.000Z", "count": 5 }, { "name": "movie.mp4", "type": "file", "path": "/downloads/movie.mp4", "size": 1073741824, "modified": "2024-01-15T10:30:00.000Z", "mimeType": "video/mp4", "thumbnail": "/cache/thumbnails/videos/abc123/movie.jpg" } ] } ``` --- ### **Search Functionality** #### **GET /api/search** **Description**: Search across torrents, files, and media library **Query Parameters**: - `q` (required): Search query - `type` (optional): Search scope (`all`, `torrents`, `movies`, `tvshows`, `files`) - `limit` (optional): Maximum results (default: 50) **Response**: ```json { "query": "example", "results": { "torrents": [ { "infoHash": "abc123...", "name": "Example Torrent", "progress": 0.75, "state": "downloading" } ], "movies": [ { "id": "movie_123", "title": "Example Movie", "year": 2024, "poster": "/cache/movie_data/123/poster.jpg" } ], "tvshows": [], "files": [ { "name": "example.txt", "path": "/downloads/example.txt", "size": 1024, "type": "file" } ] }, "total": 3 } ``` --- ### **System Information** #### **GET /api/system/info** **Description**: Get system information and status **Response**: ```json { "version": "1.2.0", "uptime": 86400, "torrents": { "active": 3, "completed": 15, "total": 18 }, "storage": { "total": 1099511627776, "used": 536870912000, "free": 562641715776, "downloads": 500000000000, "cache": 36870912000 }, "network": { "downloadSpeed": 2097152, "uploadSpeed": 1048576 } } ``` --- #### **GET /api/system/disk** **Description**: Get detailed disk usage information **Response**: ```json { "downloads": { "path": "/app/server/downloads", "total": 1000000000000, "used": 500000000000, "free": 500000000000, "percentage": 50 }, "cache": { "path": "/app/server/cache", "total": 100000000000, "used": 20000000000, "free": 80000000000, "percentage": 20 } } ``` --- ### **Trash Management** #### **GET /api/trash** **Description**: List items in trash **Response**: ```json { "items": [ { "id": "trash_123", "originalPath": "/downloads/example.mp4", "name": "example.mp4", "size": 1073741824, "deleted": "2024-01-15T10:30:00.000Z", "type": "file" } ], "total": 1, "totalSize": 1073741824 } ``` --- #### **POST /api/trash/:id/restore** **Description**: Restore item from trash **Request Parameters**: - `id` (path): Trash item ID **Response**: ```json { "success": true, "message": "Item restored successfully", "restoredPath": "/downloads/example.mp4" } ``` --- #### **DELETE /api/trash/:id** **Description**: Permanently delete item from trash **Request Parameters**: - `id` (path): Trash item ID **Response**: ```json { "success": true, "message": "Item permanently deleted" } ``` --- #### **DELETE /api/trash** **Description**: Empty trash (permanently delete all items) **Response**: ```json { "success": true, "message": "Trash emptied successfully", "deletedCount": 5 } ``` --- ## 🔒 Authentication (Planned) ### **Token-Based Authentication** Currently, the application uses basic token authentication. Full authentication system is planned for future versions. **Headers**: ``` Authorization: Bearer {token} ``` ### **Login Endpoint (Planned)** ``` POST /api/auth/login ``` ### **Logout Endpoint (Planned)** ``` POST /api/auth/logout ``` --- ## 📊 Error Handling ### **Standard Error Response Format** ```json { "error": { "code": "VALIDATION_ERROR", "message": "Invalid magnet link format", "details": "The provided magnet link is not properly formatted" } } ``` ### **Common Error Codes** - `400 Bad Request` - Invalid input parameters - `401 Unauthorized` - Authentication required - `403 Forbidden` - Insufficient permissions - `404 Not Found` - Resource not found - `429 Too Many Requests` - Rate limit exceeded - `500 Internal Server Error` - Server-side error ### **WebSocket Error Events** ```json { "type": "error", "code": "TORRENT_ERROR", "message": "Failed to add torrent", "details": "Invalid torrent file format" } ``` --- ## 🔄 Rate Limiting ### **Current Limits** - API requests: No current limits (planned) - File uploads: 100MB per file - Concurrent torrents: No hard limit - WebSocket connections: Standard browser limits ### **Planned Enhancements** - API rate limiting by IP/user - Upload size limits - Concurrent download limits - Connection throttling --- ## 🧭 Usage Examples ### **JavaScript/TypeScript Client** ```javascript // API client setup const API_BASE = 'http://localhost:3001'; class DupeAPI { constructor(apiUrl) { this.apiUrl = apiUrl; } async getTorrents() { const response = await fetch(`${this.apiUrl}/api/torrents`); return response.json(); } async addMagnet(magnetLink) { const response = await fetch(`${this.apiUrl}/api/magnet`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ magnet: magnetLink }) }); return response.json(); } async getMovies(page = 1, limit = 20) { const params = new URLSearchParams({ page, limit }); const response = await fetch(`${this.apiUrl}/api/movies?${params}`); return response.json(); } connectWebSocket(token) { const ws = new WebSocket(`${this.apiUrl.replace('http', 'ws')}?token=${token}`); ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'progress') { // Handle progress updates console.log('Torrent progress:', data.torrents); } }; return ws; } } // Usage const api = new DupeAPI(API_BASE); const torrents = await api.getTorrents(); const ws = api.connectWebSocket('your-token'); ``` ### **cURL Examples** ```bash # Get torrents curl -X GET http://localhost:3001/api/torrents # Add magnet link curl -X POST http://localhost:3001/api/magnet \ -H "Content-Type: application/json" \ -d '{"magnet":"magnet:?xt=urn:btih:abc123..."}' # Upload torrent file curl -X POST http://localhost:3001/api/transfer \ -F "torrent=@/path/to/file.torrent" # Get system info curl -X GET http://localhost:3001/api/system/info ``` --- ## 📚 Cross-References ### **Related Documentation** - [Project Structure](./project-structure.md) - Overall architecture overview - [Component Documentation](./components.md) - Frontend component details - [Deployment Guide](./deployment.md) - Production setup instructions - [WebSocket Events](./websocket-events.md) - Real-time event reference ### **Implementation Files** - [server/server.js](../server/server.js) - Main API implementation - [client/src/utils/api.js](../client/src/utils/api.js) - Frontend API client - [client/src/stores/](../client/src/stores/) - State management stores --- *This API documentation provides comprehensive coverage of all available endpoints, WebSocket events, and usage patterns. For implementation details and examples, refer to the cross-referenced files and documentation.*