accounts-manager.vala 58.4 KB
Newer Older
1 2 3
/*
 * Copyright 2017 Software Freedom Conservancy Inc.
 * Copyright 2018 Michael Gratton <mike@vee.net>
4 5 6 7 8
 *
 * This software is licensed under the GNU Lesser General Public License
 * (version 2.1 or later).  See the COPYING file in this distribution.
 */

9

10 11 12 13 14 15 16
/**
 * Manages email account lifecycle for Geary.
 *
 * This class is responsible for creating, loading, saving and
 * removing accounts and their persisted data (configuration,
 * databases, caches, authentication tokens). The manager supports
 * both locally-specified accounts (i.e. those created by the user in
17 18
 * the app) and from SSO systems such as GOA via the Accounts.Provider
 * interface.
19 20 21 22 23
 *
 * Newly loaded and newly created accounts are first added to the
 * manager with a particular status (enabled, disabled, etc). Accounts
 * can have their enabled or disabled status updated manually,
 */
24
public class Accounts.Manager : GLib.Object {
25

26

27 28 29
    /** The name of the Geary configuration file. */
    public const string SETTINGS_FILENAME = "geary.ini";

30 31 32 33
    private const string LOCAL_ID_PREFIX = "account_";
    private const string LOCAL_ID_FORMAT = "account_%02u";
    private const string GOA_ID_PREFIX = "goa_";

34
    private const int CONFIG_VERSION = 1;
35

36 37 38 39 40
    private const string GROUP_METADATA = "Metadata";

    private const string METADATA_STATUS = "status";
    private const string METADATA_VERSION = "version";
    private const string METADATA_GOA = "goa_id";
41

42

43 44 45 46 47 48 49 50 51 52
    /**
     * Specifies the overall status of an account.
     */
    public enum Status {
        /** The account is enabled and operational. */
        ENABLED,

        /** The account was disabled by the user. */
        DISABLED,

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
        /** The account is unavailable to be used, but may come back. */
        UNAVAILABLE,

        /** The account has been removed and is scheduled for deletion. */
        REMOVED;

        public static Status for_value(string value)
        throws Geary.EngineError {
            return Geary.ObjectUtils.from_enum_nick<Status>(
                typeof(Status), value.ascii_down()
            );
        }

        public string to_value() {
            return Geary.ObjectUtils.to_enum_nick<Status>(
                typeof(Status), this
            );
        }
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    }


    /** Specifies an account's current state. */
    private class AccountState {


        /** The account represented by this object. */
        public Geary.AccountInformation account { get; private set; }

        /** Determines the account's overall state. */
        public Status status {
            get {
                Status status = Status.ENABLED;
                if (!this.enabled) {
                    status = Status.DISABLED;
                }
                if (!this.available) {
                    status = Status.UNAVAILABLE;
                }
                return status;
            }
        }

Michael Gratton's avatar
Michael Gratton committed
95
        /** Whether this account is enabled. */
96 97
        public bool enabled { get; set; default = true; }

Michael Gratton's avatar
Michael Gratton committed
98
        /** Whether this account is available. */
99 100 101 102 103 104 105 106 107 108
        public bool available { get; set; default = true; }


        internal AccountState(Geary.AccountInformation account) {
            this.account = account;
        }

    }


109 110 111
    /** Returns the number of currently known accounts. */
    public int size { get { return this.accounts.size; } }

112 113 114 115 116 117
    /** Returns the base directory for account configuration. */
    public GLib.File config_dir { get; private set; }

    /** Returns the base directory for account data. */
    public GLib.File data_dir { get; private set; }

118

119 120
    private Gee.Map<string,AccountState> accounts =
        new Gee.HashMap<string,AccountState>();
121

122 123 124 125
    private Gee.LinkedList<Geary.AccountInformation> removed =
        new Gee.LinkedList<Geary.AccountInformation>();


126 127 128
    private Geary.CredentialsMediator local_mediator;
    private Goa.Client? goa_service = null;

129

130
    /** Fired when a new account is created. */
131 132 133 134 135
    public signal void account_added(Geary.AccountInformation added, Status status);

    /** Fired when an existing account's state has changed. */
    public signal void account_status_changed(Geary.AccountInformation changed,
                                              Status new_status);
136 137 138 139

    /** Fired when an account is deleted. */
    public signal void account_removed(Geary.AccountInformation removed);

140 141 142
    /** Emitted to notify an account problem has occurred. */
    public signal void report_problem(Geary.ProblemReport problem);

143

144
    public Manager(Geary.CredentialsMediator local_mediator,
145 146
                   GLib.File config_dir,
                   GLib.File data_dir) {
147
        this.local_mediator = local_mediator;
148 149 150 151 152 153 154 155 156 157
        this.config_dir = config_dir;
        this.data_dir = data_dir;
    }

