initialize method

Future<void> initialize()

Initialize the at_client connection

Implementation

Future<void> initialize() async {
  if (_initialized) return;

  try {
    _logger.info('Initializing at_client for $atSign');

    // Get the .atsign directory
    final homeDir = Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
    if (homeDir == null) {
      throw Exception('Could not determine home directory');
    }

    final atKeysPath = path.join(homeDir, '.atsign', 'keys');

    // Check if keys directory exists
    if (!Directory(atKeysPath).existsSync()) {
      throw Exception('Keys directory not found at $atKeysPath. Please onboard the atSign first.');
    }

    // Find the keys file for this atSign
    final keysFile = File(path.join(atKeysPath, '${atSign}_key.atKeys'));
    if (!keysFile.existsSync()) {
      throw Exception('Keys file not found for $atSign at ${keysFile.path}. Please onboard the atSign first.');
    }

    // Setup onboarding preferences
    // Use a unique temporary directory to avoid lock conflicts with other processes
    _tempDir = Directory.systemTemp.createTempSync('at_activate_web_');
    final storagePath = _tempDir!.path;

    _logger.info('Using temporary storage at: $storagePath');

    final parsedRoot = AtRootDomain.parse(rootDomain);

    final atOnboardingPreference = AtOnboardingPreference()
      ..hiveStoragePath = storagePath
      ..commitLogPath = storagePath
      ..isLocalStoreRequired = true
      ..rootDomain = parsedRoot.rootDomain
      ..rootPort = parsedRoot.rootPort
      ..atKeysFilePath = keysFile.path;

    // Create onboarding service
    final atOnboardingService = AtOnboardingServiceImpl(atSign, atOnboardingPreference);

    // Authenticate
    _logger.info('Authenticating $atSign...');
    await atOnboardingService.authenticate();

    _atClient = atOnboardingService.atClient!;
    _initialized = true;
    _logger.info('Successfully initialized at_client for $atSign');
  } catch (e, s) {
    _logger.severe('Failed to initialize at_client: $e', e, s);
    rethrow;
  }
}