blob: fb838ce139d2c23c487339327cce7208d0048b15 [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"
Yafei Duan69ddcfd92018-02-02 00:03:4216#include "components/url_formatter/url_formatter.h"
17#include "net/base/filename_util.h"
18#include "net/base/mime_util.h"
19#include "url/gurl.h"
20
21namespace filename_generation {
22
23namespace {
24
Yafei Duanc9f95ec2018-02-08 02:35:3125// The lower bound for file name truncation. If the truncation results in a name
26// shorter than this limit, we give up automatic truncation and prompt the user.
27const size_t kTruncatedNameLengthLowerbound = 5;
28
Yafei Duan69ddcfd92018-02-02 00:03:4229const base::FilePath::CharType kDefaultHtmlExtension[] =
30 FILE_PATH_LITERAL("html");
31
32// Check whether we can save page as complete-HTML for the contents which
33// have specified a MIME type. Now only contents which have the MIME type
34// "text/html" can be saved as complete-HTML.
35bool CanSaveAsComplete(const std::string& contents_mime_type) {
36 return contents_mime_type == "text/html" ||
37 contents_mime_type == "application/xhtml+xml";
38}
39
40} // namespace
41
42const base::FilePath::CharType* ExtensionForMimeType(
43 const std::string& contents_mime_type) {
44 static const struct {
45 const char* mime_type;
46 const base::FilePath::CharType* suggested_extension;
47 } kExtensions[] = {
48 {"text/html", kDefaultHtmlExtension},
49 {"text/xml", FILE_PATH_LITERAL("xml")},
50 {"application/xhtml+xml", FILE_PATH_LITERAL("xhtml")},
51 {"text/plain", FILE_PATH_LITERAL("txt")},
52 {"text/css", FILE_PATH_LITERAL("css")},
Pete Williamsonf7aaf3592018-02-10 00:32:2653 {"multipart/related", FILE_PATH_LITERAL("mhtml")},
Yafei Duan69ddcfd92018-02-02 00:03:4254 };
55 for (const auto& extension : kExtensions) {
56 if (contents_mime_type == extension.mime_type)
57 return extension.suggested_extension;
58 }
59 return FILE_PATH_LITERAL("");
60}
61
62base::FilePath EnsureHtmlExtension(const base::FilePath& name) {
Yafei Duan69ddcfd92018-02-02 00:03:4263 base::FilePath::StringType ext = name.Extension();
64 if (!ext.empty())
65 ext.erase(ext.begin()); // Erase preceding '.'.
66 std::string mime_type;
67 if (!net::GetMimeTypeFromExtension(ext, &mime_type) ||
68 !CanSaveAsComplete(mime_type)) {
69 return base::FilePath(name.value() + FILE_PATH_LITERAL(".") +
70 kDefaultHtmlExtension);
71 }
72 return name;
73}
74
75base::FilePath EnsureMimeExtension(const base::FilePath& name,
76 const std::string& contents_mime_type) {
Yafei Duan69ddcfd92018-02-02 00:03:4277 // Start extension at 1 to skip over period if non-empty.
78 base::FilePath::StringType ext = name.Extension();
79 if (!ext.empty())
80 ext = ext.substr(1);
81 base::FilePath::StringType suggested_extension =
82 ExtensionForMimeType(contents_mime_type);
83 std::string mime_type;
84 if (!suggested_extension.empty() &&
85 !net::GetMimeTypeFromExtension(ext, &mime_type)) {
86 // Extension is absent or needs to be updated.
87 return base::FilePath(name.value() + FILE_PATH_LITERAL(".") +
88 suggested_extension);
89 }
Pete Williamsonf7aaf3592018-02-10 00:32:2690
91 // Special treatment for MHTML: we would always want to add ".mhtml" as the
92 // extension even if there's another recognized mime_type based on |ext|.
93 // For example: the name is "page.html", we would like to have
94 // "page.html.mhtml" instead of "page.html".
95 if (contents_mime_type == "multipart/related" &&
96 mime_type != "multipart/related") {
97 return base::FilePath(name.value() + FILE_PATH_LITERAL(".mhtml"));
98 }
99
Yafei Duan69ddcfd92018-02-02 00:03:42100 return name;
101}
102
Jan Wilken Dörriefa241ba2021-03-11 17:57:01103base::FilePath GenerateFilename(const std::u16string& title,
Yafei Duan69ddcfd92018-02-02 00:03:42104 const GURL& url,
105 bool can_save_as_complete,
106 std::string contents_mime_type) {
107 base::FilePath name_with_proper_ext = base::FilePath::FromUTF16Unsafe(title);
108
109 // If the page's title matches its URL, use the URL. Try to use the last path
110 // component or if there is none, the domain as the file name.
111 // Normally we want to base the filename on the page title, or if it doesn't
112 // exist, on the URL. It's not easy to tell if the page has no title, because
113 // if the page has no title, WebContents::GetTitle() will return the page's
114 // URL (adjusted for display purposes). Therefore, we convert the "title"
115 // back to a URL, and if it matches the original page URL, we know the page
116 // had no title (or had a title equal to its URL, which is fine to treat
117 // similarly).
Jackson Loefflera73d2dfd2023-08-09 23:24:16118 if (title == url_formatter::FormatUrl(
119 url,
120 url_formatter::kFormatUrlOmitDefaults |
121 url_formatter::kFormatUrlOmitTrivialSubdomains |
122 url_formatter::kFormatUrlOmitHTTPS,
123 base::UnescapeRule::SPACES, nullptr, nullptr, nullptr)) {
Yafei Duan69ddcfd92018-02-02 00:03:42124 std::string url_path;
125 if (!url.SchemeIs(url::kDataScheme)) {
126 name_with_proper_ext = net::GenerateFileName(
127 url, std::string(), std::string(), std::string(), contents_mime_type,
128 std::string());
129
130 // If host is used as file name, try to decode punycode.
131 if (name_with_proper_ext.AsUTF8Unsafe() == url.host()) {
132 name_with_proper_ext = base::FilePath::FromUTF16Unsafe(
133 url_formatter::IDNToUnicode(url.host()));
134 }
135 } else {
136 name_with_proper_ext = base::FilePath::FromUTF8Unsafe("dataurl");
137 }
138 }
139
140 // Ask user for getting final saving name.
141 name_with_proper_ext =
142 EnsureMimeExtension(name_with_proper_ext, contents_mime_type);
143 // Adjust extension for complete types.
144 if (can_save_as_complete)
145 name_with_proper_ext = EnsureHtmlExtension(name_with_proper_ext);
146
147 base::FilePath::StringType file_name = name_with_proper_ext.value();
148 base::i18n::ReplaceIllegalCharactersInPath(&file_name, '_');
149 return base::FilePath(file_name);
150}
151
Yafei Duanc9f95ec2018-02-08 02:35:31152bool TruncateFilename(base::FilePath* path, size_t limit) {
153 base::FilePath basename(path->BaseName());
154 // It is already short enough.
155 if (basename.value().size() <= limit)
156 return true;
157
158 base::FilePath dir(path->DirName());
159 base::FilePath::StringType ext(basename.Extension());
160 base::FilePath::StringType name(basename.RemoveExtension().value());
161
162 // Impossible to satisfy the limit.
163 if (limit < kTruncatedNameLengthLowerbound + ext.size())
164 return false;
165 limit -= ext.size();
166
167 // Encoding specific truncation logic.
168 base::FilePath::StringType truncated;
Maksim Sisov183e6182024-12-09 08:22:46169#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_APPLE)
Yafei Duanc9f95ec2018-02-08 02:35:31170 // UTF-8.
171 base::TruncateUTF8ToByteSize(name, limit, &truncated);
Xiaohan Wangbca91f92022-01-15 19:56:21172#elif BUILDFLAG(IS_WIN)
Yafei Duanc9f95ec2018-02-08 02:35:31173 // UTF-16.
174 DCHECK(name.size() > limit);
175 truncated = name.substr(0, CBU16_IS_TRAIL(name[limit]) ? limit - 1 : limit);
176#else
177// We cannot generally assume that the file name encoding is in UTF-8 (see
178// the comment for FilePath::AsUTF8Unsafe), hence no safe way to truncate.
179#endif
180
181 if (truncated.size() < kTruncatedNameLengthLowerbound)
182 return false;
183 *path = dir.Append(truncated + ext);
184 return true;
185}
186
Yafei Duan69ddcfd92018-02-02 00:03:42187} // namespace filename_generation