blob: 5c304ea53b5a2acd0de571e54f122f303ec72233 [file] [log] [blame]
Avi Drissman8ba1bad2022-09-13 19:22:361// Copyright 2018 The Chromium Authors
Yafei Duan69ddcfd92018-02-02 00:03:422// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "components/filename_generation/filename_generation.h"
6
Hans Wennborgdf87046c2020-04-28 11:06:247#include "base/check.h"
Yafei Duan69ddcfd92018-02-02 00:03:428#include "base/files/file_path.h"
9#include "base/files/file_util.h"
10#include "base/i18n/file_util_icu.h"
Yafei Duan69ddcfd92018-02-02 00:03:4211#include "base/strings/string_util.h"
12#include "base/strings/sys_string_conversions.h"
13#include "base/strings/utf_string_conversions.h"
Yafei Duanc9f95ec2018-02-08 02:35:3114#include "base/third_party/icu/icu_utf.h"
Yafei Duanc9f95ec2018-02-08 02:35:3115#include "build/build_config.h"
Yuta Hijikata62dbeaf2020-12-10 04:15:5116#include "build/chromeos_buildflags.h"
Yafei Duan69ddcfd92018-02-02 00:03:4217#include "components/url_formatter/url_formatter.h"
18#include "net/base/filename_util.h"
19#include "net/base/mime_util.h"
20#include "url/gurl.h"
21
22namespace filename_generation {
23
24namespace {
25
Yafei Duanc9f95ec2018-02-08 02:35:3126// The lower bound for file name truncation. If the truncation results in a name
27// shorter than this limit, we give up automatic truncation and prompt the user.
28const size_t kTruncatedNameLengthLowerbound = 5;
29
Yafei Duan69ddcfd92018-02-02 00:03:4230const base::FilePath::CharType kDefaultHtmlExtension[] =
31 FILE_PATH_LITERAL("html");
32
33// Check whether we can save page as complete-HTML for the contents which
34// have specified a MIME type. Now only contents which have the MIME type
35// "text/html" can be saved as complete-HTML.
36bool CanSaveAsComplete(const std::string& contents_mime_type) {
37 return contents_mime_type == "text/html" ||
38 contents_mime_type == "application/xhtml+xml";
39}
40
41} // namespace
42
43const base::FilePath::CharType* ExtensionForMimeType(
44 const std::string& contents_mime_type) {
45 static const struct {
46 const char* mime_type;
47 const base::FilePath::CharType* suggested_extension;
48 } kExtensions[] = {
49 {"text/html", kDefaultHtmlExtension},
50 {"text/xml", FILE_PATH_LITERAL("xml")},
51 {"application/xhtml+xml", FILE_PATH_LITERAL("xhtml")},
52 {"text/plain", FILE_PATH_LITERAL("txt")},
53 {"text/css", FILE_PATH_LITERAL("css")},
Pete Williamsonf7aaf3592018-02-10 00:32:2654 {"multipart/related", FILE_PATH_LITERAL("mhtml")},
Yafei Duan69ddcfd92018-02-02 00:03:4255 };
56 for (const auto& extension : kExtensions) {
57 if (contents_mime_type == extension.mime_type)
58 return extension.suggested_extension;
59 }
60 return FILE_PATH_LITERAL("");
61}
62
63base::FilePath EnsureHtmlExtension(const base::FilePath& name) {
Yafei Duan69ddcfd92018-02-02 00:03:4264 base::FilePath::StringType ext = name.Extension();
65 if (!ext.empty())
66 ext.erase(ext.begin()); // Erase preceding '.'.
67 std::string mime_type;
68 if (!net::GetMimeTypeFromExtension(ext, &mime_type) ||
69 !CanSaveAsComplete(mime_type)) {
70 return base::FilePath(name.value() + FILE_PATH_LITERAL(".") +
71 kDefaultHtmlExtension);
72 }
73 return name;
74}
75
76base::FilePath EnsureMimeExtension(const base::FilePath& name,
77 const std::string& contents_mime_type) {
Yafei Duan69ddcfd92018-02-02 00:03:4278 // Start extension at 1 to skip over period if non-empty.
79 base::FilePath::StringType ext = name.Extension();
80 if (!ext.empty())
81 ext = ext.substr(1);
82 base::FilePath::StringType suggested_extension =
83 ExtensionForMimeType(contents_mime_type);
84 std::string mime_type;
85 if (!suggested_extension.empty() &&
86 !net::GetMimeTypeFromExtension(ext, &mime_type)) {
87 // Extension is absent or needs to be updated.
88 return base::FilePath(name.value() + FILE_PATH_LITERAL(".") +
89 suggested_extension);
90 }
Pete Williamsonf7aaf3592018-02-10 00:32:2691
92 // Special treatment for MHTML: we would always want to add ".mhtml" as the
93 // extension even if there's another recognized mime_type based on |ext|.
94 // For example: the name is "page.html", we would like to have
95 // "page.html.mhtml" instead of "page.html".
96 if (contents_mime_type == "multipart/related" &&
97 mime_type != "multipart/related") {
98 return base::FilePath(name.value() + FILE_PATH_LITERAL(".mhtml"));
99 }
100
Yafei Duan69ddcfd92018-02-02 00:03:42101 return name;
102}
103
Jan Wilken Dörriefa241ba2021-03-11 17:57:01104base::FilePath GenerateFilename(const std::u16string& title,
Yafei Duan69ddcfd92018-02-02 00:03:42105 const GURL& url,
106 bool can_save_as_complete,
107 std::string contents_mime_type) {
108 base::FilePath name_with_proper_ext = base::FilePath::FromUTF16Unsafe(title);
109
110 // If the page's title matches its URL, use the URL. Try to use the last path
111 // component or if there is none, the domain as the file name.
112 // Normally we want to base the filename on the page title, or if it doesn't
113 // exist, on the URL. It's not easy to tell if the page has no title, because
114 // if the page has no title, WebContents::GetTitle() will return the page's
115 // URL (adjusted for display purposes). Therefore, we convert the "title"
116 // back to a URL, and if it matches the original page URL, we know the page
117 // had no title (or had a title equal to its URL, which is fine to treat
118 // similarly).
Jackson Loefflera73d2dfd2023-08-09 23:24:16119 if (title == url_formatter::FormatUrl(
120 url,
121 url_formatter::kFormatUrlOmitDefaults |
122 url_formatter::kFormatUrlOmitTrivialSubdomains |
123 url_formatter::kFormatUrlOmitHTTPS,
124 base::UnescapeRule::SPACES, nullptr, nullptr, nullptr)) {
Yafei Duan69ddcfd92018-02-02 00:03:42125 std::string url_path;
126 if (!url.SchemeIs(url::kDataScheme)) {
127 name_with_proper_ext = net::GenerateFileName(
128 url, std::string(), std::string(), std::string(), contents_mime_type,
129 std::string());
130
131 // If host is used as file name, try to decode punycode.
132 if (name_with_proper_ext.AsUTF8Unsafe() == url.host()) {
133 name_with_proper_ext = base::FilePath::FromUTF16Unsafe(
134 url_formatter::IDNToUnicode(url.host()));
135 }
136 } else {
137 name_with_proper_ext = base::FilePath::FromUTF8Unsafe("dataurl");
138 }
139 }
140
141 // Ask user for getting final saving name.
142 name_with_proper_ext =
143 EnsureMimeExtension(name_with_proper_ext, contents_mime_type);
144 // Adjust extension for complete types.
145 if (can_save_as_complete)
146 name_with_proper_ext = EnsureHtmlExtension(name_with_proper_ext);
147
148 base::FilePath::StringType file_name = name_with_proper_ext.value();
149 base::i18n::ReplaceIllegalCharactersInPath(&file_name, '_');
150 return base::FilePath(file_name);
151}
152
Yafei Duanc9f95ec2018-02-08 02:35:31153bool TruncateFilename(base::FilePath* path, size_t limit) {
154 base::FilePath basename(path->BaseName());
155 // It is already short enough.
156 if (basename.value().size() <= limit)
157 return true;
158
159 base::FilePath dir(path->DirName());
160 base::FilePath::StringType ext(basename.Extension());
161 base::FilePath::StringType name(basename.RemoveExtension().value());
162
163 // Impossible to satisfy the limit.
164 if (limit < kTruncatedNameLengthLowerbound + ext.size())
165 return false;
166 limit -= ext.size();
167
168 // Encoding specific truncation logic.
169 base::FilePath::StringType truncated;
Xiaohan Wangbca91f92022-01-15 19:56:21170#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_APPLE)
Yafei Duanc9f95ec2018-02-08 02:35:31171 // UTF-8.
172 base::TruncateUTF8ToByteSize(name, limit, &truncated);
Xiaohan Wangbca91f92022-01-15 19:56:21173#elif BUILDFLAG(IS_WIN)
Yafei Duanc9f95ec2018-02-08 02:35:31174 // UTF-16.
175 DCHECK(name.size() > limit);
176 truncated = name.substr(0, CBU16_IS_TRAIL(name[limit]) ? limit - 1 : limit);
177#else
178// We cannot generally assume that the file name encoding is in UTF-8 (see
179// the comment for FilePath::AsUTF8Unsafe), hence no safe way to truncate.
180#endif
181
182 if (truncated.size() < kTruncatedNameLengthLowerbound)
183 return false;
184 *path = dir.Append(truncated + ext);
185 return true;
186}
187
Yafei Duan69ddcfd92018-02-02 00:03:42188} // namespace filename_generation