File: apk_web_app_service.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (718 lines) | stat: -rw-r--r-- 27,376 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
114
115
116
117
118
119
120
121
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
228
229
230
231
232
233
234
235
236
237
238
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
283
284
285
286
287
288
289
290
291
292
293
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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
413
414
415
416
417
418
419
420
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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/apps/apk_web_app_service.h"

#include <map>
#include <optional>
#include <utility>

#include "ash/constants/ash_features.h"
#include "base/containers/flat_map.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/strings/string_util.h"
#include "base/task/single_thread_task_runner.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/promise_apps/promise_app_service.h"
#include "chrome/browser/ash/apps/apk_web_app_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/shelf/chrome_shelf_controller.h"
#include "chrome/browser/web_applications/web_app_command_scheduler.h"
#include "chrome/browser/web_applications/web_app_helpers.h"
#include "chrome/browser/web_applications/web_app_install_finalizer.h"
#include "chrome/browser/web_applications/web_app_management_type.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_utils.h"
#include "chromeos/ash/experiences/arc/mojom/app.mojom.h"
#include "chromeos/ash/experiences/arc/session/connection_holder.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/services/app_service/public/cpp/app_registry_cache.h"
#include "components/services/app_service/public/cpp/app_types.h"
#include "components/services/app_service/public/cpp/types_util.h"
#include "components/webapps/browser/install_result_code.h"
#include "components/webapps/browser/installable/installable_metrics.h"
#include "url/gurl.h"

namespace ash {

namespace {

// The pref dict is:
// {
//  ...
//  "web_app_apks" : {
//    <web_app_id_1> : {
//      "package_name" : <apk_package_name_1>,
//      "should_remove": <bool>,
//      "is_web_only_twa": <bool>, (deprecated, and automatically removed)
//      "sha256_fingerprint": <string> (deprecated, and automatically removed)
//    },
//    <web_app_id_2> : {
//      "package_name" : <apk_package_name_2>,
//      "should_remove": <bool>
//    },
//    ...
//  },
//  ...
// }
const char kWebAppToApkDictPref[] = "web_app_apks";
const char kPackageNameKey[] = "package_name";
const char kShouldRemoveKey[] = "should_remove";

// TODO(crbug.com/40896350): Remove these keys after migrations are complete.
const char kIsWebOnlyTwaKey[] = "is_web_only_twa";
const char kSha256FingerprintKey[] = "sha256_fingerprint";

constexpr char kLastAppId[] = "last_app_id";
constexpr char kPinIndex[] = "pin_index";
constexpr char kGeneratedWebApkPackagePrefix[] = "org.chromium.webapk.";

// Default icon size in pixels to request from ARC for an icon.
const int kDefaultIconSize = 192;

bool IsAppInstalled(apps::AppRegistryCache& app_registry_cache,
                    const std::string& app_id) {
  bool installed = false;
  app_registry_cache.ForOneApp(
      app_id, [&installed](const apps::AppUpdate& update) {
        installed = apps_util::IsInstalled(update.Readiness());
      });
  return installed;
}

std::optional<webapps::AppId> GetWebAppIdForPackage(
    ArcAppListPrefs::PackageInfo* package) {
  if (!package || !package->web_app_info) {
    return std::nullopt;
  }

  // TWAs do not currently support manifest IDs, so the App ID is only based off
  // the start URL.
  return web_app::GenerateAppId(/*manifest_id_path=*/std::nullopt,
                                GURL(package->web_app_info->start_url));
}

// TODO(b/304184466): Refactor this DelegateImpl to reduce code duplication.
// Delegate implementation that actually talks to ARC.
// It looks up |ArcAppListPrefs| in the profile to find the ARC connection.
class ApkWebAppServiceDelegateImpl : public ApkWebAppService::Delegate,
                                     public ApkWebAppInstaller::Owner {
 public:
  explicit ApkWebAppServiceDelegateImpl(Profile* profile)
      : profile_(profile), arc_app_list_prefs_(ArcAppListPrefs::Get(profile)) {
    DCHECK(arc_app_list_prefs_);
  }

  void MaybeUninstallPackageInArc(const std::string& package_name) override {
    if (auto* instance = ARC_GET_INSTANCE_FOR_METHOD(
            arc_app_list_prefs_->app_connection_holder(), UninstallPackage)) {
      instance->UninstallPackage(package_name);
    }
  }

 private:
  void OnDidGetWebAppIcon(WebAppInstallCallback callback,
                          const std::string& package_name,
                          arc::mojom::WebAppInfoPtr web_app_info,
                          arc::mojom::RawIconPngDataPtr icon) {
    // Track the upcoming installation attempt.
    std::string web_app_id =
        web_app::GenerateAppId(std::nullopt, GURL(web_app_info->start_url));
    ApkWebAppService::Get(profile_)->AddInstallingWebApkPackageName(
        web_app_id, package_name);

    ApkWebAppInstaller::Install(profile_, package_name, std::move(web_app_info),
                                std::move(icon), std::move(callback),
                                weak_ptr_factory_.GetWeakPtr());
  }

  raw_ptr<Profile> profile_;
  raw_ptr<ArcAppListPrefs, DanglingUntriaged> arc_app_list_prefs_;

  // Must go last.
  base::WeakPtrFactory<ApkWebAppServiceDelegateImpl> weak_ptr_factory_{this};
};

}  // namespace

ApkWebAppService::Delegate::~Delegate() = default;

// static
ApkWebAppService* ApkWebAppService::Get(Profile* profile) {
  return ApkWebAppServiceFactory::GetForProfile(profile);
}

// static
void ApkWebAppService::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterDictionaryPref(kWebAppToApkDictPref);
}

