Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 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. | |
| 4 | |
| 5 #include "chrome/browser/chrome_to_mobile_service.h" | |
| 6 | |
| 7 #include "base/bind.h" | |
| 8 #include "base/json/json_writer.h" | |
| 9 #include "base/stringprintf.h" | |
| 10 #include "base/utf_string_conversions.h" | |
| 11 #include "base/values.h" | |
| 12 #include "chrome/app/chrome_command_ids.h" | |
| 13 #include "chrome/common/cloud_print/cloud_print_helpers.h" | |
|
Scott Byer
2012/03/12 23:26:23
Put in alphabetical order.
msw
2012/03/13 02:39:14
Done.
| |
| 14 #include "chrome/browser/printing/cloud_print/cloud_print_url.h" | |
| 15 #include "chrome/browser/profiles/profile.h" | |
| 16 #include "chrome/browser/signin/token_service.h" | |
| 17 #include "chrome/browser/signin/token_service_factory.h" | |
| 18 #include "chrome/browser/ui/browser.h" | |
| 19 #include "chrome/browser/ui/browser_list.h" | |
| 20 #include "chrome/common/guid.h" | |
| 21 #include "chrome/common/net/gaia/gaia_urls.h" | |
| 22 #include "chrome/common/net/gaia/oauth2_access_token_fetcher.h" | |
| 23 #include "content/public/browser/browser_thread.h" | |
| 24 #include "content/public/browser/web_contents.h" | |
| 25 #include "content/public/common/url_fetcher.h" | |
| 26 #include "net/base/escape.h" | |
| 27 #include "net/base/load_flags.h" | |
| 28 #include "net/url_request/url_request_context_getter.h" | |
| 29 | |
| 30 namespace { | |
| 31 | |
| 32 // The maximum number of retries for the URLFetcher requests. | |
| 33 size_t kMaxRetries = 10; | |
| 34 | |
| 35 // Seconds between automatically retrying authentication (on failure). | |
| 36 int kAuthRetryDelay = 30; | |
| 37 | |
| 38 // Seconds between automatically updating the mobile device list. | |
| 39 int kAutoSearchRetryDelay = 300; | |
| 40 | |
| 41 // The cloud print Oath2 scope and 'printer' type of compatible mobile devices. | |
| 42 const char kOAuth2Scope[] = "https://www.googleapis.com/auth/cloudprint"; | |
| 43 const char kTypeAndroidChromeSnapshot[] = "ANDROID_CHROME_SNAPSHOT"; | |
| 44 | |
| 45 // The types of Chrome To Mobile requests sent to the cloud print service. | |
| 46 const char kRequestTypeURL[] = "url"; | |
| 47 const char kRequestTypeDelayedSnapshot[] = "url_with_delayed_snapshot"; | |
| 48 const char kRequestTypeSnapshot[] = "snapshot"; | |
| 49 | |
| 50 // The snapshot path constants; used with a guid for each MHTML snapshot file. | |
| 51 const FilePath::CharType kSnapshotPath[] = | |
| 52 FILE_PATH_LITERAL("chrome_to_mobile_snapshot_.mht"); | |
| 53 | |
| 54 // Get the "__c2dm__job_data" tag JSON data for the cloud print job submission. | |
| 55 std::string GetJobString(const ChromeToMobileService::RequestData& data) { | |
| 56 scoped_ptr<DictionaryValue> job(new DictionaryValue()); | |
| 57 job->SetString("url", data.url.spec()); | |
| 58 if (data.type == ChromeToMobileService::URL) { | |
| 59 job->SetString("type", kRequestTypeURL); | |
| 60 } else { | |
| 61 job->SetString("snapID", data.snapshot_id); | |
| 62 job->SetString("type", (data.type == ChromeToMobileService::SNAPSHOT) ? | |
| 63 kRequestTypeSnapshot : kRequestTypeDelayedSnapshot); | |
| 64 } | |
| 65 std::string job_string; | |
| 66 base::JSONWriter::Write(job.get(), false, &job_string); | |
| 67 return job_string; | |
| 68 } | |
| 69 | |
| 70 // Get the URL for cloud print job submission; appends query params if needed. | |
| 71 GURL GetSubmitURL(GURL service_url, | |
| 72 const ChromeToMobileService::RequestData& data) { | |
| 73 GURL submit_url = cloud_print::GetUrlForSubmit(service_url); | |
| 74 if (data.type == ChromeToMobileService::SNAPSHOT) | |
| 75 return submit_url; | |
| 76 | |
| 77 // Append form data to the URL's query for |URL| and |DELAYED_SNAPSHOT| jobs. | |
| 78 static const bool kUsePlus = true; | |
| 79 std::string tag_string = net::EscapeQueryParamValue( | |
| 80 "__c2dm__job_data=" + GetJobString(data), kUsePlus); | |
| 81 GURL::Replacements replacements; | |
| 82 // Provide dummy content to workaround |errorCode| 412 'Document missing'. | |
| 83 std::string query = StringPrintf("printerid=%s&tag=%s&title=%s" | |
| 84 "&contentType=text/plain&content=dummy", | |
| 85 net::EscapeQueryParamValue(UTF16ToUTF8(data.mobile_id), kUsePlus).c_str(), | |
| 86 net::EscapeQueryParamValue(tag_string, kUsePlus).c_str(), | |
| 87 net::EscapeQueryParamValue(UTF16ToUTF8(data.title), kUsePlus).c_str()); | |
| 88 replacements.SetQueryStr(query); | |
| 89 return submit_url.ReplaceComponents(replacements); | |
| 90 } | |
| 91 | |
| 92 // Delete the specified file; called as a BlockingPoolTask. | |
| 93 void DeleteFilePath(const FilePath& file_path) { | |
| 94 bool success = file_util::Delete(file_path, false); | |
| 95 DCHECK(success); | |
| 96 } | |
| 97 | |
| 98 // Construct POST data and submit the MHTML snapshot file; deletes the snapshot. | |
| 99 void SubmitSnapshot(content::URLFetcher* request, | |
| 100 const ChromeToMobileService::RequestData& data) { | |
| 101 std::string file; | |
| 102 if (file_util::ReadFileToString(data.snapshot_path, &file) && !file.empty()) { | |
| 103 std::string post_data, mime_boundary; | |
| 104 cloud_print::CreateMimeBoundaryForUpload(&mime_boundary); | |
| 105 cloud_print::AddMultipartValueForUpload("printerid", | |
| 106 UTF16ToUTF8(data.mobile_id), mime_boundary, std::string(), &post_data); | |
| 107 cloud_print::AddMultipartValueForUpload("tag", "__c2dm__job_data=" + | |
| 108 GetJobString(data), mime_boundary, std::string(), &post_data); | |
| 109 cloud_print::AddMultipartValueForUpload("title", UTF16ToUTF8(data.title), | |
| 110 mime_boundary, std::string(), &post_data); | |
| 111 cloud_print::AddMultipartValueForUpload("contentType", "multipart/related", | |
| 112 mime_boundary, std::string(), &post_data); | |
| 113 | |
| 114 // Append the snapshot MHTML content and terminate the request body. | |
| 115 post_data.append("--" + mime_boundary + "\r\n" | |
| 116 "Content-Disposition: form-data; " | |
| 117 "name=\"content\"; filename=\"blob\"\r\n" | |
| 118 "Content-Type: text/mhtml\r\n" | |
| 119 "\r\n" + file + "\r\n" "--" + mime_boundary + "--\r\n"); | |
| 120 std::string content_type = "multipart/form-data; boundary=" + mime_boundary; | |
| 121 request->SetUploadData(content_type, post_data); | |
| 122 request->Start(); | |
| 123 } | |
| 124 | |
| 125 content::BrowserThread::PostBlockingPoolTask(FROM_HERE, | |
| 126 base::Bind(&DeleteFilePath, data.snapshot_path)); | |
| 127 } | |
| 128 | |
| 129 } // namespace | |
| 130 | |
| 131 ChromeToMobileService::RequestData::RequestData() {} | |
| 132 | |
| 133 ChromeToMobileService::RequestData::~RequestData() {} | |
| 134 | |
| 135 ChromeToMobileService::ChromeToMobileService(Profile* profile) | |
| 136 : profile_(profile), | |
| 137 cloud_print_url_(new CloudPrintURL(profile)), | |
| 138 oauth2_retry_count_(0) { | |
| 139 content::BrowserThread::PostBlockingPoolTask(FROM_HERE, | |
| 140 base::Bind(&ChromeToMobileService::CreateUniqueTempDir, | |
| 141 base::Unretained(this))); | |
| 142 RequestMobileListUpdate(); | |
| 143 } | |
| 144 | |
| 145 ChromeToMobileService::~ChromeToMobileService() {} | |
| 146 | |
| 147 void ChromeToMobileService::OnURLFetchComplete( | |
| 148 const content::URLFetcher* source) { | |
| 149 if (source == search_request_.get()) | |
| 150 HandleSearchResponse(); | |
| 151 else | |
| 152 HandleSubmitResponse(source); | |
| 153 } | |
| 154 | |
| 155 void ChromeToMobileService::OnGetTokenSuccess( | |
| 156 const std::string& access_token) { | |
| 157 oauth2_request_.reset(); | |
| 158 request_timer_.Stop(); | |
| 159 oauth2_token_ = access_token; | |
| 160 RequestSearch(); | |
| 161 } | |
| 162 | |
| 163 void ChromeToMobileService::OnGetTokenFailure( | |
| 164 const GoogleServiceAuthError& error) { | |
| 165 oauth2_request_.reset(); | |
| 166 if (request_timer_.IsRunning() || (oauth2_retry_count_++ > kMaxRetries)) | |
| 167 return; | |
| 168 request_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kAuthRetryDelay), | |
| 169 this, &ChromeToMobileService::RequestAuth); | |
| 170 } | |
| 171 | |
| 172 void ChromeToMobileService::RequestMobileListUpdate() { | |
| 173 if (oauth2_token_.empty()) | |
| 174 RequestAuth(); | |
| 175 else | |
| 176 RequestSearch(); | |
| 177 } | |
| 178 | |
| 179 void ChromeToMobileService::GenerateSnapshot(base::WeakPtr<Observer> observer) { | |
| 180 FilePath path(temp_dir_.path().Append(kSnapshotPath)); | |
| 181 BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents()-> | |
| 182 GenerateMHTML(path.InsertBeforeExtensionASCII(guid::GenerateGUID()), | |
| 183 base::Bind(&Observer::SnapshotGenerated, observer)); | |
| 184 } | |
| 185 | |
| 186 void ChromeToMobileService::SendToMobile(const string16& mobile_id, | |
| 187 const FilePath& snapshot, | |
| 188 base::WeakPtr<Observer> observer) { | |
| 189 DCHECK(!oauth2_token_.empty()); | |
| 190 RequestData data; | |
| 191 data.mobile_id = mobile_id; | |
| 192 content::WebContents* web_contents = | |
| 193 BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents(); | |
| 194 data.url = web_contents->GetURL(); | |
| 195 data.title = web_contents->GetTitle(); | |
| 196 data.snapshot_path = snapshot; | |
| 197 bool send_snapshot = !snapshot.empty(); | |
| 198 data.snapshot_id = send_snapshot ? guid::GenerateGUID() : std::string(); | |
| 199 data.type = send_snapshot ? DELAYED_SNAPSHOT : URL; | |
| 200 | |
| 201 content::URLFetcher* submit_url = CreateRequest(data); | |
|
nyquist
2012/03/13 00:52:23
Nit: This naming seems odd to me. submit_request?
msw
2012/03/13 02:39:14
Talked offline: submit_url corresponds with submit
| |
| 202 request_observer_map_[submit_url] = observer; | |
| 203 submit_url->Start(); | |
| 204 | |
| 205 if (send_snapshot) { | |
| 206 data.type = SNAPSHOT; | |
| 207 content::URLFetcher* submit_snapshot = CreateRequest(data); | |
| 208 request_observer_map_[submit_snapshot] = observer; | |
| 209 content::BrowserThread::PostBlockingPoolTask(FROM_HERE, | |
| 210 base::Bind(&SubmitSnapshot, submit_snapshot, data)); | |
| 211 } | |
| 212 } | |
| 213 | |
| 214 void ChromeToMobileService::CreateUniqueTempDir() { | |
| 215 bool success = temp_dir_.CreateUniqueTempDir(); | |
| 216 DCHECK(success); | |
| 217 } | |
| 218 | |
| 219 content::URLFetcher* ChromeToMobileService::CreateRequest( | |
| 220 const RequestData& data) { | |
| 221 bool get = data.type != SNAPSHOT; | |
| 222 GURL service_url(cloud_print_url_->GetCloudPrintServiceURL()); | |
| 223 content::URLFetcher* request = content::URLFetcher::Create( | |
| 224 data.type == SEARCH ? cloud_print::GetUrlForSearch(service_url) : | |
| 225 GetSubmitURL(service_url, data), | |
| 226 get ? content::URLFetcher::GET : content::URLFetcher::POST, this); | |
| 227 request->SetRequestContext(profile_->GetRequestContext()); | |
| 228 request->SetMaxRetries(kMaxRetries); | |
| 229 request->SetExtraRequestHeaders("Authorization: OAuth " + | |
| 230 oauth2_token_ + "\r\n" + cloud_print::kChromeCloudPrintProxyHeader); | |
| 231 request->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | | |
| 232 net::LOAD_DO_NOT_SAVE_COOKIES); | |
| 233 return request; | |
| 234 } | |
| 235 | |
| 236 void ChromeToMobileService::RequestAuth() { | |
| 237 DCHECK(oauth2_token_.empty()); | |
| 238 if (oauth2_request_.get()) | |
| 239 return; | |
| 240 | |
| 241 GURL auth_url = cloud_print::GetUrlForGetAuthCode( | |
|
nyquist
2012/03/13 00:52:23
Dead store. This doesn't seem to be used anywhere.
msw
2012/03/13 02:39:14
Awesome catch! This let me revert some CloudPrint
| |
| 242 cloud_print_url_->GetCloudPrintServiceURL(), | |
| 243 cloud_print::kDefaultCloudPrintOAuthClientId, | |
| 244 cloud_print::GenerateProxyId()); | |
| 245 oauth2_request_.reset( | |
| 246 new OAuth2AccessTokenFetcher(this, profile_->GetRequestContext())); | |
| 247 std::string token = TokenServiceFactory::GetForProfile(profile_)-> | |
| 248 GetOAuth2LoginRefreshToken(); | |
| 249 std::vector<std::string> scopes(1, kOAuth2Scope); | |
| 250 oauth2_request_->Start(GaiaUrls::GetInstance()->oauth2_chrome_client_id(), | |
| 251 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), token, scopes); | |
| 252 } | |
| 253 | |
| 254 void ChromeToMobileService::RequestSearch() { | |
| 255 DCHECK(!oauth2_token_.empty()); | |
| 256 if (search_request_.get()) | |
| 257 return; | |
| 258 | |
| 259 RequestData data; | |
| 260 data.type = SEARCH; | |
| 261 search_request_.reset(CreateRequest(data)); | |
| 262 search_request_->Start(); | |
| 263 } | |
| 264 | |
| 265 void ChromeToMobileService::HandleSearchResponse() { | |
| 266 std::string data; | |
| 267 search_request_->GetResponseAsString(&data); | |
| 268 search_request_.reset(); | |
| 269 | |
| 270 DictionaryValue* json_data = NULL; | |
| 271 ListValue* list = NULL; | |
| 272 cloud_print::ParseResponseJSON(data, NULL, &json_data); | |
| 273 if (json_data && json_data->GetList(cloud_print::kPrinterListValue, &list)) { | |
| 274 mobiles_.clear(); | |
|
nyquist
2012/03/13 00:52:23
Updating this list directly means that clients mig
msw
2012/03/13 02:39:14
I'll gladly take additional thread safety advice,
| |
| 275 for (size_t index = 0; index < list->GetSize(); index++) { | |
| 276 DictionaryValue* mobile_data = NULL; | |
| 277 if (list->GetDictionary(index, &mobile_data)) { | |
| 278 std::string mobile_type; | |
| 279 mobile_data->GetString("type", &mobile_type); | |
| 280 if (mobile_type.compare(kTypeAndroidChromeSnapshot) == 0) | |
| 281 mobiles_.push_back(mobile_data); | |
| 282 } | |
| 283 } | |
| 284 } | |
| 285 | |
| 286 BrowserList::GetLastActiveWithProfile(profile_)->command_updater()-> | |
| 287 UpdateCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE, !mobiles_.empty()); | |
| 288 | |
| 289 if (!request_timer_.IsRunning()) | |
| 290 request_timer_.Start(FROM_HERE, | |
| 291 base::TimeDelta::FromSeconds(kAutoSearchRetryDelay), | |
| 292 this, &ChromeToMobileService::RequestSearch); | |
| 293 } | |
| 294 | |
| 295 void ChromeToMobileService::HandleSubmitResponse( | |
| 296 const content::URLFetcher* source) { | |
| 297 // Get the observer for this response; bail if there is none or it is NULL. | |
| 298 RequestObserverMap::iterator i = request_observer_map_.find(source); | |
| 299 if (i == request_observer_map_.end()) | |
| 300 return; | |
| 301 base::WeakPtr<Observer> observer = i->second; | |
| 302 request_observer_map_.erase(i); | |
| 303 if (!observer.get()) | |
| 304 return; | |
| 305 | |
| 306 // Get the success value from the CloudPrint server response data. | |
| 307 std::string data; | |
| 308 source->GetResponseAsString(&data); | |
| 309 DictionaryValue* json_data = NULL; | |
| 310 cloud_print::ParseResponseJSON(data, NULL, &json_data); | |
| 311 bool success = false; | |
| 312 if (json_data) | |
| 313 json_data->GetBoolean("success", &success); | |
| 314 | |
| 315 // Check if the observer is waiting on a second response (url and snapshot). | |
| 316 RequestObserverMap::iterator other = request_observer_map_.begin(); | |
| 317 for (; other != request_observer_map_.end(); ++other) { | |
| 318 if (other->second == observer) { | |
| 319 // Do not call OnSendComplete for observers waiting on a second response. | |
| 320 if (success) | |
| 321 return; | |
| 322 | |
| 323 // Ensure a second response is not sent after reporting failure below. | |
| 324 request_observer_map_.erase(other); | |
| 325 break; | |
| 326 } | |
| 327 } | |
| 328 | |
| 329 observer->OnSendComplete(success); | |
| 330 } | |
| OLD | NEW |