    public async void connect_goa(GLib.Cancellable? cancellable)
        throws GLib.Error {
        this.goa_service = yield new Goa.Client(cancellable);
        this.goa_service.account_added.connect(on_goa_account_added);
        this.goa_service.account_changed.connect(on_goa_account_changed);
        this.goa_service.account_removed.connect(on_goa_account_removed);
158
    }
159

160 161 162 163 164 165
    /** Returns the account with the given id. */
    public Geary.AccountInformation? get_account(string id) {
        AccountState? state = this.accounts.get(id);
        return (state != null) ? state.account : null;
    }

166 167 168 169 170 171
    /** Returns the status for the given account. */
    public Status get_status(Geary.AccountInformation account) {
        AccountState? state = this.accounts.get(account.id);
        return (state != null) ? state.status : Status.UNAVAILABLE;
    }

172 173
    /** Returns a read-only iterable of all currently known accounts. */
    public Geary.Iterable<Geary.AccountInformation> iterable() {
174 175
        return Geary.traverse<AccountState>(
            this.accounts.values
176 177 178 179 180
        ).map<Geary.AccountInformation>(
            ((state) => { return state.account; })
        );
    }

181 182 183 184 185 186 187 188 189 190 191
    /**
     * Returns the display name for the current desktop login session.
     */
    public string? get_account_name() {
        string? name = Environment.get_real_name();
        if (Geary.String.is_empty(name) || name == "Unknown") {
            name = null;
        }
        return name;
    }

192 193 194
    /**
     * Returns a new account, not yet stored on disk.
     */
195
    public async Geary.AccountInformation
196
        new_orphan_account(Geary.ServiceProvider provider,
197 198 199
                           Geary.RFC822.MailboxAddress primary_mailbox,
                           GLib.Cancellable? cancellable) {
        string id = yield next_id(cancellable);
200
        return new Geary.AccountInformation(
201
            id, provider, this.local_mediator, primary_mailbox
202
        );
203
    }
204

205 206 207
    /**
     * Creates new account's disk and credential storage as needed.
     */
208 209
    public async void create_account(Geary.AccountInformation account,
                                     GLib.Cancellable? cancellable)
210
        throws GLib.Error {
211 212 213 214
        yield create_account_dirs(account, cancellable);
        yield save_account(account, cancellable);
        set_enabled(account, true);

215 216
        // if it's a local account, save the passwords now
        SecretMediator? mediator = account.mediator as SecretMediator;
217
        if (mediator != null) {
218 219
            yield mediator.update_token(account, account.incoming, cancellable);
            yield mediator.update_token(account, account.outgoing, cancellable);
220
        }
221 222
    }

223
    public async void load_accounts(GLib.Cancellable? cancellable)
224
        throws GLib.Error {
225
        // Step 1. Load existing accounts from the user config dir
226 227
        GLib.FileEnumerator? enumerator = null;
        try {
228
            enumerator = yield this.config_dir.enumerate_children_async(
229 230 231 232
                "standard::*",
                FileQueryInfoFlags.NONE,
                Priority.DEFAULT,
                cancellable
233
            );
234 235 236 237
        } catch (GLib.IOError.NOT_FOUND err) {
            // Don't worry about the dir not being found, it just
            // means we have no accounts to load.
        }
238

239 240 241 242 243
        while (enumerator != null && !cancellable.is_cancelled()) {
            // Get 10 at a time to batch the IO together
            GLib.List<GLib.FileInfo> info_list = yield enumerator.next_files_async(
                10, GLib.Priority.DEFAULT, cancellable
            );
244

245 246
            uint len = info_list.length();
            for (uint i = 0; i < len && !cancellable.is_cancelled(); i++) {
247 248
                GLib.FileInfo file = info_list.nth_data(i);
                if (file.get_file_type() == FileType.DIRECTORY) {
249
                    string id = file.get_name();
250
                    try {
251
                        Geary.AccountInformation info = yield load_account(
252
                            id, cancellable
253
                        );
254 255 256 257
                        set_enabled(info, true);
                    } catch (ConfigError.UNAVAILABLE err) {
                        // All good, this was handled properly by
                        // load_account.
258 259 260
                    } catch (ConfigError.REMOVED err) {
                        // All good, this was handled properly by
                        // load_account.
261
                    } catch (GLib.Error err) {
262
                        debug("Error loading account %s", id);
263 264 265 266 267
                        report_problem(
                            new Geary.ProblemReport(
                                Geary.ProblemType.GENERIC_ERROR,
                                err
                            ));
268
                    }
269
                }
270
            }
271 272 273 274 275

            if (len == 0) {
                // We're done
                enumerator = null;
            }
276
        }
277 278 279 280 281 282

        // Step 2. Load previously unseen accounts from GOA, if available.
        if (this.goa_service != null) {
            GLib.List<Goa.Object> list = this.goa_service.get_accounts();
            for (int i=0; i < list.length() && !cancellable.is_cancelled(); i++) {
                Goa.Object account = list.nth_data(i);
283
                string id = to_geary_id(account);
284 285
                if (!this.accounts.has_key(id)) {
                    yield this.create_goa_account(account, cancellable);
286 287 288 289
                }
            }
        }
    }
290

291 292 293 294 295 296 297 298 299 300 301 302
    /**
     * Marks an existing account as being unavailable.
     *
     * This keeps the account in the known set, but marks it as being
     * unavailable.
     */
    public void disable_account(Geary.AccountInformation account) {
        if (this.accounts.has_key(account.id)) {
            set_available(account, false);
        }
    }

303 304 305 306 307 308 309 310 311 312 313 314 315 316
    /**
     * Removes an account from the manager's set of known accounts.
     *
     * This removes the account from the known set, marks the account
     * as deleted, and queues it for deletion. The account will not
     * actually be deleted until {@link expunge_accounts} is called,
     * and until then the account can be re-added using {@link
     * restore_account}.
     */
    public async void remove_account(Geary.AccountInformation account,
                                     GLib.Cancellable cancellable)
        throws GLib.Error {
        this.accounts.unset(account.id);
        this.removed.add(account);
317
        account.changed.disconnect(on_account_changed);
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        yield save_account(account, cancellable);
        account_removed(account);
    }

    /**
     * Restores an account that has previously been removed.
     *
     * This restores an account previously removed via a call to
     * {@link remove_account}, adding it back to the known set, as
     * long as {@link expunge_accounts} has not been called since
     * he account was removed.
     */
    public async void restore_account(Geary.AccountInformation account,
                                      GLib.Cancellable cancellable)
        throws GLib.Error {
        if (this.removed.remove(account)) {
            yield save_account(account, cancellable);
            set_enabled(account, true);
        }
    }

    /**
     * Deletes all local data for all accounts that have been removed.
     */
    public async void expunge_accounts(GLib.Cancellable? cancellable)
        throws GLib.Error {
        while (!this.removed.is_empty && !cancellable.is_cancelled()) {
            yield delete_account(this.removed.remove_at(0), cancellable);
        }
    }

349 350 351
    /**
     * Saves an account's configuration data to disk.
     */
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    public async void save_account(Geary.AccountInformation info,
                                   GLib.Cancellable? cancellable)
        throws GLib.Error {
        // Ensure only one async task is saving an info at once, since
        // at least the Engine can cause multiple saves to be called
        // in quick succession when updating special folder config.
        int token = yield info.write_lock.claim_async(cancellable);

        GLib.Error? thrown = null;
        try {
            yield save_account_locked(info, cancellable);
        } catch (GLib.Error err) {
            thrown = err;
        }

        info.write_lock.release(ref token);

        if (thrown != null) {
            throw thrown;
        }
    }

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    /** Updates a local account service's credentials. */
    public async void update_local_credentials(Geary.AccountInformation account,
                                               Geary.ServiceInformation old_service,
                                               Geary.ServiceInformation new_service,
                                               GLib.Cancellable? cancellable)
        throws GLib.Error {
        SecretMediator? mediator = account.mediator as SecretMediator;
        if (mediator != null) {
            if (new_service.credentials != null) {
                yield mediator.update_token(account, new_service, cancellable);
            }

            if (old_service.credentials != null &&
                (new_service.credentials == null ||
                 (new_service.credentials != null &&
                  old_service.credentials.user != old_service.credentials.user))) {
                yield mediator.clear_token(account, old_service, cancellable);
            }
        }
    }

395 396 397 398
    /**
     * Determines if an account is a GOA account or not.
     */
    public bool is_goa_account(Geary.AccountInformation account) {
399
        return (account.mediator is GoaMediator);
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    }

    /**
     * Opens GNOME Settings to add an account of a particular type.
     *
     * Throws an error if it was not possible to open GNOME Settings,
     * or if the given type is not supported for by GOA.
     */
    public async void add_goa_account(Geary.ServiceProvider type,
                                      GLib.Cancellable? cancellable)
        throws GLib.Error {
        switch (type) {
        case Geary.ServiceProvider.GMAIL:
            yield open_goa_settings("add", "google", cancellable);
            break;

        case Geary.ServiceProvider.OUTLOOK:
            yield open_goa_settings("add", "windows_live", cancellable);
            break;

        default:
421
            throw new GLib.IOError.NOT_SUPPORTED("Not supported for GOA");
422 423 424 425 426 427 428 429 430 431 432 433
        }
    }