ApkWebAppService::ApkWebAppService(Profile* profile, Delegate* test_delegate)
    : profile_(profile),
      arc_app_list_prefs_(nullptr),
      real_delegate_(std::make_unique<ApkWebAppServiceDelegateImpl>(profile)),
      test_delegate_(test_delegate) {
  DCHECK(web_app::AreWebAppsEnabled(profile));

  apps::AppRegistryCache& app_registry_cache =
      apps::AppServiceProxyFactory::GetForProfile(profile)->AppRegistryCache();
  app_registry_cache_observer_.Observe(&app_registry_cache);

  // Can be null in tests.
  arc_app_list_prefs_ = ArcAppListPrefs::Get(profile);
  if (arc_app_list_prefs_) {
    arc_app_list_prefs_observer_.Observe(arc_app_list_prefs_.get());
  }
}

ApkWebAppService::~ApkWebAppService() = default;

bool ApkWebAppService::IsWebOnlyTwa(const webapps::AppId& app_id) {
  std::optional<std::string> package_name = GetPackageNameForWebApp(app_id);
  if (!package_name) {
    return false;
  }
  std::unique_ptr<ArcAppListPrefs::PackageInfo> package =
      arc_app_list_prefs_->GetPackage(*package_name);
  if (!(package && package->web_app_info)) {
    return false;
  }
  return package->web_app_info->is_web_only_twa;
}

bool ApkWebAppService::IsWebAppInstalledFromArc(
    const webapps::AppId& web_app_id) {
  // The web app will only be in prefs under this key if it was installed from
  // ARC++.
  return WebAppToApks().FindDict(web_app_id) != nullptr;
}

bool ApkWebAppService::IsWebAppShellPackage(const std::string& package_name) {
  // If there is no associated web app ID, the package name is not a web app
  // shell package.
  return GetWebAppIdForPackageName(package_name).has_value();
}

std::optional<std::string> ApkWebAppService::GetPackageNameForWebApp(
    const webapps::AppId& app_id,
    bool include_installing_apks) {
  if (const base::Value::Dict* app_dict = WebAppToApks().FindDict(app_id)) {
    if (const std::string* value = app_dict->FindString(kPackageNameKey)) {
      return *value;
    }
  }
  // If requested, check whether there is a package name for the web app among
  // the currently installing web app apks.
  auto it = currently_installing_apks_.find(app_id);
  if (include_installing_apks && it != currently_installing_apks_.end()) {
    return it->second;
  }
  return std::nullopt;
}

