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