File: private_api_tasks.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 (311 lines) | stat: -rw-r--r-- 11,817 bytes parent folder | download | duplicates (6)
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
// Copyright 2013 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/extensions/file_manager/private_api_tasks.h"

#include <stddef.h>

#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "ash/webui/system_apps/public/system_web_app_type.h"
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "chrome/browser/ash/drive/file_system_util.h"
#include "chrome/browser/ash/file_manager/app_service_file_tasks.h"
#include "chrome/browser/ash/file_manager/file_tasks.h"
#include "chrome/browser/ash/file_manager/fileapi_util.h"
#include "chrome/browser/ash/file_manager/filesystem_api_util.h"
#include "chrome/browser/ash/fileapi/file_system_backend.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/system_web_apps/system_web_app_ui_utils.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/extensions/api/file_manager_private.h"
#include "chrome/common/extensions/api/file_manager_private_internal.h"
#include "extensions/browser/api/file_handlers/directory_util.h"
#include "extensions/browser/api/file_handlers/mime_util.h"
#include "extensions/browser/entry_info.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_url.h"

namespace extensions {
namespace {

// Error messages.
constexpr char kInvalidTaskType[] = "Invalid task type: ";
constexpr char kInvalidFileUrl[] = "Invalid file URL";

// Make a set of unique filename suffixes out of the list of file URLs.
std::set<std::string> GetUniqueSuffixes(
    const std::vector<std::string>& file_urls,
    const storage::FileSystemContext* context) {
  std::set<std::string> suffixes;
  for (const auto& file_url : file_urls) {
    const storage::FileSystemURL url =
        context->CrackURLInFirstPartyContext(GURL{file_url});
    if (!url.is_valid() || url.path().empty()) {
      return {};
    }
    // We'll skip empty suffixes.
    if (!url.path().Extension().empty()) {
      suffixes.insert(url.path().Extension());
    }
  }
  return suffixes;
}

// Make a set of unique MIME types out of the list of MIME types.
std::set<std::string> GetUniqueMimeTypes(
    const std::vector<std::string>& mime_type_list) {
  std::set<std::string> mime_types;
  for (const auto& mime_type : mime_type_list) {
    // We'll skip empty MIME types and existing MIME types.
    if (!mime_type.empty()) {
      mime_types.insert(mime_type);
    }
  }
  return mime_types;
}

namespace api_fmp = extensions::api::file_manager_private;
namespace api_fmp_internal = extensions::api::file_manager_private_internal;

std::optional<api_fmp::PolicyDefaultHandlerStatus>
RemapPolicyDefaultHandlerStatus(
    const std::optional<file_manager::file_tasks::PolicyDefaultHandlerStatus>&
        status) {
  if (!status) {
    return {};
  }

  switch (*status) {
    case file_manager::file_tasks::PolicyDefaultHandlerStatus::
        kDefaultHandlerAssignedByPolicy:
      return api_fmp::PolicyDefaultHandlerStatus::
          kDefaultHandlerAssignedByPolicy;
    case file_manager::file_tasks::PolicyDefaultHandlerStatus::
        kIncorrectAssignment:
      return api_fmp::PolicyDefaultHandlerStatus::kIncorrectAssignment;
  }
}

}  // namespace

FileManagerPrivateInternalExecuteTaskFunction::
    FileManagerPrivateInternalExecuteTaskFunction() = default;

ExtensionFunction::ResponseAction
FileManagerPrivateInternalExecuteTaskFunction::Run() {
  using api_fmp_internal::ExecuteTask::Params;
  using api_fmp_internal::ExecuteTask::Results::Create;
  const std::optional<Params> params = Params::Create(args());
  EXTENSION_FUNCTION_VALIDATE(params);

  file_manager::file_tasks::TaskType task_type =
      file_manager::file_tasks::StringToTaskType(params->descriptor.task_type);
  if (task_type == file_manager::file_tasks::TASK_TYPE_UNKNOWN) {
    return RespondNow(Error(kInvalidTaskType + params->descriptor.task_type));
  }
  file_manager::file_tasks::TaskDescriptor task(
      params->descriptor.app_id, task_type, params->descriptor.action_id);

  if (params->urls.empty()) {
    return RespondNow(ArgumentList(Create(api_fmp::TaskResult::kEmpty)));
  }

  Profile* const profile = Profile::FromBrowserContext(browser_context());
  const scoped_refptr<storage::FileSystemContext> file_system_context =
      file_manager::util::GetFileSystemContextForRenderFrameHost(
          profile, render_frame_host());

  std::vector<storage::FileSystemURL> urls;
  for (const auto& url_param : params->urls) {
    const storage::FileSystemURL url =
        file_system_context->CrackURLInFirstPartyContext(GURL{url_param});
    if (!ash::FileSystemBackend::CanHandleURL(url)) {
      return RespondNow(Error(kInvalidFileUrl));
    }
    urls.push_back(url);
  }

  const bool result = file_manager::file_tasks::ExecuteFileTask(
      profile, task, urls,
      base::BindOnce(
          &FileManagerPrivateInternalExecuteTaskFunction::OnTaskExecuted,
          this));
  if (!result) {
    return RespondNow(Error("ExecuteFileTask failed"));
  }
  return RespondLater();
}

void FileManagerPrivateInternalExecuteTaskFunction::OnTaskExecuted(
    api_fmp::TaskResult result,
    std::string failure_reason) {
  auto result_list = api_fmp_internal::ExecuteTask::Results::Create(result);
  if (result == api_fmp::TaskResult::kFailed) {
    Respond(Error("Task result failed: " + failure_reason));
  } else {
    Respond(ArgumentList(std::move(result_list)));
  }
}

FileManagerPrivateInternalGetFileTasksFunction::
    FileManagerPrivateInternalGetFileTasksFunction() = default;

FileManagerPrivateInternalGetFileTasksFunction::
    ~FileManagerPrivateInternalGetFileTasksFunction() = default;

ExtensionFunction::ResponseAction
FileManagerPrivateInternalGetFileTasksFunction::Run() {
  using api_fmp_internal::GetFileTasks::Params;
  const std::optional<Params> params = Params::Create(args());
  EXTENSION_FUNCTION_VALIDATE(params);

  if (params->urls.empty()) {
    return RespondNow(Error("No URLs provided"));
  }

  if (params->dlp_source_urls.size() != params->urls.size()) {
    return RespondNow(Error("Mismatching URLs and DLP source URLs provided"));
  }

  Profile* const profile = Profile::FromBrowserContext(browser_context());
  const scoped_refptr<storage::FileSystemContext> file_system_context =
      file_manager::util::GetFileSystemContextForRenderFrameHost(
          profile, render_frame_host());

  // Collect all the URLs, convert them to GURLs, and crack all the urls into
  // file paths.
  for (const auto& url_param : params->urls) {
    const GURL url{url_param};
    storage::FileSystemURL file_system_url(
        file_system_context->CrackURLInFirstPartyContext(url));
    if (!ash::FileSystemBackend::CanHandleURL(file_system_url)) {
      continue;
    }
    urls_.push_back(url);
    local_paths_.push_back(file_system_url.path());
  }

  dlp_source_urls_ = std::move(params->dlp_source_urls);

  mime_type_collector_ =
      std::make_unique<app_file_handler_util::MimeTypeCollector>(profile);
  mime_type_collector_->CollectForLocalPaths(
      local_paths_,
      base::BindOnce(
          &FileManagerPrivateInternalGetFileTasksFunction::OnMimeTypesCollected,
          this));

  return RespondLater();
}

void FileManagerPrivateInternalGetFileTasksFunction::OnMimeTypesCollected(
    std::unique_ptr<std::vector<std::string>> mime_types) {
  is_directory_collector_ =
      std::make_unique<app_file_handler_util::IsDirectoryCollector>(
          Profile::FromBrowserContext(browser_context()));
  is_directory_collector_->CollectForEntriesPaths(
      local_paths_,
      base::BindOnce(&FileManagerPrivateInternalGetFileTasksFunction::
                         OnAreDirectoriesAndMimeTypesCollected,
                     this, std::move(mime_types)));
}

void FileManagerPrivateInternalGetFileTasksFunction::
    OnAreDirectoriesAndMimeTypesCollected(
        std::unique_ptr<std::vector<std::string>> mime_types,
        std::unique_ptr<std::set<base::FilePath>> directory_paths) {
  std::vector<EntryInfo> entries;
  for (size_t i = 0; i < local_paths_.size(); ++i) {
    entries.emplace_back(
        local_paths_[i], (*mime_types)[i],
        directory_paths->find(local_paths_[i]) != directory_paths->end());
  }

  file_manager::file_tasks::FindAllTypesOfTasks(
      Profile::FromBrowserContext(browser_context()), entries, urls_,
      dlp_source_urls_,
      base::BindOnce(
          &FileManagerPrivateInternalGetFileTasksFunction::OnFileTasksListed,
          this));
}

void FileManagerPrivateInternalGetFileTasksFunction::OnFileTasksListed(
    std::unique_ptr<file_manager::file_tasks::ResultingTasks> resulting_tasks) {
  // Convert the tasks into JSON compatible objects.
  std::vector<api_fmp::FileTask> results;
  for (const auto& task : resulting_tasks->tasks) {
    api_fmp::FileTask converted;
    converted.descriptor.app_id = task.task_descriptor.app_id;
    converted.descriptor.task_type =
        TaskTypeToString(task.task_descriptor.task_type);
    converted.descriptor.action_id = task.task_descriptor.action_id;
    if (!task.icon_url.is_empty()) {
      converted.icon_url = task.icon_url.spec();
    }
    converted.title = task.task_title;
    converted.is_default = task.is_default;
    converted.is_generic_file_handler = task.is_generic_file_handler;
    converted.is_dlp_blocked = task.is_dlp_blocked;
    results.push_back(std::move(converted));
  }

  api_fmp::ResultingTasks api_resulting_tasks;

  api_resulting_tasks.tasks = std::move(results);
  if (auto status = RemapPolicyDefaultHandlerStatus(
          resulting_tasks->policy_default_handler_status)) {
    api_resulting_tasks.policy_default_handler_status = *status;
  }

  Respond(ArgumentList(api_fmp_internal::GetFileTasks::Results::Create(
      std::move(api_resulting_tasks))));
}

ExtensionFunction::ResponseAction
FileManagerPrivateInternalSetDefaultTaskFunction::Run() {
  using api_fmp_internal::SetDefaultTask::Params;
  const std::optional<Params> params = Params::Create(args());
  EXTENSION_FUNCTION_VALIDATE(params);

  Profile* profile = Profile::FromBrowserContext(browser_context());
  const scoped_refptr<storage::FileSystemContext> file_system_context =
      file_manager::util::GetFileSystemContextForRenderFrameHost(
          profile, render_frame_host());

  const std::set<std::string> suffixes =
      GetUniqueSuffixes(params->urls, file_system_context.get());
  const std::set<std::string> mime_types =
      GetUniqueMimeTypes(params->mime_types);

  // If there weren't any mime_types, and all the suffixes were blank,
  // then we "succeed", but don't actually associate with anything.
  // Otherwise, any time we set the default on a file with no extension
  // on the local drive, we'd fail.
  // TODO(gspencer): Fix file manager so that it never tries to set default in
  // cases where extensionless local files are part of the selection.
  if (suffixes.empty() && mime_types.empty()) {
    return RespondNow(WithArguments(true));
  }

  file_manager::file_tasks::TaskType task_type =
      file_manager::file_tasks::StringToTaskType(params->descriptor.task_type);
  if (task_type == file_manager::file_tasks::TASK_TYPE_UNKNOWN) {
    return RespondNow(Error(kInvalidTaskType + params->descriptor.task_type));
  }
  file_manager::file_tasks::TaskDescriptor descriptor(
      params->descriptor.app_id, task_type, params->descriptor.action_id);

  file_manager::file_tasks::UpdateDefaultTask(profile, descriptor, suffixes,
                                              mime_types);
  return RespondNow(NoArguments());
}

}  // namespace extensions