std::optional<std::string> ApkWebAppService::GetPackageNameForWebApp(
    const GURL& url) {
  auto* web_app_provider = web_app::WebAppProvider::GetForWebApps(profile_);
  if (!web_app_provider) {
    return std::nullopt;
  }
  // Which capability check (if any) would fit best here?
  std::optional<webapps::AppId> app_id =
      web_app_provider->registrar_unsafe().FindBestAppWithUrlInScope(
          url, web_app::WebAppFilter::InstalledInChrome());
  if (!app_id) {
    return std::nullopt;
  }

  return GetPackageNameForWebApp(app_id.value());
}

std::optional<std::string> ApkWebAppService::GetWebAppIdForPackageName(
    const std::string& package_name) {
  for (auto [web_app_id, web_app_info_value] : WebAppToApks()) {
    const std::string* web_app_package_name =
        web_app_info_value.GetDict().FindString(kPackageNameKey);
    if (web_app_package_name && *web_app_package_name == package_name) {
      return web_app_id;
    }
  }
  return std::nullopt;
}

std::optional<std::string> ApkWebAppService::GetCertificateSha256Fingerprint(
    const webapps::AppId& app_id) {
  std::optional<std::string> package_name = GetPackageNameForWebApp(app_id);
  if (!package_name) {
    return std::nullopt;
  }
  std::unique_ptr<ArcAppListPrefs::PackageInfo> package =
      arc_app_list_prefs_->GetPackage(*package_name);
  if (!(package && package->web_app_info)) {
    return std::nullopt;
  }
  return package->web_app_info->certificate_sha256_fingerprint;
}

void ApkWebAppService::SetWebAppInstalledCallbackForTesting(
    WebAppCallbackForTesting web_app_installed_callback) {
  web_app_installed_callback_ = std::move(web_app_installed_callback);
}

void ApkWebAppService::SetWebAppUninstalledCallbackForTesting(
    WebAppCallbackForTesting web_app_uninstalled_callback) {
  web_app_uninstalled_callback_ = std::move(web_app_uninstalled_callback);
}

void ApkWebAppService::MaybeInstallWebApp(
    const std::string& package_name,
    arc::mojom::WebAppInfoPtr web_app_info) {

  auto* instance = ARC_GET_INSTANCE_FOR_METHOD(
      arc_app_list_prefs_->app_connection_holder(), GetPackageIcon);
  if (!instance) {
    return;
  }

  instance->GetPackageIcon(
      package_name, kDefaultIconSize, /*normalize=*/false,
      base::BindOnce(&ApkWebAppService::OnDidGetWebAppIcon,
                     weak_ptr_factory_.GetWeakPtr(), package_name,
                     std::move(web_app_info)));
}

void ApkWebAppService::MaybeUninstallWebApp(const webapps::AppId& web_app_id) {

  if (!IsWebAppInstalledFromArc(web_app_id)) {
    // Do not uninstall a web app that was not installed via ApkWebAppInstaller.
    return;
  }

  auto* provider = web_app::WebAppProvider::GetForWebApps(profile_);
  DCHECK(provider);
  provider->scheduler().RemoveInstallManagementMaybeUninstall(
      web_app_id, web_app::WebAppManagement::kWebAppStore,
      webapps::WebappUninstallSource::kArc,
      base::BindOnce(&ApkWebAppService::OnDidRemoveInstallSource,
                     weak_ptr_factory_.GetWeakPtr(), web_app_id));
}

void ApkWebAppService::MaybeUninstallArcPackage(
    const std::string& package_name) {

  if (auto* instance = ARC_GET_INSTANCE_FOR_METHOD(
          arc_app_list_prefs_->app_connection_holder(), UninstallPackage)) {
    instance->UninstallPackage(package_name);
  }
}

