1 // Copyright 2019 The Chromium Embedded Framework Authors. Portions copyright
2 // 2013 The Chromium Authors. All rights reserved. Use of this source code is
3 // governed by a BSD-style license that can be found in the LICENSE file.
4
5 #include "libcef/browser/devtools/devtools_file_manager.h"
6
7 #include "libcef/browser/alloy/alloy_browser_host_impl.h"
8
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/json/json_writer.h"
14 #include "base/json/values_util.h"
15 #include "base/lazy_instance.h"
16 #include "base/path_service.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/task/post_task.h"
19 #include "base/task/thread_pool.h"
20 #include "base/threading/sequenced_task_runner_handle.h"
21 #include "base/values.h"
22 #include "chrome/common/pref_names.h"
23 #include "components/prefs/scoped_user_pref_update.h"
24 #include "content/public/browser/web_contents.h"
25
26 namespace {
27
28 base::LazyInstance<base::FilePath>::Leaky g_last_save_path =
29 LAZY_INSTANCE_INITIALIZER;
30
WriteToFile(const base::FilePath & path,const std::string & content)31 void WriteToFile(const base::FilePath& path, const std::string& content) {
32 DCHECK(!path.empty());
33 base::WriteFile(path, content.c_str(), content.length());
34 }
35
AppendToFile(const base::FilePath & path,const std::string & content)36 void AppendToFile(const base::FilePath& path, const std::string& content) {
37 DCHECK(!path.empty());
38 base::AppendToFile(path, base::StringPiece(content));
39 }
40
41 } // namespace
42
CefDevToolsFileManager(AlloyBrowserHostImpl * browser_impl,PrefService * prefs)43 CefDevToolsFileManager::CefDevToolsFileManager(
44 AlloyBrowserHostImpl* browser_impl,
45 PrefService* prefs)
46 : browser_impl_(browser_impl),
47 prefs_(prefs),
48 file_task_runner_(
49 base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})),
50 weak_factory_(this) {}
51
SaveToFile(const std::string & url,const std::string & content,bool save_as)52 void CefDevToolsFileManager::SaveToFile(const std::string& url,
53 const std::string& content,
54 bool save_as) {
55 Save(url, content, save_as,
56 base::BindOnce(&CefDevToolsFileManager::FileSavedAs,
57 weak_factory_.GetWeakPtr(), url),
58 base::BindOnce(&CefDevToolsFileManager::CanceledFileSaveAs,
59 weak_factory_.GetWeakPtr(), url));
60 }
61
AppendToFile(const std::string & url,const std::string & content)62 void CefDevToolsFileManager::AppendToFile(const std::string& url,
63 const std::string& content) {
64 Append(url, content,
65 base::BindOnce(&CefDevToolsFileManager::AppendedTo,
66 weak_factory_.GetWeakPtr(), url));
67 }
68
Save(const std::string & url,const std::string & content,bool save_as,SaveCallback saveCallback,CancelCallback cancelCallback)69 void CefDevToolsFileManager::Save(const std::string& url,
70 const std::string& content,
71 bool save_as,
72 SaveCallback saveCallback,
73 CancelCallback cancelCallback) {
74 auto it = saved_files_.find(url);
75 if (it != saved_files_.end() && !save_as) {
76 SaveAsFileSelected(url, content, std::move(saveCallback), it->second);
77 return;
78 }
79
80 const base::DictionaryValue* file_map = &base::Value::AsDictionaryValue(
81 *prefs_->GetDictionary(prefs::kDevToolsEditedFiles));
82 base::FilePath initial_path;
83
84 const base::Value* path_value;
85 if (file_map->Get(base::MD5String(url), &path_value)) {
86 absl::optional<base::FilePath> path = base::ValueToFilePath(*path_value);
87 if (path)
88 initial_path = std::move(*path);
89 }
90
91 if (initial_path.empty()) {
92 GURL gurl(url);
93 std::string suggested_file_name =
94 gurl.is_valid() ? gurl.ExtractFileName() : url;
95
96 if (suggested_file_name.length() > 64)
97 suggested_file_name = suggested_file_name.substr(0, 64);
98
99 if (!g_last_save_path.Pointer()->empty()) {
100 initial_path = g_last_save_path.Pointer()->DirName().AppendASCII(
101 suggested_file_name);
102 } else {
103 // Use the temp directory. It may be an empty value.
104 base::PathService::Get(base::DIR_TEMP, &initial_path);
105 initial_path = initial_path.AppendASCII(suggested_file_name);
106 }
107 }
108
109 CefFileDialogRunner::FileChooserParams params;
110 params.mode = blink::mojom::FileChooserParams::Mode::kSave;
111 if (!initial_path.empty()) {
112 params.default_file_name = initial_path;
113 if (!initial_path.Extension().empty()) {
114 params.accept_types.push_back(CefString(initial_path.Extension()));
115 }
116 }
117
118 browser_impl_->RunFileChooser(
119 params,
120 base::BindOnce(&CefDevToolsFileManager::SaveAsDialogDismissed,
121 weak_factory_.GetWeakPtr(), url, content,
122 std::move(saveCallback), std::move(cancelCallback)));
123 }
124
SaveAsDialogDismissed(const std::string & url,const std::string & content,SaveCallback saveCallback,CancelCallback cancelCallback,int selected_accept_filter,const std::vector<base::FilePath> & file_paths)125 void CefDevToolsFileManager::SaveAsDialogDismissed(
126 const std::string& url,
127 const std::string& content,
128 SaveCallback saveCallback,
129 CancelCallback cancelCallback,
130 int selected_accept_filter,
131 const std::vector<base::FilePath>& file_paths) {
132 if (file_paths.size() == 1) {
133 SaveAsFileSelected(url, content, std::move(saveCallback), file_paths[0]);
134 } else {
135 std::move(cancelCallback).Run();
136 }
137 }
138
SaveAsFileSelected(const std::string & url,const std::string & content,SaveCallback callback,const base::FilePath & path)139 void CefDevToolsFileManager::SaveAsFileSelected(const std::string& url,
140 const std::string& content,
141 SaveCallback callback,
142 const base::FilePath& path) {
143 *g_last_save_path.Pointer() = path;
144 saved_files_[url] = path;
145
146 DictionaryPrefUpdate update(prefs_, prefs::kDevToolsEditedFiles);
147 base::Value* files_map = update.Get();
148 files_map->SetKey(base::MD5String(url), base::FilePathToValue(path));
149 std::string file_system_path = path.AsUTF8Unsafe();
150 std::move(callback).Run(file_system_path);
151 file_task_runner_->PostTask(FROM_HERE,
152 base::BindOnce(&::WriteToFile, path, content));
153 }
154
FileSavedAs(const std::string & url,const std::string & file_system_path)155 void CefDevToolsFileManager::FileSavedAs(const std::string& url,
156 const std::string& file_system_path) {
157 base::Value url_value(url);
158 base::Value file_system_path_value(file_system_path);
159 CallClientFunction("DevToolsAPI.savedURL", &url_value,
160 &file_system_path_value, nullptr);
161 }
162
CanceledFileSaveAs(const std::string & url)163 void CefDevToolsFileManager::CanceledFileSaveAs(const std::string& url) {
164 base::Value url_value(url);
165 CallClientFunction("DevToolsAPI.canceledSaveURL", &url_value, nullptr,
166 nullptr);
167 }
168
Append(const std::string & url,const std::string & content,AppendCallback callback)169 void CefDevToolsFileManager::Append(const std::string& url,
170 const std::string& content,
171 AppendCallback callback) {
172 auto it = saved_files_.find(url);
173 if (it == saved_files_.end())
174 return;
175 std::move(callback).Run();
176 file_task_runner_->PostTask(
177 FROM_HERE, base::BindOnce(&::AppendToFile, it->second, content));
178 }
179
AppendedTo(const std::string & url)180 void CefDevToolsFileManager::AppendedTo(const std::string& url) {
181 base::Value url_value(url);
182 CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr);
183 }
184
CallClientFunction(const std::string & function_name,const base::Value * arg1,const base::Value * arg2,const base::Value * arg3)185 void CefDevToolsFileManager::CallClientFunction(
186 const std::string& function_name,
187 const base::Value* arg1,
188 const base::Value* arg2,
189 const base::Value* arg3) {
190 std::string javascript = function_name + "(";
191 if (arg1) {
192 std::string json;
193 base::JSONWriter::Write(*arg1, &json);
194 javascript.append(json);
195 if (arg2) {
196 base::JSONWriter::Write(*arg2, &json);
197 javascript.append(", ").append(json);
198 if (arg3) {
199 base::JSONWriter::Write(*arg3, &json);
200 javascript.append(", ").append(json);
201 }
202 }
203 }
204 javascript.append(");");
205 browser_impl_->web_contents()->GetMainFrame()->ExecuteJavaScript(
206 base::UTF8ToUTF16(javascript), base::NullCallback());
207 }
208