    /**
     * Opens GOA settings for the given account in GNOME Settings.
     *
     * Throws an error if it was not possible to open GNOME Settings,
     * or if the given account is not backed by GOA.
     */
    public async void show_goa_account(Geary.AccountInformation account,
                                       GLib.Cancellable? cancellable)
        throws GLib.Error {
434 435
        if (!is_goa_account(account)) {
            throw new GLib.IOError.NOT_SUPPORTED("Not a GOA Account");
436 437 438
        }

        yield open_goa_settings(
439
            to_goa_id(account.id), null, cancellable
440 441 442
        );
    }

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    /** Returns the next id for a new local account. */
    private async string next_id(GLib.Cancellable? cancellable) {
        // Get the next known free id
        string? last_account = this.accounts.keys.fold<string?>((next, last) => {
                string? result = last;
                if (next.has_prefix(LOCAL_ID_PREFIX)) {
                    result = (last == null || strcmp(last, next) < 0) ? next : last;
                }
                return result;
            },
            null);

        uint next_id = 1;
        if (last_account != null) {
            next_id = int.parse(
                last_account.substring(LOCAL_ID_PREFIX.length)
            ) + 1;
        }

        // Check for existing directories that might conflict
        string id = LOCAL_ID_FORMAT.printf(next_id);
        try {
            while ((yield Geary.Files.query_exists_async(
                        this.config_dir.get_child(id), cancellable)) ||
                   (yield Geary.Files.query_exists_async(
                       this.data_dir.get_child(id), cancellable))) {
                next_id++;
                id = LOCAL_ID_FORMAT.printf(next_id);
            }
        } catch (GLib.Error err) {
            // Not much we can do here except keep going anyway?
            debug("Error checking for a free id on disk: %s", err.message);
        }

        return id;
    }

480 481 482 483 484 485
    /**
     * Loads an account info from a config directory.
     *
     * Throws an error if the config file was not found, could not be
     * parsed, or doesn't have all required fields.
     */
486
    private async Geary.AccountInformation
487
        load_account(string id, GLib.Cancellable? cancellable)
488
        throws ConfigError {
489 490
        GLib.File config_dir = this.config_dir.get_child(id);
        GLib.File data_dir = this.data_dir.get_child(id);
491

492
        Geary.ConfigFile config = new Geary.ConfigFile(
493
            config_dir.get_child(SETTINGS_FILENAME)
494
        );
495

496 497 498 499 500 501 502
        try {
            yield config.load(cancellable);
        } catch (GLib.KeyFileError err) {
            throw new ConfigError.SYNTAX(err.message);
        } catch (GLib.Error err) {
            throw new ConfigError.IO(err.message);
        }
503

504 505 506 507 508 509 510 511 512 513 514 515
        Geary.ConfigFile.Group metadata_config =
            config.get_group(GROUP_METADATA);
        int version = metadata_config.get_int(METADATA_VERSION, 0);
        Status status = Status.ENABLED;
        try {
            status = Status.for_value(
                metadata_config.get_string(
                    METADATA_STATUS, status.to_value()
                ));
        } catch (Geary.EngineError err) {
            throw new ConfigError.SYNTAX("%s: Invalid status value", id);
        }
516

517 518
        string? goa_id = metadata_config.get_string(METADATA_GOA, null);
        bool is_goa = (goa_id != null);
519 520 521 522 523 524 525 526 527

        // This exists purely for people were running master with GOA
        // accounts before the new accounts editor landed and 0.13 was
        // released. It can be removed once 0.14 is out.
        if (goa_id == null && id.has_prefix(GOA_ID_PREFIX)) {
            goa_id = to_goa_id(id);
            is_goa = true;
        }

528
        Goa.Object? goa_handle = null;
529 530
        GoaMediator? goa_mediator = null;
        Geary.ServiceProvider? default_provider = null;
531
        Geary.CredentialsMediator mediator = this.local_mediator;
532

533 534
        if (is_goa) {
            if (this.goa_service == null) {
535
                throw new ConfigError.MANAGEMENT("GOA service not available");
536 537
            }

538
            goa_handle = this.goa_service.lookup_by_id(goa_id);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
            if (goa_handle != null) {
                mediator = goa_mediator = new GoaMediator(goa_handle);
                default_provider = goa_mediator.get_service_provider();
            } else {
                // The GOA account has gone away, so there's nothing
                // we can do except to remove it locally as well
                info(
                    "%s: GOA account %s has been removed, removing local data",
                    id, goa_id
                );
                status = Status.REMOVED;
                // Use the default mediator since we can't create a
                // GOA equiv, but set a dummy default provider so we
                // don't get an error loading the config
                default_provider = Geary.ServiceProvider.OTHER;
554
            }
555 556
        }

557 558 559 560 561 562 563
        AccountConfig? accounts = null;
        ServiceConfig? services = null;
        switch (version) {
        case 0:
            accounts = new AccountConfigLegacy();
            services = new ServiceConfigLegacy();
            break;
564

565 566 567 568
        case 1:
            accounts = new AccountConfigV1(is_goa);
            services = new ServiceConfigV1();
            break;
569

570
        default:
571
            throw new ConfigError.VERSION(
572 573
                "Unsupported config version: %d", version
            );
574 575
        }

576 577 578 579 580
        Geary.AccountInformation? account = null;
        try {
            account = accounts.load(
                config,
                id,
581
                mediator,
582 583 584 585 586 587 588
                default_provider,
                get_account_name()
            );
            account.set_account_directories(config_dir, data_dir);
        } catch (GLib.KeyFileError err) {
            throw new ConfigError.SYNTAX(err.message);
        }
589

590 591 592 593 594 595 596
        // If the account has been marked as removed, now that we have
        // an account object and its dirs have been set up we can add
        // it to the removed list and just bail out.
        if (status == Status.REMOVED) {
            this.removed.add(account);
            throw new ConfigError.REMOVED("Account marked for removal");
        }
597

598 599
        if (!is_goa) {
            try {
600 601
                services.load(config, account, account.incoming);
                services.load(config, account, account.outgoing);
602 603 604 605 606 607 608 609
            } catch (GLib.KeyFileError err) {
                throw new ConfigError.SYNTAX(err.message);
            }
        } else {
            account.service_label = goa_mediator.get_service_label();
            try {
                yield goa_mediator.update(account, cancellable);
            } catch (GLib.Error err) {
610 611 612
                throw new ConfigError.MANAGEMENT(err.message);
            }

613
            if (!is_valid_goa_account(goa_handle)) {
614 615 616 617
                // If we get here, the GOA account's mail service used
                // to exist (we just loaded Geary's config for it) but
                // no longer does. This indicates the mail service has
                // been disabled, so set it as disabled.
618
                set_available(account, false);
619 620 621
                throw new ConfigError.UNAVAILABLE(
                    "GOA Mail service not available"
                );
622
            }
623 624
        }

625 626 627 628 629 630 631
        // If the account has been marked as disabled, mark it as such
        // and bail out.
        if (status == Status.DISABLED) {
            set_enabled(account, false);
            throw new ConfigError.UNAVAILABLE("Account disabled");
        }

632
        return account;
633 634
    }

635
    private async void save_account_locked(Geary.AccountInformation account,
636
                                           GLib.Cancellable? cancellable)
637
        throws GLib.Error {
638
        if (account.config_dir == null) {
639
            throw new GLib.IOError.NOT_SUPPORTED(
640
                "Account %s does not have a config directory", account.id
641
            );
642 643
        }

644 645 646
        Geary.ConfigFile config = new Geary.ConfigFile(
            account.config_dir.get_child(SETTINGS_FILENAME)
        );
647 648 649

        // Load the file first so we maintain old settings
        try {
650
            yield config.load(cancellable);
651 652 653
        } catch (GLib.Error err) {
            // Oh well, just create a new one when saving
            debug("Could not load existing config file: %s", err.message);
654
        }
655

656 657 658 659 660 661 662 663
        Geary.ConfigFile.Group metadata_config =
            config.get_group(GROUP_METADATA);
        metadata_config.set_int(
            METADATA_VERSION, CONFIG_VERSION
        );
        metadata_config.set_string(
            METADATA_STATUS, get_status(account).to_value()
        );
664

665 666 667
        bool is_goa = is_goa_account(account);
        if (is_goa) {
            metadata_config.set_string(METADATA_GOA, to_goa_id(account.id));
668
        }
669

670 671
        AccountConfig accounts = new AccountConfigV1(is_goa);
        accounts.save(account, config);
672

673 674
        if (!is_goa) {
            ServiceConfig services = new ServiceConfigV1();
675 676
            services.save(account, account.incoming, config);
            services.save(account, account.outgoing, config);
677 678
        }

679
        debug("Writing config to: %s", config.file.get_path());
680
        yield config.save(cancellable);
681 682
    }

683 684
    private async void delete_account(Geary.AccountInformation info,
                                      GLib.Cancellable? cancellable)
685
        throws GLib.Error {
686 687 688 689
        // If it's a local account, try clearing the passwords. Keep
        // going if there's an error though since we really want to
        // delete the account dirs.
        SecretMediator? mediator = info.mediator as SecretMediator;
690 691
        if (mediator != null) {
            try {
692
                yield mediator.clear_token(info, info.incoming, cancellable);
693 694 695 696 697
            } catch (Error e) {
                debug("Error clearing IMAP password: %s", e.message);
            }

            try {
698
                yield mediator.clear_token(info, info.outgoing, cancellable);
699 700 701
            } catch (Error e) {
                debug("Error clearing IMAP password: %s", e.message);
            }
702
        }
703

704 705 706 707 708 709 710 711 712 713 714 715 716
        if (info.data_dir != null) {
            yield Geary.Files.recursive_delete_async(
                info.data_dir, GLib.Priority.LOW, cancellable
            );
        }

        // Delete config last so if there are any errors above, it
        // will be re-tried at next startup.
        if (info.config_dir != null) {
            yield Geary.Files.recursive_delete_async(
                info.config_dir, GLib.Priority.LOW, cancellable
            );
        }
717 718
    }

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
    private inline AccountState lookup_state(Geary.AccountInformation account) {
        AccountState? state = this.accounts.get(account.id);
        if (state == null) {
            state = new AccountState(account);
            this.accounts.set(account.id, state);
        }
        return state;
    }