void ApkWebAppService::UpdateShelfPin(
    const std::string& package_name,
    const arc::mojom::WebAppInfoPtr& web_app_info) {
  std::string new_app_id;
  // Compute the current app id. It may have changed if the package has been
  // updated from an Android app to a web app, or vice versa.
  if (!web_app_info.is_null()) {
    new_app_id = web_app::GenerateAppId(
        /*manifest_id=*/std::nullopt, GURL(web_app_info->start_url));
  } else {
    // Get the first app in the package. If there are multiple apps in the
    // package there is no way to determine which app is more suitable to
    // replace the previous web app shortcut. For simplicity we will just use
    // the first one.
    DCHECK(arc_app_list_prefs_);
    std::unordered_set<std::string> apps =
        arc_app_list_prefs_->GetAppsForPackage(package_name);
    if (!apps.empty()) {
      new_app_id = *apps.begin();
    }
  }

  // Query for the old app id, which is cached in the package dict to ensure it
  // isn't overwritten before this method can run.
  const base::Value* last_app_id_value =
      arc_app_list_prefs_->GetPackagePrefs(package_name, kLastAppId);

  std::string last_app_id;
  if (last_app_id_value && last_app_id_value->is_string()) {
    last_app_id = last_app_id_value->GetString();
  }

  if (new_app_id != last_app_id && !new_app_id.empty()) {
    arc_app_list_prefs_->SetPackagePrefs(package_name, kLastAppId,
                                         base::Value(new_app_id));
    if (!last_app_id.empty()) {
      auto* shelf_controller = ChromeShelfController::instance();
      if (!shelf_controller) {
        return;
      }
      int index = shelf_controller->PinnedItemIndexByAppID(last_app_id);
      // The previously installed app has been uninstalled or hidden, in this
      // instance get the saved pin index and pin at that place.
      if (index == ChromeShelfController::kInvalidIndex) {
        const base::Value* saved_index =
            arc_app_list_prefs_->GetPackagePrefs(package_name, kPinIndex);
        if (!(saved_index && saved_index->is_int())) {
          return;
        }
        shelf_controller->PinAppAtIndex(new_app_id, saved_index->GetInt());
        arc_app_list_prefs_->SetPackagePrefs(
            package_name, kPinIndex,
            base::Value(ChromeShelfController::kInvalidIndex));
      } else {
        shelf_controller->ReplacePinnedItem(last_app_id, new_app_id);
      }
    }
  }
}

void ApkWebAppService::Shutdown() {
  // Can be null in tests.
  if (arc_app_list_prefs_) {
    arc_app_list_prefs_ = nullptr;
  }
}

void ApkWebAppService::OnPackageInstalled(
    const arc::mojom::ArcPackageInfo& package_info) {
  SyncArcAndWebApps();
}

void ApkWebAppService::OnPackageRemoved(const std::string& package_name,
                                        bool uninstalled) {
  std::optional<std::string> web_app_id =
      GetWebAppIdForPackageName(package_name);
  if (web_app_id) {
    const base::Value::Dict* app_dict = WebAppToApks().FindDict(*web_app_id);
    if (app_dict && app_dict->FindBool(kShouldRemoveKey).value_or(false)) {
      // This package removal was triggered by web app removal, so cleanup and
      // do not kick off the uninstallation loop again.
      ScopedDictPrefUpdate(profile_->GetPrefs(), kWebAppToApkDictPref)
          ->Remove(*web_app_id);
    } else {
      // Package was removed by the user in ARC.
      SyncArcAndWebApps();
    }
  }
}

void ApkWebAppService::OnPackageListInitialRefreshed() {
  arc_initialized_ = true;
  SyncArcAndWebApps();
}

void ApkWebAppService::OnArcAppListPrefsDestroyed() {
  arc_app_list_prefs_observer_.Reset();
}

void ApkWebAppService::OnAppUpdate(const apps::AppUpdate& update) {
  if (update.AppType() == apps::AppType::kWeb &&
      update.Readiness() == apps::Readiness::kUninstalledByUser) {
    MaybeRemoveArcPackageForWebApp(update.AppId());
  }
}

void ApkWebAppService::OnAppTypeInitialized(apps::AppType app_type) {
  if (app_type == apps::AppType::kWeb) {
    // Web apps are published, try syncing.
    SyncArcAndWebApps();
  }
}

