- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / extensions / file_manager / private_api_misc.cc
1 // Copyright 2013 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/chromeos/extensions/file_manager/private_api_misc.h"
6
7 #include "base/files/file_path.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/values.h"
10 #include "chrome/browser/browser_process.h"
11 #include "chrome/browser/chromeos/drive/drive_integration_service.h"
12 #include "chrome/browser/chromeos/drive/logging.h"
13 #include "chrome/browser/chromeos/extensions/file_manager/private_api_util.h"
14 #include "chrome/browser/chromeos/file_manager/file_manager_installer.h"
15 #include "chrome/browser/chromeos/settings/cros_settings.h"
16 #include "chrome/browser/google_apis/auth_service.h"
17 #include "chrome/browser/lifetime/application_lifetime.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/signin/profile_oauth2_token_service.h"
20 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
21 #include "chrome/common/extensions/api/file_browser_private.h"
22 #include "chrome/common/pref_names.h"
23 #include "content/public/browser/render_view_host.h"
24 #include "content/public/common/page_zoom.h"
25 #include "google_apis/gaia/oauth2_token_service.h"
26 #include "url/gurl.h"
27
28 namespace extensions {
29
30 namespace {
31 const char kCWSScope[] = "https://www.googleapis.com/auth/chromewebstore";
32 }
33
34 bool FileBrowserPrivateLogoutUserFunction::RunImpl() {
35   chrome::AttemptUserExit();
36   return true;
37 }
38
39 bool FileBrowserPrivateGetPreferencesFunction::RunImpl() {
40   api::file_browser_private::GetPreferences::Results::Result result;
41   const PrefService* const service = GetProfile()->GetPrefs();
42
43   result.drive_enabled = drive::util::IsDriveEnabledForProfile(GetProfile());
44   result.cellular_disabled =
45       service->GetBoolean(prefs::kDisableDriveOverCellular);
46   result.hosted_files_disabled =
47       service->GetBoolean(prefs::kDisableDriveHostedFiles);
48   result.use24hour_clock = service->GetBoolean(prefs::kUse24HourClock);
49   result.allow_redeem_offers = true;
50   if (!chromeos::CrosSettings::Get()->GetBoolean(
51           chromeos::kAllowRedeemChromeOsRegistrationOffers,
52           &result.allow_redeem_offers)) {
53     result.allow_redeem_offers = true;
54   }
55
56   SetResult(result.ToValue().release());
57
58   drive::util::Log(logging::LOG_INFO, "%s succeeded.", name().c_str());
59   return true;
60 }
61
62 bool FileBrowserPrivateSetPreferencesFunction::RunImpl() {
63   using extensions::api::file_browser_private::SetPreferences::Params;
64   const scoped_ptr<Params> params(Params::Create(*args_));
65   EXTENSION_FUNCTION_VALIDATE(params);
66
67   PrefService* const service = GetProfile()->GetPrefs();
68
69   if (params->change_info.cellular_disabled)
70     service->SetBoolean(prefs::kDisableDriveOverCellular,
71                         *params->change_info.cellular_disabled);
72
73   if (params->change_info.hosted_files_disabled)
74     service->SetBoolean(prefs::kDisableDriveHostedFiles,
75                         *params->change_info.hosted_files_disabled);
76
77   drive::util::Log(logging::LOG_INFO, "%s succeeded.", name().c_str());
78   return true;
79 }
80
81 FileBrowserPrivateZipSelectionFunction::
82     FileBrowserPrivateZipSelectionFunction() {}
83
84 FileBrowserPrivateZipSelectionFunction::
85     ~FileBrowserPrivateZipSelectionFunction() {}
86
87 bool FileBrowserPrivateZipSelectionFunction::RunImpl() {
88   using extensions::api::file_browser_private::ZipSelection::Params;
89   const scoped_ptr<Params> params(Params::Create(*args_));
90   EXTENSION_FUNCTION_VALIDATE(params);
91
92   // First param is the source directory URL.
93   if (params->dir_url.empty())
94     return false;
95
96   base::FilePath src_dir = file_manager::util::GetLocalPathFromURL(
97       render_view_host(), GetProfile(), GURL(params->dir_url));
98   if (src_dir.empty())
99     return false;
100
101   // Second param is the list of selected file URLs.
102   if (params->selection_urls.empty())
103     return false;
104
105   std::vector<base::FilePath> files;
106   for (size_t i = 0; i < params->selection_urls.size(); ++i) {
107     base::FilePath path = file_manager::util::GetLocalPathFromURL(
108         render_view_host(), GetProfile(), GURL(params->selection_urls[i]));
109     if (path.empty())
110       return false;
111     files.push_back(path);
112   }
113
114   // Third param is the name of the output zip file.
115   if (params->dest_name.empty())
116     return false;
117
118   // Check if the dir path is under Drive mount point.
119   // TODO(hshi): support create zip file on Drive (crbug.com/158690).
120   if (drive::util::IsUnderDriveMountPoint(src_dir))
121     return false;
122
123   base::FilePath dest_file = src_dir.Append(params->dest_name);
124   std::vector<base::FilePath> src_relative_paths;
125   for (size_t i = 0; i != files.size(); ++i) {
126     const base::FilePath& file_path = files[i];
127
128     // Obtain the relative path of |file_path| under |src_dir|.
129     base::FilePath relative_path;
130     if (!src_dir.AppendRelativePath(file_path, &relative_path))
131       return false;
132     src_relative_paths.push_back(relative_path);
133   }
134
135   zip_file_creator_ = new file_manager::ZipFileCreator(this,
136                                                        src_dir,
137                                                        src_relative_paths,
138                                                        dest_file);
139
140   // Keep the refcount until the zipping is complete on utility process.
141   AddRef();
142
143   zip_file_creator_->Start();
144   return true;
145 }
146
147 void FileBrowserPrivateZipSelectionFunction::OnZipDone(bool success) {
148   SetResult(new base::FundamentalValue(success));
149   SendResponse(true);
150   Release();
151 }
152
153 bool FileBrowserPrivateZoomFunction::RunImpl() {
154   using extensions::api::file_browser_private::Zoom::Params;
155   const scoped_ptr<Params> params(Params::Create(*args_));
156   EXTENSION_FUNCTION_VALIDATE(params);
157
158   content::RenderViewHost* const view_host = render_view_host();
159   content::PageZoom zoom_type;
160   switch (params->operation) {
161     case Params::OPERATION_IN:
162       zoom_type = content::PAGE_ZOOM_IN;
163       break;
164     case Params::OPERATION_OUT:
165       zoom_type = content::PAGE_ZOOM_OUT;
166       break;
167     case Params::OPERATION_RESET:
168       zoom_type = content::PAGE_ZOOM_RESET;
169       break;
170     default:
171       NOTREACHED();
172       return false;
173   }
174   view_host->Zoom(zoom_type);
175   return true;
176 }
177
178 bool FileBrowserPrivateInstallWebstoreItemFunction::RunImpl() {
179   using extensions::api::file_browser_private::InstallWebstoreItem::Params;
180   const scoped_ptr<Params> params(Params::Create(*args_));
181   EXTENSION_FUNCTION_VALIDATE(params);
182
183   if (params->item_id.empty())
184     return false;
185
186   const extensions::WebstoreStandaloneInstaller::Callback callback =
187       base::Bind(
188           &FileBrowserPrivateInstallWebstoreItemFunction::OnInstallComplete,
189           this);
190
191   scoped_refptr<file_manager::FileManagerInstaller> installer(
192       new file_manager::FileManagerInstaller(
193           GetAssociatedWebContents(),  // web_contents(),
194           params->item_id,
195           GetProfile(),
196           callback));
197   // installer will be AddRef()'d in BeginInstall().
198   installer->BeginInstall();
199   return true;
200 }
201
202 void FileBrowserPrivateInstallWebstoreItemFunction::OnInstallComplete(
203     bool success,
204     const std::string& error) {
205   if (success) {
206     drive::util::Log(logging::LOG_INFO,
207                      "App install succeeded. (item id: %s)",
208                      webstore_item_id_.c_str());
209   } else {
210     drive::util::Log(logging::LOG_ERROR,
211                      "App install failed. (item id: %s, reason: %s)",
212                      webstore_item_id_.c_str(),
213                      error.c_str());
214     error_ = error;
215   }
216
217   SendResponse(success);
218 }
219
220 FileBrowserPrivateRequestWebStoreAccessTokenFunction::
221     FileBrowserPrivateRequestWebStoreAccessTokenFunction() {
222 }
223
224 FileBrowserPrivateRequestWebStoreAccessTokenFunction::
225     ~FileBrowserPrivateRequestWebStoreAccessTokenFunction() {
226 }
227
228 bool FileBrowserPrivateRequestWebStoreAccessTokenFunction::RunImpl() {
229   std::vector<std::string> scopes;
230   scopes.push_back(kCWSScope);
231
232   ProfileOAuth2TokenService* oauth_service =
233       ProfileOAuth2TokenServiceFactory::GetForProfile(GetProfile());
234   net::URLRequestContextGetter* url_request_context_getter =
235       g_browser_process->system_request_context();
236
237   if (!oauth_service) {
238     drive::util::Log(logging::LOG_ERROR,
239                      "CWS OAuth token fetch failed. OAuth2TokenService can't "
240                      "be retrived.");
241     SetResult(base::Value::CreateNullValue());
242     return false;
243   }
244
245   auth_service_.reset(new google_apis::AuthService(
246       oauth_service,
247       oauth_service->GetPrimaryAccountId(),
248       url_request_context_getter,
249       scopes));
250   auth_service_->StartAuthentication(base::Bind(
251       &FileBrowserPrivateRequestWebStoreAccessTokenFunction::
252           OnAccessTokenFetched,
253       this));
254
255   return true;
256 }
257
258 void FileBrowserPrivateRequestWebStoreAccessTokenFunction::OnAccessTokenFetched(
259     google_apis::GDataErrorCode code,
260     const std::string& access_token) {
261   if (code == google_apis::HTTP_SUCCESS) {
262     DCHECK(auth_service_->HasAccessToken());
263     DCHECK(access_token == auth_service_->access_token());
264     drive::util::Log(logging::LOG_INFO,
265                      "CWS OAuth token fetch succeeded.");
266     SetResult(new base::StringValue(access_token));
267     SendResponse(true);
268   } else {
269     drive::util::Log(logging::LOG_ERROR,
270                      "CWS OAuth token fetch failed. (GDataErrorCode: %s)",
271                      google_apis::GDataErrorCodeToString(code).c_str());
272     SetResult(base::Value::CreateNullValue());
273     SendResponse(false);
274   }
275 }
276
277 }  // namespace extensions