    private bool set_enabled(Geary.AccountInformation account, bool is_enabled) {
        bool was_added = !this.accounts.has_key(account.id);
        AccountState state = lookup_state(account);
        Status existing_status = state.status;
        state.enabled = is_enabled;

        bool ret = false;
        if (was_added) {
            account_added(state.account, state.status);
737
            account.changed.connect(on_account_changed);
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
            ret = true;
        } else if (state.status != existing_status) {
            account_status_changed(state.account, state.status);
            ret = true;
        }
        return ret;
    }

    private bool set_available(Geary.AccountInformation account, bool is_available) {
        bool was_added = !this.accounts.has_key(account.id);
        AccountState state = lookup_state(account);
        Status existing_status = state.status;
        state.available = is_available;

        bool ret = false;
        if (was_added) {
            account_added(state.account, state.status);
755
            account.changed.connect(on_account_changed);
756 757 758 759 760 761
            ret = true;
        } else if (state.status != existing_status) {
            account_status_changed(state.account, state.status);
            ret = true;
        }
        return ret;
762 763
    }

764
    private async void create_account_dirs(Geary.AccountInformation info,
765 766
                                          Cancellable? cancellable)
        throws GLib.Error {
767 768
        GLib.File config = this.config_dir.get_child(info.id);
        GLib.File data = this.data_dir.get_child(info.id);
769 770 771 772 773 774 775

        yield Geary.Files.make_directory_with_parents(config, cancellable);
        yield Geary.Files.make_directory_with_parents(data, cancellable);

        info.set_account_directories(config, data);
    }

776 777
    private inline string to_geary_id(Goa.Object account) {
        return GOA_ID_PREFIX + account.get_account().id;
778 779 780 781 782 783 784 785
    }

    private inline string to_goa_id(string id) {
        return id.has_prefix(GOA_ID_PREFIX)
            ? id.substring(GOA_ID_PREFIX.length)
            : id;
    }

786
    private bool is_valid_goa_account(Goa.Object handle) {
787 788
        // Goa.Account.mail_disabled doesn't seem to reflect if we get
        // get a valid mail object here, so just rely on that instead.
789 790 791 792 793 794 795 796 797 798 799 800
        Goa.Mail? mail = handle.get_mail();
        return (
            mail != null &&
            !Geary.String.is_empty(mail.imap_host) &&
            !Geary.String.is_empty(mail.smtp_host)
        );
    }

