1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/apps/drive/drive_app_provider.h"
6
7#include <vector>
8
9#include "base/bind.h"
10#include "base/bind_helpers.h"
11#include "base/logging.h"
12#include "base/message_loop/message_loop.h"
13#include "base/stl_util.h"
14#include "chrome/browser/apps/drive/drive_app_converter.h"
15#include "chrome/browser/apps/drive/drive_app_mapping.h"
16#include "chrome/browser/apps/drive/drive_service_bridge.h"
17#include "chrome/browser/drive/drive_app_registry.h"
18#include "chrome/browser/extensions/extension_service.h"
19#include "chrome/browser/profiles/profile.h"
20#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
21#include "extensions/browser/extension_registry.h"
22#include "extensions/browser/extension_registry_factory.h"
23#include "extensions/browser/extension_system.h"
24#include "extensions/browser/uninstall_reason.h"
25#include "extensions/common/extension.h"
26
27using extensions::Extension;
28using extensions::ExtensionRegistry;
29
30namespace {
31
32void IgnoreUninstallResult(google_apis::GDataErrorCode) {
33}
34
35}  // namespace
36
37DriveAppProvider::DriveAppProvider(Profile* profile)
38    : profile_(profile),
39      service_bridge_(DriveServiceBridge::Create(profile).Pass()),
40      mapping_(new DriveAppMapping(profile->GetPrefs())),
41      weak_ptr_factory_(this) {
42  service_bridge_->GetAppRegistry()->AddObserver(this);
43  ExtensionRegistry::Get(profile_)->AddObserver(this);
44}
45
46DriveAppProvider::~DriveAppProvider() {
47  ExtensionRegistry::Get(profile_)->RemoveObserver(this);
48  service_bridge_->GetAppRegistry()->RemoveObserver(this);
49}
50
51// static
52void DriveAppProvider::AppendDependsOnFactories(
53    std::set<BrowserContextKeyedServiceFactory*>* factories) {
54  factories->insert(extensions::ExtensionRegistryFactory::GetInstance());
55  DriveServiceBridge::AppendDependsOnFactories(factories);
56}
57
58void DriveAppProvider::SetDriveServiceBridgeForTest(
59    scoped_ptr<DriveServiceBridge> test_bridge) {
60  service_bridge_->GetAppRegistry()->RemoveObserver(this);
61  service_bridge_ = test_bridge.Pass();
62  service_bridge_->GetAppRegistry()->AddObserver(this);
63}
64
65void DriveAppProvider::UpdateMappingAndExtensionSystem(
66    const std::string& drive_app_id,
67    const Extension* new_app,
68    bool is_new_app_generated) {
69  const std::string& new_chrome_app_id = new_app->id();
70
71  const std::string existing_chrome_app_id =
72      mapping_->GetChromeApp(drive_app_id);
73  if (existing_chrome_app_id == new_chrome_app_id)
74    return;
75
76  const bool is_existing_app_generated =
77      mapping_->IsChromeAppGenerated(existing_chrome_app_id);
78  mapping_->Add(drive_app_id, new_chrome_app_id, is_new_app_generated);
79
80  const Extension* existing_app =
81      ExtensionRegistry::Get(profile_)->GetExtensionById(
82          existing_chrome_app_id, ExtensionRegistry::EVERYTHING);
83  if (existing_app && is_existing_app_generated) {
84    extensions::ExtensionSystem::Get(profile_)
85        ->extension_service()
86        ->UninstallExtension(existing_chrome_app_id,
87                             extensions::UNINSTALL_REASON_SYNC,
88                             base::Bind(&base::DoNothing),
89                             NULL);
90  }
91}
92
93void DriveAppProvider::ProcessDeferredOnExtensionInstalled(
94    const std::string drive_app_id,
95    const std::string chrome_app_id) {
96  const Extension* app = ExtensionRegistry::Get(profile_)->GetExtensionById(
97      chrome_app_id, ExtensionRegistry::EVERYTHING);
98  if (!app)
99    return;
100
101  UpdateMappingAndExtensionSystem(drive_app_id, app, false);
102}
103
104void DriveAppProvider::SchedulePendingConverters() {
105  if (pending_converters_.empty())
106    return;
107
108  if (!pending_converters_.front()->IsStarted())
109    pending_converters_.front()->Start();
110}
111
112void DriveAppProvider::OnLocalAppConverted(const DriveAppConverter* converter,
113                                           bool success) {
114  DCHECK_EQ(pending_converters_.front(), converter);
115
116  if (success) {
117    const bool was_generated =
118        mapping_->GetDriveApp(converter->extension()->id()) ==
119            converter->drive_app_info().app_id &&
120        mapping_->IsChromeAppGenerated(converter->extension()->id());
121    UpdateMappingAndExtensionSystem(
122        converter->drive_app_info().app_id,
123        converter->extension(),
124        converter->is_new_install() || was_generated);
125  } else {
126    LOG(WARNING) << "Failed to convert drive app to web app, "
127                 << "drive app id= " << converter->drive_app_info().app_id
128                 << ", name=" << converter->drive_app_info().app_name;
129  }
130
131  pending_converters_.erase(pending_converters_.begin());
132  SchedulePendingConverters();
133}
134
135bool DriveAppProvider::IsMappedUrlAppUpToDate(
136    const drive::DriveAppInfo& drive_app) const {
137  const std::string& url_app_id = mapping_->GetChromeApp(drive_app.app_id);
138  if (url_app_id.empty())
139    return false;
140
141  const Extension* url_app = ExtensionRegistry::Get(profile_)->GetExtensionById(
142      url_app_id, ExtensionRegistry::EVERYTHING);
143  if (!url_app)
144    return false;
145  DCHECK(url_app->is_hosted_app() && url_app->from_bookmark());
146
147  return drive_app.app_name == url_app->name() &&
148         drive_app.create_url ==
149             extensions::AppLaunchInfo::GetLaunchWebURL(url_app);
150}
151
152void DriveAppProvider::AddOrUpdateDriveApp(
153    const drive::DriveAppInfo& drive_app) {
154  const Extension* chrome_app =
155      ExtensionRegistry::Get(profile_)->GetExtensionById(
156          drive_app.product_id, ExtensionRegistry::EVERYTHING);
157  if (chrome_app) {
158    UpdateMappingAndExtensionSystem(drive_app.app_id, chrome_app, false);
159    return;
160  }
161
162  if (IsMappedUrlAppUpToDate(drive_app))
163    return;
164
165  ScopedVector<DriveAppConverter>::iterator it = pending_converters_.begin();
166  while (it != pending_converters_.end()) {
167    if (!(*it)->IsStarted() &&
168        (*it)->drive_app_info().app_id == drive_app.app_id) {
169      it = pending_converters_.erase(it);
170    } else {
171      ++it;
172    }
173  }
174
175  pending_converters_.push_back(
176      new DriveAppConverter(profile_,
177                            drive_app,
178                            base::Bind(&DriveAppProvider::OnLocalAppConverted,
179                                       base::Unretained(this))));
180}
181
182void DriveAppProvider::ProcessRemovedDriveApp(const std::string& drive_app_id) {
183  const std::string chrome_app_id = mapping_->GetChromeApp(drive_app_id);
184  const bool is_generated = mapping_->IsChromeAppGenerated(chrome_app_id);
185  mapping_->Remove(drive_app_id);
186
187  if (chrome_app_id.empty() || !is_generated)
188    return;
189
190  const Extension* existing_app =
191      ExtensionRegistry::Get(profile_)
192          ->GetExtensionById(chrome_app_id, ExtensionRegistry::EVERYTHING);
193  if (!existing_app)
194    return;
195
196  extensions::ExtensionSystem::Get(profile_)
197      ->extension_service()
198      ->UninstallExtension(chrome_app_id,
199                           extensions::UNINSTALL_REASON_SYNC,
200                           base::Bind(&base::DoNothing),
201                           NULL);
202}
203
204void DriveAppProvider::OnDriveAppRegistryUpdated() {
205  service_bridge_->GetAppRegistry()->GetAppList(&drive_apps_);
206
207  IdSet current_ids;
208  for (size_t i = 0; i < drive_apps_.size(); ++i)
209    current_ids.insert(drive_apps_[i].app_id);
210
211  const IdSet existing_ids = mapping_->GetDriveAppIds();
212  const IdSet ids_to_remove =
213      base::STLSetDifference<IdSet>(existing_ids, current_ids);
214  for (IdSet::const_iterator it = ids_to_remove.begin();
215       it != ids_to_remove.end();
216       ++it) {
217    ProcessRemovedDriveApp(*it);
218  }
219
220  for (size_t i = 0; i < drive_apps_.size(); ++i) {
221    AddOrUpdateDriveApp(drive_apps_[i]);
222  }
223  SchedulePendingConverters();
224}
225
226void DriveAppProvider::OnExtensionInstalled(
227    content::BrowserContext* browser_context,
228    const Extension* extension,
229    bool is_update) {
230  // Bail if the |extension| is installed from a converter. The post install
231  // processing will be handled in OnLocalAppConverted.
232  if (!pending_converters_.empty() &&
233      pending_converters_.front()->IsInstalling(extension->id())) {
234    return;
235  }
236
237  // Only user installed app reaches here. If it is mapped, make sure it is not
238  // tagged as generated.
239  const std::string drive_app_id = mapping_->GetDriveApp(extension->id());
240  if (!drive_app_id.empty() &&
241      mapping_->IsChromeAppGenerated(extension->id())) {
242    mapping_->Add(drive_app_id, extension->id(), false);
243    return;
244  }
245
246  for (size_t i = 0; i < drive_apps_.size(); ++i) {
247    if (drive_apps_[i].product_id == extension->id()) {
248      // Defer the processing because it touches the extensions system and
249      // it is better to let the current task finish to avoid unexpected
250      // incomplete status.
251      base::MessageLoop::current()->PostTask(
252          FROM_HERE,
253          base::Bind(&DriveAppProvider::ProcessDeferredOnExtensionInstalled,
254                     weak_ptr_factory_.GetWeakPtr(),
255                     drive_apps_[i].app_id,
256                     extension->id()));
257      return;
258    }
259  }
260}
261
262void DriveAppProvider::OnExtensionUninstalled(
263    content::BrowserContext* browser_context,
264    const Extension* extension,
265    extensions::UninstallReason reason) {
266  std::string drive_app_id = mapping_->GetDriveApp(extension->id());
267  if (drive_app_id.empty())
268    return;
269
270  service_bridge_->GetAppRegistry()->UninstallApp(
271      drive_app_id, base::Bind(&IgnoreUninstallResult));
272}
273