UNPKG

nativescript-matrix-sdk

Version:

Native Matrix SDK integration for NativeScript

985 lines (833 loc) 24.5 kB
/** * Matrix SDK TypeScript definitions */ /** * Represents a Matrix server */ export interface MatrixServer { id: string; name: string; icon: string; description?: string; memberCount: number; isPrivate: boolean; createdAt: Date; updatedAt: Date; } /** * Represents a Matrix room/chat */ export interface MatrixChat { id: string; serverId: string; type: 'direct' | 'room' | 'group' | 'channel'; name: string; avatar: string; lastMessage: string; lastMessageAt: Date; unread: number; participants: string[]; isArchived: boolean; isPinned: boolean; } /** * File content metadata for Matrix messages */ export interface MatrixFileContent { /** * Matrix content URI for the file */ url: string; /** * MIME type of the file */ mimeType: string; /** * Original filename */ filename: string; /** * File size in bytes */ size: number; /** * Matrix content URI for the thumbnail (if available) */ thumbnailUrl?: string; /** * Width of the image/video (if applicable) */ width?: number; /** * Height of the image/video (if applicable) */ height?: number; /** * Duration in milliseconds (for audio/video) */ duration?: number; /** * Whether the file is encrypted */ isEncrypted?: boolean; /** * Additional file-specific metadata */ metadata?: Record<string, unknown>; } /** * Options for sending files */ export interface FileSendOptions { /** * MIME type of the file (if not automatically detectable) */ mimeType?: string; /** * Custom filename to use (defaults to original filename) */ filename?: string; /** * Whether to generate a thumbnail (for images/videos) */ generateThumbnail?: boolean; /** * Whether to compress the file before sending (for images) */ compress?: boolean; /** * Compression quality (0.0 - 1.0) for images */ compressionQuality?: number; } /** * Progress information for file transfers */ export interface TransferProgress { /** * Bytes transferred so far */ bytesTransferred: number; /** * Total bytes to transfer */ totalBytes: number; /** * Progress percentage (0-100) */ percentage: number; } /** * Status of a message transaction */ export enum MessageTransactionStatus { /** Message is being composed but not yet sent */ COMPOSING = 'composing', /** Message is queued to be sent */ QUEUED = 'queued', /** Message is currently being sent */ SENDING = 'sending', /** Message has been sent successfully */ SENT = 'sent', /** Message delivery was confirmed by the server */ DELIVERED = 'delivered', /** Message delivery failed */ FAILED = 'failed', /** Message was read by recipient(s) */ READ = 'read', /** Message has been deleted */ DELETED = 'deleted' } /** * Represents a pending message transaction */ export interface PendingTransaction { /** Local ID for this transaction */ localId: string; /** Chat ID where this message belongs */ chatId: string; /** Status of the transaction */ status: MessageTransactionStatus; /** Message content */ content: string; /** Content type */ contentType: 'text' | 'image' | 'file' | 'video' | 'audio' | 'system'; /** File content for non-text messages */ fileContent?: MatrixFileContent; /** Server event ID (once available) */ eventId?: string; /** Number of retry attempts */ retryCount: number; /** Maximum number of retry attempts */ maxRetries: number; /** Time to wait before next retry (in ms) */ retryDelay: number; /** Next retry timestamp */ nextRetryAt?: Date; /** Error information if failed */ error?: { message: string; code?: string; details?: Record<string, unknown>; }; /** Created timestamp */ createdAt: Date; /** Last updated timestamp */ updatedAt: Date; } /** * Represents a Matrix message */ export interface MatrixMessage { /** Server-assigned message ID */ id: string; /** Local transaction ID (for pending/sending messages) */ localId?: string; /** Chat ID where this message belongs */ chatId: string; /** Sender information */ sender: { id: string; name: string; avatar: string; }; /** Message content */ content: string; /** Content type */ contentType: 'text' | 'image' | 'file' | 'video' | 'audio' | 'system'; /** Message reactions */ reactions: MatrixReaction[]; /** Created timestamp */ createdAt: Date; /** Last edited timestamp */ editedAt?: Date; /** Transaction status */ status: MessageTransactionStatus; /** Additional metadata */ metadata?: Record<string, unknown>; /** File content for non-text messages */ fileContent?: MatrixFileContent; } /** * Represents a reaction to a message */ export interface MatrixReaction { emoji: string; count: number; users: string[]; } /** * Types of Matrix events that can be listened for */ export enum MatrixEventType { /** New message received */ MESSAGE_RECEIVED = 'message_received', /** Room state changed (e.g., name, topic, membership) */ ROOM_STATE_CHANGED = 'room_state_changed', /** Sync state changed */ SYNC_STATE_CHANGED = 'sync_state_changed', /** New room invitation received */ INVITE = 'invite', /** Room encryption state changed */ ENCRYPTION_CHANGED = 'encryption_changed', /** User presence changed */ PRESENCE_CHANGED = 'presence_changed', /** Typing notifications */ TYPING = 'typing', /** Read receipts received */ READ_RECEIPT = 'read_receipt', /** Device verification request received */ VERIFICATION_REQUEST = 'verification_request', /** Device verification status changed */ VERIFICATION_STATUS_CHANGED = 'verification_status_changed', /** Cross signing status changed */ CROSS_SIGNING_STATUS_CHANGED = 'cross_signing_status_changed', /** Key backup status changed */ KEY_BACKUP_STATUS_CHANGED = 'key_backup_status_changed' } /** * User presence status */ export enum PresenceStatus { /** User is online and active */ ONLINE = 'online', /** User is online but inactive/away */ UNAVAILABLE = 'unavailable', /** User is offline */ OFFLINE = 'offline', /** User presence is unknown */ UNKNOWN = 'unknown' } /** * User presence information */ export interface UserPresence { /** User ID */ userId: string; /** Current presence status */ status: PresenceStatus; /** Last active timestamp */ lastActiveAt?: Date; /** Custom status message set by the user */ statusMessage?: string; /** When the presence information was last updated */ updatedAt: Date; } /** * Device verification status */ export enum DeviceVerificationStatus { /** Device is verified and trusted */ VERIFIED = 'verified', /** Device is blocked/blacklisted */ BLOCKED = 'blocked', /** Device is unverified (default state) */ UNVERIFIED = 'unverified' } /** * Device key information */ export interface DeviceKeyInfo { /** Device ID */ deviceId: string; /** User ID who owns the device */ userId: string; /** Display name of the device (if available) */ displayName?: string; /** Verification status of the device */ verificationStatus: DeviceVerificationStatus; /** Key algorithms supported by this device */ algorithms: string[]; /** Public keys for this device (key_id -> key) */ keys: Record<string, string>; /** When this device was first seen */ firstSeen?: Date; /** When this device was last seen */ lastSeen?: Date; } /** * Key export format options */ export enum KeyExportFormat { /** Standard format as defined by Matrix */ STANDARD = 'standard', /** Compatibility format for older clients */ LEGACY = 'legacy' } /** * Key backup information */ export interface KeyBackupInfo { /** Backup version */ version: string; /** Number of keys in the backup */ keyCount: number; /** Algorithm used for the backup */ algorithm: string; /** When the backup was created */ createdAt: Date; } /** * Room encryption algorithm */ export enum RoomEncryptionAlgorithm { /** Megolm algorithm for group encryption */ MEGOLM = 'm.megolm.v1.aes-sha2', /** Olm algorithm for direct encryption */ OLM = 'm.olm.v1.curve25519-aes-sha2' } /** * Cross-signing information */ export interface CrossSigningInfo { /** Whether cross-signing is enabled for the user */ enabled: boolean; /** Whether the current session is verified */ verified: boolean; /** Public keys for cross-signing */ publicKeys?: { masterKey: string; selfSigningKey: string; userSigningKey: string; }; } /** * Event data for different event types */ export interface MatrixEventData { /** Base properties present in all event types */ roomId?: string; timestamp?: Date; /** Message-specific properties */ message?: { id: string; content: string; sender: { id: string; name: string; }; }; /** Room state properties */ roomState?: { name?: string; topic?: string; membersCount?: number; updatedAt: Date; }; /** Encryption-related properties */ encryption?: { enabled: boolean; algorithm?: string; /** Whether key backup is enabled */ backupEnabled?: boolean; /** Whether a recovery key is available */ recoveryKeyAvailable?: boolean; /** Whether keys have been restored from backup */ keysRestored?: boolean; /** Number of keys restored from backup */ numberOfKeysRestored?: number; /** Whether cross-signing is enabled */ crossSigningEnabled?: boolean; /** Whether cross-signing has been initialized */ crossSigningInitialized?: boolean; /** User ID that was signed with cross-signing */ userSigned?: string; /** Timestamp of the last update */ updateTime?: Date; }; /** Typing notification properties */ typing?: { users: string[]; isTyping?: boolean; }; /** Read receipt properties */ readReceipt?: { userId: string; messageId: string; timestamp: Date; }; /** Sync state properties */ syncState?: { state: string; }; /** Presence-related properties */ presence?: { userId: string; status: PresenceStatus; lastActiveAt?: Date; statusMessage?: string; }; /** Device verification properties */ deviceVerification?: { userId: string; deviceId: string; status: DeviceVerificationStatus; verified: boolean; }; /** Properties for raw events - avoid using this when possible */ raw?: Record<string, unknown>; } /** * Matrix event listener callback */ export type MatrixEventListener = (eventType: MatrixEventType, data: MatrixEventData) => void; /** * Pagination token for message retrieval */ export interface PaginationToken { /** * Token value to use for the next pagination request */ token: string; /** * Whether there are more messages to retrieve in the requested direction */ hasMore: boolean; } /** * Options for message retrieval */ export interface MessageOptions { /** * Maximum number of messages to retrieve */ limit?: number; /** * Direction to retrieve messages */ direction?: 'backward' | 'forward'; /** * Pagination token from a previous request */ fromToken?: string; } /** * Result of a message retrieval request */ export interface MessageResult { /** * Retrieved messages */ messages: MatrixMessage[]; /** * Token for retrieving more messages */ nextToken: PaginationToken; } /** * Retry options for failed message transactions */ export interface RetryOptions { /** Maximum number of retry attempts */ maxRetries: number; /** Base delay between retries in ms */ baseDelay: number; /** Whether to use exponential backoff */ useExponentialBackoff: boolean; /** Maximum delay between retries in ms */ maxDelay: number; } /** * Options for sending messages */ export interface SendMessageOptions { /** Retry options for this message */ retry?: RetryOptions; /** Whether to immediately retry failed messages from the offline queue */ retryImmediately?: boolean; /** Local ID to use (generates one if not provided) */ localId?: string; } /** * Matrix client interface - both iOS and Android implementations must follow this */ export interface MatrixClient { /** * Initialize the Matrix client * @param homeserverUrl - URL of the Matrix homeserver * @param accessToken - User's access token * @returns Promise that resolves when initialization is complete */ initialize(homeserverUrl: string, accessToken: string): Promise<void>; /** * Login with username and password * @param homeserverUrl - URL of the Matrix homeserver * @param username - Username or Matrix ID * @param password - User password * @param deviceName - Name for this device * @returns Promise that resolves with user ID and access token */ login(homeserverUrl: string, username: string, password: string, deviceName?: string): Promise<{userId: string, accessToken: string}>; /** * Login with SSO * @param homeserverUrl - URL of the Matrix homeserver * @param callbackUrl - URL to redirect to after successful SSO authentication * @returns Promise that resolves with user ID and access token */ loginWithSSO(homeserverUrl: string, callbackUrl: string): Promise<{userId: string, accessToken: string}>; /** * Register a new user * @param homeserverUrl - URL of the Matrix homeserver * @param username - Desired username * @param password - Desired password * @param deviceName - Name for this device * @returns Promise that resolves with user ID and access token */ register(homeserverUrl: string, username: string, password: string, deviceName?: string): Promise<{userId: string, accessToken: string}>; /** * Get the current user ID * @returns The user ID */ getUserId(): string | null; /** * Get available servers * @returns List of available servers */ getServers(): Promise<MatrixServer[]>; /** * Get chats for a specific server * @param serverId - ID of the server to fetch chats from * @returns List of chats in the server */ getChats(serverId: string): Promise<MatrixChat[]>; /** * Get messages for a specific chat * @param chatId - ID of the chat to fetch messages from * @param options - Options for retrieving messages * @returns List of messages in the chat and a token for pagination */ getMessages(chatId: string, options?: MessageOptions): Promise<MessageResult>; /** * Send a message to a chat * @param chatId - ID of the chat to send the message to * @param content - Content of the message * @param options - Options for sending the message * @returns The sent message */ sendMessage(chatId: string, content: string, options?: SendMessageOptions): Promise<MatrixMessage>; /** * Add a reaction to a message * @param chatId - ID of the chat containing the message * @param messageId - ID of the message to react to * @param reaction - The reaction to add */ addReaction(chatId: string, messageId: string, reaction: string): Promise<void>; /** * Join a chat room * @param chatId - ID of the chat to join */ joinChat(chatId: string): Promise<void>; /** * Leave a chat room * @param chatId - ID of the chat to leave */ leaveChat(chatId: string): Promise<void>; /** * Clean up resources when client is no longer needed * Important for memory management and proper resource release */ cleanup(): Promise<void>; /** * Enable end-to-end encryption for a room * @param roomId - ID of the room to enable encryption for */ enableEncryption(roomId: string): Promise<void>; /** * Check if a room has encryption enabled * @param roomId - ID of the room to check * @returns Whether encryption is enabled for the room */ isEncryptionEnabled(roomId: string): Promise<boolean>; /** * Add an event listener * @param eventType - Type of event to listen for * @param listener - Callback function to handle the event */ addEventListener(eventType: MatrixEventType, listener: MatrixEventListener): void; /** * Remove an event listener * @param eventType - Type of event to stop listening for * @param listener - Callback function to remove */ removeEventListener(eventType: MatrixEventType, listener: MatrixEventListener): void; /** * Start listening for events * This enables real-time updates for new messages, etc. */ startListening(): Promise<void>; /** * Stop listening for events */ stopListening(): Promise<void>; /** * Send a file to a chat * @param chatId - ID of the chat to send the file to * @param localFilePath - Path to the local file to send * @param options - Options for sending the file * @returns The sent message */ sendFile( chatId: string, localFilePath: string, options?: FileSendOptions & SendMessageOptions ): Promise<MatrixMessage>; /** * Download a file from a message * @param messageId - ID of the message containing the file * @param destinationPath - Local path to save the file to * @param onProgress - Optional callback for progress updates * @returns Promise that resolves with the local file path */ downloadFile( messageId: string, destinationPath: string, onProgress?: (progress: TransferProgress) => void ): Promise<string>; /** * Cancel an ongoing file transfer * @param messageId - ID of the message with the file transfer to cancel */ cancelFileTransfer(messageId: string): Promise<void>; /** * Get all pending message transactions * @returns Map of local IDs to pending transactions */ getPendingTransactions(): Promise<Map<string, PendingTransaction>>; /** * Get pending transactions for a specific chat * @param chatId - ID of the chat to get pending transactions for * @returns Map of local IDs to pending transactions */ getPendingTransactionsForChat(chatId: string): Promise<Map<string, PendingTransaction>>; /** * Retry a failed message transaction * @param localId - Local ID of the transaction to retry * @returns Whether the retry was initiated successfully */ retryTransaction(localId: string): Promise<boolean>; /** * Cancel a pending message transaction * @param localId - Local ID of the transaction to cancel * @returns Whether the cancellation was successful */ cancelTransaction(localId: string): Promise<boolean>; /** * Process all pending transactions * Attempts to send any queued messages */ processPendingTransactions(): Promise<void>; /** * Indicate that the user is typing in a chat * @param chatId - ID of the chat where the user is typing * @param isTyping - Whether the user is currently typing */ sendTypingNotification(chatId: string, isTyping: boolean): Promise<void>; /** * Get users currently typing in a chat * @param chatId - ID of the chat to check * @returns List of user IDs who are currently typing */ getTypingUsers(chatId: string): Promise<string[]>; /** * Mark a message as read * @param chatId - ID of the chat containing the message * @param messageId - ID of the message to mark as read */ markMessageAsRead(chatId: string, messageId: string): Promise<void>; /** * Get read receipts for a message * @param chatId - ID of the chat containing the message * @param messageId - ID of the message to get read receipts for * @returns List of read receipts for the message */ getReadReceipts(chatId: string, messageId: string): Promise<ReadReceipt[]>; /** * Set the current user's presence status * @param status - Presence status to set * @param statusMessage - Optional custom status message */ setPresence(status: PresenceStatus, statusMessage?: string): Promise<void>; /** * Get a user's presence information * @param userId - ID of the user to get presence for * @returns User's presence information */ getUserPresence(userId: string): Promise<UserPresence>; /** * Subscribe to presence updates for specific users * @param userIds - Array of user IDs to subscribe to * @returns Promise that resolves when subscription is complete */ subscribeToPresence(userIds: string[]): Promise<void>; /** * Unsubscribe from presence updates for specific users * @param userIds - Array of user IDs to unsubscribe from * @returns Promise that resolves when unsubscription is complete */ unsubscribeFromPresence(userIds: string[]): Promise<void>; /** * Get presence information for all subscribed users * @returns Map of user IDs to presence information */ getAllPresence(): Promise<Map<string, UserPresence>>; /** * Get all known devices for a user * @param userId - User ID to get devices for * @returns List of device key information */ getUserDevices(userId: string): Promise<DeviceKeyInfo[]>; /** * Set the verification status of a device * @param userId - User ID who owns the device * @param deviceId - Device ID to update * @param status - New verification status */ setDeviceVerification(userId: string, deviceId: string, status: DeviceVerificationStatus): Promise<void>; /** * Start device verification process * @param userId - User ID who owns the device * @param deviceId - Device ID to verify * @returns Verification request ID */ startDeviceVerification(userId: string, deviceId: string): Promise<string>; /** * Accept a device verification request * @param verificationId - Verification request ID */ acceptDeviceVerification(verificationId: string): Promise<void>; /** * Complete device verification with a confirmation code * @param verificationId - Verification request ID * @param confirmationCode - Code to confirm the verification (e.g., SAS emoji codes) */ completeDeviceVerification(verificationId: string, confirmationCode: string): Promise<void>; /** * Export room keys for backup or transfer * @param password - Password to encrypt the keys with * @param format - Export format * @returns Encrypted key file content as a string */ exportRoomKeys(password: string, format?: KeyExportFormat): Promise<string>; /** * Import room keys from a backup or another device * @param keyFile - Encrypted key file content * @param password - Password to decrypt the keys with * @returns Number of keys imported */ importRoomKeys(keyFile: string, password: string): Promise<number>; /** * Create a key backup * @param password - Optional password for additional encryption * @returns Backup recovery key */ createKeyBackup(password?: string): Promise<string>; /** * Restore keys from a backup * @param recoveryKey - Backup recovery key * @returns Number of keys restored */ restoreKeyBackup(recoveryKey: string): Promise<number>; /** * Get information about key backups * @returns List of key backup information */ getKeyBackups(): Promise<KeyBackupInfo[]>; /** * Get cross-signing information for a user * @param userId - User ID to get cross-signing info for (defaults to current user) * @returns Cross-signing information */ getCrossSigningInfo(userId?: string): Promise<CrossSigningInfo>; /** * Bootstrap cross-signing for the current account * @returns Promise that resolves when cross-signing is set up */ setupCrossSigning(): Promise<void>; /** * Sign another user's key with cross-signing * @param userId - User ID to sign * @returns Promise that resolves when the key is signed */ signUserKey(userId: string): Promise<void>; } /** * Main Matrix SDK class */ export declare class MatrixSDK { /** * Get the Matrix client * @returns MatrixClient instance */ static getClient(): MatrixClient; } /** * ReadReceipt interface */ export interface ReadReceipt { /** ID of the user who read the message */ userId: string; /** ID of the message that was read */ messageId: string; /** Timestamp when the message was marked as read */ timestamp: Date; }