### Manage User Profiles with Netease Kit IM UI Electron SDK Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Demonstrates how to get and update user profile information, including avatars. This involves interacting with the user store and potentially uploading files for avatar updates. Handles fetching individual and batch user profiles. ```typescript // Get current user info const myProfile = store.userStore.myUserInfo; console.log({ accountId: myProfile.accountId, name: myProfile.name, avatar: myProfile.avatar, sign: myProfile.sign, email: myProfile.email, mobile: myProfile.mobile }); // Update self profile await store.userStore.updateSelfUserProfileActive({ name: 'New Display Name', sign: 'My personal signature', email: 'newemail@example.com', birthday: '1990-01-01', gender: 1 // 0=unknown, 1=male, 2=female }); // Update avatar with file upload const avatarFile = new File([/* file data */], 'avatar.jpg', { type: 'image/jpeg' }); await store.userStore.updateSelfUserProfileActive( { name: 'Display Name' }, avatarFile // SDK uploads file and sets avatar URL automatically ); // Get other user's profile const userProfile = await store.userStore.getUserActive('user123'); // Batch get user profiles (frequency-controlled to avoid rate limiting) const users = await store.userStore.getUsersActive(['user1', 'user2', 'user3']); ``` -------------------------------- ### Manage Blocked Users and Muted Conversations Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Provides examples for managing blocked users and muted conversations. This includes adding/removing users from the blocklist, muting/unmuting P2P and team conversations, and retrieving lists of blocked and muted conversations. ```typescript // Add user to blocklist await store.relationStore.addUserToBlockListActive('user123'); // Remove from blocklist await store.relationStore.removeUserFromBlockListActive('user123'); // Get blocklist const blockedUsers = await store.relationStore.getBlockListActive(); blockedUsers.forEach(accountId => { console.log('Blocked user:', accountId); }); // Mute P2P conversation await store.relationStore.setP2PMuteActive('user123', true); // Unmute P2P conversation await store.relationStore.setP2PMuteActive('user123', false); // Get P2P mute list const mutedP2P = await store.relationStore.getP2PMuteListActive(); // Mute team conversation await store.teamStore.setTeamMuteActive({ teamId: 'team123', teamType: 2, muteMode: 1 // 0=unmute, 1=mute_all, 2=mute_exclude_normal }); // Check if conversation is muted const isMuted = store.relationStore.isP2PMuted('user123'); const isTeamMuted = store.teamStore.teams.get('team123')?.chatBannedMode === 1; ``` -------------------------------- ### Get Message History Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Load historical messages for a specific conversation with pagination support and read receipt information. ```APIDOC ## Get Message History ### Description Load historical messages for a specific conversation with pagination support and read receipt information. ### Method GET (implicitly via store access) ### Endpoint N/A (Accessed via internal store) ### Parameters #### Request Parameters (for `getHistoryMsgActive`) - **conversationId** (string) - Required - The ID of the conversation to fetch messages from. - **endTime** (number) - Required - Timestamp (in ms) before which to fetch messages. - **limit** (number) - Required - The maximum number of messages to retrieve. - **lastMsgId** (string) - Optional - An anchor message ID to start fetching messages from (for more granular pagination). ### Request Example ```typescript // Get history messages for a conversation const messages = await store.msgStore.getHistoryMsgActive({ conversationId: 'p2p-user123', endTime: Date.now(), // Load messages before this timestamp limit: 100, lastMsgId: 'optional-anchor-message-id' // Start from specific message }); // Access messages from store const conversationMsgs = store.msgs.get('p2p-user123'); // Returns QueueMap with messages conversationMsgs.forEach(msg => { console.log({ messageClientId: msg.messageClientId, messageServerId: msg.messageServerId, text: msg.text, senderId: msg.senderId, receiverId: msg.receiverId, createTime: msg.createTime, messageType: msg.messageType, // 0=text, 1=image, 2=audio, 3=video, 4=file, etc. sendingState: msg.sendingState, // 0=default, 1=sending, 2=failed, 3=succeeded readReceiptEnabled: msg.readReceiptEnabled, attachment: msg.attachment // For media messages }); }); // For team messages, SDK automatically fetches read/unread status // Access via: msg.readCount, msg.unreadCount ``` ### Response #### Success Response (Implicit) - **messages** (QueueMap) - A map where keys are conversation IDs and values are QueueMaps of message objects. Message Object: - **messageClientId** (string) - Client-generated unique ID for the message. - **messageServerId** (string) - Server-generated unique ID for the message. - **text** (string | null) - Text content of the message (for text messages). - **senderId** (string) - User ID of the message sender. - **receiverId** (string) - User ID or team ID the message was sent to. - **createTime** (number) - Timestamp (in ms) when the message was created. - **messageType** (number) - Type of the message (e.g., 0=text, 1=image, 2=audio). - **sendingState** (number) - State of the message sending process. - **readReceiptEnabled** (boolean) - Indicates if read receipts are enabled for this message. - **attachment** (object | null) - Attachment details for media or file messages. - **readCount** (number) - (Team messages) Number of members who have read the message. - **unreadCount** (number) - (Team messages) Number of members who have not read the message. #### Response Example (Messages are typically accessed via the store after fetching) ```json { "messageClientId": "client-msg-123", "messageServerId": "server-msg-456", "text": "Hello there!", "senderId": "user123", "receiverId": "p2p-user123", "createTime": 1678886400000, "messageType": 0, "sendingState": 3, "readReceiptEnabled": true, "attachment": null } ``` ``` -------------------------------- ### Get and Display Conversation List Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Retrieve conversations with unread counts and metadata. This API allows fetching active conversations and listening to real-time changes. ```APIDOC ## Get and Display Conversation List ### Description Retrieve conversations with unread counts and metadata. This API allows fetching active conversations and listening to real-time changes. ### Method GET (implicitly via store access) ### Endpoint N/A (Accessed via internal store) ### Parameters None directly exposed as endpoint parameters. ### Request Example ```typescript // Fetch conversation list (cloud mode) const conversations = await store.conversationStore.getConversationListActive(0, 100); // Access conversation data const conversationList = Array.from(store.conversationStore.conversations.values()); conversationList.forEach(conv => { console.log({ id: conv.conversationId, name: conv.name, unreadCount: conv.unreadCount, lastMessage: conv.lastMessage, stickTop: conv.stickTop, updateTime: conv.updateTime, type: conv.type // 1=P2P, 2=TEAM }); }); // Get total unread count across all conversations const totalUnread = store.conversationStore.totalUnreadCount; // Listen to conversation changes with MobX autorun import { autorun } from 'mobx'; autorun(() => { const total = store.conversationStore.totalUnreadCount; console.log(`Total unread messages: ${total}`); // UI automatically updates when this value changes }); ``` ### Response #### Success Response (Implicit) - **conversationList** (Array) - An array of conversation objects. - **totalUnreadCount** (number) - The total number of unread messages across all conversations. Conversation Object: - **id** (string) - Unique identifier for the conversation. - **name** (string) - Name of the conversation. - **unreadCount** (number) - Number of unread messages in the conversation. - **lastMessage** (MessageObject | null) - The last message in the conversation. - **stickTop** (boolean) - Whether the conversation is pinned to the top. - **updateTime** (number) - Timestamp of the last update. - **type** (number) - Type of conversation (1=P2P, 2=TEAM). #### Response Example ```json [ { "id": "p2p-user123", "name": "John Doe", "unreadCount": 5, "lastMessage": { ... }, "stickTop": false, "updateTime": 1678886400000, "type": 1 } ] // totalUnreadCount: 5 ``` ``` -------------------------------- ### Message Collections (Favorites): Add, Get, and Remove Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt This section details how to manage a message collection feature, often used for 'favorites'. It includes adding messages to a collection with custom data, retrieving a list of collected messages based on specified options, and removing messages from the collection. Key functions include `addCollectionActive`, `getCollectionListByOptionActive`, and `removeCollectionActive`. ```typescript await store.msgStore.addCollectionActive({ collectionType: 0, // Custom type identifier collectionData: JSON.stringify({ message: nim.messageConverter?.messageSerialization(message), customData: { category: 'important', tags: ['work', 'urgent'] } }), serverExtension: JSON.stringify({ source: 'chat' }) }); const collections = await store.msgStore.getCollectionListByOptionActive({ collectionType: 0, limit: 100, offset: 0, startTime: 0, endTime: Date.now() }); collections.forEach(collection => { console.log({ collectionId: collection.collectionId, collectionType: collection.collectionType, collectionData: JSON.parse(collection.collectionData), createTime: collection.createTime }); }); await store.msgStore.removeCollectionActive([ { collectionType: 0, collectionId: 'collection123' } ]); ``` -------------------------------- ### Initialize IM UIKit and Login Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Initializes the NetEase IM SDK with an appkey and authenticates the user with account credentials. It automatically triggers data synchronization for user profiles, conversations, friends, teams, and system messages. It also provides utilities to monitor connection and login statuses. ```typescript import { initIMUIKit } from './src/components/NEUIKit/utils/init'; // Initialize SDK with appkey const { nim, store } = initIMUIKit('your-appkey-here'); // Login with account credentials nim.loginService?.login('user-account', 'user-token', {}) .then(() => { console.log('Login successful'); // SDK will automatically trigger data sync and fetch: // - User profile // - Conversation list // - Friend list // - Team list // - System messages }) .catch((error) => { if (error.code === 102422) { console.error('Account has been banned'); } else { console.error('Login failed:', error); } }); // Monitor connection status store.connectStore.connectStatus; // 1=connecting, 2=waiting, 3=connected, 4=disconnected // Monitor login status store.connectStore.loginStatus; // 1=logging_in, 2=logged_in, 3=logging_out, 4=logged_out ``` -------------------------------- ### Create and Manage Team/Group Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt APIs for creating, updating, and managing team (group) information and membership. ```APIDOC ## Create and Manage Team/Group ### Description APIs for creating, updating, and managing team (group) information and membership. ### Method POST, PUT (implicitly via store actions) ### Endpoint N/A (Accessed via internal store) ### Parameters #### Create Team Parameters - **name** (string) - Required - The name of the team. - **avatar** (string) - Optional - URL of the team's avatar. - **type** (number) - Required - Type of team (e.g., 1=advanced, 2=normal). - **accounts** (Array) - Optional - Initial members' account IDs. - **intro** (string) - Optional - Team introduction. - **serverExtension** (string) - Optional - Server-side extension data (JSON string). #### Update Team Info Parameters - **teamId** (string) - Required - The ID of the team to update. - **teamType** (number) - Required - The type of the team. - **updateParams** (object) - Required - Object containing fields to update: - **name** (string) - New team name. - **intro** (string) - New team introduction. - **avatar** (string) - New team avatar URL. #### Add Members Parameters - **teamId** (string) - Required - The ID of the team to add members to. - **teamType** (number) - Required - The type of the team. - **accounts** (Array) - Required - Array of member account IDs to add. #### Remove Member Parameters - **teamId** (string) - Required - The ID of the team. - **teamType** (number) - Required - The type of the team. - **account** (string) - Required - The account ID of the member to remove. #### Transfer Ownership Parameters - **teamId** (string) - Required - The ID of the team. - **type** (number) - Required - The type of the team. - **account** (string) - Required - The account ID of the new owner. - **leave** (boolean) - Required - Whether the current owner should leave the team. ### Request Example ```typescript // Create a normal team (群组) const team = await store.teamStore.createTeamActive({ name: 'Project Team', avatar: 'https://example.com/avatar.jpg', type: 2, // V2NIMTeamType: 1=advanced, 2=normal accounts: ['user123', 'user456', 'user789'], // Initial members intro: 'Team for project collaboration', serverExtension: JSON.stringify({ department: 'Engineering' }) }); console.log('Team created:', team.teamId); // Update team information await store.teamStore.updateTeamInfoActive({ teamId: team.teamId, teamType: 2, updateParams: { name: 'Updated Team Name', intro: 'New team description', avatar: 'https://example.com/new-avatar.jpg' } }); // Add members to team await store.teamMemberStore.addTeamMembersActive( team.teamId, 2, // team type ['newuser1', 'newuser2'] ); // Remove member from team await store.teamMemberStore.removeTeamMemberActive( team.teamId, 2, 'user123' ); // Transfer team ownership await store.teamStore.transferTeamActive({ teamId: team.teamId, type: 2, account: 'newowner123', leave: false // Whether current owner leaves team }); // Dismiss team (owner only) await store.teamStore.dismissTeamActive(team.teamId, 2); ``` ### Response #### Success Response (Implicit) - **createTeamActive**: Returns the created `TeamObject`. - **updateTeamInfoActive**: Returns void or success status. - **addTeamMembersActive**: Returns void or success status. - **removeTeamMemberActive**: Returns void or success status. - **transferTeamActive**: Returns void or success status. - **dismissTeamActive**: Returns void or success status. Team Object: - **teamId** (string) - Unique identifier for the team. - **name** (string) - Name of the team. - **avatar** (string) - URL of the team's avatar. - **type** (number) - Type of the team. - **intro** (string) - Team introduction. - **owner** (string) - Account ID of the team owner. #### Response Example (Responses are typically implicit success or the created team object) ```json { "teamId": "team-abc123xyz", "name": "Project Team", "avatar": "https://example.com/avatar.jpg", "type": 2, "intro": "Team for project collaboration", "owner": "user123" } ``` ``` -------------------------------- ### Create and Manage Teams (TypeScript) Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Provides functions for creating, updating, and managing teams (groups). It covers creating normal teams with initial members, updating team information, adding/removing members, transferring ownership, and dismissing a team. Assumes a 'store' object with team and member stores is available. ```typescript const team = await store.teamStore.createTeamActive({ name: 'Project Team', avatar: 'https://example.com/avatar.jpg', type: 2, // V2NIMTeamType: 1=advanced, 2=normal accounts: ['user123', 'user456', 'user789'], // Initial members intro: 'Team for project collaboration', serverExtension: JSON.stringify({ department: 'Engineering' }) }); console.log('Team created:', team.teamId); await store.teamStore.updateTeamInfoActive({ teamId: team.teamId, teamType: 2, updateParams: { name: 'Updated Team Name', intro: 'New team description', avatar: 'https://example.com/new-avatar.jpg' } }); await store.teamMemberStore.addTeamMembersActive( team.teamId, 2, // team type ['newuser1', 'newuser2'] ); await store.teamMemberStore.removeTeamMemberActive( team.teamId, 2, 'user123' ); await store.teamStore.transferTeamActive({ teamId: team.teamId, type: 2, account: 'newowner123', leave: false // Whether current owner leaves team }); await store.teamStore.dismissTeamActive(team.teamId, 2); ``` -------------------------------- ### Handle System Messages with Netease Kit IM UI Electron SDK Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Demonstrates handling system messages such as friend requests and team invitations. This includes fetching system messages, accessing specific types like friend applications, marking messages as read, deleting them, and retrieving unread counts. ```typescript // Get system messages (friend requests, team invites, etc.) const sysMsgs = await store.sysMsgStore.getSysMsgListActive(); // Access system messages from store const friendApplications = Array.from(store.sysMsgStore.friendApplicationSysMsgs.values()); friendApplications.forEach(sysMsg => { console.log({ messageId: sysMsg.messageId, type: sysMsg.type, // 1=friend_add, 2=friend_delete, etc. senderId: sysMsg.senderId, text: sysMsg.text, status: sysMsg.status, // 0=pending, 1=accept, 2=reject, 3=ignore, 4=expired createTime: sysMsg.createTime, read: sysMsg.read }); }); // Get team system messages (invites, join requests) const teamSysMsgs = Array.from(store.sysMsgStore.teamApplicationSysMsgs.values()); // Mark system message as read await store.sysMsgStore.setSystemMessageStatusActive([sysMsg], 1); // 1=read // Delete system message await store.sysMsgStore.deleteSystemMessageActive([sysMsg]); // Get unread system message count const unreadCount = store.sysMsgStore.getTotalUnreadMsgsCount(); ``` -------------------------------- ### Manage Conversations with Netease Kit IM UI Electron SDK Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Illustrates how to manage conversations, including creating, deleting, and modifying them. Operations include inserting/selecting conversations, deleting them, sticking them to the top, marking them as read, updating extensions, and retrieving conversations by ID. ```typescript // Insert or select conversation (creates if doesn't exist) await store.conversationStore.insertConversationActive( 1, // V2NIMConversationType: 1=P2P, 2=TEAM 'user123', // Target account or team ID true // isSelected - whether to activate conversation ); // This updates UI store: store.uiStore.selectedConversation // Delete conversation await store.conversationStore.deleteConversationActive('p2p-user123'); // Stick conversation to top await store.conversationStore.stickTopConversationActive('p2p-user123', true); // Unstick from top await store.conversationStore.stickTopConversationActive('p2p-user123', false); // Mark conversation as read (clear unread count) await store.conversationStore.resetConversation('p2p-user123'); // Update conversation extension await store.conversationStore.updateConversationActive('p2p-user123', { serverExtension: JSON.stringify({ category: 'work', priority: 'high' }) }); // Get conversation by ID const conversation = store.conversationStore.conversations.get('team-team456'); ``` -------------------------------- ### Send and Handle File Messages with Netease IM UIKit Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Send various types of files, including images, audio, video, and general documents, with progress tracking for uploads. This snippet also demonstrates how to initiate file downloads. ```typescript // Create file message (supports images, audio, video, files) const fileMsg = nim.messageCreator?.createFileMessage({ filePath: '/path/to/document.pdf', name: 'document.pdf', ext: 'pdf', size: 1024000 // bytes }); // Send with progress callback let uploadProgress = 0; await store.msgStore.sendMessageActive({ msg: fileMsg, conversationId: 'p2p-user123', progress: (percentage) => { uploadProgress = percentage; console.log(`Uploading: ${percentage}%`); return true; } }); // For image messages const imageMsg = nim.messageCreator?.createImageMessage({ filePath: '/path/to/image.jpg', name: 'photo.jpg', width: 1920, height: 1080, size: 512000 }); await store.msgStore.sendMessageActive({ msg: imageMsg, conversationId: 'team-team456', previewImg: 'data:image/jpeg;base64,...' // Optional thumbnail for immediate display }); // Download file from message const fileAttachment = message.attachment; const downloadTask = nim.storageService?.createDownloadFileTask( fileAttachment.url, '/download/path/document.pdf' ); await nim.storageService?.downloadFile(downloadTask, (percentage) => { console.log(`Download progress: ${percentage}%`); }); ``` -------------------------------- ### AI Bot Integration: Send Messages and Handle Streaming Responses Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt This section covers interacting with AI bots, including sending messages with conversation context, handling AI-generated responses (both immediate and streaming), stopping streaming, regenerating responses, and retrieving a list of available AI users. It uses `nim.messageCreator` and `store.msgStore`. ```typescript const aiMsg = nim.messageCreator?.createTextMessage('What is machine learning?'); await store.msgStore.sendMessageActive({ msg: aiMsg, conversationId: 'p2p-aibot123', // AI bot account ID onAISend: (msg, aiConfig) => { console.log('AI configuration:', aiConfig); // aiConfig includes: // - accountId: AI bot ID // - content: Current message // - messages: Last 30 messages as context // - aiStream: Whether streaming is enabled } }); // If AI streaming is enabled, responses arrive incrementally // Message object updates with aiStatus and text content await store.msgStore.stopAIStreamMessageActive(aiMessage, { stopMode: 1 // 1=NORMAL, 2=ABNORMAL }); await store.msgStore.regenAIMessageActive(aiMessage, { regenMode: 1, // 1=UPDATE (replace), 2=INSERT (add new) prompt: 'Please provide more details' // Optional custom prompt }); const aiUsers = await store.aiUserStore.getAIUserListActive(); aiUsers.forEach(aiUser => { console.log({ accountId: aiUser.accountId, name: aiUser.name, avatar: aiUser.avatar, aiModelType: aiUser.aiModelType, aiConfig: aiUser.aiConfig }); }); ``` -------------------------------- ### Subscribe and Manage User Status Updates (TypeScript) Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt This snippet demonstrates how to subscribe to and unsubscribe from user status updates, access the current statuses of subscribed users, and update your own custom status. It utilizes the subscriptionStore and userService from the IM UIKit. The subscription time is specified in seconds. ```typescript await store.subscriptionStore.subscribeUserStatusActive(['user1', 'user2'], 30 * 24 * 60 * 60); // subscriptionTime in seconds (e.g., 30 days) await store.subscriptionStore.unsubscribeUserStatusActive(['user1']); const userStatuses = Array.from(store.subscriptionStore.userStatus.values()); userStatuses.forEach(status => { console.log({ accountId: status.accountId, online: status.onlineState === 1, // 1=online, 0=offline clientType: status.clientType, // Device type customStatus: status.customStatus, updateTime: status.updateTime }); }); await nim.userService?.updateSelfUserProfile({ serverExtension: JSON.stringify({ customStatus: 'In a meeting', statusEmoji: '💼' }) }); ``` -------------------------------- ### Manage Messages: Recall, Forward, Pin, Delete, and Clear History Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt This snippet demonstrates various message operations including recalling, forwarding, pinning, deleting messages locally or for everyone, and clearing conversation history. It utilizes the `store.msgStore` object for these actions. ```typescript await store.msgStore.reCallMsgActive(message); // Creates a notification message: "You recalled a message" / "XXX recalled a message" await store.msgStore.forwardMsgActive( message, 'team-team789', // Target conversation ID 'Check this out!' // Optional comment ); await store.msgStore.pinMessageActive(message, { pinOption: { pinState: 1 // 1=pin, 0=unpin }, serverExtension: { category: 'important' } }); const pinnedMsgs = await store.msgStore.getPinnedMessagesActive('team-team123', 2); await store.msgStore.deleteMsgActive([message], false); await store.msgStore.deleteMsgActive([message], true); await store.msgStore.clearHistoryMessageActive('p2p-user123'); ``` -------------------------------- ### Fetch Message History (TypeScript) Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Loads historical messages for a given conversation with pagination support. It demonstrates how to fetch messages before a specific timestamp and access message details from the store. Read receipts for team messages are also mentioned. Assumes a 'store' object with message storage is available. ```typescript const messages = await store.msgStore.getHistoryMsgActive({ conversationId: 'p2p-user123', endTime: Date.now(), // Load messages before this timestamp limit: 100, lastMsgId: 'optional-anchor-message-id' // Start from specific message }); const conversationMsgs = store.msgs.get('p2p-user123'); // Returns QueueMap with messages conversationMsgs.forEach(msg => { console.log({ messageClientId: msg.messageClientId, messageServerId: msg.messageServerId, text: msg.text, senderId: msg.senderId, receiverId: msg.receiverId, createTime: msg.createTime, messageType: msg.messageType, // 0=text, 1=image, 2=audio, 3=video, 4=file, etc. sendingState: msg.sendingState, // 0=default, 1=sending, 2=failed, 3=succeeded readReceiptEnabled: msg.readReceiptEnabled, attachment: msg.attachment // For media messages }); }); // For team messages, SDK automatically fetches read/unread status // Access via: msg.readCount, msg.unreadCount ``` -------------------------------- ### Fetch and Display Conversation List (TypeScript) Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Retrieves a list of active conversations, including unread counts and metadata. It also demonstrates how to access conversation data and listen for total unread count changes using MobX autorun. Assumes a 'store' object with conversation and message stores is available. ```typescript const conversations = await store.conversationStore.getConversationListActive(0, 100); const conversationList = Array.from(store.conversationStore.conversations.values()); conversationList.forEach(conv => { console.log({ id: conv.conversationId, name: conv.name, unreadCount: conv.unreadCount, lastMessage: conv.lastMessage, stickTop: conv.stickTop, updateTime: conv.updateTime, type: conv.type // 1=P2P, 2=TEAM }); }); const totalUnread = store.conversationStore.totalUnreadCount; import { autorun } from 'mobx'; autorun(() => { const total = store.conversationStore.totalUnreadCount; console.log(`Total unread messages: ${total}`); // UI automatically updates when this value changes }); ``` -------------------------------- ### Handle Friend Operations with Netease IM UIKit Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Manage friend relationships, including adding, deleting, updating aliases, and handling friend requests. This section covers fetching friend lists and their application statuses using the store functionalities. ```typescript // Get friend list const friends = await store.friendStore.getFriendListActive(); // Access friends from store const friendList = Array.from(store.friendStore.friends.values()); friendList.forEach(friend => { console.log({ accountId: friend.accountId, alias: friend.alias, // Friend remark name addTime: friend.addTime, serverExtension: friend.serverExtension }); }); // Add friend await store.friendStore.addFriendActive('user123', { addMode: 1, // 1=direct_add, 2=need_verify postscript: 'Hi, I would like to add you as a friend' }); // Delete friend await store.friendStore.deleteFriendActive('user123', { deleteAlias: true // Also delete friend's alias }); // Update friend alias await store.friendStore.setFriendInfoActive('user123', { alias: 'John Doe', serverExtension: JSON.stringify({ note: 'College classmate' }) }); // Get friend add applications const applications = await store.friendStore.getAddApplicationListActive({ status: [], // Empty for all, or [1=pending, 2=agreed, 3=rejected, 4=expired] offset: 0, limit: 100 }); // Accept friend request await store.friendStore.acceptAddApplicationActive('applicant123'); // Reject friend request await store.friendStore.rejectAddApplicationActive('applicant123', { postscript: 'Sorry, I do not recognize you' }); ``` -------------------------------- ### Voice-to-Text Conversion for Audio Messages Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt This functionality allows for the conversion of audio messages into text. It demonstrates sending an audio message and then initiating the voice-to-text conversion process using `store.msgStore.voiceToTextActive`. The transcribed text is then accessible via the `textOfVoice` property on the message object. ```typescript const audioMsg = nim.messageCreator?.createAudioMessage({ filePath: '/path/to/audio.mp3', name: 'audio.mp3', duration: 15000, // milliseconds size: 256000 }); await store.msgStore.sendMessageActive({ msg: audioMsg, conversationId: 'p2p-user123' }); await store.msgStore.voiceToTextActive(audioMsg); // Message object updates with textOfVoice property const updatedMsg = store.msgStore.getMsg('p2p-user123', [audioMsg.messageClientId])[0]; console.log('Transcribed text:', updatedMsg.textOfVoice); ``` -------------------------------- ### Message Read Receipts with Netease IM UIKit Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Implement and track message read receipts for both peer-to-peer (P2P) and team conversations. This includes sending receipts, retrieving read status, and accessing read counts directly from message objects. ```typescript // Send P2P message read receipt await store.msgStore.sendMsgReceiptActive(message); // Access receipt time for P2P conversation const conversation = store.conversationStore.conversations.get('p2p-user123'); const receiptTime = conversation.msgReceiptTime; // All messages with createTime <= receiptTime are read by recipient // Send team message read receipts (batch) const unreadMessages = conversationMsgs.filter(msg => !msg.isSelf); await store.msgStore.sendTeamMsgReceiptActive(unreadMessages); // Get team message read/unread details const readDetails = await store.msgStore.getTeamMessageReceiptDetailsActive( message, ['member1', 'member2', 'member3'] // Member account IDs ); console.log({ readCount: readDetails.readCount, unreadCount: readDetails.unreadCount, readAccountIds: readDetails.readAccountIds, unreadAccountIds: readDetails.unreadAccountIds }); // Access read count from message object (automatically fetched) const myMessage = store.msgStore.getMsg('team-team123', ['msgId'])[0]; console.log(`Read by ${myMessage.readCount} members, unread by ${myMessage.unreadCount}`); ``` -------------------------------- ### Send Message with @Mention in Team Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Sends a team message that includes @mentions for specific users or all members. Configures the server extension to specify which users are mentioned and their positions in the text. Notified users will see an unread @mention indicator. ```typescript // Create text with @mention const mentionText = '@张三 @李四 请查看这个文件 @所有人'; const textMsg = nim.messageCreator?.createTextMessage(mentionText); // Configure @mention server extension const serverExtension = { yxAitMsg: { 'user123': { segments: [{ start: 0, end: 3, text: '@张三' }] }, 'user456': { segments: [{ start: 4, end: 7, text: '@李四' }] }, 'ait_all': { segments: [{ start: 18, end: 22, text: '@所有人' }] } } }; // Send to team conversation await store.msgStore.sendMessageActive({ msg: textMsg, conversationId: 'team-team789', serverExtension }); // Mentioned users will see unread @mention indicator in conversation list // store.conversationStore.conversations.get('team-team789').aitMsgs contains message IDs with @mentions ``` -------------------------------- ### Send Text Message Source: https://context7.com/netease-kit/nim-uikit-electron/llms.txt Sends a text message to a specified conversation. Supports optional server extensions for custom data and provides callbacks for upload progress and pre-send message hooks. The UI updates optimistically, and the SDK handles delivery and retries. ```typescript // Create a text message const textMsg = nim.messageCreator?.createTextMessage('Hello, this is a message!'); // Send message with full options await store.msgStore.sendMessageActive({ msg: textMsg, conversationId: 'p2p-user123', // Format: 'p2p-{accountId}' or 'team-{teamId}' serverExtension: { customField: 'custom-value', metadata: { source: 'web' } }, progress: (percentage) => { console.log(`Upload progress: ${percentage}%`); return true; // Return true to continue receiving progress updates }, sendBefore: (msg) => { console.log('Message about to send:', msg); } }); // Message appears immediately in UI (optimistic update) // SDK handles delivery, retries, and status updates automatically ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.