    private async void create_goa_account(Goa.Object account,
                                          GLib.Cancellable? cancellable) {
        if (is_valid_goa_account(account)) {
            Goa.Mail? mail = account.get_mail();
801 802 803 804
            string? name = mail.name;
            if (Geary.String.is_empty_or_whitespace(name)) {
                name = get_account_name();
            }
805 806 807 808 809

            GoaMediator mediator = new GoaMediator(account);
            Geary.AccountInformation info = new Geary.AccountInformation(
                to_geary_id(account),
                mediator.get_service_provider(),
810
                mediator,
811 812 813 814 815
                new Geary.RFC822.MailboxAddress(name, mail.email_address)
            );

            info.ordinal = Geary.AccountInformation.next_ordinal++;
            info.service_label = mediator.get_service_label();
816
            info.label = account.get_account().presentation_identity;
817 818 819 820 821 822 823 824 825 826 827 828

            try {
                yield create_account_dirs(info, cancellable);
                yield save_account(info, cancellable);
                yield mediator.update(info, cancellable);
            } catch (GLib.Error err) {
                report_problem(
                    new Geary.ProblemReport(
                        Geary.ProblemType.GENERIC_ERROR,
                        err
                    ));
            }
829

830
            set_enabled(info, true);
831 832 833 834 835 836
        } else {
            debug(
                "Ignoring GOA %s account %s, mail service not enabled",
                account.get_account().provider_type,
                account.get_account().id
            );
837
        }
838 839
    }

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    private async void update_goa_account(Geary.AccountInformation account,
                                          GLib.Cancellable? cancellable) {
        GoaMediator mediator = (GoaMediator) account.mediator;
        try {
            yield mediator.update(account, cancellable);

            // Update will clear the creds, so make sure they get
            // refreshed
            yield account.load_outgoing_credentials(cancellable);
            yield account.load_incoming_credentials(cancellable);
        } catch (GLib.Error err) {
            report_problem(
                new Geary.AccountProblemReport(
                    Geary.ProblemType.GENERIC_ERROR,
                    account,
                    err
                ));
        }

        // XXX need to notify the engine that creds may have changed

        set_available(account, mediator.is_available);
    }


865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    private async void open_goa_settings(string action,
                                         string? param,
                                         GLib.Cancellable? cancellable)
        throws GLib.Error {
        // This method was based on the implementation from:
        // https://gitlab.gnome.org/GNOME/gnome-calendar/blob/master/src/gcal-source-dialog.c,
        // Courtesy Georges Basile Stavracas Neto <georges.stavracas@gmail.com>
        GLib.DBusProxy settings = yield new GLib.DBusProxy.for_bus(
            GLib.BusType.SESSION,
            GLib.DBusProxyFlags.NONE,
            null,
            "org.gnome.ControlCenter",
            "/org/gnome/ControlCenter",
            "org.gtk.Actions",
            cancellable
        );

        // @s "launch-panel"
        // @av [<@(sav) ("online-accounts", [<@s "add">, <@s "google">])>]
        // @a{sv} {}

        GLib.Variant[] args = new GLib.Variant[] {
            new GLib.Variant.variant(new GLib.Variant.string(action))
        };
        if (param != null) {
            args += new GLib.Variant.variant(new GLib.Variant.string(param));
        }

        GLib.Variant command = new GLib.Variant.tuple(
            new GLib.Variant[] {
                new GLib.Variant.string("online-accounts"),
                new GLib.Variant.array(GLib.VariantType.VARIANT, args)
            }
        );

        GLib.Variant params = new GLib.Variant.tuple(
            new GLib.Variant[] {
                new GLib.Variant.string("launch-panel"),
                new GLib.Variant.array(
                    GLib.VariantType.VARIANT,
                    new GLib.Variant[] {
                        new GLib.Variant.variant(command)
                    }
                ),
                new GLib.Variant("a{sv}")
            }
        );

        yield settings.call(
            "Activate", params, GLib.DBusCallFlags.NONE, -1, cancellable
        );
    }

918
    private void on_goa_account_added(Goa.Object account) {
919
        debug("GOA account added: %s", account.get_account().id);
920 921
        // XXX get a cancellable for this.
        this.create_goa_account.begin(account, null);
922 923 924
    }

    private void on_goa_account_changed(Goa.Object account) {
925 926 927
        debug("GOA account changed: %s", account.get_account().id);
        AccountState? state = this.accounts.get(to_geary_id(account));
        // XXX get a cancellable to these
928 929 930 931
        if (state != null) {
            // We already know about this account, so check that it is
            // still valid. If not, the account should be disabled,
            // not deleted, since it may be re-enabled at some point.
932
            this.update_goa_account.begin(state.account, null);
933 934 935 936 937 938
        } else {
            // We haven't created an account for this GOA account
            // before, so try doing so now.
            //
            // XXX get a cancellable for this.
            this.create_goa_account.begin(account, null);
939 940 941 942
        }
    }

    private void on_goa_account_removed(Goa.Object account) {
943 944
        debug("GOA account removed: %s", account.get_account().id);
        AccountState? state = this.accounts.get(to_geary_id(account));
945
        if (state != null) {
946 947
            // Just disabled it for now in case the GOA daemon as just
            // shutting down.
948
            set_available(state.account, false);
949 950 951
        }
    }

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    private void on_account_changed(Geary.AccountInformation account) {
        this.save_account.begin(
            account, null,
            (obj, res) => {
                try {
                    this.save_account.end(res);
                } catch (GLib.Error err) {
                    report_problem(
                        new Geary.AccountProblemReport(
                            Geary.ProblemType.GENERIC_ERROR,
                            account,
                            err
                        )
                    );
                }
            }
        );
    }

971
}
972

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
/** Objects that can be used to load/save account configuration. */
public interface Accounts.AccountConfig : GLib.Object {

    /** Loads a supported account from a config file. */
    public abstract Geary.AccountInformation
        load(Geary.ConfigFile config,
             string id,
             Geary.CredentialsMediator mediator,
             Geary.ServiceProvider? default_provider,
             string? default_name)
        throws ConfigError, GLib.KeyFileError;

    /** Saves an account to a config file. */
    public abstract void save(Geary.AccountInformation account,
                              Geary.ConfigFile config);

}


/** Objects that can be used to load/save service configuration. */
public interface Accounts.ServiceConfig : GLib.Object {

    /** Loads a service from a config file. */
    public abstract void load(Geary.ConfigFile config,
                              Geary.AccountInformation account,
                              Geary.ServiceInformation service)
        throws ConfigError, GLib.KeyFileError;

    /** Saves a service to a config file. */
    public abstract void save(Geary.AccountInformation account,
                              Geary.ServiceInformation service,
                              Geary.ConfigFile config);

}


public errordomain Accounts.ConfigError {
    IO,
    MANAGEMENT,
    SYNTAX,
    VERSION,
    UNAVAILABLE,
    REMOVED;
}


1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
/**
 * Manages persistence for version 1 config files.
 */
public class Accounts.AccountConfigV1 : AccountConfig, GLib.Object {


    private const string GROUP_ACCOUNT = "Account";
    private const string GROUP_FOLDERS = "Folders";

    private const string ACCOUNT_LABEL = "label";
    private const string ACCOUNT_ORDINAL = "ordinal";
    private const string ACCOUNT_PREFETCH = "prefetch_days";
    private const string ACCOUNT_PROVIDER = "service_provider";
    private const string ACCOUNT_SAVE_DRAFTS = "save_drafts";
    private const string ACCOUNT_SAVE_SENT = "save_sent";
    private const string ACCOUNT_SENDERS = "sender_mailboxes";
    private const string ACCOUNT_SIG = "signature";
    private const string ACCOUNT_USE_SIG = "use_signature";

    private const string FOLDER_ARCHIVE = "archive_folder";
    private const string FOLDER_DRAFTS = "drafts_folder";
1040
    private const string FOLDER_SENT = "sent_folder";
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    private const string FOLDER_SPAM = "spam_folder";
    private const string FOLDER_TRASH = "trash_folder";


    private bool is_managed;

    public AccountConfigV1(bool is_managed) {
        this.is_managed = is_managed;
    }