void ApkWebAppService::OnAppRegistryCacheWillBeDestroyed(
    apps::AppRegistryCache* cache) {
  app_registry_cache_observer_.Reset();
}

void ApkWebAppService::MaybeRemoveArcPackageForWebApp(
    const webapps::AppId& web_app_id) {
  std::optional<std::string> package_name = GetPackageNameForWebApp(web_app_id);
  std::string removed_package_name;

  if (package_name) {
    ScopedDictPrefUpdate web_apps_to_apks(profile_->GetPrefs(),
                                          kWebAppToApkDictPref);
    std::unique_ptr<ArcAppListPrefs::PackageInfo> package =
        arc_app_list_prefs_->GetPackage(*package_name);
    if (package && package->web_app_info) {
      // Mark for removal and kick off the sync.
      web_apps_to_apks->EnsureDict(web_app_id)->Set(kShouldRemoveKey, true);
      SyncArcAndWebApps();
      removed_package_name = *package_name;
    } else {
      // 1) ARC package was already removed and triggered web app
      //    uninstallation, so there is nothing to remove.
      // 2) ARC package is no longer a web app.
      //
      // In either case we clean up the prefs and finish.
      web_apps_to_apks->Remove(web_app_id);
    }
  }

  // Post task to make sure that all observers get fired before the callback
  // called.
  if (web_app_uninstalled_callback_) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(web_app_uninstalled_callback_),
                                  removed_package_name, web_app_id));
  }
}

void ApkWebAppService::OnDidGetWebAppIcon(
    const std::string& package_name,
    arc::mojom::WebAppInfoPtr web_app_info,
    arc::mojom::RawIconPngDataPtr icon) {
  // Track the upcoming installation attempt.
  std::string web_app_id =
      web_app::GenerateAppId(std::nullopt, GURL(web_app_info->start_url));
  AddInstallingWebApkPackageName(web_app_id, package_name);

  ApkWebAppInstaller::Install(
      profile_, package_name, std::move(web_app_info), std::move(icon),
      base::BindOnce(&ApkWebAppService::OnDidFinishInstall,
                     weak_ptr_factory_.GetWeakPtr(), package_name),
      weak_ptr_factory_.GetWeakPtr());
}

void ApkWebAppService::OnDidFinishInstall(
    const std::string& package_name,
    const webapps::AppId& web_app_id,
    bool is_web_only_twa,
    const std::optional<std::string> sha256_fingerprint,
    webapps::InstallResultCode code) {
  if (code == webapps::InstallResultCode::kSuccessNewInstall) {
    // Set a pref to map |web_app_id| to |package_name| for future
    // uninstallation.
    ScopedDictPrefUpdate dict_update(profile_->GetPrefs(),
                                     kWebAppToApkDictPref);
    base::Value::Dict* web_app_dict = dict_update->EnsureDict(web_app_id);
    web_app_dict->Set(kPackageNameKey, package_name);

    // Set that the app should not be removed next time the ARC container starts
    // up. This is to ensure that web apps which are uninstalled in the browser
    // while the ARC container isn't running can be marked for uninstallation
    // when the container starts up again.
    web_app_dict->Set(kShouldRemoveKey, false);
  }
  RemoveInstallingWebApkPackageName(web_app_id);

  // For testing.
  if (web_app_installed_callback_) {
    std::move(web_app_installed_callback_).Run(package_name, web_app_id);
  }
}

void ApkWebAppService::OnDidRemoveInstallSource(
    const webapps::AppId& app_id,
    webapps::UninstallResultCode code) {
  {
    // The web app may still exist, but is no longer managed by an ARC package,
    // so remove it from the tracking dictionary.
    ScopedDictPrefUpdate web_apps_to_apks(profile_->GetPrefs(),
                                          kWebAppToApkDictPref);
    web_apps_to_apks->Remove(app_id);
  }

  if (web_app_uninstalled_callback_) {
    std::move(web_app_uninstalled_callback_)
        .Run(/*removed_package_name=*/"", app_id);
  }
}

