Module: Lich::Common::GUI::AccountManager

Defined in:
documented/common/gui/account_manager.rb

Class Method Summary collapse

Class Method Details

.add_character(data_dir, username, character_data) ⇒ Hash

Adds a character to the specified account.

Examples:

Adding a character

AccountManager.add_character("/path/to/data", "user1", { char_name: "Hero", game_code: "game1" })

Parameters:

  • data_dir (String)

    The directory where account data is stored.

  • username (String)

    The username of the account.

  • character_data (Hash)

    The character data to add.

Returns:

  • (Hash)

    A hash containing success status and message.

Raises:

  • (StandardError)

    If an error occurs while adding the character.



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'documented/common/gui/account_manager.rb', line 169

def self.add_character(data_dir, username, character_data)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Check if YAML file exists
  unless File.exist?(yaml_file)
    return { success: false, message: "No account data file found. Please add an account first." }
  end

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username to UPCASE for consistent lookup
    normalized_username = username.to_s.upcase
    normalized_char_name = character_data[:char_name].to_s.capitalize

    # Check if account exists
    unless yaml_data['accounts'] && yaml_data['accounts'][normalized_username]
      return { success: false, message: "Account '#{username}' not found. Please add the account first." }
    end

    # Initialize characters array if not present
    yaml_data['accounts'][normalized_username]['characters'] ||= []

    # Check for duplicate character using normalized comparison
    existing_character = yaml_data['accounts'][normalized_username]['characters'].find do |char|
      char['char_name'] == normalized_char_name &&
        char['game_code'] == character_data[:game_code] &&
        char['frontend'] == character_data[:frontend]
    end

    # Return specific message if character already exists
    if existing_character
      return {
        success: false,
        message: "Character '#{normalized_char_name}' already exists for #{character_data[:game_code]} (#{character_data[:frontend]}). Duplicates are not allowed."
      }
    end

    # Add character data with normalized character name
    yaml_data['accounts'][normalized_username]['characters'] << {
      'char_name'         => normalized_char_name,
      'game_code'         => character_data[:game_code],
      'game_name'         => character_data[:game_name],
      'frontend'          => character_data[:frontend],
      'custom_launch'     => character_data[:custom_launch],
      'custom_launch_dir' => character_data[:custom_launch_dir]
    }

    # Save updated data with verification
    if write_yaml_with_headers(yaml_file, yaml_data)
      return { success: true, message: "Character '#{normalized_char_name}' added successfully." }
    else
      return { success: false, message: "Failed to save character data. Please check file permissions." }
    end
  rescue StandardError => e
    Lich.log "error: Error adding character: #{e.message}"
    return { success: false, message: "Error adding character: #{e.message}" }
  end
end

.add_or_update_account(data_dir, username, password, characters = []) ⇒ void

This method returns an undefined value.

Adds or updates an account with the given username and password.

Examples:

Adding a new account

AccountManager.("/path/to/data", "user1", "password123", [{ char_name: "Hero", game_code: "game1" }])

Parameters:

  • data_dir (String)

    The directory where account data is stored.

  • username (String)

    The username for the account.

  • password (String)

    The password for the account.

  • characters (Array<Hash>) (defaults to: [])

    (optional) An array of character data associated with the account.

Raises:

  • (StandardError)

    If the master password is required but not found.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'documented/common/gui/account_manager.rb', line 15