    public  Geary.AccountInformation load(Geary.ConfigFile config,
                                          string id,
1053
                                          Geary.CredentialsMediator mediator,
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
                                          Geary.ServiceProvider? default_provider,
                                          string? default_name)
        throws ConfigError, GLib.KeyFileError {
        Geary.ConfigFile.Group account_config =
            config.get_group(GROUP_ACCOUNT);

        Gee.List<Geary.RFC822.MailboxAddress> senders =
            new Gee.LinkedList<Geary.RFC822.MailboxAddress>();
        foreach (string sender in
                 account_config.get_required_string_list(ACCOUNT_SENDERS)) {
            try {
                senders.add(
                    new Geary.RFC822.MailboxAddress.from_rfc822_string(sender)
                );
            } catch (Geary.RFC822Error err) {
                throw new ConfigError.SYNTAX(
                    "%s: Invalid sender address: %s", id, sender
                );
            }
        }

        if (senders.is_empty) {
            throw new ConfigError.SYNTAX("%s: No sender addresses found", id);
        }

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        Geary.ServiceProvider provider = (
            default_provider != null
            ? default_provider
            : account_config.parse_required_value<Geary.ServiceProvider>(
                ACCOUNT_PROVIDER,
                (value) => {
                    try {
                        return Geary.ServiceProvider.for_value(value);
                    } catch (Geary.EngineError err) {
                        throw new GLib.KeyFileError.INVALID_VALUE(err.message);
                    }
                }
            )
        );
1093 1094

        Geary.AccountInformation account = new Geary.AccountInformation(
1095
            id, provider, mediator, senders.remove_at(0)
1096 1097 1098 1099 1100
        );

        account.ordinal = account_config.get_int(
            ACCOUNT_ORDINAL, Geary.AccountInformation.next_ordinal++
        );
1101 1102
        account.label = account_config.get_string(
            ACCOUNT_LABEL, account.label
1103 1104 1105 1106 1107 1108 1109
        );
        account.prefetch_period_days = account_config.get_int(
            ACCOUNT_PREFETCH, account.prefetch_period_days
        );
        account.save_drafts = account_config.get_bool(
            ACCOUNT_SAVE_DRAFTS, account.save_drafts
        );
1110 1111
        account.save_sent = account_config.get_bool(
            ACCOUNT_SAVE_SENT, account.save_sent
1112
        );
1113 1114
        account.use_signature = account_config.get_bool(
            ACCOUNT_USE_SIG, account.use_signature
1115
        );
1116 1117
        account.signature = account_config.get_string(
            ACCOUNT_SIG, account.signature
1118 1119 1120 1121 1122 1123 1124 1125 1126
        );
        foreach (Geary.RFC822.MailboxAddress sender in senders) {
            account.append_sender(sender);
        }

        Geary.ConfigFile.Group folder_config =
            config.get_group(GROUP_FOLDERS);
        account.archive_folder_path = load_folder(folder_config, FOLDER_ARCHIVE);
        account.drafts_folder_path = load_folder(folder_config, FOLDER_DRAFTS);
1127
        account.sent_folder_path = load_folder(folder_config, FOLDER_SENT);
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
        account.spam_folder_path = load_folder(folder_config, FOLDER_SPAM);
        account.trash_folder_path = load_folder(folder_config, FOLDER_TRASH);

        return account;
    }

    /** Saves an account to a config file. */
    public void save(Geary.AccountInformation account,
                     Geary.ConfigFile config) {
        Geary.ConfigFile.Group account_config =
            config.get_group(GROUP_ACCOUNT);
        account_config.set_int(ACCOUNT_ORDINAL, account.ordinal);
1140
        account_config.set_string(ACCOUNT_LABEL, account.label);
1141 1142
        account_config.set_int(ACCOUNT_PREFETCH, account.prefetch_period_days);
        account_config.set_bool(ACCOUNT_SAVE_DRAFTS, account.save_drafts);
1143 1144 1145
        account_config.set_bool(ACCOUNT_SAVE_SENT, account.save_sent);
        account_config.set_bool(ACCOUNT_USE_SIG, account.use_signature);
        account_config.set_string(ACCOUNT_SIG, account.signature);
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
        account_config.set_string_list(
            ACCOUNT_SENDERS,
            Geary.traverse(account.sender_mailboxes)
            .map<string>((sender) => sender.to_rfc822_string())
            .to_array_list()
        );

        if (!is_managed) {
            account_config.set_string(
                ACCOUNT_PROVIDER, account.service_provider.to_value()
            );
        }

        Geary.ConfigFile.Group folder_config =
            config.get_group(GROUP_FOLDERS);
        save_folder(folder_config, FOLDER_ARCHIVE, account.archive_folder_path);
        save_folder(folder_config, FOLDER_DRAFTS, account.drafts_folder_path);
1163
        save_folder(folder_config, FOLDER_SENT, account.sent_folder_path);
1164 1165 1166 1167 1168 1169 1170 1171
        save_folder(folder_config, FOLDER_SPAM, account.spam_folder_path);
        save_folder(folder_config, FOLDER_TRASH, account.trash_folder_path);
    }

    private void save_folder(Geary.ConfigFile.Group config,
                             string key,
                             Geary.FolderPath? path) {
        if (path != null) {
1172 1173 1174
            config.set_string_list(
                key, new Gee.ArrayList<string>.wrap(path.as_array())
            );
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
        }
    }

    private Geary.FolderPath? load_folder(Geary.ConfigFile.Group config,
                                          string key) {
        Geary.FolderPath? path = null;
        Gee.List<string> parts = config.get_string_list(key);
        if (!parts.is_empty) {
            path = Geary.AccountInformation.build_folder_path(parts);
        }
        return path;
    }

}


/**
 * Manages persistence for un-versioned account configuration.
 */
public class Accounts.AccountConfigLegacy : AccountConfig, GLib.Object {

    internal const string GROUP = "AccountInformation";

