UNPKG

fleeta-api-lib

Version:

A comprehensive library for fleet management applications - API, Auth, Device management

1,711 lines (1,403 loc) 50.2 kB
# 🚀 FleetA API Library [![npm version](https://badge.fury.io/js/fleeta-api-lib.svg)](https://badge.fury.io/js/fleeta-api-lib) [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/) [![React](https://img.shields.io/badge/React-18%2B-blue)](https://reactjs.org/) [![Tree Shaking](https://img.shields.io/badge/Tree%20Shaking-✅-green)](#tree-shaking) A comprehensive TypeScript library for BlackVue Fleeta fleet management applications. Features authentication, device management, live streaming, WebRTC communication, real-time GPS tracking, user & group management, and centralized state management. ## 🆕 What's New in v1.4.0 **🚀 MAJOR UPDATE**: Enhanced User Management API with new permission checking functions, improved Group Management API with better device assignment, and consistent naming conventions throughout ### Multi-Device Provider Fixes: - ✅ Added missing `createMultiDeviceProvider` factory function - ✅ Added missing grid factory functions (`createGrid2x2Provider`, etc.) - ✅ Added missing `MultiDeviceProvider` class export - ✅ Added missing `DeviceStreamManager` and related classes - ✅ Complete Multi-Device Provider API now publicly accessible ### User Management Enhancements: - ✅ **hasPermissions** - Check multiple permissions at once - ✅ **hasMasterPrivileges** - Check if user has Master role privileges - ✅ **hasSubMasterPrivileges** - Check if user has SubMaster role privileges - ✅ **getCloudStorageUsage** - Get cloud storage usage information - ✅ Consolidated user invitation and management into single module - ✅ Enhanced permission validation and role checking ### Group Management Improvements: - ✅ **assignUserToDevice** - Assign users to specific devices within groups - ✅ **unassignUserFromDevice** - Remove user assignments from devices - ✅ **getGroupUsers** - Get users available for device assignment - ✅ **getGroupDevices** - Get group device allocation information - ✅ Unified naming convention (dashcam → device terminology) - ✅ Enhanced group allocation and member management ### Event WebSocket Features: - ✅ Complete Event WebSocket SDK with connection management - ✅ 30+ WebPush event types with categorization - ✅ AWS API Gateway keepalive support (5-minute ping interval) - ✅ Automatic reconnection with exponential backoff - ✅ Image and video file attachment support - ✅ JWT authentication via AuthStore integration ## 🔧 What's Fixed in v1.4.0 **🚀 Complete API Access** - All major API modules fully exported: - ✅ **Multi-Device Provider** - Complete factory functions and classes - ✅ **User Management** - Unified invitation and permission APIs - ✅ **Group Management** - Complete group lifecycle and device assignment - ✅ **Event WebSocket** - Real-time WebPush notifications - ✅ **GPS Data Provider** - High-level GPS data processing - ✅ **Live Provider** - WebRTC streaming with two-way audio ## 🚀 Quick Start ### Installation ```bash npm install fleeta-api-lib ``` ### Peer Dependencies Install required peer dependencies: ```bash npm install react react-dom ``` ### Basic Setup ```tsx // main.tsx or App.tsx - Initialize API endpoints import { useApiEndpointStore } from 'fleeta-api-lib'; // Initialize API endpoints from environment variables useApiEndpointStore.getState().setConfig({ apiGateway: import.meta.env.VITE_API_GATEWAY, iotApiGateway: import.meta.env.VITE_IOT_API_GATEWAY, gpsWebSocketUrl: import.meta.env.VITE_GPS_WEBSOCKET_URL, eventWebSocketUrl: import.meta.env.VITE_EVENT_WEBSOCKET_URL }); ``` ### Environment Variables Set up your `.env` file: ```bash # Required API endpoints VITE_API_GATEWAY=https://your-api-gateway.com VITE_IOT_API_GATEWAY=https://your-iot-api-gateway.com VITE_GPS_WEBSOCKET_URL=wss://your-gps-websocket.com VITE_EVENT_WEBSOCKET_URL=wss://your-event-websocket.com ``` ### Basic Usage Example ```tsx import React, { useEffect, useState } from 'react'; import { login, logout, getDeviceList, createWebRTCProvider, createMapGpsProvider, useAuthStore } from 'fleeta-api-lib'; function MyFleetApp() { const { isAuthenticated, userToken } = useAuthStore(); const [gpsProvider, setGpsProvider] = useState(null); // Login handler const handleLogin = async () => { await login({ email: 'user@example.com', password: 'password' }); }; // Get device list const handleGetDevices = async () => { const deviceList = await getDeviceList(); console.log('Devices:', deviceList.deviceListInfo); console.log('Statistics:', deviceList.groupedData.statistics); }; // Start live view const handleStartLiveView = async () => { const provider = createWebRTCProvider({ deviceId: 'DEVICE123', channel: 'front' }); provider.setCallbacks({ onStreamReceived: (stream) => { // Handle video stream videoElement.srcObject = stream; }, onError: (error) => { console.error('WebRTC error:', error); } }); await provider.connect(); }; // Start GPS tracking const handleStartGpsTracking = () => { const provider = createMapGpsProvider(); // Register for GPS updates provider.registerUpdateCallback((devices) => { console.log('GPS Update:', devices); // Update map markers, etc. }); // Connect to GPS WebSocket provider.connectWebSocket(); // Request GPS data for specific devices provider.requestGpsPsnsMultiLiveView(['DEVICE123', 'DEVICE456']); setGpsProvider(provider); }; return ( <div> {!isAuthenticated ? ( <button onClick={handleLogin}>Login</button> ) : ( <> <button onClick={handleGetDevices}>Get Devices</button> <button onClick={handleStartLiveView}>Start Live View</button> <button onClick={handleStartGpsTracking}>Start GPS Tracking</button> </> )} </div> ); } ``` ## ✨ Features ### 🔐 Authentication Module Complete authentication solution for BlackVue Fleeta: - **Login/Logout** - Email/password authentication with SHA256 encryption - **Password Reset** - Reset password functionality via email - **Auth Store** - Zustand-based persistent state management - **Auto Token Refresh** - Automatic token validation and refresh ### 👥 User Management Module Advanced user invitation and management for fleet teams: - **Member Invitation** - Send email invitations with role assignment - **Role Management** - SubMaster and User role differentiation - **Invitation Tracking** - Monitor invitation status and validity - **Member Deletion** - Remove members with proper cleanup - **Search & Filter** - Advanced member search capabilities - **Multi-App Support** - FleetA and BlackVue login app compatibility - **Permission Management** - Check and set user permissions - **Privilege Validation** - Master/SubMaster privilege checking - **Storage Monitoring** - Cloud storage usage tracking ### 🎯 Group Management Module Complete group management for BlackVue Fleeta fleet organization: - **Group Creation** - Create single or multiple groups with batch support - **Device Assignment** - Assign devices to groups with validation - **SubMaster Management** - Assign SubMasters to manage specific groups - **User-Device Assignment** - Assign users to specific devices within groups - **Group Lifecycle** - Delete, rename, and modify group properties - **Real-time Monitoring** - Track group allocations and device assignments - **Permission Control** - Master-only operations with proper validation ### 📱 Device Management Module Advanced device management for BlackVue fleet: - **Device List API** - Get devices with real-time status and grouping - **Mock Data Support** - Testing with combined mock + real data - **Device Statistics** - Comprehensive device status analytics - **Group Management** - Organize devices into logical groups - **Search & Filter** - Advanced device filtering capabilities ### 📹 Live Streaming Module Real-time video streaming and WebRTC communication: - **WebRTC Provider** - High-level WebRTC interface for UI components - **Live View API** - Device live streaming control (PlayLiveView, StopLiveView) - **Two-Way Audio** - Bidirectional audio communication - **Multi-Camera Support** - Switch between front/rear/interior cameras - **SDK Management** - Automatic loading of Amazon Kinesis WebRTC SDK - **Media Device Support** - Check microphone/speaker availability ### 🎬 Multi-Device Streaming Module Advanced multi-device WebRTC streaming for fleet monitoring: - **Multi-Device Provider** - Manage multiple device streams simultaneously - **Grid Layout Support** - Pre-configured 2x2, 3x3, 4x4 grid layouts - **Connection Pooling** - Efficient WebRTC connection reuse and management - **Quality Management** - Adaptive quality control based on system resources - **Voice Communication** - Two-way audio for individual devices in multi-stream - **Stream Switching** - Real-time channel switching across multiple devices - **Resource Optimization** - Intelligent bandwidth and memory management ### 🌍 GPS Data Provider System Real-time GPS tracking and data management: - **GPS WebSocket SDK** - Low-level GPS WebSocket communication - **GPS Data Provider** - High-level GPS data processing and optimization - **Data Caching** - Intelligent caching with LRU eviction - **Data Filtering** - Advanced filtering by location, speed, status - **Real-time Updates** - Live GPS position updates - **Multi-device Tracking** - Track multiple devices simultaneously - **Group Integration** - GPS tracking integrated with group management ### 📨 Event WebSocket System Real-time WebPush event notifications and alerts: - **Event WebSocket SDK** - Complete WebPush event handling - **30+ Event Types** - Comprehensive event categorization - **Image & Video Support** - Events with media attachments - **AWS API Gateway Support** - 5-minute keepalive interval - **PSN Filtering** - Filter events by specific devices - **Automatic Reconnection** - Exponential backoff reconnection ### 🌐 API Endpoint Management Centralized API endpoint configuration: - **Environment Configuration** - Load from environment variables - **Runtime Configuration** - Dynamic endpoint updates - **Validation** - Ensure endpoints are properly configured - **Multi-endpoint Support** - API Gateway, IoT Gateway, GPS WebSocket, Event WebSocket ### 🏪 State Management Powerful state management with Zustand: - **Auth Store** - Authentication state with persistence - **API Endpoint Store** - Centralized endpoint configuration - **Type Safety** - Full TypeScript support throughout - **Persistence** - Automatic state persistence to localStorage ## 📖 Comprehensive API Documentation ### Authentication ```tsx import { login, logout, resetPassword, useAuthStore } from 'fleeta-api-lib'; // Login with email and password await login({ email: 'user@example.com', password: 'password' }); // Logout current user await logout(); // Password Reset const result = await resetPassword('user@example.com'); if (result.success) { console.log('Reset email sent'); } // Use Auth Store const { isAuthenticated, userToken, jwtToken, subscribeInfo, error } = useAuthStore(); ``` ### User Management ```tsx import { inviteMember, inviteSubMaster, inviteUser, getInviteMemberList, deleteMember, getUserPermissions, hasPermission, hasPermissions, hasMasterPrivileges, hasSubMasterPrivileges, getCloudStorageUsage, type FleetUserType, type InvitedMemberInfo, type UserPermissions } from 'fleeta-api-lib'; // Invite SubMaster (Fleet Manager) await inviteSubMaster('manager@company.com', 'fleeta'); // Invite User (Driver) await inviteUser('driver@company.com', 'fleeta'); // Custom invitation with specific configuration await inviteMember({ guestEmail: 'custom@company.com', userType: 'SubMaster', loginApp: 'blackvue' }); // Get invited member list with search const memberList = await getInviteMemberList({ searchKey: 'manager', // Search by name or email ordering: 0, // 0: newest first, 1: oldest first startIndex: 1, endIndex: 50 }); console.log(`Total members: ${memberList.response?.inviteMemberCount}`); memberList.response?.inviteMember.forEach(member => { console.log(`${member.firstName} ${member.lastName} (${member.role})`); console.log(` Email: ${member.email}`); console.log(` Status: ${member.mailStatus}`); console.log(` Groups: ${member.groups.length}`); }); // Delete member await deleteMember({ deleteEmail: 'olduser@company.com', deleteEmailUserType: 'User', loginApp: 'fleeta' }); // Get user permissions const permissions = await getUserPermissions(); console.log('User permissions:', permissions.response?.permissions); // Check specific permission const canInviteUsers = await hasPermission('inviteUser'); console.log('Can invite users:', canInviteUsers); // Check multiple permissions at once const multiplePermissions = await hasPermissions([ 'liveView', 'gpsTracking', 'registerGroup' ]); console.log('Multiple permissions:', multiplePermissions); // Check privilege levels const isMaster = await hasMasterPrivileges(); const isSubMaster = await hasSubMasterPrivileges(); console.log(`User role: ${isMaster ? 'Master' : isSubMaster ? 'SubMaster' : 'User'}`); // Get cloud storage usage const storage = await getCloudStorageUsage(); console.log(`Storage usage: ${storage.formatted} (${storage.bytes} bytes)`); ``` ### Group Management ```tsx import { addGroup, getGroupList, deleteGroup, assignSubMasterToGroup, addDevicesToGroup, getGroupDevices, assignUserToDevice, unassignUserFromDevice, getGroupUsers, type GroupListItem, type GroupData, type GroupDashcamsItem } from 'fleeta-api-lib'; // Create single group const singleGroup = await addGroup({ groupNameList: ['Seoul Fleet Alpha'] }); // Create multiple groups at once const multipleGroups = await addGroup({ groupNameList: [ 'Seoul Fleet Alpha', 'Busan Transport Beta', 'Daegu Logistics Gamma' ] }); // Get group list with search and pagination const groupList = await getGroupList({ ordering: 0, // 0: default, 1: desc, 2: asc keyword: 'Seoul', // Search keyword startIndex: 1, endIndex: 50 }); console.log(`Found ${groupList.response?.groupCount} groups`); groupList.response?.groupListInfo.forEach(group => { console.log(`Group: ${group.groupName} (${group.deviceCount} devices)`); }); // Assign SubMaster to group await assignSubMasterToGroup({ guestEmail: 'submaster@company.com', groupManagementID: 'GROUP_001' }); // Assign devices to group await addDevicesToGroup({ Add: [ { PSN: 'DEVICE123', GroupID: 'GROUP_001', GroupName: 'Seoul Fleet Alpha' }, { PSN: 'DEVICE456', GroupID: 'GROUP_001', GroupName: 'Seoul Fleet Alpha' } ] }); // Get group allocation data (devices and users) const allocations = await getGroupDevices(); allocations.response?.DashCamList.forEach(group => { console.log(`Group ${group.GroupName}:`); group.DashCamUser?.forEach(device => { console.log(` Device: ${device.DashCamName} (${device.Users?.length || 0} users)`); }); }); // Get users available for device assignment const availableUsers = await getGroupUsers(); console.log('Available users for assignment:', availableUsers.response?.Users); // Assign user to specific device within group await assignUserToDevice({ GroupID: 'GROUP_001', PSN: 'DEVICE123', UserEmail: ['user1@company.com', 'user2@company.com'] }); // Remove user from specific device await unassignUserFromDevice({ GroupID: 'GROUP_001', PSN: 'DEVICE123', UserEmail: 'user1@company.com' }); // Delete group await deleteGroup({ groupDeleteIDList: ['GROUP_001'] }); ``` ### Combined Group and User Workflow ```tsx import { addGroup, inviteSubMaster, assignSubMasterToGroup, addDevicesToGroup, getGroupDevices, assignUserToDevice } from 'fleeta-api-lib'; // Complete fleet setup workflow async function setupFleetGroup() { // 1. Create new fleet group const newGroup = await addGroup({ groupNameList: ['Regional Fleet North'] }); const groupId = newGroup.response!.groupData[0].groupManagementID; // 2. Invite SubMaster to manage the group await inviteSubMaster('manager@company.com', 'fleeta'); // Wait for SubMaster to complete registration... // In production, you'd check member status before proceeding // 3. Assign SubMaster to group await assignSubMasterToGroup({ guestEmail: 'manager@company.com', groupManagementID: groupId }); // 4. Assign devices to group await addDevicesToGroup({ Add: [ { PSN: 'DEVICE123', GroupID: groupId, GroupName: 'Regional Fleet North' } ] }); // 5. Assign users to specific devices await assignUserToDevice({ GroupID: groupId, PSN: 'DEVICE123', UserEmail: ['driver1@company.com', 'driver2@company.com'] }); // 6. Verify setup const allocations = await getGroupDevices(); const groupData = allocations.response?.DashCamList.find( g => g.GroupID === groupId ); console.log('✅ Fleet group setup complete:'); console.log(` Group: ${groupData?.GroupName}`); console.log(` SubMaster: ${groupData?.SubMasterEmail}`); console.log(` Devices: ${groupData?.DashCamUser?.length || 0}`); } ``` ### Device Management ```tsx import { getDeviceList, getMockDeviceList, type DeviceListResponse } from 'fleeta-api-lib'; // Get real device list (requires authentication) const deviceResponse: DeviceListResponse = await getDeviceList(); // Access device data console.log('Total devices:', deviceResponse.deviceCount); console.log('Device list:', deviceResponse.deviceListInfo); console.log('Grouped data:', deviceResponse.groupedData); // Access statistics const stats = deviceResponse.groupedData.statistics; console.log(`Active: ${stats.online}, Offline: ${stats.offline}`); console.log(`Video sharing: ${stats.videoSharing}`); // Filter devices with parameters const filteredDevices = await getDeviceList({ keyword: 'car', startIndex: 1, endIndex: 50 }); ``` ### Live Streaming & WebRTC ```tsx import { createWebRTCProvider, checkMediaDeviceSupport, requestMicrophonePermission, type WebRTCProviderConfig, type ConnectionState } from 'fleeta-api-lib'; // Create WebRTC Provider const provider = createWebRTCProvider({ deviceId: 'DEVICE123', channel: 'front', // 'front' | 'rear' | 'interior' | 'exterior' enableStats: true, statsInterval: 2000 }); // Set up event handlers provider.setCallbacks({ onStateChange: (state: ConnectionState) => { console.log('Connection state:', state); }, onStreamReceived: (stream: MediaStream) => { // Attach stream to video element videoElement.srcObject = stream; }, onError: (error: Error) => { console.error('WebRTC error:', error); }, onStatsUpdate: (stats) => { console.log('Connection stats:', stats); } }); // Connect to live stream await provider.connect(); // Change camera channel await provider.changeChannel('rear'); // Two-way audio await provider.startTwoWayAudio('DEVICE123'); await provider.stopTwoWayAudio('DEVICE123'); // Check media device support const capabilities = await checkMediaDeviceSupport(); if (capabilities.microphone.supported) { const permission = await requestMicrophonePermission(); } // Disconnect await provider.disconnect(); ``` ### GPS Data Provider System ```tsx import { createMapGpsProvider, createDashboardGpsProvider, type DeviceGpsInfo } from 'fleeta-api-lib'; // Create GPS provider for map applications const gpsProvider = createMapGpsProvider(); // Initialize provider gpsProvider.initialize(); // Register for GPS data updates gpsProvider.registerUpdateCallback((devices: DeviceGpsInfo[]) => { console.log(`Received GPS data for ${devices.length} devices`); devices.forEach(device => { console.log(`${device.psn}: ${device.latitude}, ${device.longitude}`); console.log(`Speed: ${device.speed} km/h, Status: ${device.active}`); }); }); // Connect to GPS WebSocket gpsProvider.connectWebSocket(); // Request GPS data for all user devices gpsProvider.requestGpsPsnsMyDevices(); // Request GPS data for specific devices (Multi Live View) gpsProvider.requestGpsPsnsMultiLiveView(['DEVICE123', 'DEVICE456']); // Request GPS data for devices in a geographic zone gpsProvider.requestGpsZoneMyDevices('37.5_126.9', '37.6_127.0'); // Register for connection status updates gpsProvider.registerConnectionCallback((connected: boolean) => { console.log('GPS WebSocket connected:', connected); }); // Clean up when done gpsProvider.destroy(); ``` ### Multi-Device Provider System ```tsx import { createMultiDeviceProvider, createGrid2x2Provider, createGrid4x4Provider, useAuthStore } from 'fleeta-api-lib'; // Step 1: Ensure user is logged in const { isAuthenticated } = useAuthStore(); if (!isAuthenticated) { await login({ email: 'user@example.com', password: 'password' }); } // Step 2: Create provider (auth handled automatically!) const provider = await createGrid2x2Provider(); // Or create custom size const provider = await createMultiDeviceProvider(16); // 4x4 grid // Step 3: Add devices and start streams const device1 = await provider.addDevice('DEVICE123', 'front'); const device2 = await provider.addDevice('DEVICE456', 'rear'); // Connect streams await device1.connectMainStream(); await device2.connectMainStream(); // Register for stream updates device1.onStreamUpdate((event) => { const videoElement = document.getElementById(`video-${event.psn}`); if (videoElement) { videoElement.srcObject = event.stream; } }); // Voice communication await device1.startVoiceComm(); await device1.stopVoiceComm(); // Cleanup await provider.destroy(); ``` ### Advanced Multi-Device Features ```tsx import { MultiDeviceProvider, DeviceStreamManager, useAuthStore } from 'fleeta-api-lib'; // Step 1: Authentication (handled automatically via AuthStore) const { isAuthenticated } = useAuthStore(); if (!isAuthenticated) { await login({ email: 'user@example.com', password: 'password' }); } // Step 2: Create provider with custom configuration const provider = new MultiDeviceProvider({ maxDevices: 16, defaultQuality: 'medium', enableConnectionPooling: true, connectionTimeout: 30000, enableVoiceCommSupport: true }); // Initialize provider await provider.initialize(); // Step 3: Add devices const device1 = await provider.addDevice('DEVICE123', 'front'); const device2 = await provider.addDevice('DEVICE456', 'rear'); // Step 4: Set up event handlers provider.setEvents({ onDeviceAdded: (psn) => console.log(`Device added: ${psn}`), onGlobalStatsUpdate: (stats) => console.log('Global stats:', stats), onVoiceCommStateChange: (psn, state) => { console.log(`Voice comm ${psn}:`, state.isActive ? 'Active' : 'Inactive'); } }); // Step 5: Device management await device1.connectMainStream('front'); await device2.switchChannel('interior'); // Voice communication await provider.startVoiceComm('DEVICE123'); // Get statistics const globalStats = provider.getGlobalStats(); console.log(`${globalStats.connectedDevices}/${globalStats.totalDevices} devices connected`); // Cleanup await provider.destroy(); ``` ### Event WebSocket System ```tsx import { EventWebSocketSDK, type WebPushMessage, type EventConnectionState, WEBPUSH_EVENT_DESCRIPTIONS } from 'fleeta-api-lib'; // Create Event WebSocket SDK (authentication handled automatically) const eventSDK = new EventWebSocketSDK(); // Initialize and connect eventSDK.initialize(); eventSDK.connect(); // Uses JWT token from AuthStore automatically // Handle connection events eventSDK.on('open', () => { console.log('Event WebSocket connected'); }); eventSDK.on('close', () => { console.log('Event WebSocket disconnected'); }); eventSDK.on('error', (error: Error) => { console.error('Event WebSocket error:', error); }); // Handle WebPush events eventSDK.on('webpush', (message: WebPushMessage) => { console.log('WebPush event received:', message); console.log('Event description:', WEBPUSH_EVENT_DESCRIPTIONS[message.code]); // Handle events with images if (message.image) { console.log('Image URL:', message.image); // Display image in UI } // Handle events with video files if (message.file) { console.log('Video file:', message.file); // Process video file } }); // Filter events by specific devices eventSDK.setPsnFilters(['DEVICE123', 'DEVICE456']); // Handle authentication updates eventSDK.updateAuthFromStore(); // Call when AuthStore state changes // Clean up eventSDK.destroy(); ``` ### Advanced GPS Features ```tsx import { GpsDataManager, filterByStatus, filterBySpeed, calculateDistance, isValidCoordinate } from 'fleeta-api-lib'; // Create GPS Data Manager for multiple providers const manager = GpsDataManager.getInstance(); // Create multiple providers for different use cases const mapProvider = manager.createProvider('map', { updateThreshold: { position: 0.00005, speed: 0.5, interval: 500 }, enableCaching: true }); const dashboardProvider = manager.createProvider('dashboard', { updateThreshold: { position: 0.0001, speed: 2, interval: 2000 }, autoFilter: { excludeInactive: true, excludeStatic: true } }); // Register for global data updates manager.registerDataCallback((allData) => { console.log('Global GPS data from all providers:', allData); }); // Filter GPS data const activeDevices = filterByStatus(devices, 'active'); const fastMovingDevices = filterBySpeed(devices, 30); // > 30 km/h // Calculate distance between devices const distance = calculateDistance(lat1, lng1, lat2, lng2); console.log(`Distance: ${distance} meters`); ``` ## 🌳 Tree Shaking & Bundle Optimization Import only what you need to reduce bundle size: ```tsx // Import specific functions (recommended) import { login, logout } from 'fleeta-api-lib'; // Import device management only import { getDeviceList } from 'fleeta-api-lib'; // Import GPS system only import { createMapGpsProvider, GpsDataManager } from 'fleeta-api-lib'; // Import WebRTC only import { createWebRTCProvider, checkMediaDeviceSupport } from 'fleeta-api-lib'; // Import stores only import { useAuthStore, useApiEndpointStore } from 'fleeta-api-lib'; // Import group management only import { addGroup, getGroupList, assignUserToDevice } from 'fleeta-api-lib'; // Import user management only import { inviteSubMaster, hasPermissions, hasMasterPrivileges } from 'fleeta-api-lib'; // Import event system only import { EventWebSocketSDK, WEBPUSH_EVENT_DESCRIPTIONS } from 'fleeta-api-lib'; // Import only types (zero runtime cost) import type { AuthConfig, DeviceListItem, WebRTCProviderConfig, ConnectionState, DeviceGpsInfo, UserPermissions, GroupListItem, WebPushMessage } from 'fleeta-api-lib'; ``` **Bundle size savings:** - Authentication only: ~60% smaller - Device API only: ~70% smaller - WebRTC only: ~50% smaller - GPS Data Provider only: ~55% smaller - Group Management only: ~65% smaller - User Management only: ~70% smaller - Event WebSocket only: ~75% smaller - Stores only: ~80% smaller - Types only: 100% smaller (no runtime cost) ## 📊 Data Structures ### User Data Structure ```tsx interface UserPermissions { // Device Management Permissions listDashcam: boolean; registerDashcam: boolean; changeDashcamName: boolean; deleteDashcam: boolean; dashcamInformation: boolean; // Live Streaming Permissions liveView: number; // 0: unlimited, -1: disabled, >0: seconds limit vodDownload: number; // 0: unlimited, -1: disabled, >0: seconds limit cloudFilePlay: boolean; myBlackVueFilePlay: boolean; // User Management Permissions membersInquiry: boolean; inviteSubMaster: boolean; inviteUser: boolean; deleteSubMaster: boolean; deleteUser: boolean; // Group Management Permissions (Master only) registerGroup: boolean; deleteGroup: boolean; assignUserToDevice: boolean; unassignUserFromDevice: boolean; assignSubMasterToGroup: boolean; unassignSubMasterFromGroup: boolean; // Storage and Compliance cloudStorageUsage: number; // Storage usage in bytes gpsTracking: boolean; geoFence: boolean; driveReports: boolean; // ... and more permissions } interface InvitedMemberInfo { email: string; // Member email address role: 'Master' | 'SubMaster' | 'User'; // Member role groups: InvitedMemberGroup[]; // Assigned groups dateInvited: string; // Invitation timestamp mailStatus: string; // Email delivery status firstName: string; // Member first name lastName: string; // Member last name profileImg: string; // Profile image URL hostEmail: string; // Inviting user email hostfirstName: string; // Inviting user first name hostlastName: string; // Inviting user last name hostRole: 'Master' | 'SubMaster' | 'User'; // Inviting user role } ``` ### Group Data Structure ```tsx interface GroupListItem { groupManagementID: string; // Unique group identifier groupName: string; // Group display name deviceCount: number; // Number of assigned devices userCount: number; // Number of assigned users createDT: string; // Group creation timestamp createUT: number; // Creation Unix timestamp admins: SubMasterInfo[]; // Assigned SubMaster administrators } interface GroupDashcamsItem { GroupID: string; // Group management ID GroupName: string; // Group name CreateDT: string; // Creation timestamp SubMasterEmail?: string; // Assigned SubMaster email SubMasterFirstName?: string; // SubMaster first name SubMasterLastName?: string; // SubMaster last name SubMasterStatus?: 'P' | 'A'; // P: Pending, A: Active DashCamUser?: GroupAllocationDevice[]; // Assigned devices with users } interface GroupAllocationDevice { PSN: string; // Device PSN DashCamName: string; // Device display name Users?: GroupAllocationUser[]; // Users assigned to this device } interface GroupAllocationUser { Email: string; // User email FirstName: string; // User first name LastName: string; // User last name Status: 'P' | 'A'; // P: Pending, A: Active } ``` ### Event WebSocket Data Structure ```tsx interface WebPushMessage { type: 'webpush'; // Message type code: WebPushEventCode; // Event code (30+ types) message: string; // Event message image?: string; // Image URL (for image events) file?: string; // Video file path (for video events) } // Event categories const WEBPUSH_EVENT_CATEGORIES = { device: ['DEVICE_CONNECT', 'DEVICE_DISCONNECT'], driving: ['ALARM_SPEED', 'ALARM_ACCELERATION', 'ALARM_HARSHBRAKING'], driver: ['ALARM_DROWSY', 'ALARM_MASK_OFF', 'ALARM_CALLING'], parking: ['ALARM_PARK_MOTION', 'ALARM_PARK_EVENT'], system: ['ALARM_SETTING_SAVED', 'SERVER_RESTART'], // ... more categories }; ``` ### Device List Response ```tsx interface DeviceListResponse { resultcode: string; message: string; deviceCount: number; deviceLimitCount: number; sharedEventMap: 'on' | 'off'; deviceListInfo: DeviceListItem[]; groupedData: { groups: DeviceGroupData[]; statistics: DeviceListStatistics; }; } ``` ### GPS Device Information ```tsx interface DeviceGpsInfo { psn: string; // Product Serial Number active: 'on' | 'off'; // Online status dev_name?: string; // Device name share_video: 'on' | 'off'; // Video sharing status latitude: number; // GPS latitude longitude: number; // GPS longitude speed?: number; // Speed in km/h dir_angle?: number; // Direction angle mode?: '0' | '1'; // 0: Normal, 1: Parking } ``` ## 🔒 Security Features ### User Management Security - **Email Validation** - Strict email format and domain validation - **Invitation Expiry** - 3-day validity period for security - **Role Validation** - Ensure proper role assignment and permissions - **Cleanup Automation** - Automatic cleanup of expired invitations - **Permission Control** - Fine-grained permission system for feature access - **Storage Monitoring** - Cloud storage usage tracking and limits - **Privilege Checking** - Master/SubMaster privilege validation ### Group Management Security - **Master-Only Operations** - Group creation, deletion, and device assignment restricted to Master users - **Role-Based Access** - SubMasters can only manage assigned groups - **Validation** - Comprehensive input validation for all group operations - **Audit Trail** - Track group creation, modification, and deletion activities ### Authentication Security - **SHA256 Password Encryption** - Passwords are hashed before transmission - **JWT Token Support** - Secure token-based authentication - **Persistent Auth State** - Secure local storage with auto-cleanup - **Environment Variable Protection** - API keys stored securely - **WebSocket Security** - Secure WebSocket connections with authentication ## 🛠️ Development & Testing ### User Management Testing ```tsx import { isUsersApiReady, validateInvitationEmail, validateUserType, validateLoginApp, getUserPermissions, hasPermission, hasPermissions, hasMasterPrivileges, isPermissionsApiReady } from 'fleeta-api-lib'; // Check if users API is ready if (!isUsersApiReady()) { console.log('Users API not ready - please login first'); } // Check if permissions API is ready if (!isPermissionsApiReady()) { console.log('Permissions API not ready - please login first'); } // Validate invitation email const emailError = validateInvitationEmail('user@company.com'); if (emailError) { console.error('Invalid email:', emailError); } // Validate user type const typeError = validateUserType('SubMaster'); if (typeError) { console.error('Invalid user type:', typeError); } // Validate login app const appError = validateLoginApp('fleeta'); if (appError) { console.error('Invalid login app:', appError); } // Get user permissions const permissions = await getUserPermissions(); console.log('User permissions received:', { canCreateGroups: permissions.response?.permissions.registerGroup, liveViewLimit: permissions.response?.permissions.liveView, storageUsed: permissions.response?.permissions.cloudStorageUsage }); // Check Master privileges before sensitive operations const isMaster = await hasMasterPrivileges(); if (isMaster) { console.log('User has Master privileges - can perform all operations'); } else { console.log('User has limited privileges - some operations restricted'); } // Check specific permission before action const canDeleteGroups = await hasPermission('deleteGroup'); if (canDeleteGroups) { // Show delete group button } else { // Hide delete group button } // Check multiple permissions at once const requiredPermissions = await hasPermissions([ 'registerGroup', 'assignUserToDevice', 'inviteSubMaster' ]); console.log('Required permissions available:', requiredPermissions); ``` ### Group Management Testing ```tsx import { isGroupApiReady, validateGroupName, validatePSN, validateEmailFormat, getGroupUsers, assignUserToDevice } from 'fleeta-api-lib'; // Check if group API is ready if (!isGroupApiReady()) { console.log('Group API not ready - please login first'); } // Validate group name const nameError = validateGroupName('My Fleet Group'); if (nameError) { console.error('Invalid group name:', nameError); } // Validate PSN format const psnError = validatePSN('ABC12345678'); if (psnError) { console.error('Invalid PSN:', psnError); } // Validate email format const emailValid = validateEmailFormat('user@company.com'); console.log('Email valid:', emailValid); // Get users available for device assignment const availableUsers = await getGroupUsers(); console.log('Users available for assignment:', availableUsers.response?.Users); // Assign users to specific device await assignUserToDevice({ GroupID: 'GROUP_001', PSN: 'DEVICE123', UserEmail: ['user1@company.com', 'user2@company.com'] }); ``` ### Event WebSocket Testing ```tsx import { EventWebSocketSDK, isImageIncludedEvent, WEBPUSH_EVENT_CATEGORIES } from 'fleeta-api-lib'; // Create SDK with custom configuration const eventSDK = new EventWebSocketSDK({ maxReconnectAttempts: 10, // Increase for critical applications reconnectDelay: 1000, // Start with 1-second delay heartbeatInterval: 300000 // 5-minute AWS API Gateway keepalive }); // Comprehensive error handling eventSDK.on('error', (error: Error) => { console.error('Event WebSocket error:', error); // Handle different error types if (error.message.includes('Authentication')) { // Refresh authentication eventSDK.updateAuthFromStore(); } else if (error.message.includes('network')) { // Show network error to user showNetworkErrorNotification(); } }); // Event categorization eventSDK.on('webpush', (message) => { // Check event category for (const [category, codes] of Object.entries(WEBPUSH_EVENT_CATEGORIES)) { if (codes.includes(message.code)) { console.log(`Event category: ${category}`); break; } } // Check if event includes image if (isImageIncludedEvent(message.code)) { console.log('This event includes an image:', message.image); } }); // PSN filtering for specific devices eventSDK.setPsnFilters(['DEVICE123', 'DEVICE456']); console.log('Active PSN filters:', eventSDK.getPsnFilters()); ``` ### Type Safety Full TypeScript support with comprehensive type definitions: ```tsx import type { AuthConfig, // User types InvitedMemberInfo, FleetUserType, LoginApp, UserPermissions, InviteMemberParams, GetInviteMemberListResponse, // Group types GroupListItem, GroupData, SubMasterInfo, GroupDashcamsItem, AddGroupParams, GetGroupListResponse, GroupAllocationDevice, GroupAllocationUser, // Device types DeviceListParams, DeviceListResponse, DeviceInfo, DeviceGpsInfo, BatteryInfo, // WebRTC types WebRTCProviderConfig, ConnectionState, GpsDataProviderConfig, // Event types WebPushMessage, EventConnectionState, WebPushEventCode, // Multi-device types MultiDeviceProviderConfig, DeviceStreamManager, StreamUpdateEvent } from 'fleeta-api-lib'; ``` ### Error Handling Comprehensive error handling with typed error messages for all modules: ```tsx // Authentication errors try { await login({ email, password }); } catch (error) { // Error is automatically handled and stored in auth store const { error: authError } = useAuthStore(); console.log('Login failed:', authError); } // Group management errors try { await addGroup({ groupNameList: ['New Group'] }); } catch (error) { console.error('Group creation failed:', error.message); // Handle specific error codes: BC_ERR_AUTHENTICATION, BC_ERR_INVALID_PARAMETER, etc. } // User management errors try { await inviteMember({ guestEmail: 'user@company.com', userType: 'SubMaster' }); } catch (error) { console.error('Invitation failed:', error.message); // Handle specific error codes: BC_ERR_DUPLICATED, BC_ERR_UNAVAILABLE, etc. } // Device management errors try { const devices = await getDeviceList(); } catch (error) { console.error('Device list failed:', error.message); // Handle specific error codes and display user-friendly messages } // GPS provider error handling gpsProvider.registerErrorCallback((error: Error) => { console.error('GPS error:', error); }); // Event WebSocket error handling eventSDK.on('error', (error: Error) => { console.error('Event WebSocket error:', error); }); ``` ### Mock Data Support Built-in mock data for development and testing: ```tsx import { getMockDeviceList } from 'fleeta-api-lib'; // Get combined mock + real data for testing const mockResponse = await getMockDeviceList(); ``` ## 📱 Browser Support - Chrome 90+ - Firefox 88+ - Safari 14+ - Edge 90+ **WebRTC Support:** - Chrome 80+ - Firefox 76+ - Safari 13.1+ - Edge 80+ ## 🚀 Advanced Usage ### Custom GPS Data Processing ```tsx import { GpsDataProvider, hasSignificantChange, optimizeForMapRendering, applyAutoFilter } from 'fleeta-api-lib'; // Create custom GPS provider with advanced configuration const provider = new GpsDataProvider({ updateThreshold: { position: 0.00001, // Very sensitive to position changes speed: 0.1, // Very sensitive to speed changes interval: 100 // Very frequent updates }, enableCaching: true, cacheSize: 1000, autoFilter: { excludeInactive: false, excludeInvalidCoords: true, excludeStatic: false, minSpeedThreshold: 0 }, maxDevicesPerUpdate: 200, enableBatching: false // Real-time mode }); // Register for optimized updates provider.registerUpdateCallback((devices) => { // Data is already optimized and filtered const optimized = optimizeForMapRendering(devices, { maxDevices: 50, prioritizeActive: true, prioritizeVideo: true }); updateMapMarkers(optimized); }); ``` ### WebRTC Advanced Configuration ```tsx import { createWebRTCProvider, type ICEServer } from 'fleeta-api-lib'; const provider = createWebRTCProvider({ deviceId: 'DEVICE123', channel: 'front', enableStats: true, statsInterval: 1000, // 1 second stats updates role: 'VIEWER' }); // Advanced event handling provider.setCallbacks({ onStateChange: (state) => { switch (state) { case 'connecting': showLoadingSpinner(); break; case 'connected': hideLoadingSpinner(); enableControls(); break; case 'failed': showErrorMessage(); break; } }, onStatsUpdate: (stats) => { updateBandwidthIndicator(stats.bytesReceived); updateQualityIndicator(stats.packetsLost, stats.packetsReceived); } }); ``` ### Advanced Permission Management ```tsx import { getUserPermissions, hasPermissions, hasMasterPrivileges, getTargetUserPermissions, setTargetUserPermissions } from 'fleeta-api-lib'; // Check multiple permissions at once const permissions = await hasPermissions([ 'registerGroup', 'assignUserToDevice', 'inviteSubMaster', 'deleteGroup' ]); if (permissions.registerGroup && permissions.assignUserToDevice) { // User can create and manage groups showGroupManagementUI(); } // Check privilege levels const isMaster = await hasMasterPrivileges(); if (isMaster) { // Show Master-only features showMasterControls(); // Get target user permissions (Master only) const targetPermissions = await getTargetUserPermissions({ targetEmail: 'submaster@company.com' }); // Set target user permissions (Master only) await setTargetUserPermissions({ roleSetEmail: 'submaster@company.com', permissions: { liveView: 3600, // 1 hour limit registerGroup: false, // Cannot create groups inviteUser: true // Can invite users // ... other permissions } }); } ``` ## 🤝 Contributing We welcome contributions! Please follow these guidelines: 1. Fork the repository 2. Create a feature branch 3. Make your changes with proper TypeScript types 4. Add tests if applicable 5. Update documentation for new APIs 6. Ensure all modules work independently 7. Submit a pull request ### API Module Guidelines When adding new API modules: - Follow the established file structure (`api/`, `types.ts`, `index.ts`) - Keep individual files under 200 lines - Include comprehensive error handling - Add TypeScript types for all parameters and responses - Include validation utilities - Document all public APIs with JSDoc comments ## 📄 License MIT License - see [LICENSE](LICENSE) file for details. ## 🆘 Support - 🐛 [Issue Tracker](https://github.com/hurfoong/Fleeta-Components-API/issues) - 📧 Contact: FleetA Team - 📖 [API Documentation](https://github.com/hurfoong/Fleeta-Components-API#readme) ## 📈 Version History - **v1.3.1** - 🔧 **HOTFIX**: Added missing Multi-Device Provider exports, complete User Management API with permissions, Group Management API with device-user assignments - **v1.3.0** - 📨 **NEW**: Event WebSocket System, Group Management API, User Management API with AWS API Gateway support, 30+ WebPush event types, fleet organization features - **v1.2.0** - 🎯 **BREAKING CHANGES**: Simplified Multi-Device Provider API, removed auth management from multi-device layer, complete delegation to live API - **v1.1.0** - 🆕 Complete GPS Data Provider system, WebRTC enhancements, Live streaming improvements - **v1.0.8** - Enhanced device management and API improvements - **v1.0.6** - Authentication and device API improvements - **v1.0.0** - Initial release ## 🔄 Migration Guide (v1.3.1) ### New APIs Added **Enhanced User Management:** ```tsx // Before (v1.3.0) const canInvite = await hasPermission('inviteUser'); // After (v1.3.1) - Multiple permissions at once const permissions = await hasPermissions(['inviteUser', 'registerGroup', 'liveView']); const isMaster = await hasMasterPrivileges(); const storage = await getCloudStorageUsage(); ``` **Enhanced Group Management:** ```tsx // Before (v1.3.0) - Limited group operations await addDevicesToGroup(devices); // After (v1.3.1) - Full user-device assignment await assignUserToDevice({ GroupID: 'GROUP_001', PSN: 'DEVICE123', UserEmail: ['user1@company.com'] }); const availableUsers = await getGroupUsers(); await unassignUserFromDevice({ GroupID: 'GROUP_001', PSN: 'DEVICE123', UserEmail: 'user1@company.com' }); ``` **Complete Multi-Device Provider:** ```tsx // Before (v1.3.0) - Missing exports // import { createMultiDeviceProvider } from 'fleeta-api-lib'; // ❌ Not available // After (v1.3.1) - All exports available import { createMultiDeviceProvider, createGrid2x2Provider, MultiDeviceProvider, DeviceStreamManager } from 'fleeta-api-lib'; // ✅ All available const provider = await createGrid2x2Provider(); const device = await provider.addDevice('DEVICE123', 'front'); ``` ### What's New 1. **✅ Added**: `hasPermissions()` - Check multiple permissions at once 2. **✅ Added**: `hasMasterPrivileges()` - Master role validation 3. **✅ Added**: `hasSubMasterPrivileges()` - SubMaster role validation 4. **✅ Added**: `getCloudStorageUsage()` - Storage usage tracking 5. **✅ Added**: `assignUserToDevice()` - Assign users to devices 6. **✅ Added**: `unassignUserFromDevice()` - Remove user-device assignments 7. **✅ Added**: `getGroupUsers()` - Get users available for assignment 8. **✅ Fixed**: All Multi-Device Provider factory functions exported 9. **✅ Improved**: User invitation consolidated into user management --- ## 📈 Version History - **v1.4.0** - 🚀 **MAJOR UPDATE**: Enhanced User Management API with new permission checking functions, improved Group Management API with consistent device naming, comprehensive API documentation - **v1.3.1** - 🔧 **HOTFIX**: Complete Multi-Device Provider exports, Enhanced User Management API, Group Management API improvements - **v1.3.0** - 📨 **NEW**: Event WebSocket System, Group Management API, User Management API with AWS API Gateway support, 30+ WebPush event types, fleet organization features - **v1.2.0** - 🎯 **BREAKING CHANGES**: Simplified Multi-Device Provider API, removed auth management from multi-device layer, complete delegation to live API - **v1.1.0** - 🆕 Complete GPS Data Provider system, WebRTC enhancements, Live streaming improvements - **v1.0.8** - Enhanced device management and API improvements - **v1.0.6** - Authentication and device API improvements - **v1.0.0** - Initial release ## 🔄 Migration Guide (v1.4.0) ### Enhanced User Management API ```tsx // Before (v1.3.1) const canInvite = await hasPermission('inviteUser'); // After (v1.4.0) - Multiple permissions at once const permissions = await hasPermissions(['inviteUser', 'registerGroup', 'liveView']); const isMaster = await hasMasterPrivileges(); const storage = await getCloudStorageUsage(); ``` ### Enhanced Group Management API ```tsx // Before (v1.3.1) - Mixed naming conventions await assignUserToDashcam({ GroupID: 'GROUP_001', PSN: 'DEVICE123', UserEmail: ['user@company.com'] }); // After (v1.4.0) - Consistent device naming await assignUserToDevice({ GroupID: 'GROUP_001', PSN: 'DEVICE123', UserEmail: ['user@company.com'] }); const devices = await getGroupDevices(); // Consistent naming ``` ### What's New in v1.4.0 1. **✅ Added**: `hasPermissions()` - Check multiple permissions at once 2. **✅ Added**: `hasMasterPrivileges()` - Master role validation 3. **✅ Added**: `hasSubMasterPrivileges()` - SubMaster role validation 4. **✅ Added**: `getCloudStorageUsage()` - Storage usage tracking 5. **✅ Improved**: Consistent device naming throughout Group Management API 6. **✅ Enhanced**: Comprehensive documentation with all API examples 7. **✅ Fixed**: All TypeScript naming conflicts resolved --- **🚗 FleetA API Library v1.4.0 - Complete Fleet Management Solution**</parameter> Comprehensive TypeScript library providing authentication, device management, live streaming, GPS tracking, group management, user management, event notifications, and state management for BlackVue Fleeta fleet management application