def self.(data_dir, username, password, characters = [])
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Normalize username to UPCASE for consistent storage
  normalized_username = username.to_s.upcase

  # Load existing data or create new structure
  yaml_data = if File.exist?(yaml_file)
                begin
                  YAML.load_file(yaml_file)
                rescue StandardError => e
                  Lich.log "error: Error loading YAML entry file: #{e.message}"
                  { 'accounts' => {} }
                end
              else
                { 'accounts' => {} }
              end

  # Initialize accounts hash if not present
  yaml_data['accounts'] ||= {}

  # Determine encryption mode and get master password if needed
  encryption_mode = yaml_data['encryption_mode'] || 'plaintext'
  master_password = nil
  if encryption_mode.to_sym == :enhanced
    master_password = Lich::Common::GUI::MasterPasswordManager.retrieve_master_password
    if master_password.nil?
      Lich.log "error: Enhanced mode enabled but master password not found in Keychain"
      raise StandardError, "Master password required for enhanced mode encryption"
    end
  end

  # Encrypt the password based on encryption mode
  encrypted_password = Lich::Common::GUI::YamlState.encrypt_password(
    password,
    mode: encryption_mode,
    account_name: normalized_username,
    master_password: master_password
  )

  # Normalize character data if provided
  normalized_characters = characters.map do |char|
    {
      'char_name'         => char[:char_name].to_s.strip.split.map(&:capitalize).join(' '),
      'game_code'         => char[:game_code],
      'game_name'         => char[:game_name],
      'frontend'          => char[:frontend],
      'custom_launch'     => char[:custom_launch],
      'custom_launch_dir' => char[:custom_launch_dir]
    }
  end

  # Add or update account using normalized username
  if yaml_data['accounts'][normalized_username]
    # Update existing account password with encrypted value
    yaml_data['accounts'][normalized_username]['password'] = encrypted_password

    # Merge characters: preserve existing characters and their metadata (like favorites)
    # while adding any new characters from the provided list
    if !characters.empty?
      existing_characters = yaml_data['accounts'][normalized_username]['characters'] || []

      # Add new characters that don't already exist
      characters.each do |new_char|
        normalized_new_char_name = new_char[:char_name].to_s.capitalize

        # Check if character already exists (by char_name, game_code, frontend)
        existing_char = existing_characters.find do |existing|
          existing['char_name'] == normalized_new_char_name &&
            existing['game_code'] == new_char[:game_code] &&
            existing['frontend'] == new_char[:frontend]
        end

        # Only add if character doesn't already exist
        unless existing_char
          existing_characters << {
            'char_name'         => normalized_new_char_name,
            'game_code'         => new_char[:game_code],
            'game_name'         => new_char[:game_name],
            'frontend'          => new_char[:frontend],
            'custom_launch'     => new_char[:custom_launch],
            'custom_launch_dir' => new_char[:custom_launch_dir]
          }
        end
      end

      yaml_data['accounts'][normalized_username]['characters'] = existing_characters
    end
  else
    # Create new account with normalized data and encrypted password
    yaml_data['accounts'][normalized_username] = {
      'password'   => encrypted_password,
      'characters' => normalized_characters
    }
  end

  # Save updated data with verification
  write_yaml_with_headers(yaml_file, yaml_data)
end

.change_password(data_dir, username, new_password) ⇒ void

This method returns an undefined value.

Changes the password for the specified account.

Examples:

Changing an account password

AccountManager.change_password("/path/to/data", "user1", "newpassword456")

Parameters:

  • data_dir (String)

    The directory where account data is stored.

  • username (String)

    The username of the account.

  • new_password (String)

    The new password for the account.



155
156
157
158
159
# File 'documented/common/gui/account_manager.rb', line 155

def self.change_password(data_dir, username, new_password)
  # Normalize username to UPCASE for consistent storage
  normalized_username = username.to_s.upcase
  (data_dir, normalized_username, new_password)
end

.convert_auth_data_to_characters(auth_data, frontend = 'stormfront') ⇒ Array<Hash>

Converts authentication data into character format.

Examples:

Converting auth data to characters

characters = AccountManager.convert_auth_data_to_characters(auth_data, "stormfront")

Parameters:

  • auth_data (Array<Hash>)

    The authentication data to convert.

  • frontend (String) (defaults to: 'stormfront')

    (optional) The frontend to associate with the characters.

Returns:

  • (Array<Hash>)

    An array of characters converted from the authentication data.



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'documented/common/gui/account_manager.rb', line 333

def self.convert_auth_data_to_characters(auth_data, frontend = 'stormfront')
  characters = []
  return characters unless auth_data.is_a?(Array)

  auth_data.each do |char_data|
    # Ensure we have the required fields with symbol keys (as returned by authentication)
    next unless char_data.is_a?(Hash) &&
                char_data.key?(:char_name) &&
                char_data.key?(:game_name) &&
                char_data.key?(:game_code)

    characters << {
      char_name: char_data[:char_name],
      game_code: char_data[:game_code],
      game_name: char_data[:game_name],
      frontend: frontend
    }
  end

  characters