    private const string ALTERNATE_EMAILS_KEY = "alternate_emails";
    private const string ARCHIVE_FOLDER_KEY = "archive_folder";
    private const string CREDENTIALS_METHOD_KEY = "credentials_method";
    private const string CREDENTIALS_PROVIDER_KEY = "credentials_provider";
    private const string DRAFTS_FOLDER_KEY = "drafts_folder";
    private const string EMAIL_SIGNATURE_KEY = "email_signature";
    private const string NICKNAME_KEY = "nickname";
    private const string ORDINAL_KEY = "ordinal";
    private const string PREFETCH_PERIOD_DAYS_KEY = "prefetch_period_days";
    private const string PRIMARY_EMAIL_KEY = "primary_email";
    private const string REAL_NAME_KEY = "real_name";
    private const string SAVE_DRAFTS_KEY = "save_drafts";
    private const string SAVE_SENT_MAIL_KEY = "save_sent_mail";
    private const string SENT_MAIL_FOLDER_KEY = "sent_mail_folder";
    private const string SERVICE_PROVIDER_KEY = "service_provider";
    private const string SPAM_FOLDER_KEY = "spam_folder";
    private const string TRASH_FOLDER_KEY = "trash_folder";
    private const string USE_EMAIL_SIGNATURE_KEY = "use_email_signature";


1218 1219 1220 1221 1222
    public Geary.AccountInformation load(Geary.ConfigFile config_file,
                                         string id,
                                         Geary.CredentialsMediator mediator,
                                         Geary.ServiceProvider? default_provider,
                                         string? default_name)
1223 1224 1225 1226 1227 1228
        throws ConfigError, GLib.KeyFileError {
        Geary.ConfigFile.Group config = config_file.get_group(GROUP);

        string primary_email = config.get_required_string(PRIMARY_EMAIL_KEY);
        string real_name = config.get_string(REAL_NAME_KEY, default_name);

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        Geary.ServiceProvider provider = (
            default_provider != null
            ? default_provider
            : config.parse_required_value<Geary.ServiceProvider>(
                SERVICE_PROVIDER_KEY,
                (value) => {
                    try {
                        return Geary.ServiceProvider.for_value(value);
                    } catch (Geary.EngineError err) {
                        throw new GLib.KeyFileError.INVALID_VALUE(err.message);
                    }
                }
            )
        );
1243 1244

        Geary.AccountInformation info = new Geary.AccountInformation(
1245
            id, provider, mediator,
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
            new Geary.RFC822.MailboxAddress(real_name, primary_email)
        );

        info.ordinal = config.get_int(ORDINAL_KEY, info.ordinal);
        if (info.ordinal >= Geary.AccountInformation.next_ordinal) {
            Geary.AccountInformation.next_ordinal = info.ordinal + 1;
        }

        info.append_sender(new Geary.RFC822.MailboxAddress(
            config.get_string(REAL_NAME_KEY), primary_email
        ));

1258
        info.label = config.get_string(NICKNAME_KEY);
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274

        // Store alternate emails in a list of case-insensitive strings
        Gee.List<string> alt_email_list = config.get_string_list(
            ALTERNATE_EMAILS_KEY
        );
        foreach (string alt_email in alt_email_list) {
            Geary.RFC822.MailboxAddresses mailboxes =
                new Geary.RFC822.MailboxAddresses.from_rfc822_string(alt_email);
            foreach (Geary.RFC822.MailboxAddress mailbox in mailboxes.get_all()) {
                info.append_sender(mailbox);
            }
        }

        info.prefetch_period_days = config.get_int(
            PREFETCH_PERIOD_DAYS_KEY, info.prefetch_period_days
        );
1275 1276
        info.save_sent = config.get_bool(
            SAVE_SENT_MAIL_KEY, info.save_sent
1277
        );
1278 1279
        info.use_signature = config.get_bool(
            USE_EMAIL_SIGNATURE_KEY, info.use_signature
1280
        );
1281 1282
        info.signature = config.get_string(
            EMAIL_SIGNATURE_KEY, info.signature
1283 1284 1285 1286 1287
        );

        info.drafts_folder_path = Geary.AccountInformation.build_folder_path(
            config.get_string_list(DRAFTS_FOLDER_KEY)
        );
1288
        info.sent_folder_path = Geary.AccountInformation.build_folder_path(
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
            config.get_string_list(SENT_MAIL_FOLDER_KEY)
        );
        info.spam_folder_path = Geary.AccountInformation.build_folder_path(
            config.get_string_list(SPAM_FOLDER_KEY)
        );
        info.trash_folder_path = Geary.AccountInformation.build_folder_path(
            config.get_string_list(TRASH_FOLDER_KEY)
        );
        info.archive_folder_path = Geary.AccountInformation.build_folder_path(
            config.get_string_list(ARCHIVE_FOLDER_KEY)
        );

        info.save_drafts = config.get_bool(SAVE_DRAFTS_KEY, true);

        return info;
    }

    public void save(Geary.AccountInformation info,
                     Geary.ConfigFile config_file) {

        Geary.ConfigFile.Group config = config_file.get_group(GROUP);

        config.set_string(REAL_NAME_KEY, info.primary_mailbox.name ?? "");
        config.set_string(PRIMARY_EMAIL_KEY, info.primary_mailbox.address);
1313
        config.set_string(NICKNAME_KEY, info.label);
1314 1315 1316
        config.set_string(SERVICE_PROVIDER_KEY, info.service_provider.to_value());
        config.set_int(ORDINAL_KEY, info.ordinal);
        config.set_int(PREFETCH_PERIOD_DAYS_KEY, info.prefetch_period_days);
1317 1318 1319
        config.set_bool(SAVE_SENT_MAIL_KEY, info.save_sent);
        config.set_bool(USE_EMAIL_SIGNATURE_KEY, info.use_signature);
        config.set_string(EMAIL_SIGNATURE_KEY, info.signature);
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
        if (info.has_sender_aliases) {
            Gee.List<Geary.RFC822.MailboxAddress> alts = info.sender_mailboxes;
            // Don't include the primary in the list
            alts.remove_at(0);

            config.set_string_list(
                ALTERNATE_EMAILS_KEY,
                Geary.traverse(alts)
                .map<string>((alt) => alt.to_rfc822_string())
                .to_array_list()
            );
        }

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
        Gee.ArrayList<string> empty = new Gee.ArrayList<string>();
        config.set_string_list(
            DRAFTS_FOLDER_KEY,
            (info.drafts_folder_path != null
             ? new Gee.ArrayList<string>.wrap(info.drafts_folder_path.as_array())
             : empty)
        );
        config.set_string_list(
            SENT_MAIL_FOLDER_KEY,
            (info.sent_folder_path != null
             ? new Gee.ArrayList<string>.wrap(info.sent_folder_path.as_array())
             : empty)
        );
        config.set_string_list(
            SPAM_FOLDER_KEY,
            (info.spam_folder_path != null
             ? new Gee.ArrayList<string>.wrap(info.spam_folder_path.as_array())
             : empty)
        );
        config.set_string_list(
            TRASH_FOLDER_KEY,
            (info.trash_folder_path != null
             ? new Gee.ArrayList<string>.wrap(info.trash_folder_path.as_array())
             : empty)
        );
        config.set_string_list(
            ARCHIVE_FOLDER_KEY,
            (info.archive_folder_path != null
             ? new Gee.ArrayList<string>.wrap(info.archive_folder_path.as_array())
             : empty)
        );
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

        config.set_bool(SAVE_DRAFTS_KEY, info.save_drafts);
    }

}


/**
 * Manages persistence for version 1 service configuration.
 */
public class Accounts.ServiceConfigV1 : ServiceConfig, GLib.Object {

    private const string GROUP_INCOMING = "Incoming";
    private const string GROUP_OUTGOING = "Outgoing";

    private const string CREDENTIALS = "credentials";
    private const string HOST = "host";
    private const string LOGIN = "login";
    private const string PORT = "port";
    private const string REMEMBER_PASSWORD = "remember_password";
    private const string SECURITY = "transport_security";


