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/browser/printing/cloud_print/cloud_print_url.h" |
| 14 #include "chrome/browser/profiles/profile.h" |
| 15 #include "chrome/browser/signin/token_service.h" |
| 16 #include "chrome/browser/signin/token_service_factory.h" |
| 17 #include "chrome/browser/ui/browser.h" |
| 18 #include "chrome/browser/ui/browser_list.h" |
| 19 #include "chrome/common/cloud_print/cloud_print_helpers.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::Observer::~Observer() {} |
| 132 |
| 133 ChromeToMobileService::RequestData::RequestData() {} |
| 134 |
| 135 ChromeToMobileService::RequestData::~RequestData() {} |
| 136 |
| 137 ChromeToMobileService::ChromeToMobileService(Profile* profile) |
| 138 : profile_(profile), |
| 139 cloud_print_url_(new CloudPrintURL(profile)), |
| 140 oauth2_retry_count_(0) { |
| 141 content::BrowserThread::PostBlockingPoolTask(FROM_HERE, |
| 142 base::Bind(&ChromeToMobileService::CreateUniqueTempDir, |
| 143 base::Unretained(this))); |
| 144 RequestMobileListUpdate(); |
| 145 } |
| 146 |
| 147 ChromeToMobileService::~ChromeToMobileService() {} |
| 148 |
| 149 void ChromeToMobileService::OnURLFetchComplete( |
| 150 const content::URLFetcher* source) { |
| 151 if (source == search_request_.get()) |
| 152 HandleSearchResponse(); |
| 153 else |
| 154 HandleSubmitResponse(source); |
| 155 } |
| 156 |
| 157 void ChromeToMobileService::OnGetTokenSuccess( |
| 158 const std::string& access_token) { |
| 159 DCHECK(!access_token.empty()); |
| 160 oauth2_request_.reset(); |
| 161 request_timer_.Stop(); |
| 162 oauth2_token_ = access_token; |
| 163 RequestMobileListUpdate(); |
| 164 } |
| 165 |
| 166 void ChromeToMobileService::OnGetTokenFailure( |
| 167 const GoogleServiceAuthError& error) { |
| 168 oauth2_request_.reset(); |
| 169 if (request_timer_.IsRunning() || (oauth2_retry_count_++ > kMaxRetries)) |
| 170 return; |
| 171 request_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kAuthRetryDelay), |
| 172 this, &ChromeToMobileService::RequestAuth); |
| 173 } |
| 174 |
| 175 void ChromeToMobileService::RequestMobileListUpdate() { |
| 176 if (oauth2_token_.empty()) |
| 177 RequestAuth(); |
| 178 else |
| 179 RequestSearch(); |
| 180 } |
| 181 |
| 182 void ChromeToMobileService::GenerateSnapshot(base::WeakPtr<Observer> observer) { |
| 183 FilePath path(temp_dir_.path().Append(kSnapshotPath)); |
| 184 BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents()-> |
| 185 GenerateMHTML(path.InsertBeforeExtensionASCII(guid::GenerateGUID()), |
| 186 base::Bind(&Observer::SnapshotGenerated, observer)); |
| 187 } |
| 188 |
| 189 void ChromeToMobileService::SendToMobile(const string16& mobile_id, |
| 190 const FilePath& snapshot, |
| 191 base::WeakPtr<Observer> observer) { |
| 192 DCHECK(!oauth2_token_.empty()); |
| 193 RequestData data; |
| 194 data.mobile_id = mobile_id; |
| 195 content::WebContents* web_contents = |
| 196 BrowserList::GetLastActiveWithProfile(profile_)->GetSelectedWebContents(); |
| 197 data.url = web_contents->GetURL(); |
| 198 data.title = web_contents->GetTitle(); |
| 199 data.snapshot_path = snapshot; |
| 200 bool send_snapshot = !snapshot.empty(); |
| 201 data.snapshot_id = send_snapshot ? guid::GenerateGUID() : std::string(); |
| 202 data.type = send_snapshot ? DELAYED_SNAPSHOT : URL; |
| 203 |
| 204 content::URLFetcher* submit_url = CreateRequest(data); |
| 205 request_observer_map_[submit_url] = observer; |
| 206 submit_url->Start(); |
| 207 |
| 208 if (send_snapshot) { |
| 209 data.type = SNAPSHOT; |
| 210 content::URLFetcher* submit_snapshot = CreateRequest(data); |
| 211 request_observer_map_[submit_snapshot] = observer; |
| 212 content::BrowserThread::PostBlockingPoolTask(FROM_HERE, |
| 213 base::Bind(&SubmitSnapshot, submit_snapshot, data)); |
| 214 } |
| 215 } |
| 216 |
| 217 void ChromeToMobileService::CreateUniqueTempDir() { |
| 218 bool success = temp_dir_.CreateUniqueTempDir(); |
| 219 DCHECK(success); |
| 220 } |
| 221 |
| 222 content::URLFetcher* ChromeToMobileService::CreateRequest( |
| 223 const RequestData& data) { |
| 224 bool get = data.type != SNAPSHOT; |
| 225 GURL service_url(cloud_print_url_->GetCloudPrintServiceURL()); |
| 226 content::URLFetcher* request = content::URLFetcher::Create( |
| 227 data.type == SEARCH ? cloud_print::GetUrlForSearch(service_url) : |
| 228 GetSubmitURL(service_url, data), |
| 229 get ? content::URLFetcher::GET : content::URLFetcher::POST, this); |
| 230 request->SetRequestContext(profile_->GetRequestContext()); |
| 231 request->SetMaxRetries(kMaxRetries); |
| 232 request->SetExtraRequestHeaders("Authorization: OAuth " + |
| 233 oauth2_token_ + "\r\n" + cloud_print::kChromeCloudPrintProxyHeader); |
| 234 request->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | |
| 235 net::LOAD_DO_NOT_SAVE_COOKIES); |
| 236 return request; |
| 237 } |
| 238 |
| 239 void ChromeToMobileService::RequestAuth() { |
| 240 DCHECK(oauth2_token_.empty()); |
| 241 if (oauth2_request_.get()) |
| 242 return; |
| 243 |
| 244 std::string token = TokenServiceFactory::GetForProfile(profile_)-> |
| 245 GetOAuth2LoginRefreshToken(); |
| 246 if (token.empty()) |
| 247 return; |
| 248 |
| 249 oauth2_request_.reset( |
| 250 new OAuth2AccessTokenFetcher(this, profile_->GetRequestContext())); |
| 251 std::vector<std::string> scopes(1, kOAuth2Scope); |
| 252 oauth2_request_->Start(GaiaUrls::GetInstance()->oauth2_chrome_client_id(), |
| 253 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), token, scopes); |
| 254 } |
| 255 |
| 256 void ChromeToMobileService::RequestSearch() { |
| 257 DCHECK(!oauth2_token_.empty()); |
| 258 if (search_request_.get()) |
| 259 return; |
| 260 |
| 261 RequestData data; |
| 262 data.type = SEARCH; |
| 263 search_request_.reset(CreateRequest(data)); |
| 264 search_request_->Start(); |
| 265 } |
| 266 |
| 267 void ChromeToMobileService::HandleSearchResponse() { |
| 268 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); |
| 269 |
| 270 std::string data; |
| 271 search_request_->GetResponseAsString(&data); |
| 272 search_request_.reset(); |
| 273 |
| 274 DictionaryValue* json_data = NULL; |
| 275 cloud_print::ParseResponseJSON(data, NULL, &json_data); |
| 276 |
| 277 ListValue* list = NULL; |
| 278 if (json_data && json_data->GetList(cloud_print::kPrinterListValue, &list)) { |
| 279 std::vector<base::DictionaryValue*> mobiles; |
| 280 for (size_t index = 0; index < list->GetSize(); index++) { |
| 281 DictionaryValue* mobile_data = NULL; |
| 282 if (list->GetDictionary(index, &mobile_data)) { |
| 283 std::string mobile_type; |
| 284 mobile_data->GetString("type", &mobile_type); |
| 285 if (mobile_type.compare(kTypeAndroidChromeSnapshot) == 0) |
| 286 mobiles.push_back(mobile_data); |
| 287 } |
| 288 } |
| 289 mobiles_ = mobiles; |
| 290 } |
| 291 |
| 292 BrowserList::GetLastActiveWithProfile(profile_)->command_updater()-> |
| 293 UpdateCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE, !mobiles_.empty()); |
| 294 |
| 295 if (!request_timer_.IsRunning()) |
| 296 request_timer_.Start(FROM_HERE, |
| 297 base::TimeDelta::FromSeconds(kAutoSearchRetryDelay), |
| 298 this, &ChromeToMobileService::RequestSearch); |
| 299 } |
| 300 |
| 301 void ChromeToMobileService::HandleSubmitResponse( |
| 302 const content::URLFetcher* source) { |
| 303 // Get the observer for this response; bail if there is none or it is NULL. |
| 304 RequestObserverMap::iterator i = request_observer_map_.find(source); |
| 305 if (i == request_observer_map_.end()) |
| 306 return; |
| 307 base::WeakPtr<Observer> observer = i->second; |
| 308 request_observer_map_.erase(i); |
| 309 if (!observer.get()) |
| 310 return; |
| 311 |
| 312 // Get the success value from the CloudPrint server response data. |
| 313 std::string data; |
| 314 source->GetResponseAsString(&data); |
| 315 DictionaryValue* json_data = NULL; |
| 316 cloud_print::ParseResponseJSON(data, NULL, &json_data); |
| 317 bool success = false; |
| 318 if (json_data) |
| 319 json_data->GetBoolean("success", &success); |
| 320 |
| 321 // Check if the observer is waiting on a second response (url and snapshot). |
| 322 RequestObserverMap::iterator other = request_observer_map_.begin(); |
| 323 for (; other != request_observer_map_.end(); ++other) { |
| 324 if (other->second == observer) { |
| 325 // Do not call OnSendComplete for observers waiting on a second response. |
| 326 if (success) |
| 327 return; |
| 328 |
| 329 // Ensure a second response is not sent after reporting failure below. |
| 330 request_observer_map_.erase(other); |
| 331 break; |
| 332 } |
| 333 } |
| 334 |
| 335 observer->OnSendComplete(success); |
| 336 } |
OLD | NEW |