end

.get_accounts(data_dir) ⇒ Array<String>

Retrieves a list of account usernames.

Examples:

Getting account usernames

usernames = AccountManager.get_accounts("/path/to/data")

Parameters:

  • data_dir (String)

    The directory where account data is stored.

Returns:

  • (Array<String>)

    An array of account usernames.

Raises:

  • (StandardError)

    If an error occurs while retrieving accounts.



361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'documented/common/gui/account_manager.rb', line 361

def self.get_accounts(data_dir)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Load existing data
  return [] unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)
    yaml_data['accounts']&.keys || []
  rescue StandardError => e
    Lich.log "error: Error getting accounts: #{e.message}"
    []
  end
end

.get_all_accounts(data_dir) ⇒ Hash

Retrieves all accounts with their associated characters.

Examples:

Getting all accounts

accounts = AccountManager.get_all_accounts("/path/to/data")

Parameters:

  • data_dir (String)

    The directory where account data is stored.

Returns:

  • (Hash)

    A hash of usernames and their associated characters.

Raises:

  • (StandardError)

    If an error occurs while retrieving all accounts.



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'documented/common/gui/account_manager.rb', line 382

def self.get_all_accounts(data_dir)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Load existing data
  return {} unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)
    return {} unless yaml_data['accounts']

    # Build accounts hash with characters
    accounts = {}
    yaml_data['accounts'].each do |username, |
      accounts[username] = ['characters']&.map do |char|
        {
          char_name: char['char_name'],
          game_code: char['game_code'],
          game_name: char['game_name'],
          frontend: char['frontend'],
          custom_launch: char['custom_launch'],
          custom_launch_dir: char['custom_launch_dir']
        }
      end || []
    end

    accounts
  rescue StandardError => e
    Lich.log "error: Error getting all accounts: #{e.message}"
    {}
  end
end

.get_characters(data_dir, username) ⇒ Array<Hash>

Retrieves characters for a specified account.

Examples:

Getting characters for an account

characters = AccountManager.get_characters("/path/to/data", "user1")

Parameters:

  • data_dir (String)

    The directory where account data is stored.

  • username (String)

    The username of the account.

Returns:

  • (Array<Hash>)

    An array of characters associated with the account.

Raises:

  • (StandardError)

    If an error occurs while retrieving characters.



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'documented/common/gui/account_manager.rb', line 421

def self.get_characters(data_dir, username)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Load existing data
  return [] unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username to UPCASE for consistent lookup
    normalized_username = username.to_s.upcase

    # Check if account exists
    return [] unless yaml_data['accounts'] &&
                     yaml_data['accounts'][normalized_username] &&
                     yaml_data['accounts'][normalized_username]['characters']

    # Return characters with symbolized keys
    yaml_data['accounts'][normalized_username]['characters'].map do |char|
      char.transform_keys(&:to_sym)
    end
  rescue StandardError => e
    Lich.log "error: Error getting characters: #{e.message}"
    []
  end
end

.remove_account(data_dir, username) ⇒ Boolean

Removes an account with the given username.

Examples:

Removing an account

AccountManager.("/path/to/data", "user1")

Parameters:

  • data_dir (String)

    The directory where account data is stored.

  • username (String)

    The username of the account to remove.

Returns:

  • (Boolean)

    Returns true if the account was removed, false otherwise.

Raises:

  • (StandardError)

    If an error occurs while removing the account.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'documented/common/gui/account_manager.rb', line 122

def self.(data_dir, username)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Load existing data
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username to UPCASE for consistent lookup
    normalized_username = username.to_s.upcase

    # Check if account exists
    return false unless yaml_data['accounts'] && yaml_data['accounts'][normalized_username]

    # Remove account
    yaml_data['accounts'].delete(normalized_username)

    # Save updated data with verification
    write_yaml_with_headers(yaml_file, yaml_data)
  rescue StandardError => e
    Lich.log "error: Error removing account: #{e.message}"
    false
  end
end

.remove_character(data_dir, username, char_name, game_code, frontend = nil) ⇒ Boolean

