Initial commit: libp2p-native-bridge package
- Extracted libp2p component from main app - Created modular package structure with interfaces and implementations - Added dependency injection for NativeModules - Configured for IOR loading from Gitea - Added comprehensive README and documentation
This commit is contained in:
402
implementations/Libp2pComponent.ts
Normal file
402
implementations/Libp2pComponent.ts
Normal file
@@ -0,0 +1,402 @@
|
||||
/**
|
||||
* Native libp2p bridge component for React Native
|
||||
*/
|
||||
|
||||
import { NativeEventEmitter, NativeModules } from 'react-native';
|
||||
import { LIBP2P_CONFIG } from '../utils/constants';
|
||||
import type { ConnectionStatusEvent, PeerDiscoveredEvent, PeerInfoEvent } from '../utils/types';
|
||||
import type {
|
||||
Connection,
|
||||
ILibp2pComponent,
|
||||
Libp2pEvents,
|
||||
Libp2pOptions,
|
||||
Multiaddr,
|
||||
PeerId,
|
||||
PeerInfo,
|
||||
} from '../interfaces/ILibp2pComponent';
|
||||
|
||||
// Helper class to create PeerId-like objects from strings
|
||||
export class SimplePeerId implements PeerId {
|
||||
constructor(private id: string) {}
|
||||
|
||||
toString(): string {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
toBytes(): Uint8Array {
|
||||
return new TextEncoder().encode(this.id);
|
||||
}
|
||||
|
||||
equals(other: PeerId): boolean {
|
||||
return this.toString() === other.toString();
|
||||
}
|
||||
}
|
||||
|
||||
// Helper class to create Multiaddr-like objects from strings
|
||||
export class SimpleMultiaddr implements Multiaddr {
|
||||
bytes: Uint8Array;
|
||||
|
||||
constructor(private addr: string) {
|
||||
this.bytes = new TextEncoder().encode(addr);
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return this.addr;
|
||||
}
|
||||
|
||||
protos(): Array<{ code: number; name: string }> {
|
||||
// Simple parsing of multiaddr components
|
||||
const parts = this.addr.split('/').filter((p) => p);
|
||||
const protos = [];
|
||||
|
||||
for (let i = 0; i < parts.length; i += 2) {
|
||||
const name = parts[i];
|
||||
protos.push({ code: 0, name }); // Simplified - real implementation would have proper codes
|
||||
}
|
||||
|
||||
return protos;
|
||||
}
|
||||
|
||||
getPeerId(): string | null {
|
||||
const match = this.addr.match(/\/p2p\/([^/]+)/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
}
|
||||
|
||||
// Type for event handler functions
|
||||
type EventHandler<T = unknown> = (evt: T) => void;
|
||||
|
||||
// Native implementation that wraps our iOS/Android modules
|
||||
export class Libp2pComponent implements ILibp2pComponent {
|
||||
private nativeModule: any;
|
||||
private eventEmitter: NativeEventEmitter;
|
||||
private eventHandlers: Map<string, Set<EventHandler>> = new Map();
|
||||
private _peerId?: PeerId;
|
||||
private _multiaddrs: Multiaddr[] = [];
|
||||
private _started: boolean = false;
|
||||
private cachedConnections: Connection[] = [];
|
||||
private options: Libp2pOptions;
|
||||
|
||||
constructor(options?: Libp2pOptions, nativeModules?: typeof NativeModules) {
|
||||
// Allow dependency injection of NativeModules for testing
|
||||
const modules = nativeModules || NativeModules;
|
||||
this.nativeModule = modules.Libp2pModule;
|
||||
this.eventEmitter = new NativeEventEmitter(this.nativeModule);
|
||||
this.options = options || {};
|
||||
|
||||
if (!this.nativeModule) {
|
||||
throw new Error('Libp2p native module not found');
|
||||
}
|
||||
|
||||
this.setupNativeEventListeners();
|
||||
this.setupProtocolHandlers();
|
||||
}
|
||||
|
||||
get peerId(): PeerId | null {
|
||||
return this._peerId || null;
|
||||
}
|
||||
|
||||
get multiaddrs(): Multiaddr[] {
|
||||
return this._multiaddrs;
|
||||
}
|
||||
|
||||
private setupNativeEventListeners(): void {
|
||||
// Map native events to js-libp2p style events
|
||||
|
||||
// Peer info update
|
||||
this.eventEmitter.addListener('onPeerInfo', ({ peerId, multiaddrs }: PeerInfoEvent) => {
|
||||
this._peerId = new SimplePeerId(peerId);
|
||||
this._multiaddrs = multiaddrs.map((addr: string) => new SimpleMultiaddr(addr));
|
||||
this.emit('self:peer:update', {
|
||||
peerId: this._peerId,
|
||||
multiaddrs: this._multiaddrs,
|
||||
});
|
||||
});
|
||||
|
||||
// Peer discovery
|
||||
this.eventEmitter.addListener(
|
||||
'onPeerDiscovered',
|
||||
({ peerId, addresses, multiaddrs }: PeerDiscoveredEvent) => {
|
||||
const addrs = (multiaddrs || addresses || []).map(
|
||||
(addr: string) => new SimpleMultiaddr(addr),
|
||||
);
|
||||
this.emit('peer:discovery', {
|
||||
id: new SimplePeerId(peerId),
|
||||
multiaddrs: addrs,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Peer lost (for mDNS service lost events)
|
||||
this.eventEmitter.addListener('onPeerLost', ({ peerId }: { peerId: string }) => {
|
||||
this.emit('peer:lost', {
|
||||
id: new SimplePeerId(peerId),
|
||||
});
|
||||
});
|
||||
|
||||
// Connection events
|
||||
this.eventEmitter.addListener(
|
||||
'onConnectionStatus',
|
||||
({ peerId, status, direction, multiaddr }: ConnectionStatusEvent) => {
|
||||
const connection: Connection = {
|
||||
id: `${peerId}-${Date.now()}`,
|
||||
remotePeer: new SimplePeerId(peerId),
|
||||
remoteAddr: new SimpleMultiaddr(multiaddr || ''),
|
||||
stat: {
|
||||
direction: direction || 'outbound',
|
||||
status:
|
||||
status === LIBP2P_CONFIG.CONNECTION_STATUS.CONNECTED
|
||||
? 'open'
|
||||
: status === LIBP2P_CONFIG.CONNECTION_STATUS.PENDING
|
||||
? 'pending'
|
||||
: status === LIBP2P_CONFIG.CONNECTION_STATUS.DISCONNECTED
|
||||
? 'closed'
|
||||
: 'closing',
|
||||
timeline: {
|
||||
open: Date.now(),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (
|
||||
status === LIBP2P_CONFIG.CONNECTION_STATUS.CONNECTED ||
|
||||
status === LIBP2P_CONFIG.CONNECTION_STATUS.PENDING
|
||||
) {
|
||||
// Emit peer:connect for both pending and connected states
|
||||
// The UI will differentiate based on connection.stat.status
|
||||
this.emit('peer:connect', connection);
|
||||
this.emit('connection:open', connection);
|
||||
} else if (
|
||||
status === LIBP2P_CONFIG.CONNECTION_STATUS.DISCONNECTED ||
|
||||
status === LIBP2P_CONFIG.CONNECTION_STATUS.FAILED
|
||||
) {
|
||||
connection.stat.timeline.close = Date.now();
|
||||
connection.stat.status = 'closed';
|
||||
this.emit('peer:disconnect', connection);
|
||||
this.emit('connection:close', connection);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private setupProtocolHandlers(): void {
|
||||
// Listen for protocol data events
|
||||
this.eventEmitter.addListener(
|
||||
'onProtocolData',
|
||||
(data: { protocolId: string; peerId: string; data?: number[] }) => {
|
||||
// Find matching protocol handler
|
||||
const handler = this.options.protocols?.find((p) => p.protocolId === data.protocolId);
|
||||
if (handler) {
|
||||
// Convert number array to Uint8Array if needed
|
||||
const uint8Data = data.data ? new Uint8Array(data.data) : undefined;
|
||||
handler.handler({ peerId: data.peerId, data: uint8Data });
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private emit<K extends keyof Libp2pEvents>(event: K, detail: unknown): void {
|
||||
const handlers = this.eventHandlers.get(event);
|
||||
if (handlers) {
|
||||
const customEvent = new CustomEvent(event, { detail });
|
||||
for (const handler of handlers) {
|
||||
handler(customEvent as Libp2pEvents[K]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
// Register protocols if any
|
||||
if (this.options.protocols && this.nativeModule.registerProtocolHandler) {
|
||||
for (const protocol of this.options.protocols) {
|
||||
await this.nativeModule.registerProtocolHandler(protocol.protocolId);
|
||||
}
|
||||
}
|
||||
|
||||
// Pass configuration options to native module including keypair
|
||||
const config = {
|
||||
tcpPort: this.options.config?.tcpPort,
|
||||
wsPort: this.options.config?.wsPort,
|
||||
// Convert Uint8Array to base64 for passing to native module
|
||||
keypair: this.options.keypair
|
||||
? {
|
||||
privateKey: btoa(String.fromCharCode(...this.options.keypair.privateKey)),
|
||||
publicKey: btoa(String.fromCharCode(...this.options.keypair.publicKey)),
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
await this.nativeModule.startLibp2p(config);
|
||||
this._started = true;
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
try {
|
||||
await this.nativeModule.stopLibp2p();
|
||||
this._started = false;
|
||||
} catch (error) {
|
||||
// If libp2p wasn't running, that's okay - just update our state
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const errorCode = (error as { code?: string })?.code;
|
||||
if (errorMessage.includes('not running') || errorCode === 'LIBP2P_ERROR') {
|
||||
this._started = false;
|
||||
} else {
|
||||
// Re-throw other errors
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async dial(multiaddr: string): Promise<Connection> {
|
||||
await this.nativeModule.connectToPeer(multiaddr);
|
||||
|
||||
// Create connection object
|
||||
const peerId = multiaddr.match(/\/p2p\/([^/]+)/)?.[1] || '';
|
||||
return {
|
||||
id: `${peerId}-${Date.now()}`,
|
||||
remotePeer: new SimplePeerId(peerId),
|
||||
remoteAddr: new SimpleMultiaddr(multiaddr),
|
||||
stat: {
|
||||
direction: 'outbound',
|
||||
status: 'open',
|
||||
timeline: {
|
||||
open: Date.now(),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async hangUp(peerId: string): Promise<void> {
|
||||
const result = await this.nativeModule.hangUp(peerId);
|
||||
|
||||
if (!result?.success) {
|
||||
// No active connections to peer - this is okay
|
||||
}
|
||||
}
|
||||
|
||||
async getConnections(peerId?: string): Promise<Connection[]> {
|
||||
try {
|
||||
const rawConnections = await this.nativeModule.getConnections();
|
||||
|
||||
// Transform native connections to match the Connection interface
|
||||
this.cachedConnections = (rawConnections || []).map((conn: any) => {
|
||||
// Ensure the connection has the expected structure
|
||||
// Handle different formats from native modules
|
||||
let peerIdStr = conn.peerId || 'unknown';
|
||||
if (conn.remotePeer) {
|
||||
// If remotePeer is an object with toString property (from native module)
|
||||
if (typeof conn.remotePeer.toString === 'string') {
|
||||
peerIdStr = conn.remotePeer.toString;
|
||||
}
|
||||
// If remotePeer is a PeerId object with toString method
|
||||
else if (typeof conn.remotePeer.toString === 'function') {
|
||||
peerIdStr = conn.remotePeer.toString();
|
||||
}
|
||||
}
|
||||
|
||||
const connection: Connection = {
|
||||
id: conn.id || `${peerIdStr}-${Date.now()}`,
|
||||
remotePeer: new SimplePeerId(peerIdStr),
|
||||
remoteAddr: conn.remoteAddr?.toString
|
||||
? new SimpleMultiaddr(
|
||||
typeof conn.remoteAddr.toString === 'string'
|
||||
? conn.remoteAddr.toString
|
||||
: conn.remoteAddr.toString(),
|
||||
)
|
||||
: new SimpleMultiaddr('/unknown'),
|
||||
stat: conn.stat || {
|
||||
direction: conn.direction || 'outbound',
|
||||
status: conn.status || 'open',
|
||||
timeline: conn.timeline || {
|
||||
open: Date.now(),
|
||||
},
|
||||
},
|
||||
};
|
||||
return connection;
|
||||
});
|
||||
|
||||
// Filter by peerId if provided
|
||||
if (peerId) {
|
||||
return this.cachedConnections.filter((conn) => conn.remotePeer.toString() === peerId);
|
||||
}
|
||||
|
||||
return this.cachedConnections;
|
||||
} catch (_error) {
|
||||
// Failed to get connections
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
addEventListener<K extends keyof Libp2pEvents>(
|
||||
event: K,
|
||||
handler: (evt: Libp2pEvents[K]) => void,
|
||||
): void {
|
||||
if (!this.eventHandlers.has(event)) {
|
||||
this.eventHandlers.set(event, new Set());
|
||||
}
|
||||
this.eventHandlers.get(event)?.add(handler as EventHandler);
|
||||
}
|
||||
|
||||
removeEventListener<K extends keyof Libp2pEvents>(
|
||||
event: K,
|
||||
handler: (evt: Libp2pEvents[K]) => void,
|
||||
): void {
|
||||
const handlers = this.eventHandlers.get(event);
|
||||
if (handlers) {
|
||||
handlers.delete(handler as EventHandler);
|
||||
}
|
||||
}
|
||||
|
||||
async refreshDiscovery(): Promise<void> {
|
||||
if (this.nativeModule.refreshDiscovery) {
|
||||
await this.nativeModule.refreshDiscovery();
|
||||
}
|
||||
}
|
||||
|
||||
async pingPeer(peerId: string): Promise<{ success: boolean; rtt?: number; peerId: string }> {
|
||||
if (this.nativeModule.pingPeer) {
|
||||
return await this.nativeModule.pingPeer(peerId);
|
||||
} else {
|
||||
throw new Error('Ping not supported on this platform');
|
||||
}
|
||||
}
|
||||
|
||||
async sendProtocolData(peerId: string, protocolId: string, data: Uint8Array): Promise<void> {
|
||||
if (this.nativeModule.sendProtocolData) {
|
||||
// Convert Uint8Array to regular array for native module
|
||||
const dataArray = Array.from(data);
|
||||
await this.nativeModule.sendProtocolData(peerId, protocolId, dataArray);
|
||||
} else {
|
||||
throw new Error('Protocol sending not supported on this platform');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Type definition for CustomEventInit
|
||||
interface CustomEventInit<T = unknown> {
|
||||
detail?: T;
|
||||
bubbles?: boolean;
|
||||
cancelable?: boolean;
|
||||
}
|
||||
|
||||
// Polyfill CustomEvent for React Native
|
||||
if (typeof CustomEvent === 'undefined') {
|
||||
const globalObj = global as typeof globalThis & { CustomEvent: typeof CustomEvent };
|
||||
globalObj.CustomEvent = class CustomEvent<T = unknown> {
|
||||
readonly type: string;
|
||||
readonly detail: T;
|
||||
readonly bubbles: boolean;
|
||||
readonly cancelable: boolean;
|
||||
|
||||
constructor(type: string, eventInitDict?: CustomEventInit<T>) {
|
||||
this.type = type;
|
||||
this.detail = eventInitDict?.detail as T;
|
||||
this.bubbles = eventInitDict?.bubbles || false;
|
||||
this.cancelable = eventInitDict?.cancelable || false;
|
||||
}
|
||||
|
||||
preventDefault() {}
|
||||
stopPropagation() {}
|
||||
stopImmediatePropagation() {}
|
||||
} as any;
|
||||
}
|
||||
298
implementations/SettingsService.ts
Normal file
298
implementations/SettingsService.ts
Normal file
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* Settings Service
|
||||
*
|
||||
* Manages application settings and provides methods to:
|
||||
* - Load/save settings
|
||||
* - Apply settings to native modules
|
||||
* - Reset application data
|
||||
*/
|
||||
|
||||
import { LoggerComponent } from 'ior:gitea:gitea.metatrom.net:universal-components/logger@1.0.0';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { NativeModules, Platform } from 'react-native';
|
||||
|
||||
// Storage keys
|
||||
const SETTINGS_KEY = '@libp2p_settings';
|
||||
|
||||
// Default settings
|
||||
export const DEFAULT_SETTINGS = {
|
||||
tcpPort: 10000,
|
||||
wsPort: 10005,
|
||||
discoveryTimeout: 30000,
|
||||
enableDebugLogs: false,
|
||||
autoDiscovery: false,
|
||||
useCustomPorts: false,
|
||||
dhtServerUrl: 'ws://192.168.188.40:3000/ws', // This is the default/fallback DHT server URL
|
||||
};
|
||||
|
||||
export interface AppSettings {
|
||||
tcpPort: number;
|
||||
wsPort: number;
|
||||
discoveryTimeout: number;
|
||||
enableDebugLogs: boolean;
|
||||
autoDiscovery: boolean;
|
||||
useCustomPorts: boolean;
|
||||
dhtServerUrl: string;
|
||||
}
|
||||
|
||||
export interface INativeModules {
|
||||
Libp2pModule?: any;
|
||||
DiscoveryModule?: any;
|
||||
SecureStorageModule?: any;
|
||||
}
|
||||
|
||||
export class SettingsService {
|
||||
private static instance: SettingsService | null = null;
|
||||
private currentSettings: AppSettings = DEFAULT_SETTINGS;
|
||||
private logger = new LoggerComponent('SettingsService');
|
||||
private nativeModules: INativeModules;
|
||||
|
||||
private constructor(nativeModules?: INativeModules) {
|
||||
// Allow dependency injection of native modules
|
||||
this.nativeModules = nativeModules || NativeModules;
|
||||
}
|
||||
|
||||
public static getInstance(nativeModules?: INativeModules): SettingsService {
|
||||
if (!SettingsService.instance) {
|
||||
SettingsService.instance = new SettingsService(nativeModules);
|
||||
}
|
||||
return SettingsService.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the singleton instance (useful for testing)
|
||||
*/
|
||||
public static resetInstance(): void {
|
||||
SettingsService.instance = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize settings service
|
||||
*/
|
||||
async initialize(): Promise<AppSettings> {
|
||||
try {
|
||||
const settings = await this.loadSettings();
|
||||
this.currentSettings = settings;
|
||||
return settings;
|
||||
} catch (error) {
|
||||
this.logger.error('[SettingsService] Failed to initialize:', error);
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load settings from storage
|
||||
*/
|
||||
async loadSettings(): Promise<AppSettings> {
|
||||
try {
|
||||
const stored = await AsyncStorage.getItem(SETTINGS_KEY);
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored);
|
||||
return { ...DEFAULT_SETTINGS, ...parsed };
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('[SettingsService] Failed to load settings:', error);
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save settings to storage
|
||||
*/
|
||||
async saveSettings(settings: AppSettings): Promise<void> {
|
||||
try {
|
||||
await AsyncStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
||||
this.currentSettings = settings;
|
||||
|
||||
// Apply settings to native modules if needed
|
||||
await this.applySettings(settings);
|
||||
} catch (error) {
|
||||
this.logger.error('[SettingsService] Failed to save settings:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply settings to native modules
|
||||
*/
|
||||
private async applySettings(settings: AppSettings): Promise<void> {
|
||||
const { Libp2pModule, DiscoveryModule } = this.nativeModules;
|
||||
|
||||
// Apply port settings if custom ports are enabled
|
||||
if (settings.useCustomPorts) {
|
||||
// This would need to be passed to the native modules
|
||||
// when starting the libp2p node
|
||||
this.logger.debug('[SettingsService] Custom ports:', {
|
||||
tcp: settings.tcpPort,
|
||||
ws: settings.wsPort,
|
||||
});
|
||||
}
|
||||
|
||||
// Apply debug logging
|
||||
if (Libp2pModule?.setDebugConsoleOutput) {
|
||||
Libp2pModule.setDebugConsoleOutput(settings.enableDebugLogs);
|
||||
}
|
||||
|
||||
// Apply discovery timeout
|
||||
if (DiscoveryModule?.setDiscoveryTimeout) {
|
||||
DiscoveryModule.setDiscoveryTimeout(settings.discoveryTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current settings
|
||||
*/
|
||||
getSettings(): AppSettings {
|
||||
return this.currentSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get specific setting value
|
||||
*/
|
||||
getSetting<K extends keyof AppSettings>(key: K): AppSettings[K] {
|
||||
return this.currentSettings[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Update specific setting
|
||||
*/
|
||||
async updateSetting<K extends keyof AppSettings>(key: K, value: AppSettings[K]): Promise<void> {
|
||||
const newSettings = { ...this.currentSettings, [key]: value };
|
||||
await this.saveSettings(newSettings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset all application data
|
||||
*/
|
||||
async resetAllData(): Promise<void> {
|
||||
try {
|
||||
this.logger.info('[SettingsService] Starting app reset...');
|
||||
|
||||
// Clear all AsyncStorage (this includes dht_discovered_users)
|
||||
const allKeys = await AsyncStorage.getAllKeys();
|
||||
this.logger.debug('[SettingsService] Clearing AsyncStorage keys:', allKeys);
|
||||
await AsyncStorage.multiRemove(allKeys);
|
||||
|
||||
// Clear native module data
|
||||
await this.clearNativeData();
|
||||
|
||||
// Reset settings to defaults
|
||||
this.currentSettings = DEFAULT_SETTINGS;
|
||||
|
||||
this.logger.info('[SettingsService] App reset complete');
|
||||
} catch (error) {
|
||||
this.logger.error('[SettingsService] Failed to reset app data:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear native module stored data
|
||||
*/
|
||||
private async clearNativeData(): Promise<void> {
|
||||
const { Libp2pModule, DiscoveryModule, SecureStorageModule } = this.nativeModules;
|
||||
|
||||
try {
|
||||
if (Platform.OS === 'ios') {
|
||||
// Clear iOS UserDefaults
|
||||
if (Libp2pModule?.clearStoredData) {
|
||||
await Libp2pModule.clearStoredData();
|
||||
}
|
||||
if (DiscoveryModule?.clearStoredData) {
|
||||
await DiscoveryModule.clearStoredData();
|
||||
}
|
||||
if (SecureStorageModule?.clearAll) {
|
||||
await SecureStorageModule.clearAll();
|
||||
}
|
||||
} else if (Platform.OS === 'android') {
|
||||
// Clear Android SharedPreferences
|
||||
if (Libp2pModule?.clearStoredData) {
|
||||
await Libp2pModule.clearStoredData();
|
||||
}
|
||||
if (DiscoveryModule?.clearStoredData) {
|
||||
await DiscoveryModule.clearStoredData();
|
||||
}
|
||||
if (SecureStorageModule?.clearAll) {
|
||||
await SecureStorageModule.clearAll();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('[SettingsService] Failed to clear native data:', error);
|
||||
// Continue even if native clear fails
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export all app data for debugging
|
||||
*/
|
||||
async exportDebugData(): Promise<object> {
|
||||
try {
|
||||
const allKeys = await AsyncStorage.getAllKeys();
|
||||
const allData: Record<string, unknown> = {};
|
||||
|
||||
for (const key of allKeys) {
|
||||
try {
|
||||
const value = await AsyncStorage.getItem(key);
|
||||
allData[key] = value ? JSON.parse(value) : null;
|
||||
} catch {
|
||||
// If JSON parse fails, store as string
|
||||
allData[key] = await AsyncStorage.getItem(key);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
settings: this.currentSettings,
|
||||
storedData: allData,
|
||||
platform: Platform.OS,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error('[SettingsService] Failed to export debug data:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is first app launch
|
||||
*/
|
||||
async isFirstLaunch(): Promise<boolean> {
|
||||
try {
|
||||
const hasSettings = await AsyncStorage.getItem(SETTINGS_KEY);
|
||||
return !hasSettings;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get storage info
|
||||
*/
|
||||
async getStorageInfo(): Promise<{
|
||||
keys: string[];
|
||||
totalSize: number;
|
||||
}> {
|
||||
try {
|
||||
const allKeys = await AsyncStorage.getAllKeys();
|
||||
let totalSize = 0;
|
||||
|
||||
for (const key of allKeys) {
|
||||
const value = await AsyncStorage.getItem(key);
|
||||
if (value) {
|
||||
totalSize += value.length;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
keys: [...allKeys], // Convert readonly array to mutable array
|
||||
totalSize,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error('[SettingsService] Failed to get storage info:', error);
|
||||
return { keys: [], totalSize: 0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton getter function instead of instance
|
||||
export const getSettingsService = (nativeModules?: INativeModules) =>
|
||||
SettingsService.getInstance(nativeModules);
|
||||
496
implementations/SettingsUI.tsx
Normal file
496
implementations/SettingsUI.tsx
Normal file
@@ -0,0 +1,496 @@
|
||||
/**
|
||||
* Settings UI Component
|
||||
*
|
||||
* Provides configuration options for the libp2p node including:
|
||||
* - Port configuration
|
||||
* - Network settings
|
||||
* - Data management (reset app)
|
||||
* - Debug options
|
||||
*/
|
||||
|
||||
import { LoggerComponent } from 'ior:gitea:gitea.metatrom.net:universal-components/logger@1.0.0';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import type React from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
KeyboardAvoidingView,
|
||||
NativeModules,
|
||||
Platform,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Switch,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
View,
|
||||
} from 'react-native';
|
||||
// SecureStorage removed - not needed in external package
|
||||
import { DEFAULT_SETTINGS, type AppSettings } from './SettingsService';
|
||||
|
||||
const { Libp2pModule, DiscoveryModule, SecureStorageModule } = NativeModules;
|
||||
|
||||
// Settings storage keys
|
||||
const SETTINGS_STORAGE_KEY = '@libp2p_settings';
|
||||
|
||||
// Use AppSettings from SettingsService
|
||||
// The LibP2PSettings type is now replaced by AppSettings
|
||||
|
||||
interface SettingsUIProps {
|
||||
initialSettings?: AppSettings;
|
||||
onSettingsChange?: (settings: AppSettings) => void;
|
||||
onPortsSaved?: () => void;
|
||||
onReset?: () => void;
|
||||
}
|
||||
|
||||
export const SettingsUI: React.FC<SettingsUIProps> = ({
|
||||
initialSettings,
|
||||
onSettingsChange,
|
||||
onPortsSaved,
|
||||
onReset,
|
||||
}) => {
|
||||
const loggerRef = useRef<LoggerComponent | null>(null);
|
||||
if (!loggerRef.current) {
|
||||
loggerRef.current = new LoggerComponent('SettingsUI');
|
||||
}
|
||||
const logger = loggerRef.current;
|
||||
const [settings, setSettings] = useState<AppSettings>(initialSettings || DEFAULT_SETTINGS);
|
||||
const [isDirty, setIsDirty] = useState(false);
|
||||
const [tcpPortInput, setTcpPortInput] = useState(
|
||||
String((initialSettings || DEFAULT_SETTINGS).tcpPort),
|
||||
);
|
||||
const [wsPortInput, setWsPortInput] = useState(
|
||||
String((initialSettings || DEFAULT_SETTINGS).wsPort),
|
||||
);
|
||||
const [discoveryTimeoutInput, setDiscoveryTimeoutInput] = useState(
|
||||
String((initialSettings || DEFAULT_SETTINGS).discoveryTimeout / 1000),
|
||||
);
|
||||
const [dhtServerUrlInput, setDhtServerUrlInput] = useState(
|
||||
(initialSettings || DEFAULT_SETTINGS).dhtServerUrl,
|
||||
);
|
||||
|
||||
// Update state when initialSettings changes
|
||||
useEffect(() => {
|
||||
if (initialSettings) {
|
||||
setSettings(initialSettings);
|
||||
setTcpPortInput(String(initialSettings.tcpPort));
|
||||
setWsPortInput(String(initialSettings.wsPort));
|
||||
setDiscoveryTimeoutInput(String(initialSettings.discoveryTimeout / 1000));
|
||||
setDhtServerUrlInput(initialSettings.dhtServerUrl);
|
||||
} else {
|
||||
loadSettings();
|
||||
}
|
||||
}, [initialSettings]);
|
||||
|
||||
/**
|
||||
* Load settings from AsyncStorage
|
||||
*/
|
||||
const loadSettings = async () => {
|
||||
try {
|
||||
const stored = await AsyncStorage.getItem(SETTINGS_STORAGE_KEY);
|
||||
let loadedSettings: LibP2PSettings;
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored);
|
||||
loadedSettings = { ...DEFAULT_SETTINGS, ...parsed };
|
||||
} else {
|
||||
// No stored settings, use defaults
|
||||
loadedSettings = DEFAULT_SETTINGS;
|
||||
}
|
||||
|
||||
setSettings(loadedSettings);
|
||||
setTcpPortInput(String(loadedSettings.tcpPort));
|
||||
setWsPortInput(String(loadedSettings.wsPort));
|
||||
setDiscoveryTimeoutInput(String(loadedSettings.discoveryTimeout / 1000));
|
||||
setDhtServerUrlInput(loadedSettings.dhtServerUrl);
|
||||
|
||||
// Don't call onSettingsChange during initial load
|
||||
// Parent component should handle initial settings
|
||||
} catch (error) {
|
||||
logger.error('[Settings] Failed to load settings:', error);
|
||||
// On error, still load defaults
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
setTcpPortInput(String(DEFAULT_SETTINGS.tcpPort));
|
||||
setWsPortInput(String(DEFAULT_SETTINGS.wsPort));
|
||||
setDiscoveryTimeoutInput(String(DEFAULT_SETTINGS.discoveryTimeout / 1000));
|
||||
setDhtServerUrlInput(DEFAULT_SETTINGS.dhtServerUrl);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Save settings to AsyncStorage
|
||||
*/
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
// Validate ports
|
||||
const tcpPort = Number.parseInt(tcpPortInput, 10);
|
||||
const wsPort = Number.parseInt(wsPortInput, 10);
|
||||
const discoveryTimeout = Number.parseInt(discoveryTimeoutInput, 10) * 1000;
|
||||
|
||||
if (Number.isNaN(tcpPort) || tcpPort < 1024 || tcpPort > 65535) {
|
||||
Alert.alert('Invalid TCP Port', 'Please enter a valid port number (1024-65535)');
|
||||
return;
|
||||
}
|
||||
|
||||
if (Number.isNaN(wsPort) || wsPort < 1024 || wsPort > 65535) {
|
||||
Alert.alert('Invalid WebSocket Port', 'Please enter a valid port number (1024-65535)');
|
||||
return;
|
||||
}
|
||||
|
||||
if (Number.isNaN(discoveryTimeout) || discoveryTimeout < 5000 || discoveryTimeout > 300000) {
|
||||
Alert.alert('Invalid Discovery Timeout', 'Please enter a value between 5 and 300 seconds');
|
||||
return;
|
||||
}
|
||||
|
||||
const newSettings = {
|
||||
...settings,
|
||||
tcpPort,
|
||||
wsPort,
|
||||
discoveryTimeout,
|
||||
dhtServerUrl: dhtServerUrlInput,
|
||||
};
|
||||
|
||||
await AsyncStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(newSettings));
|
||||
setSettings(newSettings);
|
||||
setIsDirty(false);
|
||||
|
||||
if (onSettingsChange) {
|
||||
onSettingsChange(newSettings);
|
||||
}
|
||||
|
||||
// Call the onPortsSaved callback to trigger libp2p restart
|
||||
if (onPortsSaved) {
|
||||
onPortsSaved();
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('[Settings] Failed to save settings:', error);
|
||||
Alert.alert('Error', 'Failed to save settings');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset all app data
|
||||
*/
|
||||
const resetApp = () => {
|
||||
Alert.alert(
|
||||
'Reset App Data',
|
||||
'This will delete all stored data including:\n\n• Your peer identity\n• All settings\n• Stored devices\n• Chat history\n\nThe app will be like freshly installed. Continue?',
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{
|
||||
text: 'Reset',
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
try {
|
||||
// Show progress alert
|
||||
Alert.alert('Resetting...', 'Please wait while we clear all data');
|
||||
|
||||
// Clear all AsyncStorage
|
||||
await AsyncStorage.clear();
|
||||
|
||||
// Clear all secure storage (identities, paired devices, etc.)
|
||||
try {
|
||||
// Clear secure storage if available
|
||||
if (SecureStorageModule?.clearAll) {
|
||||
await SecureStorageModule.clearAll();
|
||||
}
|
||||
logger.info('[SettingsUI] Cleared all secure storage data');
|
||||
} catch (error) {
|
||||
logger.error('[SettingsUI] Failed to clear secure storage:', error);
|
||||
}
|
||||
|
||||
// Clear native module stored data
|
||||
if (Platform.OS === 'ios') {
|
||||
// iOS uses UserDefaults
|
||||
if (Libp2pModule.clearStoredData) {
|
||||
await Libp2pModule.clearStoredData();
|
||||
}
|
||||
if (DiscoveryModule.clearStoredData) {
|
||||
await DiscoveryModule.clearStoredData();
|
||||
}
|
||||
// SecureStorage handled above
|
||||
} else if (Platform.OS === 'android') {
|
||||
// Android uses SharedPreferences
|
||||
if (Libp2pModule.clearStoredData) {
|
||||
await Libp2pModule.clearStoredData();
|
||||
}
|
||||
if (DiscoveryModule.clearStoredData) {
|
||||
await DiscoveryModule.clearStoredData();
|
||||
}
|
||||
if (SecureStorageModule?.clearAll) {
|
||||
await SecureStorageModule.clearAll();
|
||||
}
|
||||
}
|
||||
|
||||
// Reset settings to defaults
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
setTcpPortInput(String(DEFAULT_SETTINGS.tcpPort));
|
||||
setWsPortInput(String(DEFAULT_SETTINGS.wsPort));
|
||||
setDiscoveryTimeoutInput(String(DEFAULT_SETTINGS.discoveryTimeout / 1000));
|
||||
setDhtServerUrlInput(DEFAULT_SETTINGS.dhtServerUrl);
|
||||
|
||||
if (onReset) {
|
||||
onReset();
|
||||
}
|
||||
|
||||
Alert.alert(
|
||||
'Reset Complete',
|
||||
'All app data has been cleared. Please restart the app for a fresh start.',
|
||||
[
|
||||
{
|
||||
text: 'OK',
|
||||
onPress: () => {
|
||||
// Optionally restart the app
|
||||
// RNRestart.Restart(); // Requires react-native-restart package
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('[Settings] Failed to reset app:', error);
|
||||
Alert.alert('Error', 'Failed to reset app data');
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
const handleToggleCustomPorts = async () => {
|
||||
const newSettings = { ...settings, useCustomPorts: !settings.useCustomPorts };
|
||||
setSettings(newSettings);
|
||||
|
||||
// Auto-save switch changes immediately
|
||||
try {
|
||||
await AsyncStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(newSettings));
|
||||
if (onSettingsChange) {
|
||||
onSettingsChange(newSettings);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('[Settings] Failed to save setting:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
style={styles.container}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
|
||||
keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
|
||||
>
|
||||
<ScrollView
|
||||
style={styles.scrollView}
|
||||
contentContainerStyle={styles.scrollContent}
|
||||
showsVerticalScrollIndicator={true}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Network Configuration</Text>
|
||||
|
||||
<View style={styles.setting}>
|
||||
<Text style={styles.settingLabel}>Use Custom Ports</Text>
|
||||
<Switch
|
||||
value={settings.useCustomPorts}
|
||||
onValueChange={handleToggleCustomPorts}
|
||||
trackColor={{ false: '#767577', true: '#2196F3' }}
|
||||
thumbColor={settings.useCustomPorts ? '#fff' : '#f4f3f4'}
|
||||
ios_backgroundColor="#3e3e3e"
|
||||
/>
|
||||
</View>
|
||||
|
||||
{settings.useCustomPorts && (
|
||||
<>
|
||||
<View style={styles.inputSetting}>
|
||||
<Text style={styles.settingLabel}>TCP Port</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={tcpPortInput}
|
||||
onChangeText={(text) => {
|
||||
setTcpPortInput(text);
|
||||
setIsDirty(true);
|
||||
}}
|
||||
keyboardType="number-pad"
|
||||
placeholder="10000"
|
||||
placeholderTextColor="#666"
|
||||
maxLength={5}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputSetting}>
|
||||
<Text style={styles.settingLabel}>WebSocket Port</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={wsPortInput}
|
||||
onChangeText={(text) => {
|
||||
setWsPortInput(text);
|
||||
setIsDirty(true);
|
||||
}}
|
||||
keyboardType="number-pad"
|
||||
placeholder="10005"
|
||||
placeholderTextColor="#666"
|
||||
maxLength={5}
|
||||
/>
|
||||
</View>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Discovery Configuration</Text>
|
||||
|
||||
<View style={styles.inputSetting}>
|
||||
<Text style={styles.settingLabel}>Timeout (seconds)</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={discoveryTimeoutInput}
|
||||
onChangeText={(text) => {
|
||||
setDiscoveryTimeoutInput(text);
|
||||
setIsDirty(true);
|
||||
}}
|
||||
keyboardType="number-pad"
|
||||
placeholder="30"
|
||||
placeholderTextColor="#666"
|
||||
maxLength={3}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputSetting}>
|
||||
<Text style={styles.settingLabel}>DHT Server URL</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={dhtServerUrlInput}
|
||||
onChangeText={(text) => {
|
||||
setDhtServerUrlInput(text);
|
||||
setIsDirty(true);
|
||||
}}
|
||||
placeholder="ws://192.168.188.40:3000/ws"
|
||||
placeholderTextColor="#666"
|
||||
selectionColor="#2196F3"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
underlineColorAndroid="transparent"
|
||||
/>
|
||||
<Text style={styles.settingDescription}>
|
||||
WebSocket URL of the DHT server for global peer discovery
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{isDirty && (
|
||||
<View style={styles.section}>
|
||||
<TouchableOpacity style={styles.saveButton} onPress={saveSettings}>
|
||||
<Text style={styles.saveButtonText}>Save Settings</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={[styles.section, styles.lastSection]}>
|
||||
<TouchableOpacity style={styles.dangerButton} onPress={resetApp}>
|
||||
<Text style={styles.dangerButtonText}>🗑 Reset All App Data</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<Text style={styles.warningText}>
|
||||
This will delete all stored data and reset the app to its initial state
|
||||
</Text>
|
||||
</View>
|
||||
</ScrollView>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
};
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
scrollView: {
|
||||
flex: 1,
|
||||
},
|
||||
scrollContent: {
|
||||
paddingVertical: 20,
|
||||
paddingBottom: 100, // Increased to ensure all content is visible
|
||||
},
|
||||
section: {
|
||||
paddingHorizontal: 20,
|
||||
marginBottom: 24,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: '#fff',
|
||||
marginBottom: 16,
|
||||
},
|
||||
setting: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
paddingVertical: 16,
|
||||
},
|
||||
settingInfo: {
|
||||
flex: 1,
|
||||
marginRight: 12,
|
||||
},
|
||||
settingLabel: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: '#fff',
|
||||
marginBottom: 4,
|
||||
},
|
||||
settingDescription: {
|
||||
fontSize: 12,
|
||||
color: '#999',
|
||||
marginTop: 2,
|
||||
},
|
||||
inputSetting: {
|
||||
paddingVertical: 12,
|
||||
},
|
||||
input: {
|
||||
marginTop: 8,
|
||||
paddingHorizontal: 12,
|
||||
paddingVertical: Platform.OS === 'ios' ? 10 : 8,
|
||||
backgroundColor: '#2a2a2a',
|
||||
borderRadius: 8,
|
||||
borderWidth: 1,
|
||||
borderColor: '#333',
|
||||
fontSize: 14,
|
||||
color: '#fff',
|
||||
textAlignVertical: 'center',
|
||||
minHeight: Platform.OS === 'android' ? 40 : undefined,
|
||||
},
|
||||
dangerButton: {
|
||||
marginTop: 12,
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 20,
|
||||
backgroundColor: '#5c1e1e',
|
||||
borderRadius: 8,
|
||||
alignItems: 'center',
|
||||
},
|
||||
dangerButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: '#ff9999',
|
||||
},
|
||||
saveButton: {
|
||||
marginTop: 16,
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 20,
|
||||
backgroundColor: '#2563eb',
|
||||
borderRadius: 8,
|
||||
alignItems: 'center',
|
||||
},
|
||||
saveButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: '#fff',
|
||||
},
|
||||
warningText: {
|
||||
fontSize: 12,
|
||||
color: '#999',
|
||||
textAlign: 'center',
|
||||
marginTop: 8,
|
||||
fontStyle: 'italic',
|
||||
},
|
||||
lastSection: {
|
||||
marginBottom: 40,
|
||||
},
|
||||
});
|
||||
|
||||
export default SettingsUI;
|
||||
Reference in New Issue
Block a user