Update broken references to image assets
[chromium-blink-merge.git] / chrome / browser / extensions / convert_user_script.cc
blobf7dfe673d0501f8e0973ba3d58877da9cfe8c8a8
1 // Copyright (c) 2012 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.
5 #include "chrome/browser/extensions/convert_user_script.h"
7 #include <string>
8 #include <vector>
10 #include "base/base64.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/json/json_file_value_serializer.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/common/chrome_paths.h"
18 #include "crypto/sha2.h"
19 #include "extensions/browser/extension_user_script_loader.h"
20 #include "extensions/common/constants.h"
21 #include "extensions/common/extension.h"
22 #include "extensions/common/file_util.h"
23 #include "extensions/common/manifest_constants.h"
24 #include "extensions/common/user_script.h"
25 #include "url/gurl.h"
27 namespace extensions {
29 namespace keys = manifest_keys;
30 namespace values = manifest_values;
32 scoped_refptr<Extension> ConvertUserScriptToExtension(
33 const base::FilePath& user_script_path, const GURL& original_url,
34 const base::FilePath& extensions_dir, base::string16* error) {
35 std::string content;
36 if (!base::ReadFileToString(user_script_path, &content)) {
37 *error = base::ASCIIToUTF16("Could not read source file.");
38 return NULL;
41 if (!base::IsStringUTF8(content)) {
42 *error = base::ASCIIToUTF16("User script must be UTF8 encoded.");
43 return NULL;
46 UserScript script;
47 if (!UserScriptLoader::ParseMetadataHeader(content, &script)) {
48 *error = base::ASCIIToUTF16("Invalid script header.");
49 return NULL;
52 base::FilePath install_temp_dir =
53 file_util::GetInstallTempDir(extensions_dir);
54 if (install_temp_dir.empty()) {
55 *error = base::ASCIIToUTF16(
56 "Could not get path to profile temporary directory.");
57 return NULL;
60 base::ScopedTempDir temp_dir;
61 if (!temp_dir.CreateUniqueTempDirUnderPath(install_temp_dir)) {
62 *error = base::ASCIIToUTF16("Could not create temporary directory.");
63 return NULL;
66 // Create the manifest
67 scoped_ptr<base::DictionaryValue> root(new base::DictionaryValue);
68 std::string script_name;
69 if (!script.name().empty() && !script.name_space().empty())
70 script_name = script.name_space() + "/" + script.name();
71 else
72 script_name = original_url.spec();
74 // Create the public key.
75 // User scripts are not signed, but the public key for an extension doubles as
76 // its unique identity, and we need one of those. A user script's unique
77 // identity is its namespace+name, so we hash that to create a public key.
78 // There will be no corresponding private key, which means user scripts cannot
79 // be auto-updated, or claimed in the gallery.
80 char raw[crypto::kSHA256Length] = {0};
81 std::string key;
82 crypto::SHA256HashString(script_name, raw, crypto::kSHA256Length);
83 base::Base64Encode(std::string(raw, crypto::kSHA256Length), &key);
85 // The script may not have a name field, but we need one for an extension. If
86 // it is missing, use the filename of the original URL.
87 if (!script.name().empty())
88 root->SetString(keys::kName, script.name());
89 else
90 root->SetString(keys::kName, original_url.ExtractFileName());
92 // Not all scripts have a version, but we need one. Default to 1.0 if it is
93 // missing.
94 if (!script.version().empty())
95 root->SetString(keys::kVersion, script.version());
96 else
97 root->SetString(keys::kVersion, "1.0");
99 root->SetString(keys::kDescription, script.description());
100 root->SetString(keys::kPublicKey, key);
101 root->SetBoolean(keys::kConvertedFromUserScript, true);
103 base::ListValue* js_files = new base::ListValue();
104 js_files->Append(new base::StringValue("script.js"));
106 // If the script provides its own match patterns, we use those. Otherwise, we
107 // generate some using the include globs.
108 base::ListValue* matches = new base::ListValue();
109 if (!script.url_patterns().is_empty()) {
110 for (URLPatternSet::const_iterator i = script.url_patterns().begin();
111 i != script.url_patterns().end(); ++i) {
112 matches->Append(new base::StringValue(i->GetAsString()));
114 } else {
115 // TODO(aa): Derive tighter matches where possible.
116 matches->Append(new base::StringValue("http://*/*"));
117 matches->Append(new base::StringValue("https://*/*"));
120 // Read the exclude matches, if any are present.
121 base::ListValue* exclude_matches = new base::ListValue();
122 if (!script.exclude_url_patterns().is_empty()) {
123 for (URLPatternSet::const_iterator i =
124 script.exclude_url_patterns().begin();
125 i != script.exclude_url_patterns().end(); ++i) {
126 exclude_matches->Append(new base::StringValue(i->GetAsString()));
130 base::ListValue* includes = new base::ListValue();
131 for (size_t i = 0; i < script.globs().size(); ++i)
132 includes->Append(new base::StringValue(script.globs().at(i)));
134 base::ListValue* excludes = new base::ListValue();
135 for (size_t i = 0; i < script.exclude_globs().size(); ++i)
136 excludes->Append(new base::StringValue(script.exclude_globs().at(i)));
138 base::DictionaryValue* content_script = new base::DictionaryValue();
139 content_script->Set(keys::kMatches, matches);
140 content_script->Set(keys::kExcludeMatches, exclude_matches);
141 content_script->Set(keys::kIncludeGlobs, includes);
142 content_script->Set(keys::kExcludeGlobs, excludes);
143 content_script->Set(keys::kJs, js_files);
145 if (script.run_location() == UserScript::DOCUMENT_START)
146 content_script->SetString(keys::kRunAt, values::kRunAtDocumentStart);
147 else if (script.run_location() == UserScript::DOCUMENT_END)
148 content_script->SetString(keys::kRunAt, values::kRunAtDocumentEnd);
149 else if (script.run_location() == UserScript::DOCUMENT_IDLE)
150 // This is the default, but store it just in case we change that.
151 content_script->SetString(keys::kRunAt, values::kRunAtDocumentIdle);
153 base::ListValue* content_scripts = new base::ListValue();
154 content_scripts->Append(content_script);
156 root->Set(keys::kContentScripts, content_scripts);
158 base::FilePath manifest_path = temp_dir.path().Append(kManifestFilename);
159 JSONFileValueSerializer serializer(manifest_path);
160 if (!serializer.Serialize(*root)) {
161 *error = base::ASCIIToUTF16("Could not write JSON.");
162 return NULL;
165 // Write the script file.
166 if (!base::CopyFile(user_script_path,
167 temp_dir.path().AppendASCII("script.js"))) {
168 *error = base::ASCIIToUTF16("Could not copy script file.");
169 return NULL;
172 // TODO(rdevlin.cronin): Continue removing std::string errors and replacing
173 // with base::string16
174 std::string utf8_error;
175 scoped_refptr<Extension> extension = Extension::Create(
176 temp_dir.path(),
177 Manifest::INTERNAL,
178 *root,
179 Extension::NO_FLAGS,
180 &utf8_error);
181 *error = base::UTF8ToUTF16(utf8_error);
182 if (!extension.get()) {
183 NOTREACHED() << "Could not init extension " << *error;
184 return NULL;
187 temp_dir.Take(); // The caller takes ownership of the directory.
188 return extension;
191 } // namespace extensions