Removes a character from the specified account.

Examples:

Removing a character

AccountManager.remove_character("/path/to/data", "user1", "Hero", "game1")

Parameters:

  • data_dir (String)

    The directory where account data is stored.

  • username (String)

    The username of the account.

  • char_name (String)

    The name of the character to remove.

  • game_code (String)

    The game code of the character.

  • frontend (String, nil) (defaults to: nil)

    (optional) The frontend of the character.

Returns:

  • (Boolean)

    Returns true if the character was removed, false otherwise.

Raises:

  • (StandardError)

    If an error occurs while removing the character.



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'documented/common/gui/account_manager.rb', line 239

def self.remove_character(data_dir, username, char_name, game_code, frontend = nil)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Load existing data
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Normalize username and character name for consistent lookup
    normalized_username = username.to_s.upcase
    normalized_char_name = char_name.to_s.capitalize

    # Check if account exists
    return false unless yaml_data['accounts'] &&
                        yaml_data['accounts'][normalized_username] &&
                        yaml_data['accounts'][normalized_username]['characters']

    # Find and remove character with frontend precision
    characters = yaml_data['accounts'][normalized_username]['characters']
    initial_count = characters.size

    characters.reject! do |char|
      matches_basic = char['char_name'] == normalized_char_name && char['game_code'] == game_code

      if frontend.nil?
        # Backward compatibility: if no frontend specified, match any frontend
        matches_basic
      else
        # Frontend precision: must match exact frontend
        matches_basic && char['frontend'] == frontend
      end
    end

    # Check if any characters were removed
    return false if characters.size == initial_count

    # Save updated data with verification
    write_yaml_with_headers(yaml_file, yaml_data)
  rescue StandardError => e
    Lich.log "error: Error removing character: #{e.message}"
    false
  end
end

.to_legacy_format(data_dir) ⇒ Array

Converts the account data to a legacy format.

Examples:

Converting to legacy format

legacy_data = AccountManager.to_legacy_format("/path/to/data")

Parameters:

  • data_dir (String)

    The directory where account data is stored.

Returns:

  • (Array)

    An array of data in legacy format.

Raises:

  • (StandardError)

    If an error occurs while converting to legacy format.



454
455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'documented/common/gui/account_manager.rb', line 454

def self.to_legacy_format(data_dir)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Load existing data
  return [] unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)
    YamlState.convert_yaml_to_legacy_format(yaml_data)
  rescue StandardError => e
    Lich.log "error: Error converting to legacy format: #{e.message}"
    []
  end
end

.update_character(data_dir, username, char_name, game_code, updates) ⇒ Boolean

Updates the properties of a character in the specified account.

Examples:

Updating a character

AccountManager.update_character("/path/to/data", "user1", "Hero", "game1", { game_name: "New Game" })

Parameters:

  • data_dir (String)

    The directory where account data is stored.

  • username (String)

    The username of the account.

  • char_name (String)

    The name of the character to update.

  • game_code (String)

    The game code of the character.

  • updates (Hash)

    A hash of properties to update for the character.

Returns:

  • (Boolean)

    Returns true if the character was updated, false otherwise.

Raises:

  • (StandardError)

    If an error occurs while updating the character.



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'documented/common/gui/account_manager.rb', line 294

def self.update_character(data_dir, username, char_name, game_code, updates)
  yaml_file = Lich::Common::GUI::YamlState.yaml_file_path(data_dir)

  # Load existing data
  return false unless File.exist?(yaml_file)

  begin
    yaml_data = YAML.load_file(yaml_file)

    # Check if account exists
    return false unless yaml_data['accounts'] &&
                        yaml_data['accounts'][username] &&
                        yaml_data['accounts'][username]['characters']

    # Find and update character
    characters = yaml_data['accounts'][username]['characters']
    character = characters.find { |char| char['char_name'] == char_name && char['game_code'] == game_code }

    return false unless character

    # Update properties
    updates.each do |key, value|
      character[key.to_s] = value
    end

    # Save updated data with verification
    write_yaml_with_headers(yaml_file, yaml_data)
  rescue StandardError => e
    Lich.log "error: Error updating character: #{e.message}"
    false
  end
end