    /** Loads a supported service from a config file. */
1388 1389 1390
    public void load(Geary.ConfigFile config,
                     Geary.AccountInformation account,
                     Geary.ServiceInformation service)
1391 1392
        throws ConfigError, GLib.KeyFileError {
        Geary.ConfigFile.Group service_config = config.get_group(
1393
            service.protocol == IMAP ? GROUP_INCOMING : GROUP_OUTGOING
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
        );

        string? login = service_config.get_string(LOGIN, null);
        if (login != null) {
            service.credentials = new Geary.Credentials(
                Credentials.PASSWORD, login
            );
        }
        service.remember_password = service_config.get_bool(
            REMEMBER_PASSWORD, service.remember_password
        );


        if (account.service_provider == Geary.ServiceProvider.OTHER) {
            service.host = service_config.get_required_string(HOST);
            service.port = (uint16) service_config.get_int(PORT, service.port);

1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
            service.transport_security = service_config.parse_required_value
            <Geary.TlsNegotiationMethod>(
                SECURITY,
                (value) => {
                    try {
                        return Geary.TlsNegotiationMethod.for_value(value);
                    } catch (GLib.Error err) {
                        throw new GLib.KeyFileError.INVALID_VALUE(err.message);
                    }
                }
            );
1422

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
            service.credentials_requirement = service_config.parse_required_value
            <Geary.Credentials.Requirement>(
                CREDENTIALS,
                (value) => {
                    try {
                        return Geary.Credentials.Requirement.for_value(value);
                    } catch (GLib.Error err) {
                        throw new GLib.KeyFileError.INVALID_VALUE(err.message);
                    }
                }
            );
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460

            if (service.port == 0) {
                service.port = service.get_default_port();
            }
        }
    }

    /** Saves an service to a config file. */
    public void save(Geary.AccountInformation account,
                     Geary.ServiceInformation service,
                     Geary.ConfigFile config) {
        Geary.ConfigFile.Group service_config = config.get_group(
            service.protocol == IMAP ? GROUP_INCOMING : GROUP_OUTGOING
        );

        if (service.credentials != null) {
            service_config.set_string(LOGIN, service.credentials.user);
        }
        service_config.set_bool(REMEMBER_PASSWORD, service.remember_password);

        if (account.service_provider == Geary.ServiceProvider.OTHER) {
            service_config.set_string(HOST, service.host);
            service_config.set_int(PORT, service.port);
            service_config.set_string(
                SECURITY, service.transport_security.to_value()
            );

1461 1462 1463
            service_config.set_string(
                CREDENTIALS, service.credentials_requirement.to_value()
            );
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
        }
    }

}


/**
 * Manages persistence for un-versioned service configuration.
 */
public class Accounts.ServiceConfigLegacy : ServiceConfig, GLib.Object {


    private const string HOST = "host";
    private const string PORT = "port";
    private const string REMEMBER_PASSWORD = "remember_password";
    private const string SSL = "ssl";
    private const string STARTTLS = "starttls";
    private const string USERNAME = "username";

    private const string SMTP_NOAUTH = "smtp_noauth";
    private const string SMTP_USE_IMAP_CREDENTIALS = "smtp_use_imap_credentials";


    /** Loads a supported service from a config file. */
1488 1489 1490
    public void load(Geary.ConfigFile config,
                     Geary.AccountInformation account,
                     Geary.ServiceInformation service)
1491 1492 1493 1494
        throws ConfigError, GLib.KeyFileError {
        Geary.ConfigFile.Group service_config =
            config.get_group(AccountConfigLegacy.GROUP);

1495 1496
        string prefix = service.protocol == Geary.Protocol.IMAP
            ? "imap_" :  "smtp_";
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516

        string? login = service_config.get_string(
            prefix + USERNAME, account.primary_mailbox.address
        );
        if (login != null) {
            service.credentials = new Geary.Credentials(
                Credentials.PASSWORD, login
            );
        }
        service.remember_password = service_config.get_bool(
            prefix + REMEMBER_PASSWORD, service.remember_password
        );

        if (account.service_provider == Geary.ServiceProvider.OTHER) {
            service.host = service_config.get_string(prefix + HOST, service.host);
            service.port = (uint16) service_config.get_int(
                prefix + PORT, service.port
            );

            bool use_tls = service_config.get_bool(
1517
                prefix + SSL, service.protocol == Geary.Protocol.IMAP
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
            );
            bool use_starttls = service_config.get_bool(
                prefix + STARTTLS, true
            );
            if (use_tls) {
                service.transport_security = Geary.TlsNegotiationMethod.TRANSPORT;
            } else if (use_starttls) {
                service.transport_security = Geary.TlsNegotiationMethod.START_TLS;
            } else {
                service.transport_security = Geary.TlsNegotiationMethod.NONE;
            }

            if (service.protocol == Geary.Protocol.SMTP) {
                bool use_imap = service_config.get_bool(
                    SMTP_USE_IMAP_CREDENTIALS, service.credentials != null
                );
                bool no_auth = service_config.get_bool(
                    SMTP_NOAUTH, false
                );
                if (use_imap) {
1538 1539
                    service.credentials_requirement =
                        Geary.Credentials.Requirement.USE_INCOMING;
1540
                } else if (!no_auth) {
1541 1542
                    service.credentials_requirement =
                        Geary.Credentials.Requirement.CUSTOM;
1543
                } else {
1544 1545
                    service.credentials_requirement =
                        Geary.Credentials.Requirement.NONE;
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
                }
            }
        }
    }

    /** Saves an service to a config file. */
    public void save(Geary.AccountInformation account,
                     Geary.ServiceInformation service,
                     Geary.ConfigFile config) {
        Geary.ConfigFile.Group service_config =
            config.get_group(AccountConfigLegacy.GROUP);

1558
        string prefix = service.protocol.to_value().ascii_down() + "_";
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590

        if (service.credentials != null) {
            service_config.set_string(
                prefix + USERNAME, service.credentials.user
            );
        }
        service_config.set_bool(
            prefix + REMEMBER_PASSWORD, service.remember_password
        );

        if (account.service_provider == Geary.ServiceProvider.OTHER) {
            service_config.set_string(prefix + HOST, service.host);
            service_config.set_int(prefix + PORT, service.port);

            switch (service.transport_security) {
            case NONE:
                service_config.set_bool(prefix + SSL, false);
                service_config.set_bool(prefix + STARTTLS, false);
                break;

            case START_TLS:
                service_config.set_bool(prefix + SSL, false);
                service_config.set_bool(prefix + STARTTLS, true);
                break;

            case TRANSPORT:
                service_config.set_bool(prefix + SSL, true);
                service_config.set_bool(prefix + STARTTLS, false);
                break;
            }

            if (service.protocol == Geary.Protocol.SMTP) {
1591
                switch (service.credentials_requirement) {
1592 1593 1594 1595 1596
                case NONE:
                    service_config.set_bool(SMTP_USE_IMAP_CREDENTIALS, false);
                    service_config.set_bool(SMTP_NOAUTH, true);
                    break;

1597
                case USE_INCOMING:
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
                    service_config.set_bool(SMTP_USE_IMAP_CREDENTIALS, true);
                    service_config.set_bool(SMTP_NOAUTH, false);
                    break;

                case CUSTOM:
                    service_config.set_bool(SMTP_USE_IMAP_CREDENTIALS, false);
                    service_config.set_bool(SMTP_NOAUTH, false);
                    break;
                }
            }
        }
    }

}