const base::Value::Dict& ApkWebAppService::WebAppToApks() const {
  const base::Value::Dict& value =
      profile_->GetPrefs()->GetDict(kWebAppToApkDictPref);
  return value;
}

void ApkWebAppService::SyncArcAndWebApps() {
  // Check that we have the initial state of both ARC packages and installed web
  // apps before attempting to reconcile installation state.
  apps::AppRegistryCache& app_registry_cache =
      apps::AppServiceProxyFactory::GetForProfile(profile_)->AppRegistryCache();
  if (!app_registry_cache.IsAppTypeInitialized(apps::AppType::kWeb)) {
    return;
  }
  if (!arc_initialized_) {
    return;
  }

  std::vector<std::string> remove_from_prefs;
  for (const auto [web_app_id, web_app_info_value] : WebAppToApks()) {
    auto& web_app_info_dict = web_app_info_value.GetDict();
    const std::string* package_name =
        web_app_info_dict.FindString(kPackageNameKey);
    DCHECK(package_name);
    if (!package_name ||
        base::StartsWith(*package_name, kGeneratedWebApkPackagePrefix)) {
      // This shouldn't happen, but clean up bad data anyway.
      remove_from_prefs.push_back(web_app_id);
      continue;
    }
    if (!IsAppInstalled(app_registry_cache, web_app_id) &&
        !web_app_info_dict.FindBool(kShouldRemoveKey).value_or(false)) {
      // If the entry is for a non-existent web app AND isn't a marker for ARC
      // package uninstallation, it's stale (possibly due to a crash before web
      // app uninstallation callback is processed), so just remove it.
      remove_from_prefs.push_back(web_app_id);
    }
  }

  for (const auto& p : remove_from_prefs) {
    ScopedDictPrefUpdate(profile_->GetPrefs(), kWebAppToApkDictPref)->Remove(p);
  }

  // Collect currently installed ARC packages.
  std::map<std::string, std::unique_ptr<ArcAppListPrefs::PackageInfo>>
      arc_packages;
  for (const std::string& package_name :
       arc_app_list_prefs_->GetPackagesFromPrefs()) {
    // Automatically generated WebAPKs have their lifecycle managed by
    // WebApkManager and do not need to be considered here.
    if (base::StartsWith(package_name, kGeneratedWebApkPackagePrefix)) {
      continue;
    }
    arc_packages[package_name] = arc_app_list_prefs_->GetPackage(package_name);
  }

  // Map of package names which have migrated a web app from one package to
  // another. There should only be one package at a time on Play Store that
  // installs a particular web app. However, when migrating between packages,
  // some users might end up with two packages that are trying to install the
  // same web app. In this case, the packages will conflict over which one is
  // associated with the web app. We solve this by silently migrating installs
  // from the "deprecated" package to the "canonical" package.
  base::flat_map<std::string, std::string> migration_packages{
      {"com.google.android.apps.tachyon",   // Canonical package.
       "com.google.android.apps.meetings"}  // Deprecated package.
  };

  for (const auto& [canonical_package, deprecated_package] :
       migration_packages) {
    // We only perform a migration if both packages are installed and both
    // trying to install the same web app.
    if (!base::Contains(arc_packages, canonical_package) ||
        !base::Contains(arc_packages, deprecated_package)) {
      continue;
    }

    std::optional<webapps::AppId> canonical_id =
        GetWebAppIdForPackage(arc_packages.at(canonical_package).get());
    std::optional<webapps::AppId> deprecated_id =
        GetWebAppIdForPackage(arc_packages.at(deprecated_package).get());

    if (!canonical_id.has_value() || canonical_id != deprecated_id) {
      continue;
    }

    // If the web app is currently installed but pointing to the deprecated
    // package, switch to the canonical package. If the web app is not currently
    // installed, it will be installed later in this Sync call.
    if (GetPackageNameForWebApp(*canonical_id) == deprecated_package) {
      ScopedDictPrefUpdate dict_update(profile_->GetPrefs(),
                                       kWebAppToApkDictPref);
      base::Value::Dict* app_id_dict = dict_update->EnsureDict(*canonical_id);
      app_id_dict->Set(kPackageNameKey, canonical_package);
    }

    // Uninstalling the deprecated package is asynchronous, so we also need to
    // remove the package from `arc_packages` to prevent it from being
    // considered during the rest of this Sync call.
    MaybeUninstallArcPackage(deprecated_package);
    arc_packages.erase(deprecated_package);
  }

  // For each ARC package, decide if a matching web app needs to be installed or
  // uninstalled, if an ARC package becomes a non-web-app package.
  for (const auto& [package_name, package] : arc_packages) {
    std::optional<std::string> web_app_id =
        GetWebAppIdForPackageName(package_name);

    bool was_web_app = web_app_id.has_value();
    bool is_web_app = !package->web_app_info.is_null();

    if (!was_web_app && is_web_app) {
      UpdateShelfPin(package_name, package->web_app_info);
      // The package is a web app but we don't have a corresponding browser-side
      // artifact. Install it.
      MaybeInstallWebApp(package->package_name,
                         std::move(package->web_app_info));
    } else if (was_web_app && !is_web_app) {
      UpdateShelfPin(package_name, package->web_app_info);
      // The package was a web app, but now isn't. Remove the web app.
      DCHECK(web_app_id);
      MaybeUninstallWebApp(*web_app_id);
    }
  }

  // For each web app entry, check if needs to be uninstalled, or matching ARC
  // package needs to be uninstalled.
  std::vector<std::string> arc_apps_to_uninstall;
  std::vector<std::string> web_apps_to_uninstall;
  for (const auto [web_app_id, web_app_info_value] : WebAppToApks()) {
    auto& web_app_info_dict = web_app_info_value.GetDict();
    const std::string* package_name =
        web_app_info_dict.FindString(kPackageNameKey);
    DCHECK(package_name);
    if (!package_name) {
      // This shouldn't happen, but ignore bad data anyway.
      continue;
    }

    // If we see any app which has obsolete pref values, remove them
    // automatically.
    if (web_app_info_dict.contains(kIsWebOnlyTwaKey) ||
        web_app_info_dict.contains(kSha256FingerprintKey)) {
      RemoveObsoletePrefValues(web_app_id);
    }

    if (base::Contains(arc_packages, *package_name)) {
      if (web_app_info_dict.FindBool(kShouldRemoveKey).value_or(false)) {
        // ARC app should be uninstalled.
        arc_apps_to_uninstall.push_back(*package_name);
      }
    } else {
      // Web app should be uninstalled.
      web_apps_to_uninstall.push_back(web_app_id);
    }
  }
  for (const std::string& package_name : arc_apps_to_uninstall) {
    MaybeUninstallArcPackage(package_name);
  }
  for (const std::string& web_app_id : web_apps_to_uninstall) {
    MaybeUninstallWebApp(web_app_id);
  }
}

// TODO(crbug.com/40896350): Remove this code after migrations are complete.
void ApkWebAppService::RemoveObsoletePrefValues(
    const webapps::AppId& web_app_id) {
  ScopedDictPrefUpdate dict_update(profile_->GetPrefs(), kWebAppToApkDictPref);
  base::Value::Dict* app_id_dict = dict_update->EnsureDict(web_app_id);
  app_id_dict->Remove(kIsWebOnlyTwaKey);
  app_id_dict->Remove(kSha256FingerprintKey);
}

void ApkWebAppService::AddInstallingWebApkPackageName(
    const std::string& app_id,
    const std::string& package_name) {
  currently_installing_apks_[app_id] = package_name;
}

void ApkWebAppService::RemoveInstallingWebApkPackageName(
    const std::string& app_id) {
  std::string package_name = currently_installing_apks_[app_id];
  if (ash::features::ArePromiseIconsEnabled() && !package_name.empty()) {
    apps::AppServiceProxyFactory::GetForProfile(profile_)
        ->PromiseAppService()
        ->OnApkWebAppInstallationFinished(package_name);
  }
  currently_installing_apks_.erase(app_id);
}

}  // namespace ash